From 5e0e254ef77b7849c24eb32f3bd95de26944ac38 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Mon, 4 May 2020 22:37:04 +0300 Subject: [PATCH 01/28] fix(38177): add auto-import for missing argument type in new functions/methods (#38213) --- src/services/codefixes/helpers.ts | 28 +++++------ src/services/refactors/extractSymbol.ts | 5 +- tests/cases/fourslash/extract-method32.ts | 35 ++++++++++++++ tests/cases/fourslash/extract-method33.ts | 44 +++++++++++++++++ tests/cases/fourslash/extract-method34.ts | 54 +++++++++++++++++++++ tests/cases/fourslash/extract-method35.ts | 38 +++++++++++++++ tests/cases/fourslash/extract-method36.ts | 47 +++++++++++++++++++ tests/cases/fourslash/extract-method37.ts | 57 +++++++++++++++++++++++ 8 files changed, 294 insertions(+), 14 deletions(-) create mode 100644 tests/cases/fourslash/extract-method32.ts create mode 100644 tests/cases/fourslash/extract-method33.ts create mode 100644 tests/cases/fourslash/extract-method34.ts create mode 100644 tests/cases/fourslash/extract-method35.ts create mode 100644 tests/cases/fourslash/extract-method36.ts create mode 100644 tests/cases/fourslash/extract-method37.ts diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 7f14de02c6105..51fe5b8fad25e 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -226,18 +226,8 @@ namespace ts.codefix { const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); const checker = context.program.getTypeChecker(); const tracker = getNoopSymbolTrackerWithResolver(context); - const types = map(args, arg => { - const type = checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)); - const typeNode = checker.typeToTypeNode(type, contextNode, /*flags*/ undefined, tracker); - if (typeNode?.kind === SyntaxKind.ImportType) { - const importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); - if (importableReference) { - importSymbols(importAdder, importableReference.symbols); - return importableReference.typeReference; - } - } - return typeNode; - }); + const types = map(args, arg => + typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker)); const names = map(args, arg => isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) && isIdentifier(arg.name) ? arg.name.text : undefined); const contextualType = checker.getContextualType(call); @@ -255,6 +245,18 @@ namespace ts.codefix { body ? createStubbedMethodBody(context.preferences) : undefined); } + export function typeToAutoImportableTypeNode(checker: TypeChecker, importAdder: ImportAdder, type: Type, contextNode: Node, scriptTarget: ScriptTarget, flags?: NodeBuilderFlags, tracker?: SymbolTracker): TypeNode | undefined { + const typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && isImportTypeNode(typeNode)) { + const importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + function createDummyParameters(argCount: number, names: (string | undefined)[] | undefined, types: (TypeNode | undefined)[] | undefined, minArgumentCount: number | undefined, inJs: boolean): ParameterDeclaration[] { const parameters: ParameterDeclaration[] = []; for (let i = 0; i < argCount; i++) { @@ -456,7 +458,7 @@ namespace ts.codefix { return createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); } - function importSymbols(importAdder: ImportAdder, symbols: readonly Symbol[]) { + export function importSymbols(importAdder: ImportAdder, symbols: readonly Symbol[]) { symbols.forEach(s => importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true)); } } diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 30dcaeaebfaf6..64e9bb6f3a2c8 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -719,6 +719,8 @@ namespace ts.refactor.extractSymbol { context: RefactorContext): RefactorEditInfo { const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const importAdder = codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function const file = scope.getSourceFile(); @@ -737,7 +739,7 @@ namespace ts.refactor.extractSymbol { let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, NodeBuilderFlags.NoTruncation); + typeNode = codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, NodeBuilderFlags.NoTruncation); } const paramDecl = createParameter( @@ -823,6 +825,7 @@ namespace ts.refactor.extractSymbol { else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); const newNodes: Node[] = []; // replace range with function call diff --git a/tests/cases/fourslash/extract-method32.ts b/tests/cases/fourslash/extract-method32.ts new file mode 100644 index 0000000000000..229561e9795a1 --- /dev/null +++ b/tests/cases/fourslash/extract-method32.ts @@ -0,0 +1,35 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} +////export const a: A = { x: 1 }; + +// @Filename: /b.ts +////import { a } from "./a"; +//// +////function foo() { +//// const arg = a; +//// /*a*/console.log(arg);/*b*/ +////} + +goTo.file("/b.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to function in module scope", + newContent: +`import { a, A } from "./a"; + +function foo() { + const arg = a; + /*RENAME*/newFunction(arg); +} + +function newFunction(arg: A) { + console.log(arg); +} +` +}); diff --git a/tests/cases/fourslash/extract-method33.ts b/tests/cases/fourslash/extract-method33.ts new file mode 100644 index 0000000000000..96d4216c844d0 --- /dev/null +++ b/tests/cases/fourslash/extract-method33.ts @@ -0,0 +1,44 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} + +// @Filename: /b.ts +////import { A } from "./a"; +////export interface B { +//// payload: T; +////} +////export const b: B = { +//// payload: { x: 1 } +////} + +// @Filename: /c.ts +////import { b } from "./b"; +//// +////function foo() { +//// const prop = b; +//// /*a*/console.log(prop);/*b*/ +////} + +goTo.file("/c.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to function in module scope", + newContent: +`import { b, B } from "./b"; +import { A } from "./a"; + +function foo() { + const prop = b; + /*RENAME*/newFunction(prop); +} + +function newFunction(prop: B) { + console.log(prop); +} +` +}); diff --git a/tests/cases/fourslash/extract-method34.ts b/tests/cases/fourslash/extract-method34.ts new file mode 100644 index 0000000000000..7ffb72e7af54e --- /dev/null +++ b/tests/cases/fourslash/extract-method34.ts @@ -0,0 +1,54 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} + +// @Filename: /b.ts +////export interface B { +//// payload: T; +////} + +// @Filename: /c.ts +////import { A } from "./a"; +////import { B } from "./b"; +////export interface C { +//// payload: T; +////} +//// +////export const c: C> = { +//// payload: { +//// payload: { x: 1 } +//// } +////} + +// @Filename: /d.ts +////import { c } from "./c"; +//// +////function foo() { +//// const prop = c; +//// /*a*/console.log(prop);/*b*/ +////} + +goTo.file("/c.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to function in module scope", + newContent: +`import { c, C } from "./c"; +import { B } from "./b"; +import { A } from "./a"; + +function foo() { + const prop = c; + /*RENAME*/newFunction(prop); +} + +function newFunction(prop: C>) { + console.log(prop); +} +` +}); diff --git a/tests/cases/fourslash/extract-method35.ts b/tests/cases/fourslash/extract-method35.ts new file mode 100644 index 0000000000000..67a3edd0b4ad3 --- /dev/null +++ b/tests/cases/fourslash/extract-method35.ts @@ -0,0 +1,38 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} +////export const a: A = { x: 1 }; + +// @Filename: /b.ts +////import { a } from "./a"; +//// +////class Foo { +//// foo() { +//// const arg = a; +//// /*a*/console.log(arg);/*b*/ +//// } +////} + +goTo.file("/b.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to method in class 'Foo'", + newContent: +`import { a, A } from "./a"; + +class Foo { + foo() { + const arg = a; + this./*RENAME*/newMethod(arg); + } + + private newMethod(arg: A) { + console.log(arg); + } +}` +}); diff --git a/tests/cases/fourslash/extract-method36.ts b/tests/cases/fourslash/extract-method36.ts new file mode 100644 index 0000000000000..0b3e93e2b951a --- /dev/null +++ b/tests/cases/fourslash/extract-method36.ts @@ -0,0 +1,47 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} + +// @Filename: /b.ts +////import { A } from "./a"; +////export interface B { +//// payload: T; +////} +////export const b: B = { +//// payload: { x: 1 } +////} + +// @Filename: /c.ts +////import { b } from "./b"; +//// +////class Foo { +//// foo() { +//// const arg = b; +//// /*a*/console.log(arg);/*b*/ +//// } +////} + +goTo.file("/c.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to method in class 'Foo'", + newContent: +`import { b, B } from "./b"; +import { A } from "./a"; + +class Foo { + foo() { + const arg = b; + this./*RENAME*/newMethod(arg); + } + + private newMethod(arg: B) { + console.log(arg); + } +}` +}); diff --git a/tests/cases/fourslash/extract-method37.ts b/tests/cases/fourslash/extract-method37.ts new file mode 100644 index 0000000000000..1f71cd098187b --- /dev/null +++ b/tests/cases/fourslash/extract-method37.ts @@ -0,0 +1,57 @@ +/// + +// @Filename: /a.ts +////export interface A { +//// x: number; +////} + +// @Filename: /b.ts +////export interface B { +//// payload: T; +////} + +// @Filename: /c.ts +////import { A } from "./a"; +////import { B } from "./b"; +////export interface C { +//// payload: T; +////} +//// +////export const c: C> = { +//// payload: { +//// payload: { x: 1 } +//// } +////} + +// @Filename: /d.ts +////import { c } from "./c"; +//// +////class Foo { +//// foo() { +//// const arg = c; +//// /*a*/console.log(arg);/*b*/ +//// } +////} + +goTo.file("/d.ts"); +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Extract Symbol", + actionName: "function_scope_1", + actionDescription: "Extract to method in class 'Foo'", + newContent: +`import { c, C } from "./c"; +import { B } from "./b"; +import { A } from "./a"; + +class Foo { + foo() { + const arg = c; + this./*RENAME*/newMethod(arg); + } + + private newMethod(arg: C>) { + console.log(arg); + } +}` +}); From a09470f013c1f71054331aae856b1ce9bc3e9165 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 4 May 2020 12:46:14 -0700 Subject: [PATCH 02/28] Fix index signatures on unions of intersections (#38278) * Add missing getApparentType call * Add regression tests --- src/compiler/checker.ts | 2 +- .../reference/unionWithIndexSignature.js | 47 ++++++++++++ .../reference/unionWithIndexSignature.symbols | 72 +++++++++++++++++++ .../reference/unionWithIndexSignature.types | 62 ++++++++++++++++ .../cases/compiler/unionWithIndexSignature.ts | 28 ++++++++ 5 files changed, 210 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/unionWithIndexSignature.js create mode 100644 tests/baselines/reference/unionWithIndexSignature.symbols create mode 100644 tests/baselines/reference/unionWithIndexSignature.types create mode 100644 tests/cases/compiler/unionWithIndexSignature.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 51837897a1bb4..e86de73ee52ce 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9701,7 +9701,7 @@ namespace ts { const indexTypes: Type[] = []; let isAnyReadonly = false; for (const type of types) { - const indexInfo = getIndexInfoOfType(type, kind); + const indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } diff --git a/tests/baselines/reference/unionWithIndexSignature.js b/tests/baselines/reference/unionWithIndexSignature.js new file mode 100644 index 0000000000000..31e0ccb88d837 --- /dev/null +++ b/tests/baselines/reference/unionWithIndexSignature.js @@ -0,0 +1,47 @@ +//// [unionWithIndexSignature.ts] +interface NumList { + kind: 'n'; + [x: number]: number; +} +interface StrList { + kind: 's'; + [x: number]: string; +} + +export function foo(arr: T & (NumList | StrList)) { + let zz = arr[1]; // Error +} + +// Repro from #38102 + +export type TypedArray = Int32Array | Uint8Array; + +export function isTypedArray(a: {}): a is Int32Array | Uint8Array { + return a instanceof Int32Array || a instanceof Uint8Array; +} + +export function flatten(arr: T) { + if (isTypedArray(arr)) { + arr[1]; + } +} + + +//// [unionWithIndexSignature.js] +"use strict"; +exports.__esModule = true; +exports.flatten = exports.isTypedArray = exports.foo = void 0; +function foo(arr) { + var zz = arr[1]; // Error +} +exports.foo = foo; +function isTypedArray(a) { + return a instanceof Int32Array || a instanceof Uint8Array; +} +exports.isTypedArray = isTypedArray; +function flatten(arr) { + if (isTypedArray(arr)) { + arr[1]; + } +} +exports.flatten = flatten; diff --git a/tests/baselines/reference/unionWithIndexSignature.symbols b/tests/baselines/reference/unionWithIndexSignature.symbols new file mode 100644 index 0000000000000..5f78136b361a6 --- /dev/null +++ b/tests/baselines/reference/unionWithIndexSignature.symbols @@ -0,0 +1,72 @@ +=== tests/cases/compiler/unionWithIndexSignature.ts === +interface NumList { +>NumList : Symbol(NumList, Decl(unionWithIndexSignature.ts, 0, 0)) + + kind: 'n'; +>kind : Symbol(NumList.kind, Decl(unionWithIndexSignature.ts, 0, 19)) + + [x: number]: number; +>x : Symbol(x, Decl(unionWithIndexSignature.ts, 2, 3)) +} +interface StrList { +>StrList : Symbol(StrList, Decl(unionWithIndexSignature.ts, 3, 1)) + + kind: 's'; +>kind : Symbol(StrList.kind, Decl(unionWithIndexSignature.ts, 4, 19)) + + [x: number]: string; +>x : Symbol(x, Decl(unionWithIndexSignature.ts, 6, 3)) +} + +export function foo(arr: T & (NumList | StrList)) { +>foo : Symbol(foo, Decl(unionWithIndexSignature.ts, 7, 1)) +>T : Symbol(T, Decl(unionWithIndexSignature.ts, 9, 20)) +>NumList : Symbol(NumList, Decl(unionWithIndexSignature.ts, 0, 0)) +>StrList : Symbol(StrList, Decl(unionWithIndexSignature.ts, 3, 1)) +>arr : Symbol(arr, Decl(unionWithIndexSignature.ts, 9, 49)) +>T : Symbol(T, Decl(unionWithIndexSignature.ts, 9, 20)) +>NumList : Symbol(NumList, Decl(unionWithIndexSignature.ts, 0, 0)) +>StrList : Symbol(StrList, Decl(unionWithIndexSignature.ts, 3, 1)) + + let zz = arr[1]; // Error +>zz : Symbol(zz, Decl(unionWithIndexSignature.ts, 10, 5)) +>arr : Symbol(arr, Decl(unionWithIndexSignature.ts, 9, 49)) +} + +// Repro from #38102 + +export type TypedArray = Int32Array | Uint8Array; +>TypedArray : Symbol(TypedArray, Decl(unionWithIndexSignature.ts, 11, 1)) +>Int32Array : Symbol(Int32Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +export function isTypedArray(a: {}): a is Int32Array | Uint8Array { +>isTypedArray : Symbol(isTypedArray, Decl(unionWithIndexSignature.ts, 15, 49)) +>a : Symbol(a, Decl(unionWithIndexSignature.ts, 17, 29)) +>a : Symbol(a, Decl(unionWithIndexSignature.ts, 17, 29)) +>Int32Array : Symbol(Int32Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + return a instanceof Int32Array || a instanceof Uint8Array; +>a : Symbol(a, Decl(unionWithIndexSignature.ts, 17, 29)) +>Int32Array : Symbol(Int32Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>a : Symbol(a, Decl(unionWithIndexSignature.ts, 17, 29)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +} + +export function flatten(arr: T) { +>flatten : Symbol(flatten, Decl(unionWithIndexSignature.ts, 19, 1)) +>T : Symbol(T, Decl(unionWithIndexSignature.ts, 21, 24)) +>TypedArray : Symbol(TypedArray, Decl(unionWithIndexSignature.ts, 11, 1)) +>arr : Symbol(arr, Decl(unionWithIndexSignature.ts, 21, 53)) +>T : Symbol(T, Decl(unionWithIndexSignature.ts, 21, 24)) + + if (isTypedArray(arr)) { +>isTypedArray : Symbol(isTypedArray, Decl(unionWithIndexSignature.ts, 15, 49)) +>arr : Symbol(arr, Decl(unionWithIndexSignature.ts, 21, 53)) + + arr[1]; +>arr : Symbol(arr, Decl(unionWithIndexSignature.ts, 21, 53)) + } +} + diff --git a/tests/baselines/reference/unionWithIndexSignature.types b/tests/baselines/reference/unionWithIndexSignature.types new file mode 100644 index 0000000000000..d80e8d01ca3c4 --- /dev/null +++ b/tests/baselines/reference/unionWithIndexSignature.types @@ -0,0 +1,62 @@ +=== tests/cases/compiler/unionWithIndexSignature.ts === +interface NumList { + kind: 'n'; +>kind : "n" + + [x: number]: number; +>x : number +} +interface StrList { + kind: 's'; +>kind : "s" + + [x: number]: string; +>x : number +} + +export function foo(arr: T & (NumList | StrList)) { +>foo : (arr: T & (NumList | StrList)) => void +>arr : (T & NumList) | (T & StrList) + + let zz = arr[1]; // Error +>zz : string | number +>arr[1] : string | number +>arr : (T & NumList) | (T & StrList) +>1 : 1 +} + +// Repro from #38102 + +export type TypedArray = Int32Array | Uint8Array; +>TypedArray : Int32Array | Uint8Array + +export function isTypedArray(a: {}): a is Int32Array | Uint8Array { +>isTypedArray : (a: {}) => a is Int32Array | Uint8Array +>a : {} + + return a instanceof Int32Array || a instanceof Uint8Array; +>a instanceof Int32Array || a instanceof Uint8Array : boolean +>a instanceof Int32Array : boolean +>a : {} +>Int32Array : Int32ArrayConstructor +>a instanceof Uint8Array : boolean +>a : {} +>Uint8Array : Uint8ArrayConstructor +} + +export function flatten(arr: T) { +>flatten : (arr: T) => void +>arr : T + + if (isTypedArray(arr)) { +>isTypedArray(arr) : boolean +>isTypedArray : (a: {}) => a is Int32Array | Uint8Array +>arr : T + + arr[1]; +>arr[1] : number +>arr : (T & Int32Array) | (T & Uint8Array) +>1 : 1 + } +} + diff --git a/tests/cases/compiler/unionWithIndexSignature.ts b/tests/cases/compiler/unionWithIndexSignature.ts new file mode 100644 index 0000000000000..14b20f3d57612 --- /dev/null +++ b/tests/cases/compiler/unionWithIndexSignature.ts @@ -0,0 +1,28 @@ +// @strict: true + +interface NumList { + kind: 'n'; + [x: number]: number; +} +interface StrList { + kind: 's'; + [x: number]: string; +} + +export function foo(arr: T & (NumList | StrList)) { + let zz = arr[1]; // Error +} + +// Repro from #38102 + +export type TypedArray = Int32Array | Uint8Array; + +export function isTypedArray(a: {}): a is Int32Array | Uint8Array { + return a instanceof Int32Array || a instanceof Uint8Array; +} + +export function flatten(arr: T) { + if (isTypedArray(arr)) { + arr[1]; + } +} From aa37b282469b6002388d3de026398c2ba41c92a1 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 4 May 2020 13:02:54 -0700 Subject: [PATCH 03/28] Fix incorrect line text computation to stop comment directive searching (#38296) Fixes #38289 --- src/compiler/program.ts | 2 +- .../reference/ts-expect-error.errors.txt | 19 ++++++- tests/baselines/reference/ts-expect-error.js | 13 ++++- .../reference/ts-expect-error.symbols | 21 ++++++++ .../baselines/reference/ts-expect-error.types | 49 +++++++++++++++++++ .../conformance/directives/ts-expect-error.ts | 7 +++ 6 files changed, 107 insertions(+), 4 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index d06ee2cd0205a..437ec09e8b8ce 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1803,7 +1803,7 @@ namespace ts { } // Stop searching if the line is not empty and not a comment - const lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + const lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } diff --git a/tests/baselines/reference/ts-expect-error.errors.txt b/tests/baselines/reference/ts-expect-error.errors.txt index 7ffda9dbf1f9e..24e7ddd0d6edb 100644 --- a/tests/baselines/reference/ts-expect-error.errors.txt +++ b/tests/baselines/reference/ts-expect-error.errors.txt @@ -1,9 +1,12 @@ tests/cases/conformance/directives/ts-expect-error.ts(4,1): error TS2578: Unused '@ts-expect-error' directive. tests/cases/conformance/directives/ts-expect-error.ts(10,1): error TS2578: Unused '@ts-expect-error' directive. tests/cases/conformance/directives/ts-expect-error.ts(13,5): error TS2322: Type '"nope"' is not assignable to type 'number'. +tests/cases/conformance/directives/ts-expect-error.ts(19,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. +tests/cases/conformance/directives/ts-expect-error.ts(21,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. +tests/cases/conformance/directives/ts-expect-error.ts(22,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. -==== tests/cases/conformance/directives/ts-expect-error.ts (3 errors) ==== +==== tests/cases/conformance/directives/ts-expect-error.ts (6 errors) ==== // @ts-expect-error additional commenting var invalidCommentedFancy: number = 'nope'; @@ -25,4 +28,16 @@ tests/cases/conformance/directives/ts-expect-error.ts(13,5): error TS2322: Type !!! error TS2322: Type '"nope"' is not assignable to type 'number'. var validPlain: string = 'nope'; - \ No newline at end of file + + // @ts-expect-error + (({ a: true } as const).a === false); // <-- compiles (as expected via comment) + (({ a: true } as const).a === false); // Should error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. + + (({ a: true } as const).a === false); // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. + (({ a: true } as const).a === false); // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. \ No newline at end of file diff --git a/tests/baselines/reference/ts-expect-error.js b/tests/baselines/reference/ts-expect-error.js index f37316d92b73c..88dc6ba3aa6ea 100644 --- a/tests/baselines/reference/ts-expect-error.js +++ b/tests/baselines/reference/ts-expect-error.js @@ -14,7 +14,13 @@ var validCommentedPlain: string = 'nope'; var invalidPlain: number = 'nope'; var validPlain: string = 'nope'; - + +// @ts-expect-error +(({ a: true } as const).a === false); // <-- compiles (as expected via comment) +(({ a: true } as const).a === false); // Should error + +(({ a: true } as const).a === false); // error +(({ a: true } as const).a === false); // error //// [ts-expect-error.js] // @ts-expect-error additional commenting @@ -27,3 +33,8 @@ var invalidCommentedPlain = 'nope'; var validCommentedPlain = 'nope'; var invalidPlain = 'nope'; var validPlain = 'nope'; +// @ts-expect-error +({ a: true }.a === false); // <-- compiles (as expected via comment) +({ a: true }.a === false); // Should error +({ a: true }.a === false); // error +({ a: true }.a === false); // error diff --git a/tests/baselines/reference/ts-expect-error.symbols b/tests/baselines/reference/ts-expect-error.symbols index fec43e1eb2e01..434287cace708 100644 --- a/tests/baselines/reference/ts-expect-error.symbols +++ b/tests/baselines/reference/ts-expect-error.symbols @@ -21,3 +21,24 @@ var invalidPlain: number = 'nope'; var validPlain: string = 'nope'; >validPlain : Symbol(validPlain, Decl(ts-expect-error.ts, 14, 3)) +// @ts-expect-error +(({ a: true } as const).a === false); // <-- compiles (as expected via comment) +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) + +(({ a: true } as const).a === false); // Should error +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) + +(({ a: true } as const).a === false); // error +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) + +(({ a: true } as const).a === false); // error +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) + diff --git a/tests/baselines/reference/ts-expect-error.types b/tests/baselines/reference/ts-expect-error.types index e338b276b7c5c..c010046d36fbe 100644 --- a/tests/baselines/reference/ts-expect-error.types +++ b/tests/baselines/reference/ts-expect-error.types @@ -27,3 +27,52 @@ var validPlain: string = 'nope'; >validPlain : string >'nope' : "nope" +// @ts-expect-error +(({ a: true } as const).a === false); // <-- compiles (as expected via comment) +>(({ a: true } as const).a === false) : boolean +>({ a: true } as const).a === false : boolean +>({ a: true } as const).a : true +>({ a: true } as const) : { readonly a: true; } +>{ a: true } as const : { readonly a: true; } +>{ a: true } : { readonly a: true; } +>a : true +>true : true +>a : true +>false : false + +(({ a: true } as const).a === false); // Should error +>(({ a: true } as const).a === false) : boolean +>({ a: true } as const).a === false : boolean +>({ a: true } as const).a : true +>({ a: true } as const) : { readonly a: true; } +>{ a: true } as const : { readonly a: true; } +>{ a: true } : { readonly a: true; } +>a : true +>true : true +>a : true +>false : false + +(({ a: true } as const).a === false); // error +>(({ a: true } as const).a === false) : boolean +>({ a: true } as const).a === false : boolean +>({ a: true } as const).a : true +>({ a: true } as const) : { readonly a: true; } +>{ a: true } as const : { readonly a: true; } +>{ a: true } : { readonly a: true; } +>a : true +>true : true +>a : true +>false : false + +(({ a: true } as const).a === false); // error +>(({ a: true } as const).a === false) : boolean +>({ a: true } as const).a === false : boolean +>({ a: true } as const).a : true +>({ a: true } as const) : { readonly a: true; } +>{ a: true } as const : { readonly a: true; } +>{ a: true } : { readonly a: true; } +>a : true +>true : true +>a : true +>false : false + diff --git a/tests/cases/conformance/directives/ts-expect-error.ts b/tests/cases/conformance/directives/ts-expect-error.ts index 5baea77dc51e4..78c25dc4591f4 100644 --- a/tests/cases/conformance/directives/ts-expect-error.ts +++ b/tests/cases/conformance/directives/ts-expect-error.ts @@ -13,3 +13,10 @@ var validCommentedPlain: string = 'nope'; var invalidPlain: number = 'nope'; var validPlain: string = 'nope'; + +// @ts-expect-error +(({ a: true } as const).a === false); // <-- compiles (as expected via comment) +(({ a: true } as const).a === false); // Should error + +(({ a: true } as const).a === false); // error +(({ a: true } as const).a === false); // error \ No newline at end of file From d9c9c9d9e45a9e27a905ac5701135ce5d7cbac43 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 4 May 2020 14:47:39 -0700 Subject: [PATCH 04/28] Harden node builder APIs to no longer return `undefined` for a node when `NodeBuilderFlags.IgnoreErrors` is provided (#38273) --- src/compiler/checker.ts | 10 ++++++--- src/compiler/types.ts | 22 +++++++++---------- .../codefixes/convertToAsyncFunction.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 4 ++-- src/services/codefixes/fixJSDocTypes.ts | 2 +- src/services/signatureHelp.ts | 4 ++-- src/services/symbolDisplay.ts | 6 +++-- .../reference/api/tsserverlibrary.d.ts | 16 +++++++------- tests/baselines/reference/api/typescript.d.ts | 16 +++++++------- ...tureHelpForSignatureWithUnreachableType.ts | 19 ++++++++++++++++ 10 files changed, 63 insertions(+), 38 deletions(-) create mode 100644 tests/cases/fourslash/signatureHelpForSignatureWithUnreachableType.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e86de73ee52ce..54d1b4b7479a4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -4212,8 +4212,12 @@ namespace ts { context.flags &= ~NodeBuilderFlags.InTypeAlias; if (!type) { - context.encounteredError = true; - return undefined!; // TODO: GH#18217 + if (!(context.flags & NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + context.encounteredError = true; + return undefined!; // TODO: GH#18217 + } + context.approximateLength += 3; + return createKeywordTypeNode(SyntaxKind.AnyKeyword); } if (!(context.flags & NodeBuilderFlags.NoTypeReduction)) { @@ -5933,7 +5937,7 @@ namespace ts { function serializeSymbolWorker(symbol: Symbol, isPrivate: boolean, propertyAsAlias: boolean) { const symbolName = unescapeLeadingUnderscores(symbol.escapedName); const isDefault = symbol.escapedName === InternalSymbolName.Default; - if (isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & NodeBuilderFlags.AllowAnonymousIdentifier) && isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 62165bd78f7dd..72c6dcfd79fb6 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3437,24 +3437,24 @@ namespace ts { // TODO: GH#18217 `xToDeclaration` calls are frequently asserted as defined. /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; - /* @internal */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; + /* @internal */ typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; - /* @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; + /* @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray} | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; - /* @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; + /* @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index b0f0ee7de84a4..108acee68cfa1 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -282,7 +282,7 @@ namespace ts.codefix { varDeclIdentifier = getSynthesizedDeepClone(possibleNameForVarDecl.identifier); const typeArray: Type[] = possibleNameForVarDecl.types; const unionType = transformer.checker.getUnionType(typeArray, UnionReduction.Subtype); - const unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + const unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); const varDecl = [createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList(varDecl, NodeFlags.Let)); } diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 7f5cd59e94cf5..ad7b115f5742d 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -230,11 +230,11 @@ namespace ts.codefix { const binaryExpression = token.parent.parent as BinaryExpression; const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { const contextualType = checker.getContextualType(token.parent as Expression); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); } diff --git a/src/services/codefixes/fixJSDocTypes.ts b/src/services/codefixes/fixJSDocTypes.ts index 8769b0339e03c..f8dbe52b26db4 100644 --- a/src/services/codefixes/fixJSDocTypes.ts +++ b/src/services/codefixes/fixJSDocTypes.ts @@ -40,7 +40,7 @@ namespace ts.codefix { }); function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, oldTypeNode: TypeNode, newType: Type, checker: TypeChecker): void { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)!); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)!); // TODO: GH#18217 } function getInfo(sourceFile: SourceFile, pos: number, checker: TypeChecker): { readonly typeNode: TypeNode, readonly type: Type } | undefined { diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 799fff86ecf0d..0f168d65e7b1f 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -580,7 +580,7 @@ namespace ts.SignatureHelp { const printer = createPrinter({ removeComments: true }); const typeParameterParts = mapToDisplayParts(writer => { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - const args = createNodeArray(candidateSignature.typeParameters.map(p => checker.typeParameterToDeclaration(p, enclosingDeclaration)!)); + const args = createNodeArray(candidateSignature.typeParameters.map(p => checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags)!)); printer.writeList(ListFormat.TypeParameters, args, sourceFile, writer); } }); @@ -599,7 +599,7 @@ namespace ts.SignatureHelp { function createSignatureHelpParameterForTypeParameter(typeParameter: TypeParameter, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile, printer: Printer): SignatureHelpParameter { const displayParts = mapToDisplayParts(writer => { - const param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration)!; + const param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)!; printer.writeNode(EmitHint.Unspecified, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts, isOptional: false }; diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index a51c159f29763..b8122428e4196 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,5 +1,7 @@ /* @internal */ namespace ts.SymbolDisplay { + const symbolDisplayNodeBuilderFlags = NodeBuilderFlags.OmitParameterModifiers | NodeBuilderFlags.IgnoreErrors | NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; + // TODO(drosen): use contextual SemanticMeaning. export function getSymbolKind(typeChecker: TypeChecker, symbol: Symbol, location: Node): ScriptElementKind { const result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -471,7 +473,7 @@ namespace ts.SymbolDisplay { // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & SymbolFlags.TypeParameter) { const typeParameterParts = mapToDisplayParts(writer => { - const param = typeChecker.typeParameterToDeclaration(type as TypeParameter, enclosingDeclaration)!; + const param = typeChecker.typeParameterToDeclaration(type as TypeParameter, enclosingDeclaration, symbolDisplayNodeBuilderFlags)!; getPrinter().writeNode(EmitHint.Unspecified, param, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration)), writer); }); addRange(displayParts, typeParameterParts); @@ -631,7 +633,7 @@ namespace ts.SymbolDisplay { function writeTypeParametersOfSymbol(symbol: Symbol, enclosingDeclaration: Node | undefined) { const typeParameterParts = mapToDisplayParts(writer => { - const params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + const params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(ListFormat.TypeParameters, params, getSourceFileOfNode(getParseTreeNode(enclosingDeclaration)), writer); }); addRange(displayParts, typeParameterParts); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 22d6234d13d6b..c9c2c066f8361 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2040,23 +2040,23 @@ declare namespace ts { getNonNullableType(type: Type): Type; getTypeArguments(type: TypeReference): readonly Type[]; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): (SignatureDeclaration & { typeArguments?: NodeArray; }) | undefined; /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 4e4746560ed7c..e1a34cf708250 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2040,23 +2040,23 @@ declare namespace ts { getNonNullableType(type: Type): Type; getTypeArguments(type: TypeReference): readonly Type[]; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): (SignatureDeclaration & { typeArguments?: NodeArray; }) | undefined; /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; diff --git a/tests/cases/fourslash/signatureHelpForSignatureWithUnreachableType.ts b/tests/cases/fourslash/signatureHelpForSignatureWithUnreachableType.ts new file mode 100644 index 0000000000000..47d96d26f9c7c --- /dev/null +++ b/tests/cases/fourslash/signatureHelpForSignatureWithUnreachableType.ts @@ -0,0 +1,19 @@ +/// + +// @Filename: /node_modules/foo/node_modules/bar/index.d.ts +////export interface SomeType { +//// x?: number; +////} +// @Filename: /node_modules/foo/index.d.ts +////import { SomeType } from "bar"; +////export function func(param: T): void; +////export function func(param: T, other: T): void; +// @Filename: /usage.ts +////import { func } from "foo"; +////func({/*1*/}); + +verify.signatureHelp({ + marker: "1", + overloadsCount: 2, + text: "func(param: {}): void" +}); \ No newline at end of file From e6390efb013009a94e8cf3383f2981765b7cfd37 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 4 May 2020 15:28:00 -0700 Subject: [PATCH 05/28] Properly handle private/protected members in unions of object types (#38277) * Property handle private/protected properties in unions of object types * Add regression test --- src/compiler/checker.ts | 7 ++-- .../reference/privatePropertyInUnion.js | 24 ++++++++++++++ .../reference/privatePropertyInUnion.symbols | 32 +++++++++++++++++++ .../reference/privatePropertyInUnion.types | 20 ++++++++++++ .../cases/compiler/privatePropertyInUnion.ts | 15 +++++++++ 5 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/privatePropertyInUnion.js create mode 100644 tests/baselines/reference/privatePropertyInUnion.symbols create mode 100644 tests/baselines/reference/privatePropertyInUnion.types create mode 100644 tests/cases/compiler/privatePropertyInUnion.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 54d1b4b7479a4..c9287634789bd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10539,7 +10539,6 @@ namespace ts { let propSet: Map | undefined; let indexTypes: Type[] | undefined; const isUnion = containingType.flags & TypeFlags.Union; - const excludeModifiers = isUnion ? ModifierFlags.NonPublicAccessibilityModifier : 0; // Flags we want to propagate to the result if they exist in all source symbols let optionalFlag = isUnion ? SymbolFlags.None : SymbolFlags.Optional; let syntheticFlag = CheckFlags.SyntheticMethod; @@ -10549,7 +10548,7 @@ namespace ts { if (!(type === errorType || type.flags & TypeFlags.Never)) { const prop = getPropertyOfType(type, name); const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & SymbolFlags.Optional); } @@ -10594,7 +10593,9 @@ namespace ts { } } } - if (!singleProp) { + if (!singleProp || isUnion && (propSet || checkFlags & CheckFlags.Partial) && checkFlags & (CheckFlags.ContainsPrivate | CheckFlags.ContainsProtected)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } if (!propSet && !(checkFlags & CheckFlags.ReadPartial) && !indexTypes) { diff --git a/tests/baselines/reference/privatePropertyInUnion.js b/tests/baselines/reference/privatePropertyInUnion.js new file mode 100644 index 0000000000000..f4208e51fe4af --- /dev/null +++ b/tests/baselines/reference/privatePropertyInUnion.js @@ -0,0 +1,24 @@ +//// [privatePropertyInUnion.ts] +// Repro from #38236 + +type Type = string | object; + +class SyncableObject { + private foo: unknown; +} + +interface SyncableRef {} + +interface ISyncableObject extends SyncableObject {} + +type __ValueDescriptorType = T extends ISyncableObject ? SyncableRef : T; + + +//// [privatePropertyInUnion.js] +"use strict"; +// Repro from #38236 +var SyncableObject = /** @class */ (function () { + function SyncableObject() { + } + return SyncableObject; +}()); diff --git a/tests/baselines/reference/privatePropertyInUnion.symbols b/tests/baselines/reference/privatePropertyInUnion.symbols new file mode 100644 index 0000000000000..01b4fdea82529 --- /dev/null +++ b/tests/baselines/reference/privatePropertyInUnion.symbols @@ -0,0 +1,32 @@ +=== tests/cases/compiler/privatePropertyInUnion.ts === +// Repro from #38236 + +type Type = string | object; +>Type : Symbol(Type, Decl(privatePropertyInUnion.ts, 0, 0)) + +class SyncableObject { +>SyncableObject : Symbol(SyncableObject, Decl(privatePropertyInUnion.ts, 2, 28)) + + private foo: unknown; +>foo : Symbol(SyncableObject.foo, Decl(privatePropertyInUnion.ts, 4, 22)) +} + +interface SyncableRef {} +>SyncableRef : Symbol(SyncableRef, Decl(privatePropertyInUnion.ts, 6, 1)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 8, 22)) +>ISyncableObject : Symbol(ISyncableObject, Decl(privatePropertyInUnion.ts, 8, 51)) + +interface ISyncableObject extends SyncableObject {} +>ISyncableObject : Symbol(ISyncableObject, Decl(privatePropertyInUnion.ts, 8, 51)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 10, 26)) +>SyncableObject : Symbol(SyncableObject, Decl(privatePropertyInUnion.ts, 2, 28)) + +type __ValueDescriptorType = T extends ISyncableObject ? SyncableRef : T; +>__ValueDescriptorType : Symbol(__ValueDescriptorType, Decl(privatePropertyInUnion.ts, 10, 63)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 12, 27)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 12, 27)) +>ISyncableObject : Symbol(ISyncableObject, Decl(privatePropertyInUnion.ts, 8, 51)) +>SyncableRef : Symbol(SyncableRef, Decl(privatePropertyInUnion.ts, 6, 1)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 12, 27)) +>T : Symbol(T, Decl(privatePropertyInUnion.ts, 12, 27)) + diff --git a/tests/baselines/reference/privatePropertyInUnion.types b/tests/baselines/reference/privatePropertyInUnion.types new file mode 100644 index 0000000000000..1bc4ea394773a --- /dev/null +++ b/tests/baselines/reference/privatePropertyInUnion.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/privatePropertyInUnion.ts === +// Repro from #38236 + +type Type = string | object; +>Type : string | object + +class SyncableObject { +>SyncableObject : SyncableObject + + private foo: unknown; +>foo : unknown +} + +interface SyncableRef {} + +interface ISyncableObject extends SyncableObject {} + +type __ValueDescriptorType = T extends ISyncableObject ? SyncableRef : T; +>__ValueDescriptorType : __ValueDescriptorType + diff --git a/tests/cases/compiler/privatePropertyInUnion.ts b/tests/cases/compiler/privatePropertyInUnion.ts new file mode 100644 index 0000000000000..59069cb5de1ef --- /dev/null +++ b/tests/cases/compiler/privatePropertyInUnion.ts @@ -0,0 +1,15 @@ +// @strict: true + +// Repro from #38236 + +type Type = string | object; + +class SyncableObject { + private foo: unknown; +} + +interface SyncableRef {} + +interface ISyncableObject extends SyncableObject {} + +type __ValueDescriptorType = T extends ISyncableObject ? SyncableRef : T; From 94c5c3ff47469c3b92342192a6a8353d6c7005ac Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 4 May 2020 19:32:27 -0700 Subject: [PATCH 06/28] Add missing arguments to typeToTypeNode. (#38336) * Add missing arguments to typeToTypeNode. * Use returnTypeNode as the enclosingDeclaration. * Add a test. --- .../codefixes/fixReturnTypeInAsyncFunction.ts | 22 +++++++------------ .../codeFixReturnTypeInAsyncFunction18.ts | 20 +++++++++++++++++ 2 files changed, 28 insertions(+), 14 deletions(-) create mode 100644 tests/cases/fourslash/codeFixReturnTypeInAsyncFunction18.ts diff --git a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts index 39e2c1900f3c7..4bb9162b32ffb 100644 --- a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts +++ b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts @@ -39,14 +39,20 @@ namespace ts.codefix { }); function getInfo(sourceFile: SourceFile, checker: TypeChecker, pos: number): Info | undefined { - const returnTypeNode = getReturnTypeNode(sourceFile, pos); + if (isInJSFile(sourceFile)) { + return undefined; + } + + const token = getTokenAtPosition(sourceFile, pos); + const func = findAncestor(token, isFunctionLikeDeclaration); + const returnTypeNode = func?.type; if (!returnTypeNode) { return undefined; } const returnType = checker.getTypeFromTypeNode(returnTypeNode); const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); - const promisedTypeNode = checker.typeToTypeNode(promisedType); + const promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined); if (promisedTypeNode) { return { returnTypeNode, returnType, promisedTypeNode, promisedType }; } @@ -55,16 +61,4 @@ namespace ts.codefix { function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, returnTypeNode: TypeNode, promisedTypeNode: TypeNode): void { changes.replaceNode(sourceFile, returnTypeNode, createTypeReferenceNode("Promise", [promisedTypeNode])); } - - function getReturnTypeNode(sourceFile: SourceFile, pos: number): TypeNode | undefined { - if (isInJSFile(sourceFile)) { - return undefined; - } - - const token = getTokenAtPosition(sourceFile, pos); - const parent = findAncestor(token, isFunctionLikeDeclaration); - if (parent?.type) { - return parent.type; - } - } } diff --git a/tests/cases/fourslash/codeFixReturnTypeInAsyncFunction18.ts b/tests/cases/fourslash/codeFixReturnTypeInAsyncFunction18.ts new file mode 100644 index 0000000000000..75b6727fd0ae6 --- /dev/null +++ b/tests/cases/fourslash/codeFixReturnTypeInAsyncFunction18.ts @@ -0,0 +1,20 @@ +/// + +// @target: es2015 +//// +////interface A {} +////export { A as PublicA }; +////async function foo(): A { +//// return {} +////} + +verify.codeFix({ + index: 0, + description: [ts.Diagnostics.Replace_0_with_Promise_1.message, "A", "A"], + newFileContent: ` +interface A {} +export { A as PublicA }; +async function foo(): Promise { + return {} +}` +}); From 44c6cf74cb9761f5471f1129a810c2f96f5f8deb Mon Sep 17 00:00:00 2001 From: Marcel Laverdet Date: Tue, 5 May 2020 09:05:02 -0700 Subject: [PATCH 07/28] Fix `updateBinary` `operator` parameter (#38129) * Fix `updateBinary` `operator` parameter There is an issue in `updateBinary` where attempting to update `operator` without updating `left` or `right` results in a silent no-op. * Use defaulted parameter in `updateBinary` --- src/compiler/factoryPublic.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/compiler/factoryPublic.ts b/src/compiler/factoryPublic.ts index e17cf3c505459..d78fdfc4dac3a 100644 --- a/src/compiler/factoryPublic.ts +++ b/src/compiler/factoryPublic.ts @@ -1411,10 +1411,11 @@ namespace ts { return node; } - export function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken) { + export function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator: BinaryOperator | BinaryOperatorToken = node.operatorToken) { return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } From 2bdc8fdc94370318ce100ddb0ef4700c9fa13633 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Tue, 5 May 2020 19:29:24 +0300 Subject: [PATCH 08/28] add outlining spans for array destructuring elements (#38191) --- src/services/outliningElementsCollector.ts | 2 + .../getOutliningForArrayDestructuring.ts | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 tests/cases/fourslash/getOutliningForArrayDestructuring.ts diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index 7c9e89052ab88..c849a9a5a6ba4 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -218,6 +218,8 @@ namespace ts.OutliningElementsCollector { case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: return spanForTemplateLiteral(n); + case SyntaxKind.ArrayBindingPattern: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isBindingElement(n.parent), SyntaxKind.OpenBracketToken); } function spanForJSXElement(node: JsxElement): OutliningSpan | undefined { diff --git a/tests/cases/fourslash/getOutliningForArrayDestructuring.ts b/tests/cases/fourslash/getOutliningForArrayDestructuring.ts new file mode 100644 index 0000000000000..72a2a0807ec0b --- /dev/null +++ b/tests/cases/fourslash/getOutliningForArrayDestructuring.ts @@ -0,0 +1,45 @@ +/// + +////const[| [ +//// a, +//// b, +//// c +////]|] =[| [ +//// 1, +//// 2, +//// 3 +////]|]; + +////const[| [ +//// [|[ +//// [|[ +//// [|[ +//// a, +//// b, +//// c +//// ]|] +//// ]|] +//// ]|], +//// [|[ +//// a1, +//// b1, +//// c1 +//// ]|] +////]|] =[| [ +//// [|[ +//// [|[ +//// [|[ +//// 1, +//// 2, +//// 3 +//// ]|] +//// ]|] +//// ]|], +//// [|[ +//// 1, +//// 2, +//// 3 +//// ]|] +////]|] + +verify.outliningSpansInCurrentFile(test.ranges(), "code"); From d86bdf4e5ce45edbdebdc6a2b8e136fefe7b68dc Mon Sep 17 00:00:00 2001 From: Alexander T Date: Tue, 5 May 2020 19:48:33 +0300 Subject: [PATCH 09/28] add outlining spans for the tuple type (#38179) --- src/services/outliningElementsCollector.ts | 2 ++ .../fourslash/getOutliningForTupleType.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 tests/cases/fourslash/getOutliningForTupleType.ts diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index c849a9a5a6ba4..568d75e542d4b 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -201,6 +201,8 @@ namespace ts.OutliningElementsCollector { case SyntaxKind.CaseBlock: case SyntaxKind.TypeLiteral: return spanForNode(n); + case SyntaxKind.TupleType: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !isTupleTypeNode(n.parent), SyntaxKind.OpenBracketToken); case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: return spanForNodeArray((n as CaseClause | DefaultClause).statements); diff --git a/tests/cases/fourslash/getOutliningForTupleType.ts b/tests/cases/fourslash/getOutliningForTupleType.ts new file mode 100644 index 0000000000000..f63fb623ac4ac --- /dev/null +++ b/tests/cases/fourslash/getOutliningForTupleType.ts @@ -0,0 +1,19 @@ +/// + +////type A =[| [ +//// number, +//// number, +//// number +////]|] +//// +////type B =[| [ +//// [|[ +//// [|[ +//// number, +//// number, +//// number +//// ]|] +//// ]|] +////]|] + +verify.outliningSpansInCurrentFile(test.ranges(), "code"); From c219fdae08607e07ec875d2137fcba7c2d93792c Mon Sep 17 00:00:00 2001 From: Alexander T Date: Tue, 5 May 2020 20:29:17 +0300 Subject: [PATCH 10/28] fix(37703): forbid required parameter after optional (#38155) --- src/compiler/checker.ts | 5 ++--- .../checkJsdocOptionalParamOrder.errors.txt | 14 +++++++++++++ .../reference/checkJsdocOptionalParamOrder.js | 18 +++++++++++++++++ .../checkJsdocOptionalParamOrder.symbols | 13 ++++++++++++ .../checkJsdocOptionalParamOrder.types | 13 ++++++++++++ .../jsdocParseBackquotedParamName.errors.txt | 20 +++++++++++++++++++ .../jsdoc/checkJsdocOptionalParamOrder.ts | 11 ++++++++++ 7 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/checkJsdocOptionalParamOrder.errors.txt create mode 100644 tests/baselines/reference/checkJsdocOptionalParamOrder.js create mode 100644 tests/baselines/reference/checkJsdocOptionalParamOrder.symbols create mode 100644 tests/baselines/reference/checkJsdocOptionalParamOrder.types create mode 100644 tests/baselines/reference/jsdocParseBackquotedParamName.errors.txt create mode 100644 tests/cases/conformance/jsdoc/checkJsdocOptionalParamOrder.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c9287634789bd..7a70426aae835 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -37048,10 +37048,9 @@ namespace ts { return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } diff --git a/tests/baselines/reference/checkJsdocOptionalParamOrder.errors.txt b/tests/baselines/reference/checkJsdocOptionalParamOrder.errors.txt new file mode 100644 index 0000000000000..82e6f5c5d1521 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOptionalParamOrder.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/jsdoc/0.js(7,20): error TS1016: A required parameter cannot follow an optional parameter. + + +==== tests/cases/conformance/jsdoc/0.js (1 errors) ==== + // @ts-check + /** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ + function foo(a, b, c) {} + ~ +!!! error TS1016: A required parameter cannot follow an optional parameter. + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocOptionalParamOrder.js b/tests/baselines/reference/checkJsdocOptionalParamOrder.js new file mode 100644 index 0000000000000..69b999fb2bd85 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOptionalParamOrder.js @@ -0,0 +1,18 @@ +//// [0.js] +// @ts-check +/** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ +function foo(a, b, c) {} + + +//// [0.js] +// @ts-check +/** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ +function foo(a, b, c) { } diff --git a/tests/baselines/reference/checkJsdocOptionalParamOrder.symbols b/tests/baselines/reference/checkJsdocOptionalParamOrder.symbols new file mode 100644 index 0000000000000..786f7a1bcf5b1 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOptionalParamOrder.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/jsdoc/0.js === +// @ts-check +/** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ +function foo(a, b, c) {} +>foo : Symbol(foo, Decl(0.js, 0, 0)) +>a : Symbol(a, Decl(0.js, 6, 13)) +>b : Symbol(b, Decl(0.js, 6, 15)) +>c : Symbol(c, Decl(0.js, 6, 18)) + diff --git a/tests/baselines/reference/checkJsdocOptionalParamOrder.types b/tests/baselines/reference/checkJsdocOptionalParamOrder.types new file mode 100644 index 0000000000000..1636462c8a964 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOptionalParamOrder.types @@ -0,0 +1,13 @@ +=== tests/cases/conformance/jsdoc/0.js === +// @ts-check +/** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ +function foo(a, b, c) {} +>foo : (a: number, b?: number, c: number) => void +>a : number +>b : number +>c : number + diff --git a/tests/baselines/reference/jsdocParseBackquotedParamName.errors.txt b/tests/baselines/reference/jsdocParseBackquotedParamName.errors.txt new file mode 100644 index 0000000000000..60ba155b1f966 --- /dev/null +++ b/tests/baselines/reference/jsdocParseBackquotedParamName.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/jsdoc/a.js(5,18): error TS1016: A required parameter cannot follow an optional parameter. + + +==== tests/cases/conformance/jsdoc/a.js (1 errors) ==== + /** + * @param {string=} `args` + * @param `bwarg` {?number?} + */ + function f(args, bwarg) { + ~~~~~ +!!! error TS1016: A required parameter cannot follow an optional parameter. + } + +==== tests/cases/conformance/jsdoc/ts.ts (0 errors) ==== + /** + * @param `arg` - this is fine + */ + function g(arg: string) { + } + \ No newline at end of file diff --git a/tests/cases/conformance/jsdoc/checkJsdocOptionalParamOrder.ts b/tests/cases/conformance/jsdoc/checkJsdocOptionalParamOrder.ts new file mode 100644 index 0000000000000..c498720c133c6 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkJsdocOptionalParamOrder.ts @@ -0,0 +1,11 @@ +// @allowJS: true +// @suppressOutputPathCheck: true + +// @filename: 0.js +// @ts-check +/** + * @param {number} a + * @param {number} [b] + * @param {number} c + */ +function foo(a, b, c) {} From 2524fb164ac3d6f508b876f248a9994500c82076 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 5 May 2020 20:06:07 -0700 Subject: [PATCH 11/28] Consistent narrowing by discriminant (#38311) * Consistent requirements for narrowing by discriminant * Add tests --- src/compiler/checker.ts | 15 +- .../reference/discriminantPropertyCheck.js | 87 ++++++++++ .../discriminantPropertyCheck.symbols | 156 +++++++++++++++++ .../reference/discriminantPropertyCheck.types | 158 ++++++++++++++++++ .../compiler/discriminantPropertyCheck.ts | 63 ++++++- 5 files changed, 471 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7a70426aae835..d302e867aeaac 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20593,14 +20593,15 @@ namespace ts { } function isMatchingReferenceDiscriminant(expr: Expression, computedType: Type) { - if (!(computedType.flags & TypeFlags.Union) || !isAccessExpression(expr)) { + const type = declaredType.flags & TypeFlags.Union ? declaredType : computedType; + if (!(type.flags & TypeFlags.Union) || !isAccessExpression(expr)) { return false; } const name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type: Type, access: AccessExpression, narrowType: (t: Type) => Type): Type { @@ -20626,7 +20627,7 @@ namespace ts { if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); } return type; @@ -20682,10 +20683,10 @@ namespace ts { type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left, declaredType)) { + if (isMatchingReferenceDiscriminant(left, type)) { return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); } - if (isMatchingReferenceDiscriminant(right, declaredType)) { + if (isMatchingReferenceDiscriminant(right, type)) { return narrowTypeByDiscriminant(type, right, t => narrowTypeByEquality(t, operator, left, assumeTrue)); } if (isMatchingConstructorReference(left)) { @@ -21107,7 +21108,7 @@ namespace ts { !(getTypeFacts(predicate.type) & TypeFacts.EQUndefined)) { type = getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument as AccessExpression, t => getNarrowedType(t, predicate.type!, assumeTrue, isTypeSubtypeOf)); } } @@ -21149,7 +21150,7 @@ namespace ts { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? TypeFacts.NEUndefinedOrNull : TypeFacts.EQUndefinedOrNull); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumePresent ? TypeFacts.NEUndefinedOrNull : TypeFacts.EQUndefinedOrNull)); } return type; diff --git a/tests/baselines/reference/discriminantPropertyCheck.js b/tests/baselines/reference/discriminantPropertyCheck.js index ee1c255ed28b4..cbbaa80d2ca3f 100644 --- a/tests/baselines/reference/discriminantPropertyCheck.js +++ b/tests/baselines/reference/discriminantPropertyCheck.js @@ -174,6 +174,67 @@ function func3(value: Partial) { } } } + +// Repro from #30557 + +interface TypeA { + Name: "TypeA"; + Value1: "Cool stuff!"; +} + +interface TypeB { + Name: "TypeB"; + Value2: 0; +} + +type Type = TypeA | TypeB; + +declare function isType(x: unknown): x is Type; + +function WorksProperly(data: Type) { + if (data.Name === "TypeA") { + const value1 = data.Value1; + } +} + +function DoesNotWork(data: unknown) { + if (isType(data)) { + if (data.Name === "TypeA") { + const value1 = data.Value1; + } + } +} + +// Repro from #36777 + +type TestA = { + type: 'testA'; + bananas: 3; +} + +type TestB = { + type: 'testB'; + apples: 5; +} + +type AllTests = TestA | TestB; + +type MapOfAllTests = Record; + +const doTestingStuff = (mapOfTests: MapOfAllTests, ids: string[]) => { + ids.forEach(id => { + let test; + test = mapOfTests[id]; + if (test.type === 'testA') { + console.log(test.bananas); + } + switch (test.type) { + case 'testA': { + console.log(test.bananas); + } + } + }); +}; //// [discriminantPropertyCheck.js] @@ -269,3 +330,29 @@ function func3(value) { } } } +function WorksProperly(data) { + if (data.Name === "TypeA") { + var value1 = data.Value1; + } +} +function DoesNotWork(data) { + if (isType(data)) { + if (data.Name === "TypeA") { + var value1 = data.Value1; + } + } +} +var doTestingStuff = function (mapOfTests, ids) { + ids.forEach(function (id) { + var test; + test = mapOfTests[id]; + if (test.type === 'testA') { + console.log(test.bananas); + } + switch (test.type) { + case 'testA': { + console.log(test.bananas); + } + } + }); +}; diff --git a/tests/baselines/reference/discriminantPropertyCheck.symbols b/tests/baselines/reference/discriminantPropertyCheck.symbols index b02a8113d46c2..7fa10ac46e28e 100644 --- a/tests/baselines/reference/discriminantPropertyCheck.symbols +++ b/tests/baselines/reference/discriminantPropertyCheck.symbols @@ -508,3 +508,159 @@ function func3(value: Partial) { } } +// Repro from #30557 + +interface TypeA { +>TypeA : Symbol(TypeA, Decl(discriminantPropertyCheck.ts, 174, 1)) + + Name: "TypeA"; +>Name : Symbol(TypeA.Name, Decl(discriminantPropertyCheck.ts, 178, 17)) + + Value1: "Cool stuff!"; +>Value1 : Symbol(TypeA.Value1, Decl(discriminantPropertyCheck.ts, 179, 18)) +} + +interface TypeB { +>TypeB : Symbol(TypeB, Decl(discriminantPropertyCheck.ts, 181, 1)) + + Name: "TypeB"; +>Name : Symbol(TypeB.Name, Decl(discriminantPropertyCheck.ts, 183, 17)) + + Value2: 0; +>Value2 : Symbol(TypeB.Value2, Decl(discriminantPropertyCheck.ts, 184, 18)) +} + +type Type = TypeA | TypeB; +>Type : Symbol(Type, Decl(discriminantPropertyCheck.ts, 186, 1)) +>TypeA : Symbol(TypeA, Decl(discriminantPropertyCheck.ts, 174, 1)) +>TypeB : Symbol(TypeB, Decl(discriminantPropertyCheck.ts, 181, 1)) + +declare function isType(x: unknown): x is Type; +>isType : Symbol(isType, Decl(discriminantPropertyCheck.ts, 188, 26)) +>x : Symbol(x, Decl(discriminantPropertyCheck.ts, 190, 24)) +>x : Symbol(x, Decl(discriminantPropertyCheck.ts, 190, 24)) +>Type : Symbol(Type, Decl(discriminantPropertyCheck.ts, 186, 1)) + +function WorksProperly(data: Type) { +>WorksProperly : Symbol(WorksProperly, Decl(discriminantPropertyCheck.ts, 190, 47)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 192, 23)) +>Type : Symbol(Type, Decl(discriminantPropertyCheck.ts, 186, 1)) + + if (data.Name === "TypeA") { +>data.Name : Symbol(Name, Decl(discriminantPropertyCheck.ts, 178, 17), Decl(discriminantPropertyCheck.ts, 183, 17)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 192, 23)) +>Name : Symbol(Name, Decl(discriminantPropertyCheck.ts, 178, 17), Decl(discriminantPropertyCheck.ts, 183, 17)) + + const value1 = data.Value1; +>value1 : Symbol(value1, Decl(discriminantPropertyCheck.ts, 194, 13)) +>data.Value1 : Symbol(TypeA.Value1, Decl(discriminantPropertyCheck.ts, 179, 18)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 192, 23)) +>Value1 : Symbol(TypeA.Value1, Decl(discriminantPropertyCheck.ts, 179, 18)) + } +} + +function DoesNotWork(data: unknown) { +>DoesNotWork : Symbol(DoesNotWork, Decl(discriminantPropertyCheck.ts, 196, 1)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 198, 21)) + + if (isType(data)) { +>isType : Symbol(isType, Decl(discriminantPropertyCheck.ts, 188, 26)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 198, 21)) + + if (data.Name === "TypeA") { +>data.Name : Symbol(Name, Decl(discriminantPropertyCheck.ts, 178, 17), Decl(discriminantPropertyCheck.ts, 183, 17)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 198, 21)) +>Name : Symbol(Name, Decl(discriminantPropertyCheck.ts, 178, 17), Decl(discriminantPropertyCheck.ts, 183, 17)) + + const value1 = data.Value1; +>value1 : Symbol(value1, Decl(discriminantPropertyCheck.ts, 201, 17)) +>data.Value1 : Symbol(TypeA.Value1, Decl(discriminantPropertyCheck.ts, 179, 18)) +>data : Symbol(data, Decl(discriminantPropertyCheck.ts, 198, 21)) +>Value1 : Symbol(TypeA.Value1, Decl(discriminantPropertyCheck.ts, 179, 18)) + } + } +} + +// Repro from #36777 + +type TestA = { +>TestA : Symbol(TestA, Decl(discriminantPropertyCheck.ts, 204, 1)) + + type: 'testA'; +>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 208, 14)) + + bananas: 3; +>bananas : Symbol(bananas, Decl(discriminantPropertyCheck.ts, 209, 18)) +} + +type TestB = { +>TestB : Symbol(TestB, Decl(discriminantPropertyCheck.ts, 211, 1)) + + type: 'testB'; +>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 213, 14)) + + apples: 5; +>apples : Symbol(apples, Decl(discriminantPropertyCheck.ts, 214, 18)) +} + +type AllTests = TestA | TestB; +>AllTests : Symbol(AllTests, Decl(discriminantPropertyCheck.ts, 216, 1)) +>TestA : Symbol(TestA, Decl(discriminantPropertyCheck.ts, 204, 1)) +>TestB : Symbol(TestB, Decl(discriminantPropertyCheck.ts, 211, 1)) + +type MapOfAllTests = Record; +>MapOfAllTests : Symbol(MapOfAllTests, Decl(discriminantPropertyCheck.ts, 218, 30)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>AllTests : Symbol(AllTests, Decl(discriminantPropertyCheck.ts, 216, 1)) + +const doTestingStuff = (mapOfTests: MapOfAllTests, ids: string[]) => { +>doTestingStuff : Symbol(doTestingStuff, Decl(discriminantPropertyCheck.ts, 222, 5)) +>mapOfTests : Symbol(mapOfTests, Decl(discriminantPropertyCheck.ts, 222, 24)) +>MapOfAllTests : Symbol(MapOfAllTests, Decl(discriminantPropertyCheck.ts, 218, 30)) +>ids : Symbol(ids, Decl(discriminantPropertyCheck.ts, 222, 50)) + + ids.forEach(id => { +>ids.forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --)) +>ids : Symbol(ids, Decl(discriminantPropertyCheck.ts, 222, 50)) +>forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --)) +>id : Symbol(id, Decl(discriminantPropertyCheck.ts, 223, 16)) + + let test; +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) + + test = mapOfTests[id]; +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) +>mapOfTests : Symbol(mapOfTests, Decl(discriminantPropertyCheck.ts, 222, 24)) +>id : Symbol(id, Decl(discriminantPropertyCheck.ts, 223, 16)) + + if (test.type === 'testA') { +>test.type : Symbol(type, Decl(discriminantPropertyCheck.ts, 208, 14), Decl(discriminantPropertyCheck.ts, 213, 14)) +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) +>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 208, 14), Decl(discriminantPropertyCheck.ts, 213, 14)) + + console.log(test.bananas); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>test.bananas : Symbol(bananas, Decl(discriminantPropertyCheck.ts, 209, 18)) +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) +>bananas : Symbol(bananas, Decl(discriminantPropertyCheck.ts, 209, 18)) + } + switch (test.type) { +>test.type : Symbol(type, Decl(discriminantPropertyCheck.ts, 208, 14), Decl(discriminantPropertyCheck.ts, 213, 14)) +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) +>type : Symbol(type, Decl(discriminantPropertyCheck.ts, 208, 14), Decl(discriminantPropertyCheck.ts, 213, 14)) + + case 'testA': { + console.log(test.bananas); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>test.bananas : Symbol(bananas, Decl(discriminantPropertyCheck.ts, 209, 18)) +>test : Symbol(test, Decl(discriminantPropertyCheck.ts, 224, 11)) +>bananas : Symbol(bananas, Decl(discriminantPropertyCheck.ts, 209, 18)) + } + } + }); +}; + diff --git a/tests/baselines/reference/discriminantPropertyCheck.types b/tests/baselines/reference/discriminantPropertyCheck.types index 1e46a7dbe9dd2..da884470e6f14 100644 --- a/tests/baselines/reference/discriminantPropertyCheck.types +++ b/tests/baselines/reference/discriminantPropertyCheck.types @@ -501,3 +501,161 @@ function func3(value: Partial) { } } +// Repro from #30557 + +interface TypeA { + Name: "TypeA"; +>Name : "TypeA" + + Value1: "Cool stuff!"; +>Value1 : "Cool stuff!" +} + +interface TypeB { + Name: "TypeB"; +>Name : "TypeB" + + Value2: 0; +>Value2 : 0 +} + +type Type = TypeA | TypeB; +>Type : Type + +declare function isType(x: unknown): x is Type; +>isType : (x: unknown) => x is Type +>x : unknown + +function WorksProperly(data: Type) { +>WorksProperly : (data: Type) => void +>data : Type + + if (data.Name === "TypeA") { +>data.Name === "TypeA" : boolean +>data.Name : "TypeA" | "TypeB" +>data : Type +>Name : "TypeA" | "TypeB" +>"TypeA" : "TypeA" + + const value1 = data.Value1; +>value1 : "Cool stuff!" +>data.Value1 : "Cool stuff!" +>data : TypeA +>Value1 : "Cool stuff!" + } +} + +function DoesNotWork(data: unknown) { +>DoesNotWork : (data: unknown) => void +>data : unknown + + if (isType(data)) { +>isType(data) : boolean +>isType : (x: unknown) => x is Type +>data : unknown + + if (data.Name === "TypeA") { +>data.Name === "TypeA" : boolean +>data.Name : "TypeA" | "TypeB" +>data : Type +>Name : "TypeA" | "TypeB" +>"TypeA" : "TypeA" + + const value1 = data.Value1; +>value1 : "Cool stuff!" +>data.Value1 : "Cool stuff!" +>data : TypeA +>Value1 : "Cool stuff!" + } + } +} + +// Repro from #36777 + +type TestA = { +>TestA : TestA + + type: 'testA'; +>type : "testA" + + bananas: 3; +>bananas : 3 +} + +type TestB = { +>TestB : TestB + + type: 'testB'; +>type : "testB" + + apples: 5; +>apples : 5 +} + +type AllTests = TestA | TestB; +>AllTests : AllTests + +type MapOfAllTests = Record; +>MapOfAllTests : Record + +const doTestingStuff = (mapOfTests: MapOfAllTests, ids: string[]) => { +>doTestingStuff : (mapOfTests: MapOfAllTests, ids: string[]) => void +>(mapOfTests: MapOfAllTests, ids: string[]) => { ids.forEach(id => { let test; test = mapOfTests[id]; if (test.type === 'testA') { console.log(test.bananas); } switch (test.type) { case 'testA': { console.log(test.bananas); } } });} : (mapOfTests: MapOfAllTests, ids: string[]) => void +>mapOfTests : Record +>ids : string[] + + ids.forEach(id => { +>ids.forEach(id => { let test; test = mapOfTests[id]; if (test.type === 'testA') { console.log(test.bananas); } switch (test.type) { case 'testA': { console.log(test.bananas); } } }) : void +>ids.forEach : (callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void +>ids : string[] +>forEach : (callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void +>id => { let test; test = mapOfTests[id]; if (test.type === 'testA') { console.log(test.bananas); } switch (test.type) { case 'testA': { console.log(test.bananas); } } } : (id: string) => void +>id : string + + let test; +>test : any + + test = mapOfTests[id]; +>test = mapOfTests[id] : AllTests +>test : any +>mapOfTests[id] : AllTests +>mapOfTests : Record +>id : string + + if (test.type === 'testA') { +>test.type === 'testA' : boolean +>test.type : "testA" | "testB" +>test : AllTests +>type : "testA" | "testB" +>'testA' : "testA" + + console.log(test.bananas); +>console.log(test.bananas) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>test.bananas : 3 +>test : TestA +>bananas : 3 + } + switch (test.type) { +>test.type : "testA" | "testB" +>test : AllTests +>type : "testA" | "testB" + + case 'testA': { +>'testA' : "testA" + + console.log(test.bananas); +>console.log(test.bananas) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>test.bananas : 3 +>test : TestA +>bananas : 3 + } + } + }); +}; + diff --git a/tests/cases/compiler/discriminantPropertyCheck.ts b/tests/cases/compiler/discriminantPropertyCheck.ts index 6a15af5db65df..478bc5f3c296a 100644 --- a/tests/cases/compiler/discriminantPropertyCheck.ts +++ b/tests/cases/compiler/discriminantPropertyCheck.ts @@ -1,4 +1,4 @@ -// @strictNullChecks: true +// @strict: true type Item = Item1 | Item2; @@ -175,3 +175,64 @@ function func3(value: Partial) { } } } + +// Repro from #30557 + +interface TypeA { + Name: "TypeA"; + Value1: "Cool stuff!"; +} + +interface TypeB { + Name: "TypeB"; + Value2: 0; +} + +type Type = TypeA | TypeB; + +declare function isType(x: unknown): x is Type; + +function WorksProperly(data: Type) { + if (data.Name === "TypeA") { + const value1 = data.Value1; + } +} + +function DoesNotWork(data: unknown) { + if (isType(data)) { + if (data.Name === "TypeA") { + const value1 = data.Value1; + } + } +} + +// Repro from #36777 + +type TestA = { + type: 'testA'; + bananas: 3; +} + +type TestB = { + type: 'testB'; + apples: 5; +} + +type AllTests = TestA | TestB; + +type MapOfAllTests = Record; + +const doTestingStuff = (mapOfTests: MapOfAllTests, ids: string[]) => { + ids.forEach(id => { + let test; + test = mapOfTests[id]; + if (test.type === 'testA') { + console.log(test.bananas); + } + switch (test.type) { + case 'testA': { + console.log(test.bananas); + } + } + }); +}; From c33d6044fad55fc11c02c790df533f90535f3d0e Mon Sep 17 00:00:00 2001 From: csigs Date: Wed, 6 May 2020 04:10:41 +0000 Subject: [PATCH 12/28] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 0940490251891..d7ca345d0e27e 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -4710,6 +4710,15 @@ + + + + + + + + + @@ -5160,6 +5169,15 @@ + + + + + + + + + @@ -8730,6 +8748,15 @@ + + + ']]> + + ]]> + + + + @@ -10296,11 +10323,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - .]]> + . Zamýšleli jste napsat Promise<{0}>?]]> From 8746d1708fe6ab2dcad1337422def3596231a5c7 Mon Sep 17 00:00:00 2001 From: Andrei Arkhipov Date: Wed, 6 May 2020 21:38:49 +0300 Subject: [PATCH 13/28] Updating dependencies (#37788) * Bump fs-extra from 6.0.1 to 9.0.0 Bumps [fs-extra](https://github.com/jprichardson/node-fs-extra) from 6.0.1 to 9.0.0. - [Release notes](https://github.com/jprichardson/node-fs-extra/releases) - [Changelog](https://github.com/jprichardson/node-fs-extra/blob/master/CHANGELOG.md) - [Commits](https://github.com/jprichardson/node-fs-extra/compare/6.0.1...9.0.0) Signed-off-by: dependabot-preview[bot] * Bump azure-devops-node-api from 8.1.1 to 10.1.0 Bumps [azure-devops-node-api](https://github.com/Microsoft/azure-devops-node-api) from 8.1.1 to 10.1.0. - [Release notes](https://github.com/Microsoft/azure-devops-node-api/releases) - [Commits](https://github.com/Microsoft/azure-devops-node-api/commits) Signed-off-by: dependabot-preview[bot] * Bump eslint-plugin-jsdoc from 21.0.0 to 22.1.0 Bumps [eslint-plugin-jsdoc](https://github.com/gajus/eslint-plugin-jsdoc) from 21.0.0 to 22.1.0. - [Release notes](https://github.com/gajus/eslint-plugin-jsdoc/releases) - [Commits](https://github.com/gajus/eslint-plugin-jsdoc/compare/v21.0.0...v22.1.0) Signed-off-by: dependabot-preview[bot] * Bump @typescript-eslint/eslint-plugin from 2.18.0 to 2.26.0 Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 2.18.0 to 2.26.0. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v2.26.0/packages/eslint-plugin) Signed-off-by: dependabot-preview[bot] * Bump eslint-plugin-import from 2.20.0 to 2.20.2 Bumps [eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import) from 2.20.0 to 2.20.2. - [Release notes](https://github.com/benmosher/eslint-plugin-import/releases) - [Changelog](https://github.com/benmosher/eslint-plugin-import/blob/master/CHANGELOG.md) - [Commits](https://github.com/benmosher/eslint-plugin-import/compare/v2.20.0...v2.20.2) Signed-off-by: dependabot-preview[bot] * Bump eslint-formatter-autolinkable-stylish from 1.1.1 to 1.1.2 Bumps [eslint-formatter-autolinkable-stylish](https://github.com/a-tarasyuk/eslint-formatter-autolinkable-stylish) from 1.1.1 to 1.1.2. - [Release notes](https://github.com/a-tarasyuk/eslint-formatter-autolinkable-stylish/releases) - [Commits](https://github.com/a-tarasyuk/eslint-formatter-autolinkable-stylish/compare/v1.1.1...v1.1.2) Signed-off-by: dependabot-preview[bot] * Bump @typescript-eslint/parser from 2.18.0 to 2.27.0 Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 2.18.0 to 2.27.0. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/parser/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v2.27.0/packages/parser) Signed-off-by: dependabot-preview[bot] * Bump @typescript-eslint/eslint-plugin from 2.26.0 to 2.27.0 Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 2.26.0 to 2.27.0. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v2.27.0/packages/eslint-plugin) Signed-off-by: dependabot-preview[bot] * Bump @typescript-eslint/experimental-utils from 2.18.0 to 2.27.0 Bumps [@typescript-eslint/experimental-utils](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/experimental-utils) from 2.18.0 to 2.27.0. - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/experimental-utils/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v2.27.0/packages/experimental-utils) Signed-off-by: dependabot-preview[bot] Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> --- package.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 6fa73b0e28c6f..7fc410ad60c40 100644 --- a/package.json +++ b/package.json @@ -54,11 +54,11 @@ "@types/through2": "latest", "@types/travis-fold": "latest", "@types/xml2js": "^0.4.0", - "@typescript-eslint/eslint-plugin": "2.18.0", - "@typescript-eslint/experimental-utils": "2.18.0", - "@typescript-eslint/parser": "2.18.0", + "@typescript-eslint/eslint-plugin": "2.27.0", + "@typescript-eslint/experimental-utils": "2.27.0", + "@typescript-eslint/parser": "2.27.0", "async": "latest", - "azure-devops-node-api": "^8.0.0", + "azure-devops-node-api": "^10.1.0", "browser-resolve": "^1.11.2", "browserify": "latest", "chai": "latest", @@ -66,12 +66,12 @@ "convert-source-map": "latest", "del": "5.1.0", "eslint": "6.8.0", - "eslint-formatter-autolinkable-stylish": "1.1.1", - "eslint-plugin-import": "2.20.0", - "eslint-plugin-jsdoc": "21.0.0", + "eslint-formatter-autolinkable-stylish": "1.1.2", + "eslint-plugin-import": "2.20.2", + "eslint-plugin-jsdoc": "22.1.0", "eslint-plugin-no-null": "1.0.2", "fancy-log": "latest", - "fs-extra": "^6.0.1", + "fs-extra": "^9.0.0", "glob": "latest", "gulp": "^4.0.0", "gulp-concat": "latest", From ec93a7cf7bf1b6b0d25b9a71b287f3a15042e140 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Wed, 6 May 2020 21:41:50 +0300 Subject: [PATCH 14/28] fix(36055): forbid union type with invalid types in the 'in' operator (#37786) --- src/compiler/checker.ts | 3 +- .../inOperatorWithInvalidOperands.errors.txt | 48 +++--- .../inOperatorWithInvalidOperands.js | 17 +- .../inOperatorWithInvalidOperands.symbols | 152 ++++++++++-------- .../inOperatorWithInvalidOperands.types | 24 ++- .../reference/inOperatorWithValidOperands.js | 8 + .../inOperatorWithValidOperands.symbols | 106 ++++++------ .../inOperatorWithValidOperands.types | 18 +++ .../inOperatorWithInvalidOperands.ts | 8 +- .../inOperator/inOperatorWithValidOperands.ts | 4 + 10 files changed, 251 insertions(+), 137 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d302e867aeaac..474100799b9a2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28034,7 +28034,8 @@ namespace ts { // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, TypeFlags.NumberLike | TypeFlags.ESSymbolLike))) { + if (!(allTypesAssignableToKind(leftType, TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.ESSymbolLike) || + isTypeAssignableToKind(leftType, TypeFlags.Index | TypeFlags.TypeParameter))) { error(left, Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, TypeFlags.NonPrimitive | TypeFlags.InstantiableNonPrimitive)) { diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt b/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt index ff411f60c475d..7827dc44b7647 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.errors.txt @@ -1,25 +1,28 @@ -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(12,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(13,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(14,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(16,11): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(17,11): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(19,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(20,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(30,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(31,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(32,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(33,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(34,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(15,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(16,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(17,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(19,11): error TS2531: Object is possibly 'null'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(20,11): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(22,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(23,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(24,12): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(25,12): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(35,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(36,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(37,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(38,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(39,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(43,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. -tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(43,17): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(38,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(39,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(40,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(41,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(42,16): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(43,16): error TS2531: Object is possibly 'null'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(44,17): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(47,11): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts(47,17): error TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter. -==== tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts (19 errors) ==== +==== tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts (21 errors) ==== + class Foo {} enum E { a } var x: any; @@ -29,7 +32,9 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInv var a1: boolean; var a2: void; var a3: {}; - var a4: E + var a4: E; + var a5: Foo | string; + var a6: Foo; var ra1 = a1 in x; ~~ @@ -54,6 +59,12 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInv var ra9 = {} in x; ~~ !!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. + var ra10 = a5 in x; + ~~ +!!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. + var ra11 = a6 in x; + ~~ +!!! error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type @@ -94,7 +105,6 @@ tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInv ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. - // both operands are invalid var rc1 = {} in ''; ~~ diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.js b/tests/baselines/reference/inOperatorWithInvalidOperands.js index 005681b62857b..beab89965c572 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.js +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.js @@ -1,4 +1,5 @@ //// [inOperatorWithInvalidOperands.ts] +class Foo {} enum E { a } var x: any; @@ -8,7 +9,9 @@ var x: any; var a1: boolean; var a2: void; var a3: {}; -var a4: E +var a4: E; +var a5: Foo | string; +var a6: Foo; var ra1 = a1 in x; var ra2 = a2 in x; @@ -19,6 +22,8 @@ var ra6 = undefined in x; var ra7 = E.a in x; var ra8 = false in x; var ra9 = {} in x; +var ra10 = a5 in x; +var ra11 = a6 in x; // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type @@ -39,11 +44,15 @@ var rb8 = x in ''; var rb9 = x in null; var rb10 = x in undefined; - // both operands are invalid var rc1 = {} in ''; //// [inOperatorWithInvalidOperands.js] +var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; +}()); var E; (function (E) { E[E["a"] = 0] = "a"; @@ -55,6 +64,8 @@ var a1; var a2; var a3; var a4; +var a5; +var a6; var ra1 = a1 in x; var ra2 = a2 in x; var ra3 = a3 in x; @@ -64,6 +75,8 @@ var ra6 = undefined in x; var ra7 = E.a in x; var ra8 = false in x; var ra9 = {} in x; +var ra10 = a5 in x; +var ra11 = a6 in x; // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1; diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.symbols b/tests/baselines/reference/inOperatorWithInvalidOperands.symbols index 62f4633ecbd61..904509feff148 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.symbols +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.symbols @@ -1,135 +1,155 @@ === tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts === +class Foo {} +>Foo : Symbol(Foo, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) + enum E { a } ->E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) ->a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 0, 8)) +>E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 12)) +>a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 1, 8)) var x: any; ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) // invalid left operands // the left operand is required to be of type Any, the String primitive type, or the Number primitive type var a1: boolean; ->a1 : Symbol(a1, Decl(inOperatorWithInvalidOperands.ts, 6, 3)) +>a1 : Symbol(a1, Decl(inOperatorWithInvalidOperands.ts, 7, 3)) var a2: void; ->a2 : Symbol(a2, Decl(inOperatorWithInvalidOperands.ts, 7, 3)) +>a2 : Symbol(a2, Decl(inOperatorWithInvalidOperands.ts, 8, 3)) var a3: {}; ->a3 : Symbol(a3, Decl(inOperatorWithInvalidOperands.ts, 8, 3)) +>a3 : Symbol(a3, Decl(inOperatorWithInvalidOperands.ts, 9, 3)) + +var a4: E; +>a4 : Symbol(a4, Decl(inOperatorWithInvalidOperands.ts, 10, 3)) +>E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 12)) + +var a5: Foo | string; +>a5 : Symbol(a5, Decl(inOperatorWithInvalidOperands.ts, 11, 3)) +>Foo : Symbol(Foo, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) -var a4: E ->a4 : Symbol(a4, Decl(inOperatorWithInvalidOperands.ts, 9, 3)) ->E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) +var a6: Foo; +>a6 : Symbol(a6, Decl(inOperatorWithInvalidOperands.ts, 12, 3)) +>Foo : Symbol(Foo, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) var ra1 = a1 in x; ->ra1 : Symbol(ra1, Decl(inOperatorWithInvalidOperands.ts, 11, 3)) ->a1 : Symbol(a1, Decl(inOperatorWithInvalidOperands.ts, 6, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra1 : Symbol(ra1, Decl(inOperatorWithInvalidOperands.ts, 14, 3)) +>a1 : Symbol(a1, Decl(inOperatorWithInvalidOperands.ts, 7, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra2 = a2 in x; ->ra2 : Symbol(ra2, Decl(inOperatorWithInvalidOperands.ts, 12, 3)) ->a2 : Symbol(a2, Decl(inOperatorWithInvalidOperands.ts, 7, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra2 : Symbol(ra2, Decl(inOperatorWithInvalidOperands.ts, 15, 3)) +>a2 : Symbol(a2, Decl(inOperatorWithInvalidOperands.ts, 8, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra3 = a3 in x; ->ra3 : Symbol(ra3, Decl(inOperatorWithInvalidOperands.ts, 13, 3)) ->a3 : Symbol(a3, Decl(inOperatorWithInvalidOperands.ts, 8, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra3 : Symbol(ra3, Decl(inOperatorWithInvalidOperands.ts, 16, 3)) +>a3 : Symbol(a3, Decl(inOperatorWithInvalidOperands.ts, 9, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra4 = a4 in x; ->ra4 : Symbol(ra4, Decl(inOperatorWithInvalidOperands.ts, 14, 3)) ->a4 : Symbol(a4, Decl(inOperatorWithInvalidOperands.ts, 9, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra4 : Symbol(ra4, Decl(inOperatorWithInvalidOperands.ts, 17, 3)) +>a4 : Symbol(a4, Decl(inOperatorWithInvalidOperands.ts, 10, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra5 = null in x; ->ra5 : Symbol(ra5, Decl(inOperatorWithInvalidOperands.ts, 15, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra5 : Symbol(ra5, Decl(inOperatorWithInvalidOperands.ts, 18, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra6 = undefined in x; ->ra6 : Symbol(ra6, Decl(inOperatorWithInvalidOperands.ts, 16, 3)) +>ra6 : Symbol(ra6, Decl(inOperatorWithInvalidOperands.ts, 19, 3)) >undefined : Symbol(undefined) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra7 = E.a in x; ->ra7 : Symbol(ra7, Decl(inOperatorWithInvalidOperands.ts, 17, 3)) ->E.a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 0, 8)) ->E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 0)) ->a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 0, 8)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra7 : Symbol(ra7, Decl(inOperatorWithInvalidOperands.ts, 20, 3)) +>E.a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 1, 8)) +>E : Symbol(E, Decl(inOperatorWithInvalidOperands.ts, 0, 12)) +>a : Symbol(E.a, Decl(inOperatorWithInvalidOperands.ts, 1, 8)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra8 = false in x; ->ra8 : Symbol(ra8, Decl(inOperatorWithInvalidOperands.ts, 18, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra8 : Symbol(ra8, Decl(inOperatorWithInvalidOperands.ts, 21, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var ra9 = {} in x; ->ra9 : Symbol(ra9, Decl(inOperatorWithInvalidOperands.ts, 19, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>ra9 : Symbol(ra9, Decl(inOperatorWithInvalidOperands.ts, 22, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) + +var ra10 = a5 in x; +>ra10 : Symbol(ra10, Decl(inOperatorWithInvalidOperands.ts, 23, 3)) +>a5 : Symbol(a5, Decl(inOperatorWithInvalidOperands.ts, 11, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) + +var ra11 = a6 in x; +>ra11 : Symbol(ra11, Decl(inOperatorWithInvalidOperands.ts, 24, 3)) +>a6 : Symbol(a6, Decl(inOperatorWithInvalidOperands.ts, 12, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1: number; ->b1 : Symbol(b1, Decl(inOperatorWithInvalidOperands.ts, 23, 3)) +>b1 : Symbol(b1, Decl(inOperatorWithInvalidOperands.ts, 28, 3)) var b2: boolean; ->b2 : Symbol(b2, Decl(inOperatorWithInvalidOperands.ts, 24, 3)) +>b2 : Symbol(b2, Decl(inOperatorWithInvalidOperands.ts, 29, 3)) var b3: string; ->b3 : Symbol(b3, Decl(inOperatorWithInvalidOperands.ts, 25, 3)) +>b3 : Symbol(b3, Decl(inOperatorWithInvalidOperands.ts, 30, 3)) var b4: void; ->b4 : Symbol(b4, Decl(inOperatorWithInvalidOperands.ts, 26, 3)) +>b4 : Symbol(b4, Decl(inOperatorWithInvalidOperands.ts, 31, 3)) var b5: string | number; ->b5 : Symbol(b5, Decl(inOperatorWithInvalidOperands.ts, 27, 3)) +>b5 : Symbol(b5, Decl(inOperatorWithInvalidOperands.ts, 32, 3)) var rb1 = x in b1; ->rb1 : Symbol(rb1, Decl(inOperatorWithInvalidOperands.ts, 29, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) ->b1 : Symbol(b1, Decl(inOperatorWithInvalidOperands.ts, 23, 3)) +>rb1 : Symbol(rb1, Decl(inOperatorWithInvalidOperands.ts, 34, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) +>b1 : Symbol(b1, Decl(inOperatorWithInvalidOperands.ts, 28, 3)) var rb2 = x in b2; ->rb2 : Symbol(rb2, Decl(inOperatorWithInvalidOperands.ts, 30, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) ->b2 : Symbol(b2, Decl(inOperatorWithInvalidOperands.ts, 24, 3)) +>rb2 : Symbol(rb2, Decl(inOperatorWithInvalidOperands.ts, 35, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) +>b2 : Symbol(b2, Decl(inOperatorWithInvalidOperands.ts, 29, 3)) var rb3 = x in b3; ->rb3 : Symbol(rb3, Decl(inOperatorWithInvalidOperands.ts, 31, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) ->b3 : Symbol(b3, Decl(inOperatorWithInvalidOperands.ts, 25, 3)) +>rb3 : Symbol(rb3, Decl(inOperatorWithInvalidOperands.ts, 36, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) +>b3 : Symbol(b3, Decl(inOperatorWithInvalidOperands.ts, 30, 3)) var rb4 = x in b4; ->rb4 : Symbol(rb4, Decl(inOperatorWithInvalidOperands.ts, 32, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) ->b4 : Symbol(b4, Decl(inOperatorWithInvalidOperands.ts, 26, 3)) +>rb4 : Symbol(rb4, Decl(inOperatorWithInvalidOperands.ts, 37, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) +>b4 : Symbol(b4, Decl(inOperatorWithInvalidOperands.ts, 31, 3)) var rb5 = x in b5; ->rb5 : Symbol(rb5, Decl(inOperatorWithInvalidOperands.ts, 33, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) ->b5 : Symbol(b5, Decl(inOperatorWithInvalidOperands.ts, 27, 3)) +>rb5 : Symbol(rb5, Decl(inOperatorWithInvalidOperands.ts, 38, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) +>b5 : Symbol(b5, Decl(inOperatorWithInvalidOperands.ts, 32, 3)) var rb6 = x in 0; ->rb6 : Symbol(rb6, Decl(inOperatorWithInvalidOperands.ts, 34, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>rb6 : Symbol(rb6, Decl(inOperatorWithInvalidOperands.ts, 39, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var rb7 = x in false; ->rb7 : Symbol(rb7, Decl(inOperatorWithInvalidOperands.ts, 35, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>rb7 : Symbol(rb7, Decl(inOperatorWithInvalidOperands.ts, 40, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var rb8 = x in ''; ->rb8 : Symbol(rb8, Decl(inOperatorWithInvalidOperands.ts, 36, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>rb8 : Symbol(rb8, Decl(inOperatorWithInvalidOperands.ts, 41, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var rb9 = x in null; ->rb9 : Symbol(rb9, Decl(inOperatorWithInvalidOperands.ts, 37, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>rb9 : Symbol(rb9, Decl(inOperatorWithInvalidOperands.ts, 42, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) var rb10 = x in undefined; ->rb10 : Symbol(rb10, Decl(inOperatorWithInvalidOperands.ts, 38, 3)) ->x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 2, 3)) +>rb10 : Symbol(rb10, Decl(inOperatorWithInvalidOperands.ts, 43, 3)) +>x : Symbol(x, Decl(inOperatorWithInvalidOperands.ts, 3, 3)) >undefined : Symbol(undefined) - // both operands are invalid var rc1 = {} in ''; ->rc1 : Symbol(rc1, Decl(inOperatorWithInvalidOperands.ts, 42, 3)) +>rc1 : Symbol(rc1, Decl(inOperatorWithInvalidOperands.ts, 46, 3)) diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.types b/tests/baselines/reference/inOperatorWithInvalidOperands.types index d85ec6d7a3db9..aa6567cee8898 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.types +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.types @@ -1,4 +1,7 @@ === tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts === +class Foo {} +>Foo : Foo + enum E { a } >E : E >a : E.a @@ -17,9 +20,15 @@ var a2: void; var a3: {}; >a3 : {} -var a4: E +var a4: E; >a4 : E +var a5: Foo | string; +>a5 : string | Foo + +var a6: Foo; +>a6 : Foo + var ra1 = a1 in x; >ra1 : boolean >a1 in x : boolean @@ -76,6 +85,18 @@ var ra9 = {} in x; >{} : {} >x : any +var ra10 = a5 in x; +>ra10 : boolean +>a5 in x : boolean +>a5 : string | Foo +>x : any + +var ra11 = a6 in x; +>ra11 : boolean +>a6 in x : boolean +>a6 : Foo +>x : any + // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1: number; @@ -153,7 +174,6 @@ var rb10 = x in undefined; >x : any >undefined : undefined - // both operands are invalid var rc1 = {} in ''; >rc1 : boolean diff --git a/tests/baselines/reference/inOperatorWithValidOperands.js b/tests/baselines/reference/inOperatorWithValidOperands.js index f01380b35dd58..ad2f29109e229 100644 --- a/tests/baselines/reference/inOperatorWithValidOperands.js +++ b/tests/baselines/reference/inOperatorWithValidOperands.js @@ -5,12 +5,16 @@ var x: any; // the left operand is required to be of type Any, the String primitive type, or the Number primitive type var a1: string; var a2: number; +var a3: string | number | symbol; +var a4: any; var ra1 = x in x; var ra2 = a1 in x; var ra3 = a2 in x; var ra4 = '' in x; var ra5 = 0 in x; +var ra6 = a3 in x; +var ra7 = a4 in x; // valid right operands // the right operand is required to be of type Any, an object type, or a type parameter type @@ -48,11 +52,15 @@ var x; // the left operand is required to be of type Any, the String primitive type, or the Number primitive type var a1; var a2; +var a3; +var a4; var ra1 = x in x; var ra2 = a1 in x; var ra3 = a2 in x; var ra4 = '' in x; var ra5 = 0 in x; +var ra6 = a3 in x; +var ra7 = a4 in x; // valid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1; diff --git a/tests/baselines/reference/inOperatorWithValidOperands.symbols b/tests/baselines/reference/inOperatorWithValidOperands.symbols index cbe0dbeef4a37..c9156a4170dd5 100644 --- a/tests/baselines/reference/inOperatorWithValidOperands.symbols +++ b/tests/baselines/reference/inOperatorWithValidOperands.symbols @@ -10,110 +10,126 @@ var a1: string; var a2: number; >a2 : Symbol(a2, Decl(inOperatorWithValidOperands.ts, 5, 3)) +var a3: string | number | symbol; +>a3 : Symbol(a3, Decl(inOperatorWithValidOperands.ts, 6, 3)) + +var a4: any; +>a4 : Symbol(a4, Decl(inOperatorWithValidOperands.ts, 7, 3)) + var ra1 = x in x; ->ra1 : Symbol(ra1, Decl(inOperatorWithValidOperands.ts, 7, 3)) +>ra1 : Symbol(ra1, Decl(inOperatorWithValidOperands.ts, 9, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) var ra2 = a1 in x; ->ra2 : Symbol(ra2, Decl(inOperatorWithValidOperands.ts, 8, 3)) +>ra2 : Symbol(ra2, Decl(inOperatorWithValidOperands.ts, 10, 3)) >a1 : Symbol(a1, Decl(inOperatorWithValidOperands.ts, 4, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) var ra3 = a2 in x; ->ra3 : Symbol(ra3, Decl(inOperatorWithValidOperands.ts, 9, 3)) +>ra3 : Symbol(ra3, Decl(inOperatorWithValidOperands.ts, 11, 3)) >a2 : Symbol(a2, Decl(inOperatorWithValidOperands.ts, 5, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) var ra4 = '' in x; ->ra4 : Symbol(ra4, Decl(inOperatorWithValidOperands.ts, 10, 3)) +>ra4 : Symbol(ra4, Decl(inOperatorWithValidOperands.ts, 12, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) var ra5 = 0 in x; ->ra5 : Symbol(ra5, Decl(inOperatorWithValidOperands.ts, 11, 3)) +>ra5 : Symbol(ra5, Decl(inOperatorWithValidOperands.ts, 13, 3)) +>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) + +var ra6 = a3 in x; +>ra6 : Symbol(ra6, Decl(inOperatorWithValidOperands.ts, 14, 3)) +>a3 : Symbol(a3, Decl(inOperatorWithValidOperands.ts, 6, 3)) +>x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) + +var ra7 = a4 in x; +>ra7 : Symbol(ra7, Decl(inOperatorWithValidOperands.ts, 15, 3)) +>a4 : Symbol(a4, Decl(inOperatorWithValidOperands.ts, 7, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) // valid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1: {}; ->b1 : Symbol(b1, Decl(inOperatorWithValidOperands.ts, 15, 3)) +>b1 : Symbol(b1, Decl(inOperatorWithValidOperands.ts, 19, 3)) var rb1 = x in b1; ->rb1 : Symbol(rb1, Decl(inOperatorWithValidOperands.ts, 17, 3)) +>rb1 : Symbol(rb1, Decl(inOperatorWithValidOperands.ts, 21, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->b1 : Symbol(b1, Decl(inOperatorWithValidOperands.ts, 15, 3)) +>b1 : Symbol(b1, Decl(inOperatorWithValidOperands.ts, 19, 3)) var rb2 = x in {}; ->rb2 : Symbol(rb2, Decl(inOperatorWithValidOperands.ts, 18, 3)) +>rb2 : Symbol(rb2, Decl(inOperatorWithValidOperands.ts, 22, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) function foo(t: T) { ->foo : Symbol(foo, Decl(inOperatorWithValidOperands.ts, 18, 18)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 20, 13)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 20, 16)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 20, 13)) +>foo : Symbol(foo, Decl(inOperatorWithValidOperands.ts, 22, 18)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 13)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 16)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 13)) var rb3 = x in t; ->rb3 : Symbol(rb3, Decl(inOperatorWithValidOperands.ts, 21, 7)) +>rb3 : Symbol(rb3, Decl(inOperatorWithValidOperands.ts, 25, 7)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 20, 16)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 16)) } function unionCase(t: T | U) { ->unionCase : Symbol(unionCase, Decl(inOperatorWithValidOperands.ts, 22, 1)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 19)) ->U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 24, 21)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 25)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 24, 19)) ->U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 24, 21)) +>unionCase : Symbol(unionCase, Decl(inOperatorWithValidOperands.ts, 26, 1)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 19)) +>U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 28, 21)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 25)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 19)) +>U : Symbol(U, Decl(inOperatorWithValidOperands.ts, 28, 21)) var rb4 = x in t; ->rb4 : Symbol(rb4, Decl(inOperatorWithValidOperands.ts, 25, 7)) +>rb4 : Symbol(rb4, Decl(inOperatorWithValidOperands.ts, 29, 7)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 24, 25)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 25)) } function unionCase2(t: T | object) { ->unionCase2 : Symbol(unionCase2, Decl(inOperatorWithValidOperands.ts, 26, 1)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 20)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 23)) ->T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 28, 20)) +>unionCase2 : Symbol(unionCase2, Decl(inOperatorWithValidOperands.ts, 30, 1)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 32, 20)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 32, 23)) +>T : Symbol(T, Decl(inOperatorWithValidOperands.ts, 32, 20)) var rb5 = x in t; ->rb5 : Symbol(rb5, Decl(inOperatorWithValidOperands.ts, 29, 7)) +>rb5 : Symbol(rb5, Decl(inOperatorWithValidOperands.ts, 33, 7)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 28, 23)) +>t : Symbol(t, Decl(inOperatorWithValidOperands.ts, 32, 23)) } interface X { x: number } ->X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1)) ->x : Symbol(X.x, Decl(inOperatorWithValidOperands.ts, 32, 13)) +>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 34, 1)) +>x : Symbol(X.x, Decl(inOperatorWithValidOperands.ts, 36, 13)) interface Y { y: number } ->Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25)) ->y : Symbol(Y.y, Decl(inOperatorWithValidOperands.ts, 33, 13)) +>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 36, 25)) +>y : Symbol(Y.y, Decl(inOperatorWithValidOperands.ts, 37, 13)) var c1: X | Y; ->c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 35, 3)) ->X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1)) ->Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25)) +>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 39, 3)) +>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 34, 1)) +>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 36, 25)) var c2: X; ->c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 36, 3)) ->X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 30, 1)) +>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 40, 3)) +>X : Symbol(X, Decl(inOperatorWithValidOperands.ts, 34, 1)) var c3: Y; ->c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 37, 3)) ->Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 32, 25)) +>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 41, 3)) +>Y : Symbol(Y, Decl(inOperatorWithValidOperands.ts, 36, 25)) var rc1 = x in c1; ->rc1 : Symbol(rc1, Decl(inOperatorWithValidOperands.ts, 39, 3)) +>rc1 : Symbol(rc1, Decl(inOperatorWithValidOperands.ts, 43, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 35, 3)) +>c1 : Symbol(c1, Decl(inOperatorWithValidOperands.ts, 39, 3)) var rc2 = x in (c2 || c3); ->rc2 : Symbol(rc2, Decl(inOperatorWithValidOperands.ts, 40, 3)) +>rc2 : Symbol(rc2, Decl(inOperatorWithValidOperands.ts, 44, 3)) >x : Symbol(x, Decl(inOperatorWithValidOperands.ts, 0, 3)) ->c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 36, 3)) ->c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 37, 3)) +>c2 : Symbol(c2, Decl(inOperatorWithValidOperands.ts, 40, 3)) +>c3 : Symbol(c3, Decl(inOperatorWithValidOperands.ts, 41, 3)) diff --git a/tests/baselines/reference/inOperatorWithValidOperands.types b/tests/baselines/reference/inOperatorWithValidOperands.types index 20b4bfdf6fbde..ed99262f8b08c 100644 --- a/tests/baselines/reference/inOperatorWithValidOperands.types +++ b/tests/baselines/reference/inOperatorWithValidOperands.types @@ -10,6 +10,12 @@ var a1: string; var a2: number; >a2 : number +var a3: string | number | symbol; +>a3 : string | number | symbol + +var a4: any; +>a4 : any + var ra1 = x in x; >ra1 : boolean >x in x : boolean @@ -40,6 +46,18 @@ var ra5 = 0 in x; >0 : 0 >x : any +var ra6 = a3 in x; +>ra6 : boolean +>a3 in x : boolean +>a3 : string | number | symbol +>x : any + +var ra7 = a4 in x; +>ra7 : boolean +>a4 in x : boolean +>a4 : any +>x : any + // valid right operands // the right operand is required to be of type Any, an object type, or a type parameter type var b1: {}; diff --git a/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts b/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts index 0c6f140322014..3087a728f1008 100644 --- a/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts +++ b/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts @@ -1,3 +1,4 @@ +class Foo {} enum E { a } var x: any; @@ -7,7 +8,9 @@ var x: any; var a1: boolean; var a2: void; var a3: {}; -var a4: E +var a4: E; +var a5: Foo | string; +var a6: Foo; var ra1 = a1 in x; var ra2 = a2 in x; @@ -18,6 +21,8 @@ var ra6 = undefined in x; var ra7 = E.a in x; var ra8 = false in x; var ra9 = {} in x; +var ra10 = a5 in x; +var ra11 = a6 in x; // invalid right operands // the right operand is required to be of type Any, an object type, or a type parameter type @@ -38,6 +43,5 @@ var rb8 = x in ''; var rb9 = x in null; var rb10 = x in undefined; - // both operands are invalid var rc1 = {} in ''; \ No newline at end of file diff --git a/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithValidOperands.ts b/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithValidOperands.ts index 738edca2bc371..3ad3198276eba 100644 --- a/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithValidOperands.ts +++ b/tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithValidOperands.ts @@ -4,12 +4,16 @@ var x: any; // the left operand is required to be of type Any, the String primitive type, or the Number primitive type var a1: string; var a2: number; +var a3: string | number | symbol; +var a4: any; var ra1 = x in x; var ra2 = a1 in x; var ra3 = a2 in x; var ra4 = '' in x; var ra5 = 0 in x; +var ra6 = a3 in x; +var ra7 = a4 in x; // valid right operands // the right operand is required to be of type Any, an object type, or a type parameter type From 4b08c0582d1b672cffc8478602ba4de65ff06550 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 6 May 2020 12:04:28 -0700 Subject: [PATCH 15/28] Fix regression in name resolution in parameter (#38351) --- src/compiler/checker.ts | 4 +++- .../parameterInitializersBackwardReferencing.ts | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 tests/cases/conformance/functions/parameterInitializersBackwardReferencing.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 474100799b9a2..529c5c1884e56 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1889,7 +1889,9 @@ namespace ts { lastLocation === (location as BindingElement).name && isBindingPattern(lastLocation))) { const root = getRootDeclaration(location); if (root.kind === SyntaxKind.Parameter) { - associatedDeclarationForContainingInitializerOrBindingName = location as BindingElement; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location as BindingElement; + } } } break; diff --git a/tests/cases/conformance/functions/parameterInitializersBackwardReferencing.ts b/tests/cases/conformance/functions/parameterInitializersBackwardReferencing.ts new file mode 100644 index 0000000000000..dce4818a5094e --- /dev/null +++ b/tests/cases/conformance/functions/parameterInitializersBackwardReferencing.ts @@ -0,0 +1,13 @@ +// @target: es5, es2015, esnext +// @noEmit: true +// @noTypesAndSymbols: true + +// https://github.com/microsoft/TypeScript/issues/38243 + +function test0({ a = 0, b = a } = {}) { + return { a, b }; +} + +function test1({ c: { a = 0, b = a } = {} } = {}) { + return { a, b }; +} \ No newline at end of file From be2eb8a2e1d8734c79b5638c8dd3d587e47c3236 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Wed, 6 May 2020 16:09:29 -0400 Subject: [PATCH 16/28] Allowed comment directives to be multiline (#38228) * Allowed comment directives to be multiline * Added tests, and perhaps fixed a test runner bug? * I think it's going to need a consistent variable to loop over * Used dynamically computed indexes in verifies * Added multiline tests * Increased flexibility for multiline comment parsing * Undid a couple of formatting changes; removed backslashes from multiline regexp * Added baseline tests for multiline comment skipping Co-authored-by: Orta Therox --- src/compiler/scanner.ts | 54 +++- src/compiler/utilities.ts | 2 +- src/testRunner/unittests/incrementalParser.ts | 303 +++++++++--------- .../checkJsFiles_skipDiagnostics.errors.txt | 53 +++ .../checkJsFiles_skipDiagnostics.symbols | 14 + .../checkJsFiles_skipDiagnostics.types | 26 +- .../baselines/reference/multiline.errors.txt | 60 ++++ tests/baselines/reference/multiline.js | 86 +++++ tests/baselines/reference/multiline.symbols | 89 +++++ tests/baselines/reference/multiline.types | 113 +++++++ .../reference/ts-expect-error.errors.txt | 49 ++- tests/baselines/reference/ts-expect-error.js | 47 ++- .../reference/ts-expect-error.symbols | 67 ++-- .../baselines/reference/ts-expect-error.types | 44 ++- .../compiler/checkJsFiles_skipDiagnostics.ts | 12 + .../conformance/directives/multiline.tsx | 53 +++ .../conformance/directives/ts-expect-error.ts | 26 +- 17 files changed, 876 insertions(+), 222 deletions(-) create mode 100644 tests/baselines/reference/checkJsFiles_skipDiagnostics.errors.txt create mode 100644 tests/baselines/reference/multiline.errors.txt create mode 100644 tests/baselines/reference/multiline.js create mode 100644 tests/baselines/reference/multiline.symbols create mode 100644 tests/baselines/reference/multiline.types create mode 100644 tests/cases/conformance/directives/multiline.tsx diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index c841d5bdba44f..a4513e8cdf6df 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -270,9 +270,14 @@ namespace ts { const unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - const commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + const commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + const commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code: number, map: readonly number[]): boolean { // Bail out quickly if it couldn't possibly be in the map. @@ -1735,16 +1740,12 @@ namespace ts { pos++; } - const type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = append( - commentDirectives, - { - range: { pos: tokenPos, end: pos }, - type, - }, - ); - } + commentDirectives = appendIfCommentDirective( + commentDirectives, + text.slice(tokenPos, pos), + commentDirectiveRegExSingleLine, + tokenPos, + ); if (skipTrivia) { continue; @@ -1761,6 +1762,7 @@ namespace ts { } let commentClosed = false; + let lastLineStart = tokenPos; while (pos < end) { const ch = text.charCodeAt(pos); @@ -1770,12 +1772,16 @@ namespace ts { break; } + pos++; + if (isLineBreak(ch)) { + lastLineStart = pos; tokenFlags |= TokenFlags.PrecedingLineBreak; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); + if (!commentClosed) { error(Diagnostics.Asterisk_Slash_expected); } @@ -2118,7 +2124,27 @@ namespace ts { return token; } - function getDirectiveFromComment(text: string) { + function appendIfCommentDirective( + commentDirectives: CommentDirective[] | undefined, + text: string, + commentDirectiveRegEx: RegExp, + lineStart: number, + ) { + const type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + + return append( + commentDirectives, + { + range: { pos: lineStart, end: pos }, + type, + }, + ); + } + + function getDirectiveFromComment(text: string, commentDirectiveRegEx: RegExp) { const match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 9452910feece7..8ecac56c8f93a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -474,7 +474,7 @@ namespace ts { export function createCommentDirectivesMap(sourceFile: SourceFile, commentDirectives: CommentDirective[]): CommentDirectivesMap { const directivesByLine = createMapFromEntries( commentDirectives.map(commentDirective => ([ - `${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line}`, + `${getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line}`, commentDirective, ])) ); diff --git a/src/testRunner/unittests/incrementalParser.ts b/src/testRunner/unittests/incrementalParser.ts index cd06c60d096dd..07be24b4b5b4a 100644 --- a/src/testRunner/unittests/incrementalParser.ts +++ b/src/testRunner/unittests/incrementalParser.ts @@ -832,157 +832,162 @@ module m3 { }\ insertCode(source, index, "Fo"); }); - describe("comment directives", () => { - const tsIgnoreComment = "// @ts-ignore"; - const textWithIgnoreComment = `const x = 10; -function foo() { - // @ts-ignore - let y: string = x; - return y; -} -function bar() { - // @ts-ignore - let z : string = x; - return z; -} -function bar3() { - // @ts-ignore - let z : string = x; - return z; -} -foo(); -bar(); -bar3();`; - verifyScenario("when deleting ts-ignore comment", verifyDelete); - verifyScenario("when inserting ts-ignore comment", verifyInsert); - verifyScenario("when changing ts-ignore comment to blah", verifyChangeToBlah); - verifyScenario("when changing blah comment to ts-ignore", verifyChangeBackToDirective); - verifyScenario("when deleting blah comment", verifyDeletingBlah); - verifyScenario("when changing text that adds another comment", verifyChangeDirectiveType); - verifyScenario("when changing text that keeps the comment but adds more nodes", verifyReuseChange); - - function verifyCommentDirectives(oldText: IScriptSnapshot, newTextAndChange: { text: IScriptSnapshot; textChangeRange: TextChangeRange; }) { - const { incrementalNewTree, newTree } = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1); - assert.deepEqual(incrementalNewTree.commentDirectives, newTree.commentDirectives); - } - - function verifyScenario(scenario: string, verifyChange: (atIndex: number, singleIgnore?: true) => void) { - it(`${scenario} - 0`, () => { - verifyChange(0); - }); - it(`${scenario} - 1`, () => { - verifyChange(1); - }); - it(`${scenario} - 2`, () => { - verifyChange(2); - }); - it(`${scenario} - with single ts-ignore`, () => { - verifyChange(0, /*singleIgnore*/ true); - }); - } - - function getIndexOfTsIgnoreComment(atIndex: number) { - let index: number; - for (let i = 0; i <= atIndex; i++) { - index = textWithIgnoreComment.indexOf(tsIgnoreComment); + for (const tsIgnoreComment of [ + "// @ts-ignore", + "/* @ts-ignore */", + "/*\n @ts-ignore */" + ]) { + describe(`${tsIgnoreComment} comment directives`, () => { + const textWithIgnoreComment = `const x = 10; + function foo() { + ${tsIgnoreComment} + let y: string = x; + return y; + } + function bar() { + ${tsIgnoreComment} + let z : string = x; + return z; + } + function bar3() { + ${tsIgnoreComment} + let z : string = x; + return z; + } + foo(); + bar(); + bar3();`; + verifyScenario("when deleting ts-ignore comment", verifyDelete); + verifyScenario("when inserting ts-ignore comment", verifyInsert); + verifyScenario("when changing ts-ignore comment to blah", verifyChangeToBlah); + verifyScenario("when changing blah comment to ts-ignore", verifyChangeBackToDirective); + verifyScenario("when deleting blah comment", verifyDeletingBlah); + verifyScenario("when changing text that adds another comment", verifyChangeDirectiveType); + verifyScenario("when changing text that keeps the comment but adds more nodes", verifyReuseChange); + + function verifyCommentDirectives(oldText: IScriptSnapshot, newTextAndChange: { text: IScriptSnapshot; textChangeRange: TextChangeRange; }) { + const { incrementalNewTree, newTree } = compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, -1); + assert.deepEqual(incrementalNewTree.commentDirectives, newTree.commentDirectives); + } + + function verifyScenario(scenario: string, verifyChange: (atIndex: number, singleIgnore?: true) => void) { + it(`${scenario} - 0`, () => { + verifyChange(0); + }); + it(`${scenario} - 1`, () => { + verifyChange(1); + }); + it(`${scenario} - 2`, () => { + verifyChange(2); + }); + it(`${scenario} - with single ts-ignore`, () => { + verifyChange(0, /*singleIgnore*/ true); + }); } - return index!; - } - - function textWithIgnoreCommentFrom(text: string, singleIgnore: true | undefined) { - if (!singleIgnore) return text; - const splits = text.split(tsIgnoreComment); - if (splits.length > 2) { - const tail = splits[splits.length - 2] + splits[splits.length - 1]; - splits.length = splits.length - 2; - return splits.join(tsIgnoreComment) + tail; + + function getIndexOfTsIgnoreComment(atIndex: number) { + let index = 0; + for (let i = 0; i <= atIndex; i++) { + index = textWithIgnoreComment.indexOf(tsIgnoreComment, index); + } + return index; } - else { - return splits.join(tsIgnoreComment); + + function textWithIgnoreCommentFrom(text: string, singleIgnore: true | undefined) { + if (!singleIgnore) return text; + const splits = text.split(tsIgnoreComment); + if (splits.length > 2) { + const tail = splits[splits.length - 2] + splits[splits.length - 1]; + splits.length = splits.length - 2; + return splits.join(tsIgnoreComment) + tail; + } + else { + return splits.join(tsIgnoreComment); + } } - } - - function verifyDelete(atIndex: number, singleIgnore?: true) { - const index = getIndexOfTsIgnoreComment(atIndex); - const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); - const newTextAndChange = withDelete(oldText, index, tsIgnoreComment.length); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyInsert(atIndex: number, singleIgnore?: true) { - const index = getIndexOfTsIgnoreComment(atIndex); - const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + textWithIgnoreComment.slice(index + tsIgnoreComment.length), singleIgnore); - const oldText = ScriptSnapshot.fromString(source); - const newTextAndChange = withInsert(oldText, index, tsIgnoreComment); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyChangeToBlah(atIndex: number, singleIgnore?: true) { - const index = getIndexOfTsIgnoreComment(atIndex) + "// ".length; - const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); - const newTextAndChange = withChange(oldText, index, 1, "blah "); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyChangeBackToDirective(atIndex: number, singleIgnore?: true) { - const index = getIndexOfTsIgnoreComment(atIndex) + "// ".length; - const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + "blah " + textWithIgnoreComment.slice(index + 1), singleIgnore); - const oldText = ScriptSnapshot.fromString(source); - const newTextAndChange = withChange(oldText, index, "blah ".length, "@"); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyDeletingBlah(atIndex: number, singleIgnore?: true) { - const tsIgnoreIndex = getIndexOfTsIgnoreComment(atIndex); - const index = tsIgnoreIndex + "// ".length; - const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + "blah " + textWithIgnoreComment.slice(index + 1), singleIgnore); - const oldText = ScriptSnapshot.fromString(source); - const newTextAndChange = withDelete(oldText, tsIgnoreIndex, tsIgnoreComment.length + "blah".length); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyChangeDirectiveType(atIndex: number, singleIgnore?: true) { - const index = getIndexOfTsIgnoreComment(atIndex) + "// @ts-".length; - const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); - const newTextAndChange = withChange(oldText, index, "ignore".length, "expect-error"); - verifyCommentDirectives(oldText, newTextAndChange); - } - - function verifyReuseChange(atIndex: number, singleIgnore?: true) { - const source = `const x = 10; -function foo1() { - const x1 = 10; - // @ts-ignore - let y0: string = x; - let y1: string = x; - return y1; -} -function foo2() { - const x2 = 10; - // @ts-ignore - let y0: string = x; - let y2: string = x; - return y2; -} -function foo3() { - const x3 = 10; - // @ts-ignore - let y0: string = x; - let y3: string = x; - return y3; -} -foo1(); -foo2(); -foo3();`; - const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(source, singleIgnore)); - const start = source.indexOf(`const x${atIndex + 1}`); - const letStr = `let y${atIndex + 1}: string = x;`; - const end = source.indexOf(letStr) + letStr.length; - const oldSubStr = source.slice(start, end); - const newText = oldSubStr.replace(letStr, `let yn : string = x;`); - const newTextAndChange = withChange(oldText, start, end - start, newText); - verifyCommentDirectives(oldText, newTextAndChange); - } - }); + + function verifyDelete(atIndex: number, singleIgnore?: true) { + const index = getIndexOfTsIgnoreComment(atIndex); + const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); + const newTextAndChange = withDelete(oldText, index, tsIgnoreComment.length); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyInsert(atIndex: number, singleIgnore?: true) { + const index = getIndexOfTsIgnoreComment(atIndex); + const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + textWithIgnoreComment.slice(index + tsIgnoreComment.length), singleIgnore); + const oldText = ScriptSnapshot.fromString(source); + const newTextAndChange = withInsert(oldText, index, tsIgnoreComment); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyChangeToBlah(atIndex: number, singleIgnore?: true) { + const index = getIndexOfTsIgnoreComment(atIndex) + tsIgnoreComment.indexOf("@"); + const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); + const newTextAndChange = withChange(oldText, index, 1, "blah "); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyChangeBackToDirective(atIndex: number, singleIgnore?: true) { + const index = getIndexOfTsIgnoreComment(atIndex) + tsIgnoreComment.indexOf("@"); + const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + "blah " + textWithIgnoreComment.slice(index + 1), singleIgnore); + const oldText = ScriptSnapshot.fromString(source); + const newTextAndChange = withChange(oldText, index, "blah ".length, "@"); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyDeletingBlah(atIndex: number, singleIgnore?: true) { + const tsIgnoreIndex = getIndexOfTsIgnoreComment(atIndex); + const index = tsIgnoreIndex + tsIgnoreComment.indexOf("@"); + const source = textWithIgnoreCommentFrom(textWithIgnoreComment.slice(0, index) + "blah " + textWithIgnoreComment.slice(index + 1), singleIgnore); + const oldText = ScriptSnapshot.fromString(source); + const newTextAndChange = withDelete(oldText, tsIgnoreIndex, tsIgnoreComment.length + "blah".length); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyChangeDirectiveType(atIndex: number, singleIgnore?: true) { + const index = getIndexOfTsIgnoreComment(atIndex) + tsIgnoreComment.indexOf("ignore"); + const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(textWithIgnoreComment, singleIgnore)); + const newTextAndChange = withChange(oldText, index, "ignore".length, "expect-error"); + verifyCommentDirectives(oldText, newTextAndChange); + } + + function verifyReuseChange(atIndex: number, singleIgnore?: true) { + const source = `const x = 10; + function foo1() { + const x1 = 10; + ${tsIgnoreComment} + let y0: string = x; + let y1: string = x; + return y1; + } + function foo2() { + const x2 = 10; + ${tsIgnoreComment} + let y0: string = x; + let y2: string = x; + return y2; + } + function foo3() { + const x3 = 10; + ${tsIgnoreComment} + let y0: string = x; + let y3: string = x; + return y3; + } + foo1(); + foo2(); + foo3();`; + const oldText = ScriptSnapshot.fromString(textWithIgnoreCommentFrom(source, singleIgnore)); + const start = source.indexOf(`const x${atIndex + 1}`); + const letStr = `let y${atIndex + 1}: string = x;`; + const end = source.indexOf(letStr) + letStr.length; + const oldSubStr = source.slice(start, end); + const newText = oldSubStr.replace(letStr, `let yn : string = x;`); + const newTextAndChange = withChange(oldText, start, end - start, newText); + verifyCommentDirectives(oldText, newTextAndChange); + } + }); + } }); } diff --git a/tests/baselines/reference/checkJsFiles_skipDiagnostics.errors.txt b/tests/baselines/reference/checkJsFiles_skipDiagnostics.errors.txt new file mode 100644 index 0000000000000..7a1455efeadcf --- /dev/null +++ b/tests/baselines/reference/checkJsFiles_skipDiagnostics.errors.txt @@ -0,0 +1,53 @@ +tests/cases/compiler/a.js(29,1): error TS2349: This expression is not callable. + Type 'Number' has no call signatures. +tests/cases/compiler/a.js(35,1): error TS2349: This expression is not callable. + Type 'Number' has no call signatures. + + +==== tests/cases/compiler/a.js (2 errors) ==== + var x = 0; + + + /// @ts-ignore + x(); + + /// @ts-ignore + x(); + + /// @ts-ignore + x( + 2, + 3); + + + + // @ts-ignore + // come comment + // some other comment + + // @another + + x(); + + /* @ts-ignore */ + /*another comment + that could be multiline*/ + + x(); + ~ +!!! error TS2349: This expression is not callable. +!!! error TS2349: Type 'Number' has no call signatures. + + /* @ts-ignore + continuing comment + that could be multiline*/ + + x(); + ~ +!!! error TS2349: This expression is not callable. +!!! error TS2349: Type 'Number' has no call signatures. + + + + // @ts-ignore: no call signature + x(); \ No newline at end of file diff --git a/tests/baselines/reference/checkJsFiles_skipDiagnostics.symbols b/tests/baselines/reference/checkJsFiles_skipDiagnostics.symbols index ca9b9a934445f..7bf2e437d05ab 100644 --- a/tests/baselines/reference/checkJsFiles_skipDiagnostics.symbols +++ b/tests/baselines/reference/checkJsFiles_skipDiagnostics.symbols @@ -29,6 +29,20 @@ x( x(); >x : Symbol(x, Decl(a.js, 0, 3)) +/* @ts-ignore */ +/*another comment + that could be multiline*/ + +x(); +>x : Symbol(x, Decl(a.js, 0, 3)) + +/* @ts-ignore +continuing comment + that could be multiline*/ + +x(); +>x : Symbol(x, Decl(a.js, 0, 3)) + // @ts-ignore: no call signature diff --git a/tests/baselines/reference/checkJsFiles_skipDiagnostics.types b/tests/baselines/reference/checkJsFiles_skipDiagnostics.types index 69768fe638ac2..67c4fbaad1aa1 100644 --- a/tests/baselines/reference/checkJsFiles_skipDiagnostics.types +++ b/tests/baselines/reference/checkJsFiles_skipDiagnostics.types @@ -6,17 +6,17 @@ var x = 0; /// @ts-ignore x(); ->x() : error +>x() : any >x : number /// @ts-ignore x(); ->x() : error +>x() : any >x : number /// @ts-ignore x( ->x( 2, 3) : error +>x( 2, 3) : any >x : number 2, @@ -34,13 +34,29 @@ x( // @another x(); ->x() : error +>x() : any +>x : number + +/* @ts-ignore */ +/*another comment + that could be multiline*/ + +x(); +>x() : any +>x : number + +/* @ts-ignore +continuing comment + that could be multiline*/ + +x(); +>x() : any >x : number // @ts-ignore: no call signature x(); ->x() : error +>x() : any >x : number diff --git a/tests/baselines/reference/multiline.errors.txt b/tests/baselines/reference/multiline.errors.txt new file mode 100644 index 0000000000000..0a27378a8295d --- /dev/null +++ b/tests/baselines/reference/multiline.errors.txt @@ -0,0 +1,60 @@ +tests/cases/conformance/directives/a.ts(12,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/b.tsx(32,1): error TS2578: Unused '@ts-expect-error' directive. + + +==== tests/cases/conformance/directives/a.ts (1 errors) ==== + export const texts: string[] = []; + + /** + @ts-ignore */ + texts.push(100); + + /** + @ts-expect-error */ + texts.push(100); + + /** + @ts-expect-error */ + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2578: Unused '@ts-expect-error' directive. + texts.push("100"); + +==== tests/cases/conformance/directives/b.tsx (1 errors) ==== + import * as React from "react"; + + export function MyComponent(props: { foo: string }) { + return
; + } + + let x = ( +
+ {/* + @ts-ignore */} + + + {/*@ts-ignore*/} + + + {/* + @ts-expect-error */} + + + {/* + // @ts-expect-error */} + + + {/* + * @ts-expect-error */} + + + {/*@ts-expect-error*/} + + + {/* + @ts-expect-error */} + ~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2578: Unused '@ts-expect-error' directive. + +
+ ); + \ No newline at end of file diff --git a/tests/baselines/reference/multiline.js b/tests/baselines/reference/multiline.js new file mode 100644 index 0000000000000..e8bb458b61f4e --- /dev/null +++ b/tests/baselines/reference/multiline.js @@ -0,0 +1,86 @@ +//// [tests/cases/conformance/directives/multiline.tsx] //// + +//// [a.ts] +export const texts: string[] = []; + +/** + @ts-ignore */ +texts.push(100); + +/** + @ts-expect-error */ +texts.push(100); + +/** + @ts-expect-error */ +texts.push("100"); + +//// [b.tsx] +import * as React from "react"; + +export function MyComponent(props: { foo: string }) { + return
; +} + +let x = ( +
+ {/* + @ts-ignore */} + + + {/*@ts-ignore*/} + + + {/* + @ts-expect-error */} + + + {/* + // @ts-expect-error */} + + + {/* + * @ts-expect-error */} + + + {/*@ts-expect-error*/} + + + {/* + @ts-expect-error */} + +
+); + + +//// [a.js] +"use strict"; +exports.__esModule = true; +exports.texts = void 0; +exports.texts = []; +/** + @ts-ignore */ +exports.texts.push(100); +/** + @ts-expect-error */ +exports.texts.push(100); +/** + @ts-expect-error */ +exports.texts.push("100"); +//// [b.js] +"use strict"; +exports.__esModule = true; +exports.MyComponent = void 0; +var React = require("react"); +function MyComponent(props) { + return React.createElement("div", null); +} +exports.MyComponent = MyComponent; +var x = (React.createElement("div", null, + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: 100 }), + React.createElement(MyComponent, { foo: "hooray" }))); diff --git a/tests/baselines/reference/multiline.symbols b/tests/baselines/reference/multiline.symbols new file mode 100644 index 0000000000000..b0a93c7138102 --- /dev/null +++ b/tests/baselines/reference/multiline.symbols @@ -0,0 +1,89 @@ +=== tests/cases/conformance/directives/a.ts === +export const texts: string[] = []; +>texts : Symbol(texts, Decl(a.ts, 0, 12)) + +/** + @ts-ignore */ +texts.push(100); +>texts.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>texts : Symbol(texts, Decl(a.ts, 0, 12)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + +/** + @ts-expect-error */ +texts.push(100); +>texts.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>texts : Symbol(texts, Decl(a.ts, 0, 12)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + +/** + @ts-expect-error */ +texts.push("100"); +>texts.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>texts : Symbol(texts, Decl(a.ts, 0, 12)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + +=== tests/cases/conformance/directives/b.tsx === +import * as React from "react"; +>React : Symbol(React, Decl(b.tsx, 0, 6)) + +export function MyComponent(props: { foo: string }) { +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>props : Symbol(props, Decl(b.tsx, 2, 28)) +>foo : Symbol(foo, Decl(b.tsx, 2, 36)) + + return
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45)) +} + +let x = ( +>x : Symbol(x, Decl(b.tsx, 6, 3)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45)) + + {/* + @ts-ignore */} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 10, 16)) + + {/*@ts-ignore*/} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 13, 16)) + + {/* + @ts-expect-error */} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 17, 16)) + + {/* + // @ts-expect-error */} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 21, 16)) + + {/* + * @ts-expect-error */} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 25, 16)) + + {/*@ts-expect-error*/} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 28, 16)) + + {/* + @ts-expect-error */} + +>MyComponent : Symbol(MyComponent, Decl(b.tsx, 0, 31)) +>foo : Symbol(foo, Decl(b.tsx, 32, 16)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2400, 45)) + +); + diff --git a/tests/baselines/reference/multiline.types b/tests/baselines/reference/multiline.types new file mode 100644 index 0000000000000..b83f82571c232 --- /dev/null +++ b/tests/baselines/reference/multiline.types @@ -0,0 +1,113 @@ +=== tests/cases/conformance/directives/a.ts === +export const texts: string[] = []; +>texts : string[] +>[] : undefined[] + +/** + @ts-ignore */ +texts.push(100); +>texts.push(100) : number +>texts.push : (...items: string[]) => number +>texts : string[] +>push : (...items: string[]) => number +>100 : 100 + +/** + @ts-expect-error */ +texts.push(100); +>texts.push(100) : number +>texts.push : (...items: string[]) => number +>texts : string[] +>push : (...items: string[]) => number +>100 : 100 + +/** + @ts-expect-error */ +texts.push("100"); +>texts.push("100") : number +>texts.push : (...items: string[]) => number +>texts : string[] +>push : (...items: string[]) => number +>"100" : "100" + +=== tests/cases/conformance/directives/b.tsx === +import * as React from "react"; +>React : typeof React + +export function MyComponent(props: { foo: string }) { +>MyComponent : (props: { foo: string;}) => JSX.Element +>props : { foo: string; } +>foo : string + + return
; +>
: JSX.Element +>div : any +} + +let x = ( +>x : JSX.Element +>(
{/* @ts-ignore */} {/*@ts-ignore*/} {/* @ts-expect-error */} {/* // @ts-expect-error */} {/* * @ts-expect-error */} {/*@ts-expect-error*/} {/* @ts-expect-error */}
) : JSX.Element + +
+>
{/* @ts-ignore */} {/*@ts-ignore*/} {/* @ts-expect-error */} {/* // @ts-expect-error */} {/* * @ts-expect-error */} {/*@ts-expect-error*/} {/* @ts-expect-error */}
: JSX.Element +>div : any + + {/* + @ts-ignore */} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/*@ts-ignore*/} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/* + @ts-expect-error */} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/* + // @ts-expect-error */} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/* + * @ts-expect-error */} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/*@ts-expect-error*/} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : number +>100 : 100 + + {/* + @ts-expect-error */} + +> : JSX.Element +>MyComponent : (props: { foo: string; }) => JSX.Element +>foo : string +>"hooray" : "hooray" + +
+>div : any + +); + diff --git a/tests/baselines/reference/ts-expect-error.errors.txt b/tests/baselines/reference/ts-expect-error.errors.txt index 24e7ddd0d6edb..05d1eb2e110fa 100644 --- a/tests/baselines/reference/ts-expect-error.errors.txt +++ b/tests/baselines/reference/ts-expect-error.errors.txt @@ -1,27 +1,54 @@ -tests/cases/conformance/directives/ts-expect-error.ts(4,1): error TS2578: Unused '@ts-expect-error' directive. -tests/cases/conformance/directives/ts-expect-error.ts(10,1): error TS2578: Unused '@ts-expect-error' directive. -tests/cases/conformance/directives/ts-expect-error.ts(13,5): error TS2322: Type '"nope"' is not assignable to type 'number'. -tests/cases/conformance/directives/ts-expect-error.ts(19,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. -tests/cases/conformance/directives/ts-expect-error.ts(21,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. -tests/cases/conformance/directives/ts-expect-error.ts(22,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. +tests/cases/conformance/directives/ts-expect-error.ts(8,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/ts-expect-error.ts(11,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/ts-expect-error.ts(21,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/ts-expect-error.ts(24,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/ts-expect-error.ts(28,1): error TS2578: Unused '@ts-expect-error' directive. +tests/cases/conformance/directives/ts-expect-error.ts(31,5): error TS2322: Type '"nope"' is not assignable to type 'number'. +tests/cases/conformance/directives/ts-expect-error.ts(37,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. +tests/cases/conformance/directives/ts-expect-error.ts(39,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. +tests/cases/conformance/directives/ts-expect-error.ts(40,2): error TS2367: This condition will always return 'false' since the types 'true' and 'false' have no overlap. -==== tests/cases/conformance/directives/ts-expect-error.ts (6 errors) ==== +==== tests/cases/conformance/directives/ts-expect-error.ts (9 errors) ==== // @ts-expect-error additional commenting - var invalidCommentedFancy: number = 'nope'; + var invalidCommentedFancySingle: number = 'nope'; + + /* + @ts-expect-error additional commenting */ + var invalidCommentedFancyMulti: number = 'nope'; // @ts-expect-error additional commenting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2578: Unused '@ts-expect-error' directive. - var validCommentedFancy: string = 'nope'; + var validCommentedFancySingle: string = 'nope'; + + /* @ts-expect-error additional commenting */ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2578: Unused '@ts-expect-error' directive. + var validCommentedFancyMulti: string = 'nope'; // @ts-expect-error - var invalidCommentedPlain: number = 'nope'; + var invalidCommentedPlainSingle: number = 'nope'; + + /* + @ts-expect-error */ + var invalidCommentedPlainMulti: number = 'nope'; // @ts-expect-error ~~~~~~~~~~~~~~~~~~~ !!! error TS2578: Unused '@ts-expect-error' directive. - var validCommentedPlain: string = 'nope'; + var validCommentedPlainSingle: string = 'nope'; + + /* @ts-expect-error */ + ~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2578: Unused '@ts-expect-error' directive. + var validCommentedPlainMulti1: string = 'nope'; + + /* + @ts-expect-error */ + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2578: Unused '@ts-expect-error' directive. + var validCommentedPlainMulti2: string = 'nope'; var invalidPlain: number = 'nope'; ~~~~~~~~~~~~ diff --git a/tests/baselines/reference/ts-expect-error.js b/tests/baselines/reference/ts-expect-error.js index 88dc6ba3aa6ea..2c06d26391d40 100644 --- a/tests/baselines/reference/ts-expect-error.js +++ b/tests/baselines/reference/ts-expect-error.js @@ -1,15 +1,33 @@ //// [ts-expect-error.ts] // @ts-expect-error additional commenting -var invalidCommentedFancy: number = 'nope'; +var invalidCommentedFancySingle: number = 'nope'; + +/* + @ts-expect-error additional commenting */ +var invalidCommentedFancyMulti: number = 'nope'; // @ts-expect-error additional commenting -var validCommentedFancy: string = 'nope'; +var validCommentedFancySingle: string = 'nope'; + +/* @ts-expect-error additional commenting */ +var validCommentedFancyMulti: string = 'nope'; // @ts-expect-error -var invalidCommentedPlain: number = 'nope'; +var invalidCommentedPlainSingle: number = 'nope'; + +/* + @ts-expect-error */ +var invalidCommentedPlainMulti: number = 'nope'; // @ts-expect-error -var validCommentedPlain: string = 'nope'; +var validCommentedPlainSingle: string = 'nope'; + +/* @ts-expect-error */ +var validCommentedPlainMulti1: string = 'nope'; + +/* +@ts-expect-error */ +var validCommentedPlainMulti2: string = 'nope'; var invalidPlain: number = 'nope'; @@ -24,13 +42,26 @@ var validPlain: string = 'nope'; //// [ts-expect-error.js] // @ts-expect-error additional commenting -var invalidCommentedFancy = 'nope'; +var invalidCommentedFancySingle = 'nope'; +/* + @ts-expect-error additional commenting */ +var invalidCommentedFancyMulti = 'nope'; // @ts-expect-error additional commenting -var validCommentedFancy = 'nope'; +var validCommentedFancySingle = 'nope'; +/* @ts-expect-error additional commenting */ +var validCommentedFancyMulti = 'nope'; // @ts-expect-error -var invalidCommentedPlain = 'nope'; +var invalidCommentedPlainSingle = 'nope'; +/* + @ts-expect-error */ +var invalidCommentedPlainMulti = 'nope'; // @ts-expect-error -var validCommentedPlain = 'nope'; +var validCommentedPlainSingle = 'nope'; +/* @ts-expect-error */ +var validCommentedPlainMulti1 = 'nope'; +/* +@ts-expect-error */ +var validCommentedPlainMulti2 = 'nope'; var invalidPlain = 'nope'; var validPlain = 'nope'; // @ts-expect-error diff --git a/tests/baselines/reference/ts-expect-error.symbols b/tests/baselines/reference/ts-expect-error.symbols index 434287cace708..29800a1bd115a 100644 --- a/tests/baselines/reference/ts-expect-error.symbols +++ b/tests/baselines/reference/ts-expect-error.symbols @@ -1,44 +1,67 @@ === tests/cases/conformance/directives/ts-expect-error.ts === // @ts-expect-error additional commenting -var invalidCommentedFancy: number = 'nope'; ->invalidCommentedFancy : Symbol(invalidCommentedFancy, Decl(ts-expect-error.ts, 1, 3)) +var invalidCommentedFancySingle: number = 'nope'; +>invalidCommentedFancySingle : Symbol(invalidCommentedFancySingle, Decl(ts-expect-error.ts, 1, 3)) + +/* + @ts-expect-error additional commenting */ +var invalidCommentedFancyMulti: number = 'nope'; +>invalidCommentedFancyMulti : Symbol(invalidCommentedFancyMulti, Decl(ts-expect-error.ts, 5, 3)) // @ts-expect-error additional commenting -var validCommentedFancy: string = 'nope'; ->validCommentedFancy : Symbol(validCommentedFancy, Decl(ts-expect-error.ts, 4, 3)) +var validCommentedFancySingle: string = 'nope'; +>validCommentedFancySingle : Symbol(validCommentedFancySingle, Decl(ts-expect-error.ts, 8, 3)) + +/* @ts-expect-error additional commenting */ +var validCommentedFancyMulti: string = 'nope'; +>validCommentedFancyMulti : Symbol(validCommentedFancyMulti, Decl(ts-expect-error.ts, 11, 3)) // @ts-expect-error -var invalidCommentedPlain: number = 'nope'; ->invalidCommentedPlain : Symbol(invalidCommentedPlain, Decl(ts-expect-error.ts, 7, 3)) +var invalidCommentedPlainSingle: number = 'nope'; +>invalidCommentedPlainSingle : Symbol(invalidCommentedPlainSingle, Decl(ts-expect-error.ts, 14, 3)) + +/* + @ts-expect-error */ +var invalidCommentedPlainMulti: number = 'nope'; +>invalidCommentedPlainMulti : Symbol(invalidCommentedPlainMulti, Decl(ts-expect-error.ts, 18, 3)) // @ts-expect-error -var validCommentedPlain: string = 'nope'; ->validCommentedPlain : Symbol(validCommentedPlain, Decl(ts-expect-error.ts, 10, 3)) +var validCommentedPlainSingle: string = 'nope'; +>validCommentedPlainSingle : Symbol(validCommentedPlainSingle, Decl(ts-expect-error.ts, 21, 3)) + +/* @ts-expect-error */ +var validCommentedPlainMulti1: string = 'nope'; +>validCommentedPlainMulti1 : Symbol(validCommentedPlainMulti1, Decl(ts-expect-error.ts, 24, 3)) + +/* +@ts-expect-error */ +var validCommentedPlainMulti2: string = 'nope'; +>validCommentedPlainMulti2 : Symbol(validCommentedPlainMulti2, Decl(ts-expect-error.ts, 28, 3)) var invalidPlain: number = 'nope'; ->invalidPlain : Symbol(invalidPlain, Decl(ts-expect-error.ts, 12, 3)) +>invalidPlain : Symbol(invalidPlain, Decl(ts-expect-error.ts, 30, 3)) var validPlain: string = 'nope'; ->validPlain : Symbol(validPlain, Decl(ts-expect-error.ts, 14, 3)) +>validPlain : Symbol(validPlain, Decl(ts-expect-error.ts, 32, 3)) // @ts-expect-error (({ a: true } as const).a === false); // <-- compiles (as expected via comment) ->({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 17, 3)) +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 35, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 35, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 35, 3)) (({ a: true } as const).a === false); // Should error ->({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 18, 3)) +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 36, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 36, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 36, 3)) (({ a: true } as const).a === false); // error ->({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 20, 3)) +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 38, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 38, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 38, 3)) (({ a: true } as const).a === false); // error ->({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) ->a : Symbol(a, Decl(ts-expect-error.ts, 21, 3)) +>({ a: true } as const).a : Symbol(a, Decl(ts-expect-error.ts, 39, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 39, 3)) +>a : Symbol(a, Decl(ts-expect-error.ts, 39, 3)) diff --git a/tests/baselines/reference/ts-expect-error.types b/tests/baselines/reference/ts-expect-error.types index c010046d36fbe..ecb1cec5d19c3 100644 --- a/tests/baselines/reference/ts-expect-error.types +++ b/tests/baselines/reference/ts-expect-error.types @@ -1,22 +1,50 @@ === tests/cases/conformance/directives/ts-expect-error.ts === // @ts-expect-error additional commenting -var invalidCommentedFancy: number = 'nope'; ->invalidCommentedFancy : number +var invalidCommentedFancySingle: number = 'nope'; +>invalidCommentedFancySingle : number +>'nope' : "nope" + +/* + @ts-expect-error additional commenting */ +var invalidCommentedFancyMulti: number = 'nope'; +>invalidCommentedFancyMulti : number >'nope' : "nope" // @ts-expect-error additional commenting -var validCommentedFancy: string = 'nope'; ->validCommentedFancy : string +var validCommentedFancySingle: string = 'nope'; +>validCommentedFancySingle : string +>'nope' : "nope" + +/* @ts-expect-error additional commenting */ +var validCommentedFancyMulti: string = 'nope'; +>validCommentedFancyMulti : string >'nope' : "nope" // @ts-expect-error -var invalidCommentedPlain: number = 'nope'; ->invalidCommentedPlain : number +var invalidCommentedPlainSingle: number = 'nope'; +>invalidCommentedPlainSingle : number +>'nope' : "nope" + +/* + @ts-expect-error */ +var invalidCommentedPlainMulti: number = 'nope'; +>invalidCommentedPlainMulti : number >'nope' : "nope" // @ts-expect-error -var validCommentedPlain: string = 'nope'; ->validCommentedPlain : string +var validCommentedPlainSingle: string = 'nope'; +>validCommentedPlainSingle : string +>'nope' : "nope" + +/* @ts-expect-error */ +var validCommentedPlainMulti1: string = 'nope'; +>validCommentedPlainMulti1 : string +>'nope' : "nope" + +/* +@ts-expect-error */ +var validCommentedPlainMulti2: string = 'nope'; +>validCommentedPlainMulti2 : string >'nope' : "nope" var invalidPlain: number = 'nope'; diff --git a/tests/cases/compiler/checkJsFiles_skipDiagnostics.ts b/tests/cases/compiler/checkJsFiles_skipDiagnostics.ts index 0f233e5e574a4..4a246d58c7c91 100644 --- a/tests/cases/compiler/checkJsFiles_skipDiagnostics.ts +++ b/tests/cases/compiler/checkJsFiles_skipDiagnostics.ts @@ -27,6 +27,18 @@ x( x(); +/* @ts-ignore */ +/*another comment + that could be multiline*/ + +x(); + +/* @ts-ignore +continuing comment + that could be multiline*/ + +x(); + // @ts-ignore: no call signature diff --git a/tests/cases/conformance/directives/multiline.tsx b/tests/cases/conformance/directives/multiline.tsx new file mode 100644 index 0000000000000..740e9936f4d3a --- /dev/null +++ b/tests/cases/conformance/directives/multiline.tsx @@ -0,0 +1,53 @@ +// @filename: a.ts +export const texts: string[] = []; + +/** + @ts-ignore */ +texts.push(100); + +/** + @ts-expect-error */ +texts.push(100); + +/** + @ts-expect-error */ +texts.push("100"); + +// @filename: b.tsx +// @jsx: react +// @libFiles: react.d.ts,lib.d.ts +import * as React from "react"; + +export function MyComponent(props: { foo: string }) { + return
; +} + +let x = ( +
+ {/* + @ts-ignore */} + + + {/*@ts-ignore*/} + + + {/* + @ts-expect-error */} + + + {/* + // @ts-expect-error */} + + + {/* + * @ts-expect-error */} + + + {/*@ts-expect-error*/} + + + {/* + @ts-expect-error */} + +
+); diff --git a/tests/cases/conformance/directives/ts-expect-error.ts b/tests/cases/conformance/directives/ts-expect-error.ts index 78c25dc4591f4..3ae0527e73063 100644 --- a/tests/cases/conformance/directives/ts-expect-error.ts +++ b/tests/cases/conformance/directives/ts-expect-error.ts @@ -1,14 +1,32 @@ // @ts-expect-error additional commenting -var invalidCommentedFancy: number = 'nope'; +var invalidCommentedFancySingle: number = 'nope'; + +/* + @ts-expect-error additional commenting */ +var invalidCommentedFancyMulti: number = 'nope'; // @ts-expect-error additional commenting -var validCommentedFancy: string = 'nope'; +var validCommentedFancySingle: string = 'nope'; + +/* @ts-expect-error additional commenting */ +var validCommentedFancyMulti: string = 'nope'; // @ts-expect-error -var invalidCommentedPlain: number = 'nope'; +var invalidCommentedPlainSingle: number = 'nope'; + +/* + @ts-expect-error */ +var invalidCommentedPlainMulti: number = 'nope'; // @ts-expect-error -var validCommentedPlain: string = 'nope'; +var validCommentedPlainSingle: string = 'nope'; + +/* @ts-expect-error */ +var validCommentedPlainMulti1: string = 'nope'; + +/* +@ts-expect-error */ +var validCommentedPlainMulti2: string = 'nope'; var invalidPlain: number = 'nope'; From 35c1ba67baac2fd5152908184f8b2ec565815942 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 6 May 2020 14:42:05 -0700 Subject: [PATCH 17/28] Update LKG 2020 05 06 (#38371) * Update LKG * remove now-extraneous casts --- lib/cs/diagnosticMessages.generated.json | 47 +- lib/de/diagnosticMessages.generated.json | 46 +- lib/es/diagnosticMessages.generated.json | 44 +- lib/fr/diagnosticMessages.generated.json | 40 +- lib/it/diagnosticMessages.generated.json | 44 +- lib/ja/diagnosticMessages.generated.json | 44 +- lib/ko/diagnosticMessages.generated.json | 40 +- lib/lib.es2015.core.d.ts | 17 +- lib/lib.es2015.d.ts | 2 +- lib/lib.es2015.symbol.wellknown.d.ts | 2 +- lib/lib.es2018.d.ts | 2 +- lib/lib.es2019.array.d.ts | 170 +- lib/lib.es5.d.ts | 2 +- lib/lib.esnext.string.d.ts | 7 + lib/pl/diagnosticMessages.generated.json | 42 +- lib/protocol.d.ts | 8 +- lib/pt-br/diagnosticMessages.generated.json | 40 +- lib/ru/diagnosticMessages.generated.json | 42 +- lib/tr/diagnosticMessages.generated.json | 36 +- lib/tsc.js | 2427 ++++++++---- lib/tsserver.js | 3727 +++++++++++++------ lib/tsserverlibrary.d.ts | 42 +- lib/tsserverlibrary.js | 3727 +++++++++++++------ lib/typescript.d.ts | 34 +- lib/typescript.js | 3647 +++++++++++++----- lib/typescriptServices.d.ts | 34 +- lib/typescriptServices.js | 3647 +++++++++++++----- lib/typingsInstaller.js | 2683 ++++++++----- lib/zh-cn/diagnosticMessages.generated.json | 52 +- lib/zh-tw/diagnosticMessages.generated.json | 48 +- src/compiler/checker.ts | 2 +- src/compiler/utilities.ts | 4 +- 32 files changed, 14643 insertions(+), 6106 deletions(-) diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 3558d66bf4d07..65e7b7f95d69b 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená jenom v oboru názvů nebo v modulu.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Za výrazem new s argumenty typů musí vždy následovat seznam argumentů v závorkách.", "A_non_dry_build_would_build_project_0_6357": "Build bez příznaku -dry by vytvořil projekt {0}.", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Build bez příznaku -dry by odstranil následující soubory: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Build bez příznaku -dry by aktualizoval výstup projektu {0}.", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", "Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}", "Add_0_to_unresolved_variable_90008": "Přidat {0}. k nerozpoznané proměnné", + "Add_a_return_statement_95111": "Přidat příkaz return", "Add_all_missing_async_modifiers_95041": "Přidat všechny chybějící modifikátory async", "Add_all_missing_call_parentheses_95068": "Přidat všechny chybějící závorky volání", "Add_all_missing_imports_95064": "Přidat všechny chybějící importy", "Add_all_missing_members_95022": "Přidat všechny chybějící členy", + "Add_all_missing_return_statement_95114": "Přidat všechny chybějící příkazy return", "Add_all_missing_super_calls_95039": "Přidat všechna chybějící volání pomocí super", "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", "Add_await_95083": "Přidat await", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Cesta pro import nemůže končit příponou {0}. Zvažte možnost importovat místo toho {1}.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument výrazu indexu musí být typu string, number, symbol nebo any.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Signatura indexu indexu nemůže obsahovat parametr rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Signatura indexu nemůže mít na konci čárku.", "An_index_signature_must_have_a_type_annotation_1021": "Signatura indexu musí mít anotaci typu.", "An_index_signature_must_have_exactly_one_parameter_1096": "Signatura indexu musí mít právě jeden parametr.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "V parametru signatury indexu nemůže být otazník.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Hodnota se nedá iterovat, protože metoda next jejího iterátoru očekává typ {1}, ale rozsah pole bude vždy posílat {0}.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Hodnota se nedá iterovat, protože metoda next jejího iterátoru očekává typ {1}, ale for-of bude vždy posílat {0}.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Projekt {0} se nedá předřadit, protože nemá nastavenou hodnotu outFile.", + "Cannot_read_file_0_5083": "Nejde přečíst soubor {0}.", "Cannot_read_file_0_Colon_1_5012": "Nejde číst soubor {0}: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Nejde předeklarovat proměnnou bloku {0}.", "Cannot_redeclare_exported_variable_0_2323": "Exportovanou proměnnou {0} není možné znovu deklarovat.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Zkompilujte projekt podle cesty k jeho konfiguračnímu souboru nebo do složky se souborem tsconfig.json.", "Compiler_option_0_expects_an_argument_6044": "Parametr kompilátoru {0} očekává argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Parametr kompilátoru {0} vyžaduje hodnotu typu {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Kompilátor si rezervuje název {0} při generování nižší úrovně privátního identifikátoru.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Kompilátor si rezervuje název {0} při generování privátního identifikátoru pro nižší úroveň.", "Composite_projects_may_not_disable_declaration_emit_6304": "Složené projekty nemůžou zakázat generování deklarací.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Složené projekty nemůžou zakázat přírůstkovou kompilaci.", "Computed_property_names_are_not_allowed_in_enums_1164": "Názvy počítaných vlastností se ve výčtech nepovolují.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Nepovedlo se přeložit cestu {0} s příponami {1}.", "Could_not_write_file_0_Colon_1_5033": "Nedá se zapisovat do souboru {0}: {1}", "DIRECTORY_6038": "ADRESÁŘ", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Deklarace rozšiřuje deklaraci v jiném souboru. Toto není možné serializovat.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Generování deklarací pro tento soubor vyžaduje, aby se použil privátní název {0}. Explicitní anotace typu může generování deklarací odblokovat.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Generování deklarací pro tento soubor vyžaduje, aby se použil privátní název {0} z modulu {1}. Explicitní anotace typu může generování deklarací odblokovat.", "Declaration_expected_1146": "Očekává se deklarace.", @@ -504,6 +510,7 @@ "Experimental_Options_6177": "Experimentální možnosti", "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentální podpora dekorátorů je funkce, která se v budoucí verzi může změnit. Toto upozornění odstraníte nastavením možnosti experimentalDecorators v tsconfig nebo jsconfig.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explicitně zadaný druh překladu modulu: {0}.", + "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Pokud možnost target není nastavená na es2016 nebo novější, nedají se hodnoty bigint umocnit.", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Přiřazení exportu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít export default nebo jiný formát modulu.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Když má příznak --module hodnotu system, nepodporuje se přiřazení exportu.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Konflikty deklarace exportu s exportovanou deklarací {0}", @@ -553,6 +560,7 @@ "Fix_all_detected_spelling_errors_95026": "Opravit všechny zjištěné pravopisné chyby", "Fix_all_expressions_possibly_missing_await_95085": "Opravit všechny výrazy, kde je možné, že chybí await", "Fix_all_implicit_this_errors_95107": "Opravit všechny chyby implicit-'this'", + "Fix_all_incorrect_return_type_of_an_async_functions_90037": "Opravit všechny nesprávné návratové typy asynchronních funkcí", "Found_0_errors_6217": "Našel se tento počet chyb: {0}.", "Found_0_errors_Watching_for_file_changes_6194": "Byl nalezen tento počet chyb: {0}. Sledují se změny souborů.", "Found_1_error_6216": "Našla se 1 chyba.", @@ -606,7 +614,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "Deklarace importu {0} používá privátní název {1}.", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Deklarace importu je v konfliktu s místní deklarací {0}.", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Deklarace importu v oboru názvů nemůžou odkazovat na modul.", - "Import_default_0_from_module_1_90032": "Importovat výchozí {0} z modulu {1}", + "Import_default_0_from_module_1_90032": "Importovat výchozí hodnotu {0} z modulu {1}", "Import_emit_helpers_from_tslib_6139": "Importovat pomocné rutiny pro generování z tslib", "Import_may_be_converted_to_a_default_import_80003": "Import se může převést na výchozí import.", "Import_name_cannot_be_0_2438": "Název importu nemůže být {0}.", @@ -626,7 +634,6 @@ "Initialize_property_0_in_the_constructor_90020": "Inicializovat vlastnost {0} v konstruktoru", "Initialize_static_property_0_90021": "Inicializovat statickou vlastnost {0}", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicializátor instance členské proměnné {0} nemůže odkazovat na identifikátor {1} deklarovaný v konstruktoru.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicializátor parametru {0} nemůže odkazovat na identifikátor {1} deklarovaný po něm.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicializátor tomuto elementu vazby neposkytuje žádnou hodnotu. Element vazby nemá žádnou výchozí hodnotu.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializátory nejsou povolené v ambientních kontextech.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializuje projekt TypeScript a vytvoří soubor tsconfig.json.", @@ -646,6 +653,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Neplatné použití {0} ve striktním režimu", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Neplatná hodnota pro jsxFactory. {0} není platný identifikátor nebo kvalifikovaný název.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Neplatná hodnota --reactNamespace. {0} není platný identifikátor.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Jeho typ prvku {0} není platný prvek JSX.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Jeho typ instance {0} není platný prvek JSX.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Jeho návratový typ {0} není platný prvek JSX.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Značka JSDoc @{0} {1} neodpovídá klauzuli extends {2}.", "JSDoc_0_is_not_attached_to_a_class_8022": "Značka JSDoc @{0} není připojená k třídě.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc ... se může nacházet jen v posledním parametru signatury.", @@ -770,6 +780,7 @@ "Only_emit_d_ts_declaration_files_6014": "Bude vydávat jen soubory deklarací .d.ts.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "V klauzuli třídy extends se aktuálně podporují jenom identifikátory nebo kvalifikované názvy s volitelnými argumenty typu.", "Only_named_exports_may_use_export_type_1383": "Jenom pojmenované exporty mohou používat typ exportu.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Počítané členy můžou obsahovat jen číselné výčty, ale tento výraz je typu {0}. Pokud nepotřebujete kontroly úplnosti, zvažte místo něho použít objekt literálu.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Prostřednictvím klíčového slova super jsou přístupné jenom veřejné a chráněné metody základní třídy.", "Operator_0_cannot_be_applied_to_type_1_2736": "Operátor {0} se nedá použít na typ {1}.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Operátor {0} nejde použít u typů {1} a {2}.", @@ -799,7 +810,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Signatury přetížení musí být všechny exportované nebo neexportované.", "Overload_signatures_must_all_be_optional_or_required_2386": "Signatury přetížení musí být všechny nepovinné nebo povinné.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Signatury přetížení musí být všechny veřejné, privátní nebo chráněné.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr {0} se nedá odkazovat v jeho vlastním inicializátoru.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Parametr {0} nemůže odkazovat na identifikátor {1} deklarovaný za ním.", + "Parameter_0_cannot_reference_itself_2372": "Parametr {0} nemůže odkazovat sám na sebe.", "Parameter_0_implicitly_has_an_1_type_7006": "Parametr {0} má implicitně typ {1}.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Parametr {0} má implicitně typ {1}, ale je možné, že lepší typ by se vyvodil z použití.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr {0} není na stejné pozici jako parametr {1}.", @@ -867,7 +879,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "Vlastnost {0} ve výčtu const {1} neexistuje.", "Property_0_does_not_exist_on_type_1_2339": "Vlastnost {0} v typu {1} neexistuje.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Vlastnost {0} v typu {1} neexistuje. Měli jste na mysli {2}?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Vlastnost {0} má konfliktní deklarace a v typu {1} není přístupná.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", @@ -923,9 +934,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Opětovný export typu ve chvíli, kdy se poskytl příznak --isolatedModules, vyžaduje, aby se použilo export type.", "Redirect_output_structure_to_the_directory_6006": "Přesměrování výstupní struktury do adresáře", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Odkazovaný projekt {0} musí mít nastavení \"composite\": true.", + "Remove_all_incorrect_body_block_braces_95115": "Odebrat všechny nesprávné závorky bloku kódu", "Remove_all_unnecessary_uses_of_await_95087": "Odebrat všechna nepotřebná použití výrazu await", "Remove_all_unreachable_code_95051": "Odebrat veškerý nedosažitelný kód", "Remove_all_unused_labels_95054": "Odebrat všechny nepoužívané popisky", + "Remove_block_body_braces_95112": "Odebrat všechny závorky bloku kódu", "Remove_braces_from_arrow_function_95060": "Odebrat složené závorky z funkce šipky", "Remove_destructuring_90009": "Odebrat destrukci", "Remove_import_from_0_90005": "Odebrat import z {0}", @@ -936,6 +949,7 @@ "Remove_unused_declaration_for_Colon_0_90004": "Odebrat nepoužívané deklarace pro {0}", "Remove_unused_label_95053": "Odebrat nepoužitý popisek", "Remove_variable_statement_90010": "Odebrat příkaz proměnné", + "Replace_0_with_Promise_1_90036": "Místo {0} použijte Promise<{1}>", "Replace_all_unused_infer_with_unknown_90031": "Nahradit všechny nepoužívané příkazy infer za unknown", "Replace_import_with_0_95015": "Nahradí import použitím: {0}.", "Replace_infer_0_with_unknown_90030": "Nahradit infer {0} za unknown", @@ -1076,6 +1090,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Metavlastnost import.meta se povoluje jen v případě, že možnost --module je nastavená na esnext nebo system.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Odvozený typ {0} se nedá pojmenovat bez odkazu na {1}. Pravděpodobně to nebude přenosné. Vyžaduje se anotace typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Odvozený typ {0} odkazuje na nepřístupný typ {1}. Musí se použít anotace typu.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Průnik {0} se omezil na never, protože vlastnost {1} existuje v několika konstituentech a v některých z nich je privátní.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Průnik {0} se omezil na never, protože vlastnost {1} má v některých konstituentech konfliktní typy.", "The_last_overload_gave_the_following_error_2770": "Poslední přetížení vrátilo následující chybu.", "The_last_overload_is_declared_here_2771": "Poslední přetížení je deklarované tady.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Levá strana příkazu for...in nemůže být destrukturačním vzorem.", @@ -1096,6 +1112,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Operandem operátoru delete nemůže být privátní identifikátor.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Operandem operátoru delete nemůže být vlastnost určená jen pro čtení.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Operandem operátoru delete musí být odkaz na vlastnost.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Operand operátoru delete musí být nepovinný.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Operandem operátoru inkrementace nebo dekrementace nemůže být přístup k nepovinné vlastnosti.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operátoru inkrementace nebo dekrementace musí být proměnná nebo přístup k vlastnosti.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "Parser očekával, že najde token }, který by odpovídal zdejšímu tokenu {.", @@ -1104,12 +1121,12 @@ "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237": "Návratový typ funkce dekorátoru parametru funkce musí být void nebo any.", "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236": "Návratový typ funkce dekorátoru vlastnosti musí být void nebo any.", "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058": "Návratový typ asynchronní funkce musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", - "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise.", + "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise. Zamýšleli jste napsat Promise<{0}>?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Pravá strana příkazu for...in musí být typu any, typem objektu nebo parametrem typu, ale tady má typ {0}.", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Pravá strana aritmetické operace musí mít typ any, number, bigint nebo být typu výčtu.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Pravá strana výrazu in musí být typu any, objektového typu nebo parametrem typu.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Pravá strana výrazu instanceof musí mít typ any nebo typ, který se dá přiřadit k typu rozhraní Function.", - "The_shadowing_declaration_of_0_is_defined_here_18017": "Překrývající se deklarace {0} je definovaná tady.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "Překrývající deklarace {0} je definovaná tady.", "The_specified_path_does_not_exist_Colon_0_5058": "Zadaná cesta neexistuje: {0}", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Cíl přiřazení musí být proměnná nebo přístup k vlastnosti.", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "Cíl přiřazení rest objektu nemůže představovat přístup k nepovinné vlastnosti.", @@ -1134,6 +1151,7 @@ "This_expression_is_not_callable_2349": "Tento výraz se nedá zavolat.", "This_expression_is_not_constructable_2351": "Tento výraz se nedá vytvořit.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Tento import se nikdy nepoužívá jako hodnota a musí používat import type, protože importsNotUsedAsValues je nastavené na error.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Toto je deklarace, která se rozšiřuje. Zvažte možnost přesunout rozšiřující deklaraci do stejného souboru.", "This_may_be_converted_to_an_async_function_80006": "Toto je možné převést na asynchronní funkci.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Na tento modul je možné se pomocí importů nebo exportů ECMAScript odkazovat jen tak, že se zapne příznak {0} a odkáže se na výchozí export.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Tento modul se deklaroval pomocí export =, a když se používá příznak {0}, dá se použít jen s výchozím importem.", @@ -1196,7 +1214,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Typ iterovaných elementů yield* musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Typ vlastnosti {0} cyklicky odkazuje sám na sebe v mapovaném typu {1}.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Typ operandu yield v asynchronním generátoru musí být buď platný příslib, nebo nesmí obsahovat člen then, který se dá volat.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Typ pochází z tohoto importu. Import stylu oboru názvů není možné zavolat ani vytvořit a při běhu způsobí chybu. Zvažte možnost použít tady místo toho výchozí import nebo požadavek na import.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Typ pochází z tohoto importu. Import stylu oboru názvů není možné zavolat ani vytvořit a při běhu způsobí chybu. Zvažte možnost použít tady místo toho výchozí import nebo importovat require.", "Type_parameter_0_has_a_circular_constraint_2313": "Parametr typu {0} má cyklické omezení.", "Type_parameter_0_has_a_circular_default_2716": "Parametr typu {0} má cyklickou výchozí hodnotu.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Parametr typu {0} signatury volání z exportovaného rozhraní má nebo používá privátní název {1}.", @@ -1258,7 +1276,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Aktualizují se nezměněná výstupní časová razítka projektu {0}...", "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "Používají se možnosti kompilátoru přesměrování odkazu projektu {0}.", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", "VERSION_6036": "VERZE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Hodnota typu {0} se nedá volat. Nechtěli jste zahrnout new?", @@ -1270,17 +1288,27 @@ "Variable_declaration_expected_1134": "Očekává se deklarace proměnné.", "Variable_declaration_list_cannot_be_empty_1123": "Seznam deklarací proměnných nemůže být prázdný.", "Version_0_6029": "Verze {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Další informace o tomto souboru najdete tady: https://aka.ms/tsconfig.json", "Watch_input_files_6005": "Sledovat vstupní soubory", "Watch_option_0_requires_a_value_of_type_1_5080": "Možnost sledování {0} vyžaduje hodnotu typu {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Určuje, jestli se místo vymazání obrazovky má zachovat zastaralý výstup konzoly v režimu sledování.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Zabalit všechny neplatné znaky do kontejneru výrazu", + "Wrap_all_object_literal_with_parentheses_95116": "Uzavřít všechny literály objektů do závorek", "Wrap_invalid_character_in_an_expression_container_95108": "Zabalit neplatný znak do kontejneru výrazu", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Uzavřít následující kód, který by měl být literál objektu, do závorek", "You_cannot_rename_a_module_via_a_global_import_8031": "Přes globální import se modul nedá přejmenovat.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nejde přejmenovat elementy definované ve standardní knihovně TypeScriptu.", "You_cannot_rename_this_element_8000": "Tento element nejde přejmenovat.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Objekt {0} přijímá málo argumentů k tomu, aby se dal použít jako dekoratér. Nechtěli jste ho nejprve volat a napsat @{0}()?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Operace {0} a {1} se nedají kombinovat bez závorek.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Položka {0} je zadána dvakrát. Atribut s názvem {0} se přepíše.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "{0} se dá importovat jen zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "{0} se dá importovat jen pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "{0} se dá importovat jen pomocí volání require nebo zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "{0} se dá importovat jen pomocí volání require nebo pomocí výchozího importu.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "{0} se dá importovat jen pomocí import {1} = require({2}) nebo výchozího importu.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "{0} se dá importovat jen pomocí import {1} = require({2}) nebo zapnutím příznaku esModuleInterop a pomocí výchozího importu.", + "_0_cannot_be_used_as_a_JSX_component_2786": "{0} se nedá použít jako součást JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "{0} se nedá používat jako hodnota, protože se exportovalo pomocí export type.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "{0} se nedá používat jako hodnota, protože se importovalo pomocí import type.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Komponenty {0} nepřijímají text jako podřízené prvky. Text v JSX má typ string, ale očekávaný typ {1} je {2}.", @@ -1350,6 +1378,7 @@ "constructor_is_a_reserved_word_18012": "#constructor je rezervované slovo.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "odstranit toto – projekt {0} je aktuální, protože byl sestaven dříve", + "export_Asterisk_does_not_re_export_a_default_1195": "export * neprovádí opakovaný export výchozí hodnoty.", "export_can_only_be_used_in_TypeScript_files_8003": "export = se dá používat jen v typescriptových souborech.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modifikátor export se nedá použít u ambientních modulů a rozšíření modulů, protože jsou vždy viditelné.", "extends_clause_already_seen_1172": "Klauzule extends se už jednou vyskytla.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 1d0a4f70d1f2e..092a02d46b01f 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Auf einen new-Ausdruck mit Typargumenten muss immer eine in Klammern gesetzte Argumentliste folgen.", "A_non_dry_build_would_build_project_0_6357": "Bei einem Build ohne das Flag \"-dry\" würde das Projekt \"{0}\" erstellt.", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Bei einem Build ohne das Flag \"-dry\" würden die folgenden Dateien gelöscht: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Ein Build ohne das Flag \"-dry\" würde die Ausgabe des Projekts \"{0}\" aktualisieren.", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen", "Add_0_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"{0}.\" hinzufügen", + "Add_a_return_statement_95111": "return-Anweisung hinzufügen", "Add_all_missing_async_modifiers_95041": "Alle fehlenden async-Modifizierer hinzufügen", "Add_all_missing_call_parentheses_95068": "Alle fehlenden Klammern in Aufrufen hinzufügen", "Add_all_missing_imports_95064": "Alle fehlenden Importe hinzufügen", "Add_all_missing_members_95022": "Alle fehlenden Member hinzufügen", + "Add_all_missing_return_statement_95114": "Alle fehlenden return-Anweisungen hinzufügen", "Add_all_missing_super_calls_95039": "Alle fehlenden super-Aufrufe hinzufügen", "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", "Add_await_95083": "\"await\" hinzufügen", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "Standardimport \"{0}\" zur vorhandenen Importdeklaration aus \"{1}\" hinzufügen", "Add_definite_assignment_assertion_to_property_0_95020": "Definitive Zuweisungsassertion zu Eigenschaft \"{0}\" hinzufügen", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Allen nicht initialisierten Eigenschaften definitive Zuweisungsassertionen hinzufügen", - "Add_export_to_make_this_file_into_a_module_95097": "\"export {}\" hinzufügen, um diese Datei zu einem Modul zu machen", + "Add_export_to_make_this_file_into_a_module_95097": "\"export {}\" hinzufügen, um diese Datei in ein Modul umzuwandeln", "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", "Add_initializer_to_property_0_95019": "Initialisierer zu Eigenschaft \"{0}\" hinzufügen", "Add_initializers_to_all_uninitialized_properties_95027": "Allen nicht initialisierten Eigenschaften Initialisierer hinzufügen", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ein Importpfad darf nicht mit einer Erweiterung \"{0}\" enden. Importieren Sie ggf. stattdessen \"{1}\".", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Ein Indexausdrucksargument muss vom Typ \"string\", \"number\", \"symbol\" oder \"any\" sein.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Eine Indexsignatur darf keinen rest-Parameter besitzen.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Eine Indexsignatur darf kein nachstehendes Komma aufweisen.", "An_index_signature_must_have_a_type_annotation_1021": "Eine Indexsignatur muss eine Typanmerkung besitzen.", "An_index_signature_must_have_exactly_one_parameter_1096": "Eine Indexsignatur muss genau einen Parameter besitzen.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Ein Indexsignaturparameter darf kein Fragezeichen aufweisen.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Der Wert kann nicht durchlaufen werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, die Arrayverteilung aber immer \"{0}\" sendet.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Der Wert kann nicht durchlaufen werden, weil die next-Methode des zugehörigen Iterators den Typ \"{1}\" erwartet, \"for-of\" aber immer \"{0}\" sendet.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Das Projekt \"{0}\" kann nicht vorgestellt werden, weil \"outFile\" nicht festgelegt wurde.", + "Cannot_read_file_0_5083": "Die Datei \"{0}\" kann nicht gelesen werden.", "Cannot_read_file_0_Colon_1_5012": "Die Datei \"{0}\" kann nicht gelesen werden: {1}", "Cannot_redeclare_block_scoped_variable_0_2451": "Die blockbezogene Variable \"{0}\" Blockbereich kann nicht erneut deklariert werden.", "Cannot_redeclare_exported_variable_0_2323": "Die exportierte Variable \"{0}\" kann nicht erneut deklariert werden.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Kompilieren Sie das dem Pfad zugewiesene Projekt zu dessen Konfigurationsdatei oder zu einem Ordner mit der Datei \"tsconfig.json\".", "Compiler_option_0_expects_an_argument_6044": "Die Compileroption \"{0}\" erwartet ein Argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Die Compileroption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Der Compiler reserviert den Namen \"{0}\", wenn er einen älteren privaten Bezeichner ausgibt.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Der Compiler reserviert den Namen \"{0}\", wenn er einen privaten Bezeichner für Vorgängerversionen ausgibt.", "Composite_projects_may_not_disable_declaration_emit_6304": "In zusammengesetzten Projekten kann die Deklarationsausgabe nicht deaktiviert werden.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Zusammengesetzte Projekte dürfen die inkrementelle Kompilierung nicht deaktivieren.", "Computed_property_names_are_not_allowed_in_enums_1164": "Berechnete Eigenschaftennamen sind in Enumerationen unzulässig.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Der Pfad \"{0}\" mit den Erweiterungen konnte nicht aufgelöst werden: {1}.", "Could_not_write_file_0_Colon_1_5033": "Die Datei \"{0}\" konnte nicht geschrieben werden. {1}.", "DIRECTORY_6038": "VERZEICHNIS", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Die Deklaration erweitert die Deklaration in einer anderen Datei. Dieser Vorgang kann nicht serialisiert werden.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Zur Deklarationsausgabe für diese Datei muss der private Name \"{0}\" verwendet werden. Eine explizite Typanmerkung kann die Deklarationsausgabe freigeben.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Zur Deklarationsausgabe für diese Datei muss der private Name \"{0}\" aus dem Modul \"{1}\" verwendet werden. Eine explizite Typanmerkung kann die Deklarationsausgabe freigeben.", "Declaration_expected_1146": "Es wurde eine Deklaration erwartet.", @@ -606,7 +612,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "Die Importdeklaration \"{0}\" verwendet den privaten Namen \"{1}\".", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Die Importdeklaration verursacht einen Konflikt mit der lokalen Deklaration von \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Importdeklarationen in einem Namespace dürfen nicht auf ein Modul verweisen.", - "Import_default_0_from_module_1_90032": "Importstandard \"{0}\" aus Modul \"{1}\"", + "Import_default_0_from_module_1_90032": "Standard \"{0}\" aus Modul \"{1}\" importieren", "Import_emit_helpers_from_tslib_6139": "Ausgabehilfsprogramme aus \"tslib\" importieren.", "Import_may_be_converted_to_a_default_import_80003": "Der Import kann in einen Standardimport konvertiert werden.", "Import_name_cannot_be_0_2438": "Der Importname darf nicht \"{0}\" sein.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Eigenschaft \"{0}\" im Konstruktor initialisieren", "Initialize_static_property_0_90021": "Statische Eigenschaft \"{0}\" initialisieren", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Der Initialisierer der Instanzmembervariablen \"{0}\" darf nicht auf den im Konstruktor deklarierten Bezeichner \"{1}\" verweisen.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Initialisierer des Parameters \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Der Initialisierer stellt keinen Wert für dieses Bindungselement bereit, und das Bindungselement besitzt keinen Standardwert.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Initialisierer sind in Umgebungskontexten unzulässig.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialisiert ein TypeScript-Projekt und erstellt eine Datei \"tsconfig.json\".", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Ungültige Verwendung von \"{0}\" im Strict-Modus.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Ungültiger Wert für \"jsxFactory\". \"{0}\" ist kein gültiger Bezeichner oder qualifizierter Name.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Ungültiger Wert für \"-reactNamespace\". \"{0}\" ist kein gültiger Bezeichner.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Der zugehörige Elementtyp \"{0}\" ist kein gültiges JSX-Element.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Der zugehörige Instanztyp \"{0}\" ist kein gültiges JSX-Element.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Der Rückgabetyp \"{0}\" ist kein gültiges JSX-Element.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" entspricht nicht der Klausel \"extends {2}\".", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" ist keiner Klassendeklaration zugeordnet.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Das JSDoc-Tag \"...\" wird möglicherweise nur im letzten Parameter einer Signatur angezeigt.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Geben Sie nur .d.ts-Deklarationsdateien aus.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Derzeit werden nur Bezeichner/qualifizierte Namen mit optionalen Typargumenten in den \"extends\"-Klauseln einer Klasse unterstützt.", "Only_named_exports_may_use_export_type_1383": "\"Exporttyp\" kann nur von benannten Exporten verwendet werden.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Nur numerische Enumerationen können berechnete Member umfassen, aber dieser Ausdruck weist den Typ \"{0}\" auf. Wenn Sie keine Vollständigkeitsprüfung benötigen, erwägen Sie stattdessen die Verwendung eines Objektliterals.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Nur auf öffentliche und geschützte Methoden der Basisklasse kann über das Schlüsselwort \"super\" zugegriffen werden.", "Operator_0_cannot_be_applied_to_type_1_2736": "Der Operator \"{0}\" kann nicht auf den Typ \"{1}\" angewendet werden.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Der Operator \"{0}\" darf nicht auf die Typen \"{1}\" und \"{2}\" angewendet werden.", @@ -799,7 +808,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Überladungssignaturen müssen alle exportiert oder nicht exportiert sein.", "Overload_signatures_must_all_be_optional_or_required_2386": "Überladungssignaturen müssen alle optional oder erforderlich sein.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Überladungssignaturen müssen alle öffentlich, privat oder geschützt sein.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Auf den Parameter \"{0}\" darf in diesem Initialisierer nicht verwiesen werden.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Der Parameter \"{0}\" darf nicht auf den anschließend deklarierten Bezeichner \"{1}\" verweisen.", + "Parameter_0_cannot_reference_itself_2372": "Der Parameter \"{0}\" kann nicht auf sich selbst verweisen.", "Parameter_0_implicitly_has_an_1_type_7006": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Der Parameter \"{0}\" weist implizit einen Typ \"{1}\" auf, möglicherweise kann jedoch ein besserer Typ aus der Syntax abgeleitet werden.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Der Parameter \"{0}\" befindet sich nicht an der gleichen Position wie der Parameter \"{1}\".", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "Die Eigenschaft \"{0}\" ist für die const-Enumeration \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_2339": "Die Eigenschaft \"{0}\" ist für den Typ \"{1}\" nicht vorhanden.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Die Eigenschaft \"{0}\" existiert nicht für Typ \"{1}\". Meinten Sie \"{2}\"?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Eigenschaft \"{0}\" weist widersprüchliche Deklarationen auf und ein Zugriff in Typ \"{1}\" ist nicht möglich.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Das erneute Exportieren eines Typs erfordert bei Festlegung des Flags \"--isolatedModules\" die Verwendung von \"export type\".", "Redirect_output_structure_to_the_directory_6006": "Die Ausgabestruktur in das Verzeichnis umleiten.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Das referenzierte Projekt \"{0}\" muss für die Einstellung \"composite\" den Wert TRUE aufweisen.", + "Remove_all_incorrect_body_block_braces_95115": "Alle falschen geschweiften Klammern aus Textblock entfernen", "Remove_all_unnecessary_uses_of_await_95087": "Alle nicht benötigten Verwendungen von \"await\" entfernen", "Remove_all_unreachable_code_95051": "Gesamten nicht erreichbaren Code entfernen", "Remove_all_unused_labels_95054": "Alle nicht verwendeten Bezeichnungen entfernen", + "Remove_block_body_braces_95112": "Geschweifte Klammern aus Blocktextkörper entfernen", "Remove_braces_from_arrow_function_95060": "Geschweifte Klammern aus Pfeilfunktion entfernen", "Remove_destructuring_90009": "Destrukturierung entfernen", "Remove_import_from_0_90005": "Import aus \"{0}\" entfernen", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Die Metaeigenschaft \"import.meta\" ist nur zulässig, wenn die Option \"--module\" den Wert \"esnext\" oder \"system\" aufweist.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Der abgeleitete Typ von \"{0}\" kann nicht ohne einen Verweis auf \"{1}\" benannt werden. Eine Portierung ist wahrscheinlich nicht möglich. Eine Typanmerkung ist erforderlich.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Der abgeleitete Typ von \"{0}\" verweist auf einen Typ \"{1}\", auf den nicht zugegriffen werden kann. Eine Typanmerkung ist erforderlich.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Die Schnittmenge \"{0}\" wurde auf \"niemals\" reduziert, weil die Eigenschaft \"{1}\" in mehreren Bestandteilen vorhanden und in einigen davon privat ist.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Die Schnittmenge \"{0}\" wurde auf \"niemals\" reduziert, weil die Eigenschaft \"{1}\" in einigen Bestandteilen widersprüchliche Typen aufweist.", "The_last_overload_gave_the_following_error_2770": "Die letzte Überladung hat den folgenden Fehler verursacht.", "The_last_overload_is_declared_here_2771": "Die letzte Überladung wird hier deklariert.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Die linke Seite einer for...in-Anweisung darf kein Destrukturierungsmuster sein.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Der Operand eines delete-Operators darf kein privater Bezeichner sein.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Der Operand eines delete-Operators darf keine schreibgeschützte Eigenschaft sein.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Der Operand eines delete-Operators muss ein Eigenschaftenverweis sein.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Der Operand eines delete-Operators muss optional sein.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Der Operand eines Inkrement- oder Dekrementoperators darf kein optionaler Eigenschaftenzugriff sein.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable oder ein Eigenschaftenzugriff sein.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "Der Parser hat eine entsprechende Klammer \"}\" zu dem hier vorhandenen Token \"{\" erwartet.", @@ -1109,7 +1123,7 @@ "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Die rechte Seite einer arithmetischen Operation muss den Typ \"any\", \"number\" oder \"bigint\" aufweisen oder ein Enumerationstyp sein.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "Die rechte Seite eines in-Ausdrucks muss den Typ \"any\" aufweisen oder ein Objekttyp bzw. ein Typparameter sein.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Die rechte Seite eines instanceof-Ausdrucks muss den Typ \"any\" oder einen Typ aufweisen, der dem Schnittstellentyp \"Function\" zugewiesen werden kann.", - "The_shadowing_declaration_of_0_is_defined_here_18017": "Die Shadowing-Deklaration von \"{0}\" ist hier definiert.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "Die verbergende Deklaration von \"{0}\" ist hier definiert.", "The_specified_path_does_not_exist_Colon_0_5058": "Der angegebene Pfad \"{0}\" ist nicht vorhanden.", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "Das Ziel einer Zuweisung muss eine Variable oder ein Eigenschaftenzugriff sein.", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "Das Ziel einer rest-Zuweisung für ein Objekt darf kein optionaler Eigenschaftenzugriff sein.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Dieser Ausdruck kann nicht aufgerufen werden.", "This_expression_is_not_constructable_2351": "Dieser Ausdruck kann nicht erstellt werden.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Dieser Import wird nie als Wert verwendet und muss \"import type\" verwenden, weil \"importsNotUsedAsValues\" auf \"error\" festgelegt ist.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Dies ist die erweiterte Deklaration. Die erweiternde Deklaration sollte in dieselbe Datei verschoben werden.", "This_may_be_converted_to_an_async_function_80006": "Es kann eine Konvertierung in ein asynchrone Funktion durchgeführt werden.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Auf dieses Modul kann nur mit ECMAScript-Importen/-Exporten verwiesen werden, indem das Flag \"{0}\" aktiviert und auf den Standardexport verwiesen wird.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Dieses Modul wird mit \"export =\" deklariert und kann nur bei Verwendung des Flags \"{0}\" mit einem Standardimport verwendet werden.", @@ -1158,8 +1173,8 @@ "Type_0_has_no_construct_signatures_2761": "Der Typ \"{0}\" weist keine Konstruktsignaturen auf.", "Type_0_has_no_matching_index_signature_for_type_1_2537": "Der Typ \"{0}\" weist keine übereinstimmende Indexsignatur für den Typ \"{1}\" auf.", "Type_0_has_no_properties_in_common_with_type_1_2559": "Der Typ \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit Typ \"{1}\".", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": {2}", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": {2} und {3} weitere.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": \"{2}\".", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "Im Typ \"{0}\" fehlen die folgenden Eigenschaften von Typ \"{1}\": \"{2}\" und {3} weitere.", "Type_0_is_not_a_constructor_function_type_2507": "Der Typ \"{0}\" ist kein Konstruktorfunktionstyp.", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Der Typ \"{0}\" ist in ES5/ES3 kein gültiger Rückgabetyp einer asynchronen Funktion, weil er nicht auf einen Promise-kompatiblen Konstruktorwert verweist.", "Type_0_is_not_an_array_type_2461": "Der Typ \"{0}\" ist kein Arraytyp.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Der Typ iterierter Elemente eines \"yield*\"-Operanden muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Der Typ der Eigenschaft \"{0}\" verweist im zugeordneten Typ \"{1}\" auf sich selbst.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Der Typ eines \"yield\"-Operanden in einem asynchronen Generator muss entweder eine gültige Zusage sein oder darf keinen aufrufbaren \"then\"-Member enthalten.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Der Typ stammt aus diesem Import. Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler. Erwägen Sie hier stattdessen die Verwendung eines Standardimports oder die Verwendung von \"import require\".", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Der Typ stammt aus diesem Import. Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler. Erwägen Sie hier stattdessen die Verwendung eines Standardimports oder die den Import über \"require\".", "Type_parameter_0_has_a_circular_constraint_2313": "Der Typparameter \"{0}\" weist eine zirkuläre Einschränkung auf.", "Type_parameter_0_has_a_circular_default_2716": "Der Typparameter \"{0}\" besitzt einen zirkulären Standardwert.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Der Typparameter \"{0}\" der Aufrufsignatur aus der exportierten Schnittstelle besitzt oder verwendet den privaten Namen \"{1}\".", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Eine Variablendeklaration wurde erwartet.", "Variable_declaration_list_cannot_be_empty_1123": "Die Variablendeklarationsliste darf nicht leer sein.", "Version_0_6029": "Version {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Besuchen Sie https://aka.ms/tsconfig.json, um mehr über diese Datei zu erfahren.", "Watch_input_files_6005": "Eingabedateien überwachen.", "Watch_option_0_requires_a_value_of_type_1_5080": "Die Überwachungsoption \"{0}\" erfordert einen Wert vom Typ \"{1}\".", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Gibt an, ob eine veraltete Konsolenausgabe im Überwachungsmodus beibehalten wird, statt den Bildschirm zu löschen.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Alle ungültigen Zeichen mit einem Ausdruckscontainer umschließen", + "Wrap_all_object_literal_with_parentheses_95116": "Gesamtes Objektliteral in Klammern einschließen", "Wrap_invalid_character_in_an_expression_container_95108": "Ungültiges Zeichen mit Ausdruckscontainer umschließen", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Schließen Sie den folgenden Text, der ein Objektliteral darstellt, in Klammern ein.", "You_cannot_rename_a_module_via_a_global_import_8031": "Ein Modul kann nicht über einen globalen Import umbenannt werden.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Sie können keine Elemente umbenennen, die in der TypeScript-Standardbibliothek definiert sind.", "You_cannot_rename_this_element_8000": "Sie können dieses Element nicht umbenennen.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" akzeptiert zu wenige Argumente, um hier als Decorator verwendet zu werden. Wollten Sie es zuerst aufrufen und \"@{0}()\" schreiben?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Die Vorgänge \"{0}\" und \"{1}\" dürfen nicht ohne Klammern kombiniert werden.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" ist zweimal angegeben. Das Attribut mit dem Namen \"{0}\" wird überschrieben.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "\"{0}\" kann nur importiert werden, indem das Flag \"esModuleInterop\" aktiviert und ein Standardimport verwendet wird.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "\"{0}\" kann nur mithilfe eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "\"{0}\" kann nur mit einem Aufruf von \"require\" oder durch Aktivieren des Flags \"esModuleInterop\" und Verwendung eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "\"{0}\" kann nur mit einem Aufruf von \"require\" oder durch Verwendung eines Standardimports importiert werden.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "\"{0}\" kann nur mit \"import {1} = require({2})\" oder über einen Standardimport importiert werden.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "\"{0}\" kann nur mit \"import {1} = require({2})\" oder durch Aktivieren des Flags \"esModuleInterop\" und Verwendung eines Standardimports importiert werden.", + "_0_cannot_be_used_as_a_JSX_component_2786": "\"{0}\" kann nicht als JSX-Komponente verwendet werden.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "\"{0}\" kann nicht als Wert verwendet werden, weil der Export mit \"export type\" durchgeführt wurde.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "\"{0}\" kann nicht als Wert verwendet werden, weil der Import mit \"import type\" durchgeführt wurde.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "{0}-Komponenten akzeptieren Text nicht als untergeordnete Elemente. Der Text in der JSX weist den Typ \"string\" auf, aber für \"{1}\" wird der Typ \"{2}\" erwartet.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "\"#constructor\" ist ein reserviertes Wort.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "\"delete\" kann für einen Bezeichner im Strict-Modus nicht aufgerufen werden.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "Dies löschen – Projekt \"{0}\" ist auf dem neuesten Stand, da es bereits zuvor erstellt wurde", + "export_Asterisk_does_not_re_export_a_default_1195": "Mit \"export *\" wird ein Standardwert nicht erneut exportiert.", "export_can_only_be_used_in_TypeScript_files_8003": "\"export =\" kann nur in TypeScript-Dateien verwendet werden.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Der Modifizierer \"export\" kann nicht auf Umgebungsmodule und Modulerweiterungen angewendet werden, da diese immer sichtbar sind.", "extends_clause_already_seen_1172": "Die extends-Klausel ist bereits vorhanden.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 9883d9b0a866e..914d8b4c7c136 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -44,7 +44,7 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "Un generador no puede tener una anotación de tipo \"void\".", "A_get_accessor_cannot_have_parameters_1054": "Un descriptor de acceso \"get\" no puede tener parámetros.", "A_get_accessor_must_return_a_value_2378": "Un descriptor de acceso \"get\" debe devolver un valor.", - "A_label_is_not_allowed_here_1344": "Aquí no se permite una etiqueta.", + "A_label_is_not_allowed_here_1344": "No se permite una etiqueta aquí.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un inicializador de miembro de una declaración de enumeración no puede hacer referencia a los miembros que se declaran después de este, incluidos aquellos definidos en otras enumeraciones.", "A_method_cannot_be_named_with_a_private_identifier_18022": "No se puede denominar un método con un identificador privado.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Una clase mixin debe tener un constructor con un solo parámetro rest de tipo \"any[]\"", @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en un espacio de nombres o en un módulo.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Una expresión \"new\" con argumentos de tipo siempre debe ir seguida de una lista de argumentos entre paréntesis.", "A_non_dry_build_would_build_project_0_6357": "Una compilación no -dry compilaría el proyecto \"{0}\"", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Una compilación no -dry eliminaría los archivos siguientes: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Una compilación no -dry actualizaría la salida del proyecto \"{0}\".", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", "Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"", "Add_0_to_unresolved_variable_90008": "Agregar \"{0}.\" a una variable no resuelta", + "Add_a_return_statement_95111": "Agregar una instrucción \"return\"", "Add_all_missing_async_modifiers_95041": "Agregar todos los modificadores \"async\" que faltan", "Add_all_missing_call_parentheses_95068": "Agregar todos los paréntesis de llamada que faltan", "Add_all_missing_imports_95064": "Agregar todas las importaciones que faltan", "Add_all_missing_members_95022": "Agregar todos los miembros que faltan", + "Add_all_missing_return_statement_95114": "Agregar todas las instrucciones \"return\" que faltan", "Add_all_missing_super_calls_95039": "Agregar todas las llamadas a super que faltan", "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", "Add_await_95083": "Agregar \"await\"", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "Agregar la importación \"{0}\" predeterminada a la declaración de importación existente de \"{1}\"", "Add_definite_assignment_assertion_to_property_0_95020": "Agregar aserción de asignación definitiva a la propiedad \"{0}\"", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Agregar aserciones de asignación definitiva a todas las propiedades sin inicializar", - "Add_export_to_make_this_file_into_a_module_95097": "Agregar \"export {}\" para convertir este archivo en un módulo", + "Add_export_to_make_this_file_into_a_module_95097": "Agregar \"export {}\" para transformar este archivo en un módulo", "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", "Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Una ruta de acceso de importación no puede terminar con una extensión '{0}'. Puede importar '{1}' en su lugar.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argumento de expresión de índice debe ser de tipo \"string\", \"number\", \"symbol\" o \"any\".", "An_index_signature_cannot_have_a_rest_parameter_1017": "Una signatura de índice no puede tener un parámetro rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Una signatura de índice no puede finalizar con una coma.", "An_index_signature_must_have_a_type_annotation_1021": "Una signatura de índice debe tener una anotación de tipo.", "An_index_signature_must_have_exactly_one_parameter_1096": "Una signatura de índice debe tener exactamente un parámetro.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parámetro de signatura de índice no puede tener un signo de interrogación.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "No se puede iterar el valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero la propagación de matriz siempre enviará \"{0}\".", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "No se puede iterar el valor porque el método \"next\" de su iterador espera el tipo \"{1}\", pero for-of siempre enviará \"{0}\".", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "No se puede anteponer el proyecto \"{0}\" porque no se ha establecido \"outFile\".", + "Cannot_read_file_0_5083": "No se puede leer el archivo \"{0}\".", "Cannot_read_file_0_Colon_1_5012": "No se puede leer el archivo \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "No se puede volver a declarar la variable con ámbito de bloque '{0}'.", "Cannot_redeclare_exported_variable_0_2323": "No se puede volver a declarar la variable '{0}' exportada.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila el proyecto teniendo en cuenta la ruta de acceso a su archivo de configuración o a una carpeta con un archivo \"tsconfig.json\".", "Compiler_option_0_expects_an_argument_6044": "La opción '{0}' del compilador espera un argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "La opción '{0}' del compilador requiere un valor de tipo {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "El compilador reserva el nombre \"{0}\" al emitir un identificador privado en el nivel inferior.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "El compilador reserva el nombre \"{0}\" al emitir un identificador privado válido para versiones anteriores.", "Composite_projects_may_not_disable_declaration_emit_6304": "Los proyectos compuestos no pueden deshabilitar la emisión de declaración.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Los proyectos compuestos no pueden deshabilitar la compilación incremental.", "Computed_property_names_are_not_allowed_in_enums_1164": "No se permiten nombres de propiedad calculada en las enumeraciones.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "No se pudo resolver la ruta de acceso \"{0}\" con las extensiones: {1}.", "Could_not_write_file_0_Colon_1_5033": "No se puede escribir en el archivo \"{0}\": \"{1}\".", "DIRECTORY_6038": "DIRECTORIO", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "La declaración aumenta la declaración en otro archivo. Esto no se puede serializar.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "La emisión de declaración para este archivo requiere el uso del nombre privado \"{0}\". Una anotación de tipo explícito puede desbloquear la emisión de declaración.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "La emisión de declaración para este archivo requiere el uso del nombre privado \"{0}\" del módulo \"{1}\". Una anotación de tipo explícito puede desbloquear la emisión de declaración.", "Declaration_expected_1146": "Se esperaba una declaración.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Inicializar la propiedad \"{0}\" en el constructor", "Initialize_static_property_0_90021": "Inicializar la propiedad estática \"{0}\"", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "El inicializador de la variable miembro de instancia '{0}' no puede hacer referencia al identificador '{1}' declarado en el constructor.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El inicializador del parámetro '{0}' no puede hacer referencia al identificador '{1}' declarado después.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "El inicializador no proporciona ningún valor para este elemento de enlace que, a su vez, no tiene un valor predeterminado.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "No se permiten inicializadores en los contextos de ambiente.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa un proyecto de TypeScript y crea un archivo tsconfig.json.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso no válido de '{0}' en modo strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor no válido para \"jsxFactory\". \"{0}\" no es un nombre calificado o un identificador válido.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor no válido para '--reactNamespace'. '{0}' no es un identificador válido.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "El tipo de elemento \"{0}\" no es un elemento JSX válido.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "El tipo de instancia \"{0}\" no es un elemento JSX válido.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "El tipo de valor devuelto \"{0}\" no es un elemento JSX válido.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La etiqueta \"@{0} {1}\" de JSDoc no coincide con la cláusula \"extends {2}\".", "JSDoc_0_is_not_attached_to_a_class_8022": "La etiqueta \"@{0}\" de JSDoc no está asociada a una clase.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "\"...\" de JSDoc solo puede aparecer en el último parámetro de una signatura.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Solo deben emitirse archivos de declaración \".d.ts\".", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Actualmente, solo se admiten identificadores o nombres completos con argumentos de tipo opcional en la cláusula \"extends\" de una clase.", "Only_named_exports_may_use_export_type_1383": "Solo las exportaciones con nombre pueden usar \"tipo de exportación\".", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Solo las enumeraciones numéricas pueden tener miembros calculados, pero esta expresión tiene el tipo \"{0}\". Si no requiere comprobaciones de exhaustividad, considere la posibilidad de usar un literal de objeto en su lugar.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Solo es posible tener acceso a los métodos públicos y protegidos de la clase base mediante la palabra clave \"super\".", "Operator_0_cannot_be_applied_to_type_1_2736": "El operador \"{0}\" no se puede aplicar al tipo \"{1}\".", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "El operador '{0}' no se puede aplicar a los tipos '{1}' y '{2}'.", @@ -799,7 +808,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Las signaturas de sobrecarga deben ser todas exportadas o no exportadas.", "Overload_signatures_must_all_be_optional_or_required_2386": "Las signaturas de sobrecarga deben ser todas opcionales u obligatorias.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Las signaturas de sobrecarga deben ser todas públicas, privadas o protegidas.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "No se puede hacer referencia al parámetro '{0}' en su inicializador.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "El parámetro \"{0}\" no puede hacer referencia al identificador \"{1}\" declarado después de este.", + "Parameter_0_cannot_reference_itself_2372": "El parámetro \"{0}\" no puede hacer referencia a sí mismo.", "Parameter_0_implicitly_has_an_1_type_7006": "El parámetro '{0}' tiene un tipo '{1}' implícitamente.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "El parámetro \"{0}\" tiene un tipo \"{1}\" de forma implícita, pero se puede inferir un tipo más adecuado a partir del uso.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "El parámetro '{0}' no está en la misma posición que el parámetro '{1}'.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "La propiedad '{0}' no existe en la enumeración 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propiedad '{0}' no existe en el tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propiedad \"{0}\" no existe en el tipo \"{1}\". ¿Quería decir \"{2}\"?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propiedad \"{0}\" tiene declaraciones en conflicto y no está accesible en el tipo \"{1}\".", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Para volver a exportar un tipo cuando se proporciona la marca \"--isolatedModules\", se requiere el uso de \"export type\".", "Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.", + "Remove_all_incorrect_body_block_braces_95115": "Quitar todas las llaves de cuerpo de bloque incorrectas", "Remove_all_unnecessary_uses_of_await_95087": "Quitar todos los usos innecesarios de \"await\"", "Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible", "Remove_all_unused_labels_95054": "Quitar todas las etiquetas no utilizadas", + "Remove_block_body_braces_95112": "Quitar llaves de cuerpo del bloque", "Remove_braces_from_arrow_function_95060": "Quitar las llaves de la función de flecha", "Remove_destructuring_90009": "Quitar la desestructuración", "Remove_import_from_0_90005": "Quitar importación de \"{0}\"", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "La propiedad Meta \"import.meta\" solo se permite cuando la opción \"--module\" es \"esnext\" o \"system\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "No se puede asignar un nombre al tipo inferido de \"{0}\" sin una referencia a \"{1}\". Es probable que no sea portable. Se requiere una anotación de tipo.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "El tipo inferido de \"{0}\" hace referencia a un tipo \"{1}\" no accesible. Se requiere una anotación de tipo.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "La intersección \"{0}\" se redujo a \"never\" porque la propiedad \"{1}\" existe en varios constituyentes y es privada en algunos de ellos.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "La intersección \"{0}\" se redujo a \"never\" porque la propiedad \"{1}\" tiene tipos en conflicto en algunos constituyentes.", "The_last_overload_gave_the_following_error_2770": "La última sobrecarga dio el error siguiente.", "The_last_overload_is_declared_here_2771": "La última sobrecarga se declara aquí.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte izquierda de una instrucción \"for...in\" no puede ser un patrón de desestructuración.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "El operando de un operador \"delete\" no puede ser un identificador privado.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "El operando de un operador \"delete\" no puede ser una propiedad de solo lectura.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "El operando de un operador \"delete\" debe ser una referencia de propiedad.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "El operando de un operador \"delete\" debe ser opcional.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "El operando de un operador de incremento o decremento no puede ser un acceso de propiedad opcional.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "El operando de un operador de incremento o decremento debe ser una variable o el acceso a una propiedad.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "El analizador esperaba encontrar un elemento \"}\" que coincidiera con el del token \"{\" aquí.", @@ -1109,7 +1123,7 @@ "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La parte derecha de una operación aritmética debe ser de tipo \"any\", \"number\", \"bigint\" o un tipo de enumeración.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte derecha de una expresión \"in\" debe ser de tipo \"any\", un tipo de objeto o un parámetro de tipo.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte derecha de una expresión \"instanceof\" debe ser de tipo \"any\" o un tipo que pueda asignarse al tipo de interfaz \"Function\".", - "The_shadowing_declaration_of_0_is_defined_here_18017": "La declaración de reemplazo de \"{0}\" se define aquí.", + "The_shadowing_declaration_of_0_is_defined_here_18017": "La declaración que ensombrece a \"{0}\" se define aquí.", "The_specified_path_does_not_exist_Colon_0_5058": "La ruta de acceso especificada no existe: \"{0}\".", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "El destino de la asignación debe ser una variable o el acceso a una propiedad.", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "El destino de una asignación rest de objeto no puede ser un acceso de propiedad opcional.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "No se puede llamar a esta expresión.", "This_expression_is_not_constructable_2351": "No se puede construir esta expresión.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Esta importación nunca se usa como valor y debe utilizar \"import type\" porque el valor \"importsNotUsedAsValues\" está establecido en \"error\".", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Esta es la declaración que se está aumentando. Considere la posibilidad de mover la declaración en aumento al mismo archivo.", "This_may_be_converted_to_an_async_function_80006": "Puede convertirse en una función asincrónica.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Solo se puede hacer referencia a este módulo con las importaciones o exportaciones de ECMAScript mediante la activación de la marca \"{0}\" y la referencia a su exportación predeterminada.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Este módulo se declara con \"export =\" y solo se puede usar con una importación predeterminada cuando se usa la marca \"{0}\".", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "El tipo de elementos iterados de un operando \"yield*\" debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "El tipo de propiedad \"{0}\" hace referencia circular a sí misma en el tipo asignado \"{1}\".", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "El tipo de operando \"yield\" en un generador asincrónico debe ser una promesa válida o no debe contener un miembro \"then\" invocable.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "El tipo se origina en esta importación. No se puede construir ni llamar a una importación de estilo de espacio de nombres y provocará un error en tiempo de ejecución. Considere la posibilidad de usar una importación predeterminada o requerir la importación aquí.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "El tipo se origina en esta importación. No se puede construir ni llamar a una importación de estilo de espacio de nombres y provocará un error en tiempo de ejecución. Considere la posibilidad de usar una importación predeterminada o require aquí en su lugar.", "Type_parameter_0_has_a_circular_constraint_2313": "El parámetro de tipo '{0}' tiene una restricción circular.", "Type_parameter_0_has_a_circular_default_2716": "El parámetro de tipo \"{0}\" tiene un valor circular predeterminado.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "El parámetro de tipo '{0}' de la signatura de llamada de la interfaz exportada tiene o usa el nombre privado '{1}'.", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Actualizando las marcas de hora de salida no modificadas del proyecto \"{0}\"...", "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "El uso de las opciones del compilador de la referencia del proyecto redirige \"{0}\".", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Uso de las opciones del compilador de redireccionamiento de la referencia del proyecto \"{0}\".", "VERSION_6036": "VERSIÓN", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "No se puede llamar a un valor de tipo '{0}'. ¿Pretendía incluir \"new\"?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Se esperaba una declaración de variable.", "Variable_declaration_list_cannot_be_empty_1123": "La lista de declaraciones de variable no puede estar vacía.", "Version_0_6029": "Versión {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Visite https://aka.ms/tsconfig.json para leer más información sobre este archivo", "Watch_input_files_6005": "Inspeccionar archivos de entrada.", "Watch_option_0_requires_a_value_of_type_1_5080": "La opción \"{0}\" de inspección requiere un valor de tipo {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Si se debe mantener la salida de la consola no actualizada en el modo de inspección en lugar de borrar la pantalla.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Encapsular todos los caracteres no válidos en un contenedor de expresiones", + "Wrap_all_object_literal_with_parentheses_95116": "Encapsular todos los literales de objeto entre paréntesis", "Wrap_invalid_character_in_an_expression_container_95108": "Encapsular el carácter no válido en un contenedor de expresiones", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Encapsular el cuerpo siguiente entre paréntesis, lo cual debe ser un literal de objeto", "You_cannot_rename_a_module_via_a_global_import_8031": "No se puede cambiar el nombre de un módulo mediante una importación global.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "No se puede cambiar el nombre de elementos definidos en la biblioteca TypeScript estándar.", "You_cannot_rename_this_element_8000": "No se puede cambiar el nombre a este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" no acepta suficientes argumentos para utilizarse como decorador aquí. ¿Pretendía llamar primero y escribir \"@{0}()\"?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Las operaciones \"{0}\" y \"{1}\" no se pueden mezclar sin paréntesis.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" se especifica dos veces. El atributo denominado \"{0}\" se sobrescribirá.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "\"{0}\" solo se puede importar si se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "\"{0}\" solo se puede importar si se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "\"{0}\" solo se puede importar si se usa una llamada a \"require\" o bien se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "\"{0}\" solo se puede importar si se usa una llamada a \"require\" o una importación predeterminada.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "\"{0}\" solo se puede importar si se usa \"import {1} = require({2})\" o una importación predeterminada.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "\"{0}\" solo se puede importar si se usa \"import {1} = require({2})\" o bien se activa la marca \"esModuleInterop\" y se usa una importación predeterminada.", + "_0_cannot_be_used_as_a_JSX_component_2786": "No se puede usar \"{0}\" como componente JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "No se puede usar \"{0}\" como valor porque se exportó mediante \"export type\".", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "No se puede usar \"{0}\" como valor porque se importó mediante \"import type\".", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Los componentes \"{0}\" no aceptan el texto como elemento secundario. El texto de JSX tiene el tipo \"string\", pero el tipo que se esperaba de \"{1}\" es \"{2}\".", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "\"#constructor\" es una palabra reservada.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "eliminar esto - El proyecto \"{0}\" está actualizado porque se compiló previamente", + "export_Asterisk_does_not_re_export_a_default_1195": "\"export *\" no vuelve a exportar un valor predeterminado.", "export_can_only_be_used_in_TypeScript_files_8003": "\"export =\" solo se puede usar en los archivos TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "El modificador 'export' no se puede aplicar a módulos de ambiente ni aumentos de módulos, porque siempre están visibles.", "extends_clause_already_seen_1172": "La cláusula \"extends\" ya se ha visto.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 5cc69dc6df4e2..ffb30aa23a74c 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -44,7 +44,7 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "Un générateur ne peut pas avoir d'annotation de type 'void'.", "A_get_accessor_cannot_have_parameters_1054": "Un accesseur 'get' ne peut pas avoir de paramètres.", "A_get_accessor_must_return_a_value_2378": "Un accesseur 'get' doit retourner une valeur.", - "A_label_is_not_allowed_here_1344": "'Étiquette non autorisée ici.", + "A_label_is_not_allowed_here_1344": "Étiquette non autorisée ici.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Un initialiseur de membre dans une déclaration d'enum ne peut pas référencer des membres déclarés après lui, notamment des membres définis dans d'autres enums.", "A_method_cannot_be_named_with_a_private_identifier_18022": "Une méthode ne peut pas être nommée avec un identificateur privé.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Une classe mixin doit avoir un constructeur avec un paramètre rest unique de type 'any[]'.", @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Une déclaration d'espace de noms est autorisée uniquement dans un espace de noms ou un module.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Une expression 'new' avec des arguments de type doit toujours être suivie d'une liste d'arguments entre parenthèses.", "A_non_dry_build_would_build_project_0_6357": "Une build non-dry va générer le projet '{0}'", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Une build non-dry va supprimer les fichiers suivants : {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Une build non-dry va mettre à jour la sortie du projet '{0}'", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", "Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"", "Add_0_to_unresolved_variable_90008": "Ajouter '{0}.' à la variable non résolue", + "Add_a_return_statement_95111": "Ajouter une instruction return", "Add_all_missing_async_modifiers_95041": "Ajouter tous les modificateurs 'async' manquants", "Add_all_missing_call_parentheses_95068": "Ajouter toutes les parenthèses d'appel manquantes", "Add_all_missing_imports_95064": "Ajouter toutes les importations manquantes", "Add_all_missing_members_95022": "Ajouter tous les membres manquants", + "Add_all_missing_return_statement_95114": "Ajouter toutes les instructions return manquantes", "Add_all_missing_super_calls_95039": "Ajouter tous les appels super manquants", "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", "Add_await_95083": "Ajouter 'await'", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un chemin d'importation ne peut pas finir par une extension '{0}'. Importez '{1}' à la place.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argument d'expression d'index doit être de type 'string', 'number', 'symbol' ou 'any'.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Une signature d'index ne peut pas avoir de paramètre rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Une signature d'index ne peut pas avoir de virgule de fin.", "An_index_signature_must_have_a_type_annotation_1021": "Une signature d'index doit avoir une annotation de type.", "An_index_signature_must_have_exactly_one_parameter_1096": "Une signature d'index doit avoir un seul paramètre.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un paramètre de signature d'index ne peut pas contenir de point d'interrogation.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Impossible d'itérer la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais la diffusion de tableau envoie toujours '{0}'.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Impossible d'itérer la valeur, car la méthode 'next' de son itérateur attend le type '{1}', mais la boucle for-of envoie toujours '{0}'.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Impossible de préfixer le projet '{0}', car 'outFile' n'est pas défini", + "Cannot_read_file_0_5083": "Impossible de lire le fichier '{0}'.", "Cannot_read_file_0_Colon_1_5012": "Impossible de lire le fichier '{0}' : {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Impossible de redéclarer la variable de portée de bloc '{0}'.", "Cannot_redeclare_exported_variable_0_2323": "Impossible de redéclarer la variable exportée '{0}'.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compilez le projet en fonction du chemin de son fichier config ou d'un dossier contenant 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "L'option de compilateur '{0}' attend an argument.", "Compiler_option_0_requires_a_value_of_type_1_5024": "L'option de compilateur '{0}' exige une valeur de type {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Le compilateur réserve le nom '{0}' quand il émet un identificateur privé de niveau inférieur.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Le compilateur réserve le nom '{0}' quand il émet un identificateur privé pour une version antérieure.", "Composite_projects_may_not_disable_declaration_emit_6304": "Les projets composites ne doivent pas désactiver l'émission de déclaration.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Les projets composites ne doivent pas désactiver la compilation incrémentielle.", "Computed_property_names_are_not_allowed_in_enums_1164": "Les noms de propriétés calculées ne sont pas autorisés dans les enums.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Impossible de résoudre le chemin '{0}' avec les extensions {1}.", "Could_not_write_file_0_Colon_1_5033": "Impossible d'écrire le fichier '{0}' : {1}.", "DIRECTORY_6038": "RÉPERTOIRE", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "La déclaration augmente la déclaration dans un autre fichier. Cela ne peut pas être sérialisé.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "L'émission de déclaration pour ce fichier nécessite l'utilisation du nom privé '{0}'. Une annotation de type explicite peut débloquer l'émission de déclaration.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "L'émission de déclaration pour ce fichier nécessite l'utilisation du nom privé '{0}' à partir du module '{1}'. Une annotation de type explicite peut débloquer l'émission de déclaration.", "Declaration_expected_1146": "Déclaration attendue.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Initialiser la propriété '{0}' dans le constructeur", "Initialize_static_property_0_90021": "Initialiser la propriété statique '{0}'", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'initialiseur de la variable membre d'instance '{0}' ne peut pas référencer l'identificateur '{1}' déclaré dans le constructeur.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'initialiseur du paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'initialiseur ne fournit aucune valeur pour cet élément de liaison, et ce dernier n'a pas de valeur par défaut.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Les initialiseurs ne sont pas autorisés dans les contextes ambiants.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Initialise un projet TypeScript et crée un fichier tsconfig.json.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Utilisation non valide de '{0}' en mode strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valeur non valide pour 'jsxFactory'. '{0}' n'est pas un identificateur valide ou un nom qualifié.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valeur non valide pour '--reactNamespace'. '{0}' n'est pas un identificateur valide.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Son type d'élément '{0}' n'est pas un élément JSX valide.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Son type d'instance '{0}' n'est pas un élément JSX valide.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Son type de retour '{0}' n'est pas un élément JSX valide.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "La balise JSDoc '@{0} {1}' ne correspond pas à la clause 'extends {2}'.", "JSDoc_0_is_not_attached_to_a_class_8022": "La balise JSDoc '@{0}' n'est pas attachée à une classe.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' peut apparaître uniquement dans le dernier paramètre d'une signature.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Émettez uniquement les fichiers de déclaration '.d.ts'.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Seuls les identificateurs/noms qualifiés avec des arguments de type facultatifs sont pris en charge dans une clause 'extends' de classe.", "Only_named_exports_may_use_export_type_1383": "Seules les exportations nommées peuvent utiliser 'export type'.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Seules les enums numériques peuvent avoir des membres calculés, mais cette expression a le type '{0}'. Si vous n'avez pas besoin de contrôles d'exhaustivité, utilisez un littéral d'objet à la place.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Seules les méthodes publiques et protégées de la classe de base sont accessibles par le biais du mot clé 'super'.", "Operator_0_cannot_be_applied_to_type_1_2736": "Impossible d'appliquer l'opérateur '{0}' au type '{1}'.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Impossible d'appliquer l'opérateur '{0}' aux types '{1}' et '{2}'.", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "Répertoire de sortie pour les fichiers de déclaration générés.", "Output_file_0_from_project_1_does_not_exist_6309": "Le fichier de sortie '{0}' du projet '{1}' n'existe pas", "Output_file_0_has_not_been_built_from_source_file_1_6305": "Le fichier de sortie '{0}' n'a pas été créé à partir du fichier source '{1}'.", - "Overload_0_of_1_2_gave_the_following_error_2772": "La surcharge {0} de {1}, '{2}', a généré l'erreur suivante.", + "Overload_0_of_1_2_gave_the_following_error_2772": "La surcharge {0} sur {1}, '{2}', a généré l'erreur suivante.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Les signatures de surcharge doivent toutes être abstraites ou non abstraites.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Les signatures de surcharge doivent toutes être ambiantes ou non ambiantes.", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Les signatures de surcharge doivent toutes être exportées ou non exportées.", "Overload_signatures_must_all_be_optional_or_required_2386": "Les signatures de surcharge doivent toutes être facultatives ou requises.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Les signatures de surcharge doivent toutes être publiques, privées ou protégées.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Le paramètre '{0}' ne peut pas être référencé dans son initialiseur.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Le paramètre '{0}' ne peut pas référencer l'identificateur '{1}' déclaré après lui.", + "Parameter_0_cannot_reference_itself_2372": "Le paramètre '{0}' ne peut pas se référencer lui-même.", "Parameter_0_implicitly_has_an_1_type_7006": "Le paramètre '{0}' possède implicitement un type '{1}'.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Le paramètre '{0}' a implicitement un type '{1}', mais il est possible de déduire un meilleur type à partir de l'utilisation.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Le paramètre '{0}' n'est pas à la même position que le paramètre '{1}'.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "La propriété '{0}' n'existe pas sur l'enum 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La propriété '{0}' n'existe pas sur le type '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La propriété '{0}' n'existe pas sur le type '{1}'. Est-ce qu'il ne s'agit pas plutôt de '{2}' ?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La propriété '{0}' a des déclarations en conflit et est inaccessible dans le type '{1}'.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "La réexportation d'un type quand l'indicateur '--isolatedModules' est spécifié nécessite l'utilisation de 'export type'.", "Redirect_output_structure_to_the_directory_6006": "Rediriger la structure de sortie vers le répertoire.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Le projet référencé '{0}' doit avoir le paramètre \"composite\" avec la valeur true.", + "Remove_all_incorrect_body_block_braces_95115": "Supprimer toutes les accolades de corps de bloc incorrectes", "Remove_all_unnecessary_uses_of_await_95087": "Supprimer toutes les utilisations non nécessaires de 'await'", "Remove_all_unreachable_code_95051": "Supprimer tout le code inaccessible", "Remove_all_unused_labels_95054": "Supprimer toutes les étiquettes inutilisées", + "Remove_block_body_braces_95112": "Supprimer les accolades de corps de bloc", "Remove_braces_from_arrow_function_95060": "Supprimer les accolades de la fonction arrow", "Remove_destructuring_90009": "Supprimer la déstructuration", "Remove_import_from_0_90005": "Supprimer l'importation de '{0}'", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "La métapropriété 'import.meta' est autorisée uniquement quand l'option '--module' a la valeur 'esnext' ou 'system'.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Le type déduit de '{0}' ne peut pas être nommé sans référence à '{1}'. Cela n'est probablement pas portable. Une annotation de type est nécessaire.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Le type déduit de '{0}' référence un type '{1}' inaccessible. Une annotation de type est nécessaire.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "L'intersection '{0}' a été réduite à 'never', car la propriété '{1}' existe dans plusieurs constituants et est privée dans certains d'entre eux.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "L'intersection '{0}' a été réduite à 'never', car la propriété '{1}' a des types en conflit dans certains constituants.", "The_last_overload_gave_the_following_error_2770": "La dernière surcharge a généré l'erreur suivante.", "The_last_overload_is_declared_here_2771": "La dernière surcharge est déclarée ici.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La partie gauche d'une instruction 'for...in' ne peut pas être un modèle de déstructuration.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "L'opérande d'un opérateur 'delete' ne peut pas être un identificateur privé.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'opérande d'un opérateur 'delete' ne peut pas être une propriété en lecture seule.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'opérande d'un opérateur 'delete' doit être une référence de propriété.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "L'opérande d'un opérateur 'delete' doit être facultatif.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "L'opérande d'un opérateur d'incrémentation ou de décrémentation ne doit pas être un accès à une propriété facultative.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être un accès à une variable ou une propriété.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "L'analyseur s'attendait à trouver '}' pour correspondre au jeton '{' ici.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Impossible d'appeler cette expression.", "This_expression_is_not_constructable_2351": "Impossible de construire cette expression.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Cette importation n'est jamais utilisée en tant que valeur. Elle doit utiliser 'import type', car 'importsNotUsedAsValues' a la valeur 'error'.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Ceci est la déclaration augmentée. Pensez à déplacer la déclaration d'augmentation dans le même fichier.", "This_may_be_converted_to_an_async_function_80006": "Ceci peut être converti en fonction asynchrone.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Vous pouvez référencer ce module uniquement avec les importations/exportations ECMAScript en activant l'indicateur '{0}' et en référençant son exportation par défaut.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Ce module est déclaré à l'aide de 'export =' et peut être utilisé uniquement avec une importation par défaut quand l'indicateur '{0}' est employé.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Le type des éléments itérés d'un opérande 'yield*' doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Le type de la propriété '{0}' se référence de façon circulaire dans le type mappé '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Le type d'un opérande 'yield' dans un générateur asynchrone doit être une promesse valide ou ne doit contenir aucun membre 'then' pouvant être appelé.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Le type provient de cette importation. Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution. À la place, utilisez une importation par défaut ou une obligation d'importation ici.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Le type provient de cette importation. Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution. À la place, utilisez ici une importation par défaut ou une importation avec require.", "Type_parameter_0_has_a_circular_constraint_2313": "Le paramètre de type '{0}' possède une contrainte circulaire.", "Type_parameter_0_has_a_circular_default_2716": "Le paramètre de type '{0}' a une valeur par défaut circulaire.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Le paramètre de type '{0}' de la signature d'appel de l'interface exportée possède ou utilise le nom privé '{1}'.", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Déclaration de variable attendue.", "Variable_declaration_list_cannot_be_empty_1123": "La liste des déclarations de variable ne peut pas être vide.", "Version_0_6029": "Version {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Visitez https://aka.ms/tsconfig.json pour en savoir plus sur ce fichier", "Watch_input_files_6005": "Fichiers d'entrée d'espion.", "Watch_option_0_requires_a_value_of_type_1_5080": "L'option de surveillance '{0}' nécessite une valeur de type {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Garder la sortie de console obsolète en mode espion au lieu d'effacer l'écran.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Inclure dans un wrapper tous les caractères non valides au sein d'un conteneur d'expressions", + "Wrap_all_object_literal_with_parentheses_95116": "Placer tous les littéraux d'objet entre parenthèses", "Wrap_invalid_character_in_an_expression_container_95108": "Inclure dans un wrapper un caractère non valide au sein d'un conteneur d'expressions", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Placer le corps suivant entre parenthèses pour indiquer qu'il s'agit d'un littéral d'objet", "You_cannot_rename_a_module_via_a_global_import_8031": "Vous ne pouvez pas renommer un module via une importation globale.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Vous ne pouvez pas renommer des éléments définis dans la bibliothèque TypeScript standard.", "You_cannot_rename_this_element_8000": "Vous ne pouvez pas renommer cet élément.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accepte trop peu d'arguments pour pouvoir être utilisé ici en tant qu'élément décoratif. Voulez-vous vraiment l'appeler d'abord et écrire '@{0}()' ?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Les opérations '{0}' et '{1}' ne peuvent pas être mélangées sans parenthèses.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' spécifié deux fois. L'attribut nommé '{0}' va être remplacé.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' peut uniquement être importé via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' peut uniquement être importé via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' peut uniquement être importé à l'aide d'un appel 'require' ou via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' peut uniquement être importé à l'aide d'un appel 'require' ou via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' peut uniquement être importé à l'aide de 'import {1} = require({2})' ou via l'utilisation d'une importation par défaut.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' peut uniquement être importé à l'aide de 'import {1} = require({2})' ou via l'activation de l'indicateur 'esModuleInterop' et l'utilisation d'une importation par défaut.", + "_0_cannot_be_used_as_a_JSX_component_2786": "Impossible d'utiliser '{0}' comme composant JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}' ne peut pas être utilisé en tant que valeur, car il a été exporté à l'aide de 'export type'.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}' ne peut pas être utilisé en tant que valeur, car il a été importé à l'aide de 'import type'.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Les composants '{0}' n'acceptent pas du texte en tant qu'éléments enfants. Le texte dans JSX a le type 'string', mais le type attendu de '{1}' est '{2}'.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' est un mot réservé.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "supprimer ceci - Le projet '{0}' est à jour car il a déjà été généré", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' ne réexporte pas une valeur par défaut.", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' peut uniquement être utilisé dans les fichiers TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Impossible d'appliquer le modificateur 'export' aux modules ambients et aux augmentations de module, car ils sont toujours visibles.", "extends_clause_already_seen_1172": "Clause 'extends' déjà rencontrée.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index 2aaea91192696..cd2af3e393fc7 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo in uno spazio dei nomi o in un modulo.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Un'espressione 'new' con argomenti di tipo deve essere sempre seguita da un elenco di argomenti tra parentesi.", "A_non_dry_build_would_build_project_0_6357": "Se si esegue una compilazione senza flag -dry, verrà compilato il progetto '{0}'", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Se si esegue una compilazione senza flag -dry, i file seguenti verranno eliminati: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Se si esegue una compilazione non di prova, l'output del progetto '{0}' verrà aggiornato", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"", "Add_0_to_unresolved_variable_90008": "Aggiungere '{0}.' alla variabile non risolta", + "Add_a_return_statement_95111": "Aggiungere un'istruzione return", "Add_all_missing_async_modifiers_95041": "Aggiungere tutti i modificatori 'async' mancanti", "Add_all_missing_call_parentheses_95068": "Aggiungere tutte le parentesi mancanti nelle chiamate", "Add_all_missing_imports_95064": "Aggiungere tutte le importazioni mancanti", "Add_all_missing_members_95022": "Aggiungere tutti i membri mancanti", + "Add_all_missing_return_statement_95114": "Aggiungere tutte le istruzioni return mancanti", "Add_all_missing_super_calls_95039": "Aggiungere tutte le chiamate a super mancanti", "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", "Add_await_95083": "Aggiungere 'await'", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "Aggiungere l'importazione predefinita '{0}' alla dichiarazione di importazione esistente restituita da \"{1}\"", "Add_definite_assignment_assertion_to_property_0_95020": "Aggiungere l'asserzione di assegnazione definita alla proprietà '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Aggiungere le asserzioni di assegnazione definite a tutte le proprietà non inizializzate", - "Add_export_to_make_this_file_into_a_module_95097": "Aggiungere 'export {}' per creare questo file in un modulo", + "Add_export_to_make_this_file_into_a_module_95097": "Aggiungere 'export {}' per trasformare questo file in un modulo", "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", "Add_initializer_to_property_0_95019": "Aggiungere l'inizializzatore alla proprietà '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "Aggiungere gli inizializzatori a tutte le proprietà non inizializzate", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Un percorso di importazione non può terminare con l'estensione '{0}'. In alternativa, provare a importare '{1}'.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Un argomento di espressione di indice deve essere di tipo 'string', 'number', 'symbol' o 'any'.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Una firma dell'indice non può contenere un parametro rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Una firma dell'indice non può contenere una virgola finale.", "An_index_signature_must_have_a_type_annotation_1021": "Una firma dell'indice deve contenere un'annotazione di tipo.", "An_index_signature_must_have_exactly_one_parameter_1096": "Una firma dell'indice deve contenere un solo parametro.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Un parametro della firma dell'indice non può contenere un punto interrogativo.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Non è possibile eseguire l'iterazione del valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma l'estensione della matrice invierà sempre '{0}'.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Non è possibile eseguire l'iterazione del valore perché il metodo 'next' del relativo iteratore prevede il tipo '{1}', ma for-of invierà sempre '{0}'.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Non è possibile anteporre il progetto '{0}' perché 'outFile' non è impostato", + "Cannot_read_file_0_5083": "Non è possibile leggere il file '{0}'.", "Cannot_read_file_0_Colon_1_5012": "Non è possibile leggere il file '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Non è possibile dichiarare di nuovo la variabile con ambito blocco '{0}'.", "Cannot_redeclare_exported_variable_0_2323": "Non è possibile dichiarare di nuovo la variabile esportata '{0}'.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compila il progetto in base al percorso del file di configurazione o della cartella contenente un file 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "Con l'opzione '{0}' del compilatore è previsto un argomento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Con l'opzione '{0}' del compilatore è richiesto un valore di tipo {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Il compilatore riserva il nome '{0}' quando si crea l'identificatore provato di livello inferiore.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Il compilatore riserva il nome '{0}' quando si crea l'identificatore privato per browser meno recenti.", "Composite_projects_may_not_disable_declaration_emit_6304": "I progetti compositi non possono disabilitare la creazione di dichiarazioni.", "Composite_projects_may_not_disable_incremental_compilation_6379": "I progetti compositi non possono disabilitare la compilazione incrementale.", "Computed_property_names_are_not_allowed_in_enums_1164": "I nomi di proprietà calcolati non sono consentiti nelle enumerazioni.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Non è stato possibile risolvere il percorso '{0}' con le estensioni: {1}.", "Could_not_write_file_0_Colon_1_5033": "Non è stato possibile scrivere il file '{0}': {1}.", "DIRECTORY_6038": "DIRECTORY", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "La dichiarazione causa un aumento della dichiarazione in un altro file. Questa condizione non è serializzabile.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Per la creazione della dichiarazione per questo file è necessario usare il nome privato '{0}'. Un'annotazione di tipo esplicita può sbloccare la creazione della dichiarazione.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Per la creazione della dichiarazione per questo file è necessario usare il nome privato '{0}' dal modulo '{1}'. Un'annotazione di tipo esplicita può sbloccare la creazione della dichiarazione.", "Declaration_expected_1146": "È prevista la dichiarazione.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Inizializzare la proprietà '{0}' nel costruttore", "Initialize_static_property_0_90021": "Inizializzare la proprietà statica '{0}'", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "L'inizializzatore della variabile del membro di istanza '{0}' non può fare riferimento all'identificatore '{1}' dichiarato nel costruttore.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "L'inizializzatore del parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "L'inizializzatore non fornisce alcun valore per questo elemento di binding e per quest'ultimo non è disponibile un valore predefinito.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Gli inizializzatori non sono consentiti in contesti di ambiente.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inizializza un progetto TypeScript e crea un file tsconfig.json.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso non valido di '{0}' in modalità strict.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Il valore non è valido per 'jsxFactory'. '{0}' non è un identificatore o un nome qualificato valido.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Il valore di '--reactNamespace' non è valido. '{0}' non è un identificatore valido", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Il relativo tipo di elemento '{0}' non è un elemento JSX valido.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Il relativo tipo di istanza '{0}' non è un elemento JSX valido.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Il relativo tipo restituito '{0}' non è un elemento JSX valido.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Il tag '@{0} {1}' di JSDoc non corrisponde alla clausola 'extends {2}'.", "JSDoc_0_is_not_attached_to_a_class_8022": "Il tag '@{0}' di JSDoc non è collegato a una classe.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' può essere presente solo nell'ultimo parametro di una firma.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Creare solo i file di dichiarazione '.d.ts'.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Nella clausola 'extends' di una classe sono attualmente supportati solo identificatori/nomi qualificati con argomenti tipo facoltativi.", "Only_named_exports_may_use_export_type_1383": "Solo le esportazioni denominate possono usare 'export type'.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Solo le enumerazioni numeriche possono includere membri calcolati, ma il tipo di questa espressione è '{0}'. Se non sono necessari controlli di esaustività, provare a usare un valore letterale di oggetto.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Con la parola chiave 'super' è possibile accedere solo ai metodi pubblico e protetto della classe di base.", "Operator_0_cannot_be_applied_to_type_1_2736": "Non è possibile applicare l'operatore '{0}' al tipo '{1}'.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Non è possibile applicare l'operatore '{0}' ai tipi '{1}' e '{2}'.", @@ -799,7 +808,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Le firme di overload devono essere tutte esportate o tutte non esportate.", "Overload_signatures_must_all_be_optional_or_required_2386": "Le firme di overload devono essere tutte facoltative o obbligatorie.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Le firme di overload devono essere tutte pubbliche, private o protette.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Non è possibile fare riferimento al parametro '{0}' nel relativo inizializzatore.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Il parametro '{0}' non può fare riferimento all'identificatore '{1}' dichiarato dopo di esso.", + "Parameter_0_cannot_reference_itself_2372": "Il parametro '{0}' non può fare riferimento a se stesso.", "Parameter_0_implicitly_has_an_1_type_7006": "Il parametro '{0}' contiene implicitamente un tipo '{1}'.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Il parametro '{0}' include implicitamente un tipo '{1}', ma è possibile dedurre un tipo migliore dall'utilizzo.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Il parametro '{0}' non si trova nella stessa posizione del parametro '{1}'.", @@ -839,7 +849,7 @@ "Prefix_0_with_an_underscore_90025": "Anteporre un carattere di sottolineatura a '{0}'", "Prefix_all_incorrect_property_declarations_with_declare_95095": "Aggiungere 'declare' come prefisso a tutte le dichiarazioni di proprietà non corrette", "Prefix_all_unused_declarations_with_where_possible_95025": "Aggiungere a tutte le dichiarazioni non usate il prefisso '_', laddove possibile", - "Prefix_with_declare_95094": "Aggiungere 'declare' come prefisso", + "Prefix_with_declare_95094": "Aggiungere il prefisso 'declare'", "Print_names_of_files_part_of_the_compilation_6155": "Stampa i nomi dei file che fanno parte della compilazione.", "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Stampa i nomi dei file che fanno parte della compilazione, quindi arresta l'elaborazione.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Stampa i nomi dei file generati che fanno parte della compilazione.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "La proprietà '{0}' non esiste nell'enumerazione 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "La proprietà '{0}' non esiste nel tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "La proprietà '{0}' non esiste nel tipo '{1}'. Si intendeva '{2}'?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "La proprietà '{0}' include dichiarazioni in conflitto ed è inaccessibile nel tipo '{1}'.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Per riesportare un tipo quando è specificato il flag '--isolatedModules', è necessario usare 'export type'.", "Redirect_output_structure_to_the_directory_6006": "Reindirizza la struttura di output alla directory.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Il progetto di riferimento '{0}' deve includere l'impostazione \"composite\": true.", + "Remove_all_incorrect_body_block_braces_95115": "Rimuovere tutte le parentesi graffe errate presenti nel corpo del blocco", "Remove_all_unnecessary_uses_of_await_95087": "Rimuovere tutti gli utilizzi non necessari di 'await'", "Remove_all_unreachable_code_95051": "Rimuovere tutto il codice non eseguibile", "Remove_all_unused_labels_95054": "Rimuovere tutte le etichette inutilizzate", + "Remove_block_body_braces_95112": "Rimuovere le parentesi graffe presenti nel corpo del blocco", "Remove_braces_from_arrow_function_95060": "Rimuovere le parentesi graffe dalla funzione arrow", "Remove_destructuring_90009": "Rimuovere la destrutturazione", "Remove_import_from_0_90005": "Rimuovere l'importazione da '{0}'", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "La metaproprietà 'import.meta' è consentita solo se l'opzione '--module' è impostata su 'esnext' o 'system'.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Non è possibile assegnare un nome al tipo derivato di '{0}' senza un riferimento a '{1}'. È probabile che non sia portabile. È necessaria un'annotazione di tipo.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Il tipo dedotto di '{0}' fa riferimento a un tipo '{1}' non accessibile. È necessaria un'annotazione di tipo.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "L'intersezione '{0}' è stata ridotta a 'never' perché la proprietà '{1}' esiste in più costituenti ed è privata in alcuni.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "L'intersezione '{0}' è stata ridotta a 'never' perché in alcuni costituenti della proprietà '{1}' sono presenti tipi in conflitto.", "The_last_overload_gave_the_following_error_2770": "L'ultimo overload ha restituito l'errore seguente.", "The_last_overload_is_declared_here_2771": "In questo punto viene dichiarato l'ultimo overload.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "La parte sinistra di un'espressione 'for...in' non può essere un criterio di destrutturazione.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "L'operando di un operatore 'delete' non può essere un identificatore privato.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "L'operando di un operatore 'delete' non può essere una proprietà di sola lettura.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "L'operando di un operatore 'delete' deve essere un riferimento a proprietà.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "L'operando di un operatore 'delete' deve essere facoltativo.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "L'operando di un operatore di incremento o decremento non può essere un accesso a proprietà facoltativo.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "L'operando di un operatore di incremento o decremento deve essere una variabile o un accesso a proprietà.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "In questo punto il parser dovrebbe trovare un simbolo '}' abbinato al token '{'.", @@ -1109,7 +1123,7 @@ "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La parte destra di un'operazione aritmetica deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "La parte destra di un'espressione 'in' deve essere di tipo 'any' oppure deve essere un tipo di oggetto o un parametro di tipo.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any' o di un tipo assegnabile al tipo di interfaccia 'Function'.", - "The_shadowing_declaration_of_0_is_defined_here_18017": "La dichiarazione di shadowing di '{0}' viene definita in questo punto", + "The_shadowing_declaration_of_0_is_defined_here_18017": "La dichiarazione di oscuramento di '{0}' viene definita in questo punto", "The_specified_path_does_not_exist_Colon_0_5058": "Il percorso specificato non esiste: '{0}'.", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "La destinazione di un'assegnazione deve essere una variabile o un accesso a proprietà.", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "La destinazione di un'assegnazione rest di oggetto non può essere un accesso a proprietà facoltativo.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Questa espressione non può essere chiamata.", "This_expression_is_not_constructable_2351": "Questa espressione non può essere costruita.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Questa importazione non viene mai usata come valore e deve usare 'import type' perché 'importsNotUsedAsValues' è impostato su 'error'.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Questa è la dichiarazione che verrà aumentata. Provare a spostare la dichiarazione che causa l'aumento nello stesso file.", "This_may_be_converted_to_an_async_function_80006": "Può essere convertita in una funzione asincrona.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "È possibile fare riferimento a questo modulo solo con importazioni/esportazioni ECMAScript attivando il flag '{0}' e facendo riferimento alla relativa esportazione predefinita.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Il modulo viene dichiarato con 'export =' e può essere usato solo con un'importazione predefinita quando si usa il flag '{0}'.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Il tipo di elementi iterati di un operando 'yield*' deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Il tipo di proprietà '{0}' contiene un riferimento circolare a se stesso nel tipo con mapping '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Il tipo dell'operando 'yield' in un generatore asincrono deve essere una promessa valida oppure non deve contenere un membro 'then' chiamabile.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Il tipo è originato in corrispondenza di questa importazione. Non è possibile chiamare o costruire un'importazione di tipo spazio dei nomi e verrà restituito un errore in fase di esecuzione. Provare a usare un'importazione o un'importazione predefinita in questo punto.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Il tipo è originato in corrispondenza di questa importazione. Non è possibile chiamare o costruire un'importazione di tipo spazio dei nomi e verrà restituito un errore in fase di esecuzione. Provare a usare un'importazione predefinita o un'importazione di require in questo punto.", "Type_parameter_0_has_a_circular_constraint_2313": "Il parametro di tipo '{0}' contiene un vincolo circolare.", "Type_parameter_0_has_a_circular_default_2716": "Il parametro di tipo '{0}' contiene un'impostazione predefinita circolare.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Il parametro di tipo '{0}' della firma di chiamata dell'interfaccia esportata contiene o usa il nome privato '{1}'.", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Aggiornamento dei timestamp di output non modificati del progetto '{0}'...", "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "Verranno usate le opzione del compilatore del progetto per fare riferimento al reindirizzamento '{0}'.", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", "VERSION_6036": "VERSIONE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Il valore di tipo '{0}' non è chiamabile. Si intendeva includere 'new'?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "È prevista la dichiarazione di variabile.", "Variable_declaration_list_cannot_be_empty_1123": "L'elenco delle dichiarazioni di variabile non può essere vuoto.", "Version_0_6029": "Versione {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Per altre informazioni su questo file, visitare il sito all'indirizzo https://aka.ms/tsconfig.json", "Watch_input_files_6005": "Controlla i file di input.", "Watch_option_0_requires_a_value_of_type_1_5080": "Con l'opzione '{0}' dell'espressione di controllo è richiesto un valore di tipo {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Indica se mantenere l'output della console obsoleto in modalità espressione di controllo invece di pulire lo schermo.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Eseguire il wrapping di tutti i caratteri non validi in un contenitore di espressioni", + "Wrap_all_object_literal_with_parentheses_95116": "Racchiudere tra parentesi tutti i valori letterali di oggetto", "Wrap_invalid_character_in_an_expression_container_95108": "Eseguire il wrapping del carattere non valido in un contenitore di espressioni", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Racchiudere tra parentesi il corpo seguente che deve essere un valore letterale di oggetto", "You_cannot_rename_a_module_via_a_global_import_8031": "Non è possibile rinominare un modulo tramite un'importazione globale.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Non è possibile rinominare elementi definiti nella libreria TypeScript standard.", "You_cannot_rename_this_element_8000": "Non è possibile rinominare questo elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' accetta un numero troppo ridotto di argomenti da usare come espressione Decorator in questo punto. Si intendeva chiamarlo prima e scrivere '@{0}()'?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Non è possibile combinare le operazioni '{0}' e '{1}' senza parentesi.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Gli attributi '{0}' sono stati specificati due volte. L'attributo denominato '{0}' verrà sovrascritto.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' può essere importato solo attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' può essere importato solo usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' può essere importato solo usando una chiamata 'require' o attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' può essere importato solo usando una chiamata 'require' o usando un'importazione predefinita.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' può essere importato solo usando 'import {1} = require({2})' o un'importazione predefinita.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' può essere importato solo usando 'import {1} = require({2})' o attivando il flag 'esModuleInterop' e usando un'importazione predefinita.", + "_0_cannot_be_used_as_a_JSX_component_2786": "Non è possibile usare '{0}' come componente JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "Non è possibile usare '{0}' come valore perché è stato esportato con 'export type'.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "Non è possibile usare '{0}' come valore perché è stato importato con 'import type'.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "I componenti di '{0}' non accettano testo come elementi figlio. Il tipo di testo in JSX è 'string ', ma il tipo previsto di '{1}' è '{2}'.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' è una parola riservata.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "eliminare - Il progetto '{0}' è aggiornato perché è stato compilato in precedenza", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' non consente di riesportare un'impostazione predefinita.", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' può essere usato solo in file TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Non è possibile applicare il modificatore 'export' a moduli di ambiente e aumenti di modulo perché sono sempre visibili.", "extends_clause_already_seen_1172": "La clausola 'extends' è già presente.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index d990eea1892b4..54a9ac22d91e8 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -44,7 +44,7 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "ジェネレーターに 'void' 型の注釈を指定することはできません。", "A_get_accessor_cannot_have_parameters_1054": "'get' アクセサーにパラメーターを指定することはできません。", "A_get_accessor_must_return_a_value_2378": "'get' アクセサーは値を返す必要があります。", - "A_label_is_not_allowed_here_1344": "'A ラベルはここでは使用できません。", + "A_label_is_not_allowed_here_1344": "A ラベルはここでは使用できません。", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "列挙型宣言のメンバー初期化子は、他の列挙型で定義されたメンバーを含め、その後で宣言されたメンバーを参照できません。", "A_method_cannot_be_named_with_a_private_identifier_18022": "メソッドに private 識別子を付けることはできません。", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin クラスには、型 'any[]' の単一の rest パラメーターを持つコンストラクターが必要です。", @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "名前空間宣言は、名前空間かモジュールでのみ使用できます。", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "型引数を伴う 'new' 式の後には常に、かっこで囲んだ引数リストを指定しなければなりません。", "A_non_dry_build_would_build_project_0_6357": "非 -dry ビルドを実行した場合、プロジェクト '{0}' がビルドされます", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry ビルドを実行した場合、次のファイルが削除されます: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "non-dry build では、プロジェクト '{0}' の出力が更新されます", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する", "Add_0_to_unresolved_variable_90008": "'{0}' を未解決の変数に追加します", + "Add_a_return_statement_95111": "return ステートメントを追加する", "Add_all_missing_async_modifiers_95041": "不足しているすべての 'async' 修飾子を追加します", "Add_all_missing_call_parentheses_95068": "見つからない呼び出しのかっこをすべて追加します", "Add_all_missing_imports_95064": "不足しているすべてのインポートを追加する", "Add_all_missing_members_95022": "不足しているすべてのメンバーを追加します", + "Add_all_missing_return_statement_95114": "不足しているすべての return ステートメントを追加する", "Add_all_missing_super_calls_95039": "不足しているすべての super の呼び出しを追加します", "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", "Add_await_95083": "'await' を追加する", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "既定のインポート '{0}' を \"{1}\" からの既存のインポート宣言に追加する", "Add_definite_assignment_assertion_to_property_0_95020": "プロパティ '{0}' に限定代入アサーションを追加します", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "初期化されていないすべてのプロパティに限定代入アサーションを追加します", - "Add_export_to_make_this_file_into_a_module_95097": "'export {}' を追加して、このファイルをモジュールに含める", + "Add_export_to_make_this_file_into_a_module_95097": "'export {}' を追加して、このファイルをモジュールにする", "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", "Add_initializer_to_property_0_95019": "プロパティ '{0}' に初期化子を追加します", "Add_initializers_to_all_uninitialized_properties_95027": "初期化されていないすべてのプロパティに初期化子を追加します", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "インポート パスの末尾を拡張子 '{0}' にすることはできません。代わりに '{1}' のインポートをご検討ください。", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "インデックス式の引数の型は、'string'、'number'、'symbol' または 'any' である必要があります。", "An_index_signature_cannot_have_a_rest_parameter_1017": "インデックス シグネチャに rest パラメーターを指定することはできません。", + "An_index_signature_cannot_have_a_trailing_comma_1025": "インデックス シグネチャの末尾にコンマを指定することはできません。", "An_index_signature_must_have_a_type_annotation_1021": "インデックス シグネチャには型の注釈が必要です。", "An_index_signature_must_have_exactly_one_parameter_1096": "インデックス シグネチャには、パラメーターを 1 つだけ指定しなければなりません。", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "インデックス シグネチャのパラメーターに疑問符を指定することはできません。", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "反復子の 'next' メソッドは型 '{1}' を予期するため、値を反復処理できませんが、配列展開は常に '{0}' を送信します。", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "反復子の 'next' メソッドは型 '{1}' を予期するため、値を反復処理できませんが、for-of は常に '{0}' を送信します。", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'outFile' が設定されていないため、プロジェクト '{0}' を先頭に追加することはできません", + "Cannot_read_file_0_5083": "ファイル '{0}' を読み取れません。", "Cannot_read_file_0_Colon_1_5012": "ファイル '{0}' を読み取れません: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "ブロック スコープの変数 '{0}' を再宣言することはできません。", "Cannot_redeclare_exported_variable_0_2323": "エクスポートされた変数 '{0}' を再び宣言できません。", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "構成ファイルか、'tsconfig.json' を含むフォルダーにパスが指定されたプロジェクトをコンパイルします。", "Compiler_option_0_expects_an_argument_6044": "コンパイラ オプション '{0}' には引数が必要です。", "Compiler_option_0_requires_a_value_of_type_1_5024": "コンパイラ オプション '{0}' には {1} の型の値が必要です。", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "private 識別子を下位レベルで出力するときに、コンパイラは名前 '{0}' を予約します。", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "private 識別子を下位レベルに生成するときに、コンパイラは名前 '{0}' を予約します。", "Composite_projects_may_not_disable_declaration_emit_6304": "複合プロジェクトで宣言の生成を無効にすることはできません。", "Composite_projects_may_not_disable_incremental_compilation_6379": "複合プロジェクトではインクリメンタル コンパイルを無効にできません。", "Computed_property_names_are_not_allowed_in_enums_1164": "計算されたプロパティ名は列挙型では使用できません。", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "次の拡張子を持つパス '{0}' を解決できませんでした: {1}。", "Could_not_write_file_0_Colon_1_5033": "ファイル '{0}' を書き込めませんでした: '{1}'。", "DIRECTORY_6038": "ディレクトリ", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "宣言は別のファイル内の宣言を拡張します。これをシリアル化できません。", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "このファイルの宣言の生成では、プライベート名 '{0}' を使用する必要があります。明示的な型の注釈では、宣言の生成のブロックを解除できます。", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "このファイルの宣言の生成では、モジュール '{1}' からのプライベート名 '{0}' を使用する必要があります。明示的な型の注釈では、宣言の生成のブロックを解除できます。", "Declaration_expected_1146": "宣言が必要です。", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "コンストラクターのプロパティ '{0}' を初期化する", "Initialize_static_property_0_90021": "静的プロパティ '{0}' を初期化する", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "インスタンス メンバー変数 '{0}' の初期化子はコンストラクターで宣言された識別子 '{1}' を参照できません。", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' の初期化子はその後で宣言された識別子 '{1}' を参照できません。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初期化子にこのバインド要素の値が提示されていません。またバインド要素に既定値がありません。", "Initializers_are_not_allowed_in_ambient_contexts_1039": "初期化子は環境コンテキストでは使用できません。", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript プロジェクトを初期化して、tsconfig.json ファイルを作成します。", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "厳格モードでは '{0}' の使用は無効です。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' の値が無効です。'{0}' が有効な識別子または修飾名ではありません。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' の値が無効です。'{0}' は有効な識別子ではありません。", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "その要素の型 '{0}' は有効な JSX 要素ではありません。", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "そのインスタンスの型 '{0}' は、有効な JSX 要素ではありません。", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "その戻り値の型 '{0}' は、有効な JSX 要素ではありません。", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' が 'extends {2}' 句と一致しません。", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' はクラスにアタッチされていません。", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' は、シグネチャの最後のパラメーターにのみ使用できます。", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 宣言ファイルのみを生成します。", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "クラス 'extends' 句で現在サポートされているのは、オプションの型引数が指定された ID/完全修飾名のみです。", "Only_named_exports_may_use_export_type_1383": "'export type' を使用できるのは名前付きエクスポートのみです。", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "計算されたメンバーを使用できるのは数値列挙型のみですが、この式には '{0}' 型があります。網羅性チェックが不要な場合は、代わりにオブジェクト リテラルを使用することをご検討ください。", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' キーワードを使用してアクセスできるのは、基底クラスのパブリック メソッドと保護されたメソッドのみです。", "Operator_0_cannot_be_applied_to_type_1_2736": "演算子 '{0}' は型 '{1}' に適用できません。", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "演算子 '{0}' を型 '{1}' および '{2}' に適用することはできません。", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "生成された宣言ファイルの出力ディレクトリ。", "Output_file_0_from_project_1_does_not_exist_6309": "プロジェクト '{1}' からの出力ファイル '{0}' がありません", "Output_file_0_has_not_been_built_from_source_file_1_6305": "出力ファイル '{0}' はソース ファイル '{1}' からビルドされていません。", - "Overload_0_of_1_2_gave_the_following_error_2772": "{1}、'{2}' の {0} のオーバーロードにより、次のエラーが発生しました。", + "Overload_0_of_1_2_gave_the_following_error_2772": "{1} 中 {0} のオーバーロード, '{2}' により、次のエラーが発生しました。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "オーバーロードのシグネチャはすべてが抽象または非抽象である必要があります。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "オーバーロードのシグネチャは、すべてアンビエントであるか、すべてアンビエントでないかのどちらかである必要があります。", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "オーバーロードのシグネチャはすべてがエクスポート済みであるか、またはエクスポート済みでない必要があります。", "Overload_signatures_must_all_be_optional_or_required_2386": "オーバーロードのシグネチャは、すべて省略可能であるか、すべて必須であるかのどちらかである必要があります。", "Overload_signatures_must_all_be_public_private_or_protected_2385": "オーバーロードのシグネチャはすべて、public、private、または protected でなければなりません。", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "パラメーター '{0}' はその初期化子内では参照できません。", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "パラメーター '{0}' はその後で宣言された識別子 '{1}' を参照できません。", + "Parameter_0_cannot_reference_itself_2372": "パラメーター '{0}' は、それ自体を参照できません。", "Parameter_0_implicitly_has_an_1_type_7006": "パラメーター '{0}' の型は暗黙的に '{1}' になります。", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "パラメーター '{0}' の型は暗黙的に '{1}' になっていますが、使い方からより良い型を推論できます。", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "パラメーター '{0}' がパラメーター '{1}' と同じ位置にありません。", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "プロパティ '{0}' が 'const' 列挙型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_2339": "プロパティ '{0}' は型 '{1}' に存在しません。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "プロパティ '{0}' は型 '{1}' に存在していません。'{2}' ですか?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "プロパティ '{0}' には競合する宣言があり、型 '{1}' ではアクセスできません。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "'--IsolatedModules' フラグが指定されている場合に型を再エクスポートするには、 'export type' を使用する必要があります。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "参照されているプロジェクト '{0}' には、設定 \"composite\": true が必要です。", + "Remove_all_incorrect_body_block_braces_95115": "本体ブロックの中かっこで間違っているものをすべて削除する", "Remove_all_unnecessary_uses_of_await_95087": "不要な 'await' の使用をすべて削除する", "Remove_all_unreachable_code_95051": "到達できないコードをすべて削除します", "Remove_all_unused_labels_95054": "すべての未使用のラベルを削除します", + "Remove_block_body_braces_95112": "ブロック本体の中かっこを削除する", "Remove_braces_from_arrow_function_95060": "アロー関数から中かっこを削除します", "Remove_destructuring_90009": "非構造化を削除します", "Remove_import_from_0_90005": "'{0}' からのインポートを削除", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "'import.meta' メタプロパティは、'--module' オプションが 'esnext' または 'system' の場合にのみ許可されます。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' の推論された型には、'{1}' への参照なしで名前を付けることはできません。これは、移植性がない可能性があります。型の注釈が必要です。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' の推定型はアクセス不可能な '{1}' 型を参照します。型の注釈が必要です。", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "交差 '{0}' は 'なし' に縮小されました。プロパティ '{1}' が複数の構成要素に存在し、一部ではプライベートであるためです。", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "交差 '{0}' は 'なし' に縮小されました。一部の構成要素でプロパティ '{1}' の型が競合しているためです。", "The_last_overload_gave_the_following_error_2770": "前回のオーバーロードにより、次のエラーが発生しました。", "The_last_overload_is_declared_here_2771": "前回のオーバーロードはここで宣言されています。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' ステートメントの左側を非構造化パターンにすることはできません。", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' 演算子のオペランドには、private 識別子を指定できません。", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' 演算子のオペランドには、読み取り専用のプロパティを指定できません。", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' 演算子のオペランドはプロパティ参照である必要があります。", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' 演算子のオペランドはオプションである必要があります。", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "インクリメント演算子またはデクリメント演算子のオペランドには、省略可能なプロパティ アクセスを指定することはできません。", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "インクリメントまたはデクリメント演算子のオペランドは、変数またはプロパティ アクセスである必要があります。", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "パーサーは、ここで '{' トークンに一致する '}' を予期していました。", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "この式は呼び出し可能ではありません。", "This_expression_is_not_constructable_2351": "この式はコンストラクト可能ではありません。", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "このインポートは値として使用されることはありません。'importsNotUsedAsValues' が 'error' に設定されているため、'import type' を使用する必要があります。", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "これは拡張される宣言です。拡張する側の宣言を同じファイルに移動することを検討してください。", "This_may_be_converted_to_an_async_function_80006": "これは非同期関数に変換できます。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "このモジュールは、'{0}' フラグをオンにして既定のエクスポートを参照することにより、ECMAScript のインポートまたはエクスポートのみを使用して参照できます。", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "このモジュールは 'export =' を使用して宣言されていて、'{0}' フラグを使用する場合は既定のインポートでのみ使用できます。", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' オペランドの反復要素の型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "マップされた型 '{1}' で、プロパティ '{0}' の型によってそれ自体が循環参照されています。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同期ジェネレーター内の 'yield' オペランドの型は、有効な Promise であるか、呼び出し可能な 'then' メンバーを含んでいないかのどちらかであることが必要です。", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "型はこのインポートで生成されます。名前空間スタイルのインポートは、呼び出すこともコンストラクトすることもできず、実行時にエラーが発生します。代わりに、ここで既定のインポートまたはインポートの要求を使用することを検討してください。", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "型はこのインポートで生成されます。名前空間スタイルのインポートは、呼び出すこともコンストラクトすることもできず、実行時にエラーが発生します。代わりに、ここで既定のインポートまたはインポートの require を使用することを検討してください。", "Type_parameter_0_has_a_circular_constraint_2313": "型パラメーター '{0}' に循環制約があります。", "Type_parameter_0_has_a_circular_default_2716": "型パラメーター '{0}' に循環既定値があります。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "エクスポートされたインターフェイスの呼び出しシグネチャの型パラメーター '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "プロジェクト '{0}' の変更されていない出力タイムスタンプを更新しています...", "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", - "Using_compiler_options_of_project_reference_redirect_0_6215": "プロジェクト参照リダイレクト '{0}' のコンパイラ オプションを使用します。", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", "VERSION_6036": "バージョン", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "型 '{0}' の値は呼び出せません。'new' を含めますか?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "変数の宣言が必要です。", "Variable_declaration_list_cannot_be_empty_1123": "変数宣言リストを空にすることはできません。", "Version_0_6029": "バージョン {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "このファイルの詳細については、https://aka.ms/tsconfig.json をご覧ください", "Watch_input_files_6005": "入力ファイルを監視します。", "Watch_option_0_requires_a_value_of_type_1_5080": "監視オプション '{0}' には型 {1} の値が必要です。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "画面をクリアする代わりに、古くなったコンソール出力をウォッチ モードで保持するかどうか。", "Wrap_all_invalid_characters_in_an_expression_container_95109": "式のコンテナー内のすべての無効な文字をラップする", + "Wrap_all_object_literal_with_parentheses_95116": "すべてのオブジェクト リテラルをかっこで囲みます", "Wrap_invalid_character_in_an_expression_container_95108": "式のコンテナー内の無効な文字をラップする", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "次の本体をかっこで囲みます。これはオブジェクト リテラルです", "You_cannot_rename_a_module_via_a_global_import_8031": "グローバル インポートを使用してモジュールの名前を変更することはできません。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "標準の TypeScript ライブラリで定義された要素の名前を変更することはできません。", "You_cannot_rename_this_element_8000": "この要素の名前を変更することはできません。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' は受け入れる引数が少なすぎるので、ここでデコレーターとして使用することができません。最初にこれを呼び出してから、'@{0}()' を書き込むつもりでしたか?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' および '{1}' 演算をかっこなしで混在させることはできません。", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' は 2 回指定されています。'{0}' という名前の属性は上書きされます。", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' をインポートするには、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' をインポートするには、既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' をインポートするには、'require' 呼び出しを使用するか、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' をインポートするには、'require' 呼び出しを使用するか、既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' をインポートするには、'import {1} = require ({2})' または既定のインポートを使用する必要があります。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' をインポートするには、'import {1} = require ({2})' を使用するか、'esModuleInterop' フラグをオンにして既定のインポートを使用する必要があります。", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}' を JSX コンポーネントとして使用することはできません。", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'export type' を使用してエクスポートされたため、'{0}' は値として使用できません。", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'import type' を使用してインポートされたため、'{0}' は値として使用できません。", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' コンポーネントには、テキストを子要素として指定できません。JSX のテキストには 'string' 型が含まれていますが、'{1}' の予期された型は '{2}' です。", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' は予約語です。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "これを削除します - プロジェクト '{0}' は、以前にビルドされているため、最新の状態です", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' では既定値が再エクスポートされません。", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' は、TypeScript ファイルでのみ使用できます。", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "環境モジュールとモジュール拡張は常に表示されるので、これらに 'export' 修飾子を適用することはできません。", "extends_clause_already_seen_1172": "'extends' 句は既に存在します。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 553eeb44318e5..91b55b710f598 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -44,7 +44,7 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "생성기에는 'void' 형식 주석을 사용할 수 없습니다.", "A_get_accessor_cannot_have_parameters_1054": "'get' 접근자에는 매개 변수를 사용할 수 없습니다.", "A_get_accessor_must_return_a_value_2378": "'get' 접근자는 값을 반환해야 합니다.", - "A_label_is_not_allowed_here_1344": "'여기서는 레이블을 사용할 수 없습니다.", + "A_label_is_not_allowed_here_1344": "여기서는 레이블을 사용할 수 없습니다.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "열거형 선언의 멤버 이니셜라이저는 그 뒤에 선언된 멤버와 다른 열거형에 정의된 멤버를 참조할 수 없습니다.", "A_method_cannot_be_named_with_a_private_identifier_18022": "프라이빗 식별자를 사용하여 메서드 이름을 지정할 수 없습니다.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "mixin 클래스에는 'any[]' 형식의 rest 매개 변수 하나를 사용하는 생성자가 있어야 합니다.", @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "형식 인수가 포함된 'new' 식은 뒤에 항상 괄호로 묶인 인수 목록이 있어야 합니다.", "A_non_dry_build_would_build_project_0_6357": "-dry가 아닌 빌드는 프로젝트 '{0}'을(를) 빌드합니다.", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry가 아닌 빌드는 다음 파일을 삭제합니다. {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "DRY가 아닌 빌드는 '{0}' 프로젝트의 출력을 업데이트합니다.", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가", "Add_0_to_unresolved_variable_90008": "확인되지 않은 변수에 '{0}.' 추가", + "Add_a_return_statement_95111": "return 문 추가", "Add_all_missing_async_modifiers_95041": "누락된 모든 'async' 한정자 추가", "Add_all_missing_call_parentheses_95068": "누락된 호출 괄호 모두 추가", "Add_all_missing_imports_95064": "누락된 모든 가져오기 추가", "Add_all_missing_members_95022": "누락된 모든 멤버 추가", + "Add_all_missing_return_statement_95114": "누락된 모든 return 문 추가", "Add_all_missing_super_calls_95039": "누락된 모든 super 호출 추가", "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", "Add_await_95083": "'await' 추가", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "가져오기 경로는 '{0}' 확장으로 끝날 수 없습니다. 대신 '{1}' 가져오기를 고려하세요.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "인덱스 식 인수는 'string', 'number', 'symbol' 또는 'any' 형식이어야 합니다.", "An_index_signature_cannot_have_a_rest_parameter_1017": "인덱스 시그니처에는 rest 매개 변수를 사용할 수 없습니다.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "인덱스 시그니처에는 후행 쉼표를 사용할 수 없습니다.", "An_index_signature_must_have_a_type_annotation_1021": "인덱스 시그니처에는 형식 주석을 사용할 수 없습니다.", "An_index_signature_must_have_exactly_one_parameter_1096": "인덱스 시그니처에는 한 개의 매개 변수만 사용할 수 있습니다.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "인덱스 시그니처 매개 변수에는 물음표를 사용할 수 없습니다.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 배열 spread는 항상 '{0}'을(를) 전송하므로 값을 반복할 수 없습니다.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "반복기의 'next' 메서드에 '{1}' 형식이 필요하지만 for-of는 항상 '{0}'을(를) 전송하므로 값을 반복할 수 없습니다.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "'{0}' 프로젝트는 'outFile'이 설정되어 있지 않기 때문에 앞에 추가할 수 없습니다.", + "Cannot_read_file_0_5083": "'{0}' 파일을 읽을 수 없습니다.", "Cannot_read_file_0_Colon_1_5012": "파일 '{0}'을(를) 읽을 수 없습니다. {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "블록 범위 변수 '{0}'을(를) 다시 선언할 수 없습니다.", "Cannot_redeclare_exported_variable_0_2323": "내보낸 변수 '{0}'을(를) 다시 선언할 수 없습니다.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "{1} 확장이 포함된 '{0}' 경로를 확인할 수 없습니다.", "Could_not_write_file_0_Colon_1_5033": "'{0}' 파일을 쓸 수 없습니다. '{1}'.", "DIRECTORY_6038": "디렉터리", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "선언이 다른 파일의 선언을 확대합니다. 직렬화할 수 없습니다.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "이 파일의 선언 내보내기에는 프라이빗 이름 '{0}'을(를) 사용해야 합니다. 명시적 형식 주석은 선언 내보내기를 차단 해제할 수 있습니다.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "이 파일의 선언 내보내기에는 '{1}' 모듈의 프라이빗 이름 '{0}'을(를) 사용해야 합니다. 명시적 형식 주석은 선언 내보내기를 차단 해제할 수 있습니다.", "Declaration_expected_1146": "선언이 필요합니다.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "생성자에서 속성 '{0}' 초기화", "Initialize_static_property_0_90021": "정적 속성 '{0}' 초기화", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "인스턴스 멤버 변수 '{0}'의 이니셜라이저는 생성자에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'의 이니셜라이저는 그 다음에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "이니셜라이저는 이 바인딩 요소에 대한 값을 제공하지 않으며 바인딩 요소에는 기본값이 없습니다.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "앰비언트 컨텍스트에서는 이니셜라이저가 허용되지 않습니다.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "TypeScript 프로젝트를 초기화하고 tsconfig.json 파일을 만듭니다.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "strict 모드에서 '{0}'을(를) 잘못 사용했습니다.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory'에 대한 값이 잘못되었습니다. '{0}'이(가) 올바른 식별자 또는 정규화된 이름이 아닙니다.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace'의 값이 잘못되었습니다. '{0}'은(는) 올바른 식별자가 아닙니다.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "해당 요소 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "인스턴스 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "반환 형식 '{0}'은(는) 유효한 JSX 요소가 아닙니다.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}'이(가) 'extends {2}' 절과 일치하지 않습니다.", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}'이(가) 클래스에 연결되어 있지 않습니다.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...'은 시그니처의 마지막 매개 변수에만 나타날 수 있습니다.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "'.d.ts' 선언 파일만 내보냅니다.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "선택적 형식 인수가 포함된 식별자/정규화된 이름만 현재 클래스 'extends' 절에서 지원됩니다.", "Only_named_exports_may_use_export_type_1383": "명명된 내보내기에서만 '내보내기 형식'을 사용할 수 있습니다.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "숫자 열거형에는 컴퓨팅된 구성원만 사용할 수 있는데 이 식에는 '{0}' 형식이 있습니다. 전체 검사가 필요하지 않은 경우에는 개체 리터럴을 대신 사용해 보세요.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "기본 클래스의 공용 및 보호된 메서드만 'super' 키워드를 통해 액세스할 수 있습니다.", "Operator_0_cannot_be_applied_to_type_1_2736": "'{0}' 연산자는 '{1}' 형식에 적용할 수 없습니다.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' 연산자를 '{1}' 및 '{2}' 형식에 적용할 수 없습니다.", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "생성된 선언 파일의 출력 디렉터리입니다.", "Output_file_0_from_project_1_does_not_exist_6309": "프로젝트 '{1}'의 출력 파일 '{0}'이(가) 존재하지 않습니다.", "Output_file_0_has_not_been_built_from_source_file_1_6305": "출력 파일 '{0}'이(가) 소스 파일 '{1}'에서 빌드되지 않았습니다.", - "Overload_0_of_1_2_gave_the_following_error_2772": "{1}, '{2}'의 오버로드 {0}에서 다음 오류가 발생했습니다.", + "Overload_0_of_1_2_gave_the_following_error_2772": "오버로드 {0}/{1}('{2}')에서 다음 오류가 발생했습니다.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "오버로드 시그니처는 모두 추상이거나 비추상이어야 합니다.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "오버로드 시그니처는 모두 앰비언트이거나 앰비언트가 아니어야 합니다.", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "오버로드 시그니처는 모두 내보내거나 모두 내보내지 않아야 합니다.", "Overload_signatures_must_all_be_optional_or_required_2386": "오버로드 시그니처는 모두 선택 사항이거나 필수 사항이어야 합니다.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "오버로드 시그니처는 모두 퍼블릭, 프라이빗 또는 보호된 상태여야 합니다.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "매개 변수 '{0}'은(는) 해당 이니셜라이저에서 참조할 수 없습니다.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "매개 변수 '{0}'은(는) 이 매개 변수 뒤에 선언된 식별자 '{1}'을(를) 참조할 수 없습니다.", + "Parameter_0_cannot_reference_itself_2372": "매개 변수 '{0}'은(는) 자신을 참조할 수 없습니다.", "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' 매개 변수에는 암시적으로 '{1}' 형식이 포함됩니다.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "'{0}' 매개 변수는 암시적으로 '{1}' 형식이지만, 사용량에서 더 나은 형식을 유추할 수 있습니다.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' 매개 변수는 '{1}' 매개 변수와 같은 위치에 있지 않습니다.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 열거형 '{1}'에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_2339": "'{1}' 형식에 '{0}' 속성이 없습니다.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' 속성이 '{1}' 형식에 없습니다. '{2}'을(를) 사용하시겠습니까?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' 속성은 충돌하는 선언이 있고 '{1}' 형식에서 액세스할 수 없습니다.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "'--isolatedModules' 플래그가 제공될 때 형식을 다시 내보내려면 'export type'을 사용해야 합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "참조되는 프로젝트 '{0}'에는 \"composite\": true 설정이 있어야 합니다.", + "Remove_all_incorrect_body_block_braces_95115": "잘못된 본문 블록 중괄호 모두 제거", "Remove_all_unnecessary_uses_of_await_95087": "불필요한 'await' 사용 모두 제거", "Remove_all_unreachable_code_95051": "접근할 수 없는 코드 모두 제거", "Remove_all_unused_labels_95054": "사용되지 않는 레이블 모두 제거", + "Remove_block_body_braces_95112": "블록 본문 중괄호 제거", "Remove_braces_from_arrow_function_95060": "화살표 함수에서 중괄호 제거", "Remove_destructuring_90009": "구조 파괴 제거", "Remove_import_from_0_90005": "'{0}'에서 가져오기 제거", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "'import.meta' 메타 속성은 '--module' 옵션이 'esnext' 또는 'system'인 경우에만 사용할 수 있습니다.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}'의 유추된 형식 이름을 지정하려면 '{1}'에 대한 참조가 있어야 합니다. 이식하지 못할 수 있습니다. 형식 주석이 필요합니다.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}'의 유추 형식이 액세스할 수 없는 '{1}' 형식을 참조합니다. 형식 주석이 필요합니다.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "속성 '{1}'이(가) 여러 구성원에 있고 일부 구성원에서는 프라이빗 상태이므로 교집합 '{0}'이(가) 'never'로 감소했습니다.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "일부 구성원에 속성 '{1}'에 충돌하는 형식이 있으므로 교집합 '{0}'이(가) 'never'로 감소했습니다.", "The_last_overload_gave_the_following_error_2770": "마지막 오버로드에서 다음 오류가 발생했습니다.", "The_last_overload_is_declared_here_2771": "여기서 마지막 오버로드가 선언됩니다.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 문의 왼쪽에는 구조 파괴 패턴을 사용할 수 없습니다.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' 연산자의 피연산자는 프라이빗 식별자일 수 없습니다.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' 연산자의 피연산자는 읽기 전용 속성일 수 없습니다.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' 연산자의 피연산자는 속성 참조여야 합니다.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' 연산자의 피연산자는 선택 사항이어야 합니다.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "증분 또는 감소 연산자의 피연산자는 선택적 속성 액세스일 수 없습니다.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "증가 또는 감소 연산자의 피연산자는 변수 또는 속성 액세스여야 합니다.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "여기서 파서는 '{' 토큰과 일치하는 '}'를 찾아야 합니다.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "이 식은 호출할 수 없습니다.", "This_expression_is_not_constructable_2351": "이 식은 생성할 수 없습니다.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "이 가져오기는 값으로 사용되지 않아야 하며 'importsNotUsedAsValues'가 'error'로 설정되어 있기 때문에 'import type'을 사용해야 합니다.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "확대되는 선언입니다. 확대하는 선언을 같은 파일로 이동하는 것이 좋습니다.", "This_may_be_converted_to_an_async_function_80006": "비동기 함수로 변환될 수 있습니다.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "이 모듈은 '{0}' 플래그를 켜고 기본 내보내기를 참조하여 ECMAScript 가져오기/내보내기를 통해서만 참조할 수 있습니다.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "이 모듈은 'export ='를 사용하여 선언되었으며 '{0}' 플래그를 사용하는 경우에만 기본 가져오기와 함께 사용할 수 있습니다.", @@ -1159,7 +1174,7 @@ "Type_0_has_no_matching_index_signature_for_type_1_2537": "'{0}' 형식에 '{1}' 형식에 대한 일치하는 인덱스 시그니처가 없습니다.", "Type_0_has_no_properties_in_common_with_type_1_2559": "'{0}' 유형에 '{1}' 유형과 공통적인 속성이 없습니다.", "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "'{0}' 형식에 '{1}' 형식의 {2} 속성이 없습니다.", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "'{0}' 형식에 '{1}' 형식의 {2}, {3} 속성 등이 없습니다.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "'{0}' 형식에 '{1}' 형식의 {2} 외 {3}개 속성이 없습니다.", "Type_0_is_not_a_constructor_function_type_2507": "'{0}' 형식은 생성자 함수 형식이 아닙니다.", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "'{0}' 형식은 Promise 호환 생성자 값을 참조하지 않으므로 ES5/ES3에서 유효한 비동기 함수 반환 형식이 아닙니다.", "Type_0_is_not_an_array_type_2461": "'{0}' 형식은 배열 형식이 아닙니다.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*'의 반복되는 요소 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "'{0}' 속성의 형식은 매핑된 형식 '{1}'에서 순환적으로 자신을 참조합니다.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "비동기 생성기에 있는 'yield' 형식의 피연산자는 유효한 프라미스여야 하거나 호출 가능 'then' 멤버를 포함하지 않아야 합니다.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "형식이 이 가져오기에서 시작됩니다. 네임스페이스 스타일 가져오기는 호출하거나 생성할 수 없으며, 런타임에 오류를 초래합니다. 여기서는 대신 기본 가져오기 또는 가져오기 필요를 사용하는 것이 좋습니다.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "형식이 이 가져오기에서 시작됩니다. 네임스페이스 스타일 가져오기는 호출하거나 생성할 수 없으며, 런타임에 오류를 초래합니다. 여기서는 대신 기본 가져오기 또는 가져오기 require를 사용하는 것이 좋습니다.", "Type_parameter_0_has_a_circular_constraint_2313": "형식 매개 변수 '{0}'에 순환 제약 조건이 있습니다.", "Type_parameter_0_has_a_circular_default_2716": "형식 매개 변수 '{0}'에 순환 기본값이 있습니다.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "내보낸 인터페이스에 있는 호출 시그니처의 형식 매개 변수 '{0}'이(가) 프라이빗 이름 '{1}'을(를) 가지고 있거나 사용 중입니다.", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "변수 선언이 필요합니다.", "Variable_declaration_list_cannot_be_empty_1123": "변수 선언 목록은 비워 둘 수 없습니다.", "Version_0_6029": "버전 {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "이 파일에 대한 자세한 내용을 보려면 https://aka.ms/tsconfig.json을 방문하세요.", "Watch_input_files_6005": "조사식 입력 파일입니다.", "Watch_option_0_requires_a_value_of_type_1_5080": "조사식 옵션 '{0}'에 {1} 형식의 값이 필요합니다.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "화면을 지우지 않고, 감시 모드의 오래된 콘솔 출력을 유지할지 여부입니다.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "식 컨테이너에서 모든 잘못된 문자 래핑", + "Wrap_all_object_literal_with_parentheses_95116": "괄호를 사용하여 모든 개체 리터럴 래핑", "Wrap_invalid_character_in_an_expression_container_95108": "식 컨테이너에서 잘못된 문자 래핑", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "괄호를 사용하여 개체 리터럴이어야 하는 다음 본문 래핑", "You_cannot_rename_a_module_via_a_global_import_8031": "전역 가져오기를 통해 모듈 이름을 바꿀 수 없습니다.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "표준 TypeScript 라이브러리에 정의된 요소의 이름을 바꿀 수 없습니다.", "You_cannot_rename_this_element_8000": "이 요소의 이름을 바꿀 수 없습니다.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}'이(가) 여기에서 decorator로 사용할 인수를 너무 적게 허용합니다. 먼저 이를 호출하고 '@{0}()'을(를) 작성하시겠습니까?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' 및 '{1}' 작업은 괄호 없이 혼합해서 사용할 수 없습니다.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}'이(가) 두 번 지정되었습니다. 이름이 '{0}'인 특성을 덮어씁니다.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}'은(는) 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}'은(는) 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}'은(는) 'require' 호출을 사용하거나 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}'은(는) 'require' 호출을 사용하거나 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}'은(는) 'import {1} = require({2})' 또는 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}'은(는) 'import {1} = require({2})'를 사용하거나 'esModuleInterop' 플래그를 설정하고 기본 가져오기를 사용해서만 가져올 수 있습니다.", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}'은(는) JSX 구성 요소로 사용할 수 없습니다.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}'은(는) 'export type'을 사용하여 내보냈으므로 값으로 사용할 수 없습니다.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}'은(는) 'import type'을 사용하여 가져왔으므로 값으로 사용할 수 없습니다.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' 구성 요소는 텍스트를 자식 요소로 수락하지 않습니다. JSX의 텍스트는 'string' 형식이지만, '{1}'의 필요한 형식은 '{2}'입니다.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor'는 예약어입니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "이 항목 삭제 - '{0}' 프로젝트는 이전에 빌드되었기 때문에 최신 상태입니다.", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *'는 기본값을 다시 내보내지 않습니다.", "export_can_only_be_used_in_TypeScript_files_8003": "'export ='는 TypeScript 파일에서만 사용할 수 있습니다.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "앰비언트 모듈 및 모듈 확대는 항상 표시되므로 'export' 한정자를 적용할 수 없습니다.", "extends_clause_already_seen_1172": "'extends' 절이 이미 있습니다.", diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 981072bd46128..d8601c0ee6a31 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -62,15 +62,6 @@ interface Array { * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; - - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. If deleteCount is omitted, or if its value is equal to or larger - * than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, - * starting at start), then all the elements from start to the end of the array will be deleted. - */ - splice(start: number, deleteCount?: number): T[]; } interface ArrayConstructor { @@ -233,13 +224,13 @@ interface NumberConstructor { * number. Only finite values of the type number, result in true. * @param number A numeric value. */ - isFinite(number: number): boolean; + isFinite(number: unknown): boolean; /** * Returns true if the value passed is an integer, false otherwise. * @param number A numeric value. */ - isInteger(number: number): boolean; + isInteger(number: unknown): boolean; /** * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a @@ -247,13 +238,13 @@ interface NumberConstructor { * to a number. Only values of the type number, that are also NaN, result in true. * @param number A numeric value. */ - isNaN(number: number): boolean; + isNaN(number: unknown): boolean; /** * Returns true if the value passed is a safe integer. * @param number A numeric value. */ - isSafeInteger(number: number): boolean; + isSafeInteger(number: unknown): boolean; /** * The value of the largest integer n such that n and n + 1 are both exactly representable as diff --git a/lib/lib.es2015.d.ts b/lib/lib.es2015.d.ts index 339832b546e6b..791284b6dad0b 100644 --- a/lib/lib.es2015.d.ts +++ b/lib/lib.es2015.d.ts @@ -21,9 +21,9 @@ and limitations under the License. /// /// /// +/// /// /// -/// /// /// /// diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index afef55cf043cb..d3a54c2dca08f 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -274,7 +274,7 @@ interface Int8Array { } interface Uint8Array { - readonly [Symbol.toStringTag]: "UInt8Array"; + readonly [Symbol.toStringTag]: "Uint8Array"; } interface Uint8ClampedArray { diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts index 73cb9812847f5..db0a3d1b027cf 100644 --- a/lib/lib.es2018.d.ts +++ b/lib/lib.es2018.d.ts @@ -19,8 +19,8 @@ and limitations under the License. /// -/// /// +/// /// /// /// diff --git a/lib/lib.es2019.array.d.ts b/lib/lib.es2019.array.d.ts index 99fecc09fd6cc..1607483465a27 100644 --- a/lib/lib.es2019.array.d.ts +++ b/lib/lib.es2019.array.d.ts @@ -18,6 +18,13 @@ and limitations under the License. /// +type FlatArray = { + "done": Arr, + "recur": Arr extends ReadonlyArray + ? FlatArray + : Arr +}[Depth extends -1 ? "done" : "recur"]; + interface ReadonlyArray { /** @@ -42,95 +49,11 @@ interface ReadonlyArray { * * @param depth The maximum recursion depth */ - flat(this: - ReadonlyArray | - - ReadonlyArray> | - ReadonlyArray[]> | - ReadonlyArray[][]> | - ReadonlyArray[][][]> | - - ReadonlyArray>> | - ReadonlyArray[][]>> | - ReadonlyArray>[][]> | - ReadonlyArray[]>[]> | - ReadonlyArray>[]> | - ReadonlyArray[]>> | - - ReadonlyArray>>> | - ReadonlyArray[]>>> | - ReadonlyArray>[]>> | - ReadonlyArray>>[]> | - - ReadonlyArray>>>>, - depth: 4): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: - ReadonlyArray | - - ReadonlyArray[][]> | - ReadonlyArray[]> | - ReadonlyArray> | - - ReadonlyArray>> | - ReadonlyArray[]>> | - ReadonlyArray>[]> | - - ReadonlyArray>>>, - depth: 3): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: - ReadonlyArray | - - ReadonlyArray> | - ReadonlyArray[]> | - - ReadonlyArray>>, - depth: 2): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: - ReadonlyArray | - ReadonlyArray>, - depth?: 1 - ): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: - ReadonlyArray, - depth: 0 - ): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. If no depth is provided, flat method defaults to the depth of 1. - * - * @param depth The maximum recursion depth - */ - flat(depth?: number): any[]; -} + flat( + this: A, + depth?: D + ): FlatArray[] + } interface Array { @@ -155,69 +78,8 @@ interface Array { * * @param depth The maximum recursion depth */ - flat(this: U[][][][][][][][], depth: 7): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][][][][][][], depth: 6): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][][][][][], depth: 5): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][][][][], depth: 4): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][][][], depth: 3): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][][], depth: 2): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[][], depth?: 1): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. - * - * @param depth The maximum recursion depth - */ - flat(this: U[], depth: 0): U[]; - - /** - * Returns a new array with all sub-array elements concatenated into it recursively up to the - * specified depth. If no depth is provided, flat method defaults to the depth of 1. - * - * @param depth The maximum recursion depth - */ - flat(depth?: number): any[]; + flat( + this: A, + depth?: D + ): FlatArray[] } diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 65c0c012fe71d..ec5e1a5723ced 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1274,7 +1274,7 @@ interface Array { * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. */ - splice(start: number, deleteCount: number): T[]; + splice(start: number, deleteCount?: number): T[]; /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. diff --git a/lib/lib.esnext.string.d.ts b/lib/lib.esnext.string.d.ts index 406f0e6069ea4..89b27e2fe9094 100644 --- a/lib/lib.esnext.string.d.ts +++ b/lib/lib.esnext.string.d.ts @@ -25,4 +25,11 @@ interface String { * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. */ replaceAll(searchValue: string | RegExp, replaceValue: string): string; + + /** + * Replace all instances of a substring in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replacer A function that returns the replacement text. + */ + replaceAll(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; } diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index fe42ef144e269..7a0f57a78e756 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -44,7 +44,7 @@ "A_generator_cannot_have_a_void_type_annotation_2505": "Generator nie może mieć adnotacji typu „void”.", "A_get_accessor_cannot_have_parameters_1054": "Metoda dostępu „get” nie może mieć parametrów.", "A_get_accessor_must_return_a_value_2378": "Metoda dostępu „get” musi zwracać wartość.", - "A_label_is_not_allowed_here_1344": "„Etykieta nie jest dozwolona w tym miejscu.", + "A_label_is_not_allowed_here_1344": "Etykieta nie jest dozwolona w tym miejscu.", "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651": "Inicjator składowej w deklaracji wyliczenia nie może przywoływać składowych zadeklarowanych po nim, w tym składowych zdefiniowanych w innych wyliczeniach.", "A_method_cannot_be_named_with_a_private_identifier_18022": "Metody nie można nazwać za pomocą identyfikatora prywatnego.", "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545": "Klasa mixin musi mieć konstruktor z pojedynczym parametrem rest o typie „any[]”.", @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklaracja przestrzeni nazw nie może znajdować się w innym pliku niż klasa lub funkcja, z którą ją scalono.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklaracja przestrzeni nazw nie może występować przed klasą lub funkcją, z którą ją scalono.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklaracja przestrzeni nazw jest dozwolona tylko w przestrzeni nazw lub module.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Po wyrażeniu „new” z argumentami typu musi zawsze występować lista argumentów ujęta w nawiasy.", "A_non_dry_build_would_build_project_0_6357": "Kompilacja inna niż -dry spowodowałaby skompilowanie projektu „{0}”", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Kompilacja inna niż -dry spowodowałaby usunięcie następujących plików: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Kompilacja bez opcji dry spowoduje zaktualizowanie danych wyjściowych projektu „{0}”", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”", "Add_0_to_unresolved_variable_90008": "Dodaj „{0}.” do nierozpoznanej zmiennej", + "Add_a_return_statement_95111": "Dodaj instrukcję return", "Add_all_missing_async_modifiers_95041": "Dodaj wszystkie brakujące modyfikatory „async”", "Add_all_missing_call_parentheses_95068": "Dodaj wszystkie brakujące nawiasy wywołań", "Add_all_missing_imports_95064": "Dodaj wszystkie brakujące importy", "Add_all_missing_members_95022": "Dodaj wszystkie brakujące elementy członkowskie", + "Add_all_missing_return_statement_95114": "Dodaj wszystkie brakujące instrukcje return", "Add_all_missing_super_calls_95039": "Dodaj wszystkie brakujące wywołania typu super", "Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej", "Add_await_95083": "Dodaj operator „await”", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Ścieżka importu nie może kończyć się rozszerzeniem „{0}”. Rozważ zaimportowanie „{1}”.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Argument wyrażenia indeksu musi być typu „string”, „number”, „symbol” lub „any”.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Sygnatura indeksu nie może mieć parametru rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Sygnatura indeksu nie może być zakończona przecinkiem.", "An_index_signature_must_have_a_type_annotation_1021": "Sygnatura indeksu musi mieć adnotację typu.", "An_index_signature_must_have_exactly_one_parameter_1096": "Sygnatura indeksu musi mieć dokładnie jeden parametr.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Parametr sygnatury indeksu nie może zawierać znaku zapytania.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Nie można iterować wartości, ponieważ metoda „next” jej iteratora oczekuje typu „{1}”, ale rozkładanie tablicy będzie zawsze wysyłało „{0}”.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Nie można iterować wartości, ponieważ metoda „next” jej iteratora oczekuje typu „{1}”, ale pętla for-of będzie zawsze wysyłała „{0}”.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Nie można poprzedzić projektu „{0}”, ponieważ nie ma on ustawionej właściwości „outFile”", + "Cannot_read_file_0_5083": "Nie można odczytać pliku „{0}”.", "Cannot_read_file_0_Colon_1_5012": "Nie można odczytać pliku „{0}”: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Nie można ponownie zadeklarować zmiennej „{0}” o zakresie bloku.", "Cannot_redeclare_exported_variable_0_2323": "Nie można zadeklarować ponownie wyeksportowanej zmiennej „{0}”.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Skompiluj projekt z uwzględnieniem ścieżki jego pliku konfiguracji lub folderu z plikiem „tsconfig.json”.", "Compiler_option_0_expects_an_argument_6044": "Opcja kompilatora „{0}” oczekuje argumentu.", "Compiler_option_0_requires_a_value_of_type_1_5024": "Opcja kompilatora „{0}” wymaga wartości typu {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Kompilator rezerwuje nazwę „{0}” podczas emitowania niższego poziomu identyfikatora prywatnego.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "Kompilator rezerwuje nazwę „{0}” podczas emitowania identyfikatora prywatnego na niższy poziom.", "Composite_projects_may_not_disable_declaration_emit_6304": "Projekty kompozytowe nie mogą wyłączyć emitowania deklaracji.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Projekty złożone nie mogą wyłączać kompilacji przyrostowej.", "Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Nie można rozpoznać ścieżki „{0}” z rozszerzeniami: {1}.", "Could_not_write_file_0_Colon_1_5033": "Nie można zapisać pliku „{0}”: {1}.", "DIRECTORY_6038": "KATALOG", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Deklaracja rozszerza deklarację w innym pliku. Nie można przeprowadzić serializacji.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Emitowanie deklaracji dla tego pliku wymaga użycia nazwy prywatnej „{0}”. Jawna adnotacja typu może odblokować emitowanie deklaracji.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Emitowanie deklaracji dla tego pliku wymaga użycia nazwy prywatnej „{0}” z modułu „{1}”. Jawna adnotacja typu może odblokować emitowanie deklaracji.", "Declaration_expected_1146": "Oczekiwano deklaracji.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Zainicjuj właściwość „{0}” w konstruktorze", "Initialize_static_property_0_90021": "Zainicjuj właściwość statyczną „{0}”", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Inicjator zmiennej składowej wystąpienia „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego w konstruktorze.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Inicjator parametru „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego po nim.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Inicjator nie określa żadnej wartości dla tego elementu powiązania, a element powiązania nie ma wartości domyślnej.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicjatory są niedozwolone w otaczających kontekstach.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicjuje projekt TypeScript i tworzy plik tsconfig.json.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Nieprawidłowe użycie elementu „{0}” w trybie z ograniczeniami.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Nieprawidłowa wartość elementu „jsxFactory”. „{0}” to nie jest prawidłowy identyfikator ani kwalifikowana nazwa.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Nieprawidłowa wartość opcji „--reactNamespace”. Element „{0}” nie jest prawidłowym identyfikatorem.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Typ elementu „{0}” nie jest prawidłowym elementem JSX.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Typ wystąpienia „{0}” nie jest prawidłowym elementem JSX.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Zwracany typ „{0}” nie jest prawidłowym elementem JSX.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Element JSDoc „@{0} {1}” nie pasuje do klauzuli „extends {2}”.", "JSDoc_0_is_not_attached_to_a_class_8022": "Element JSDoc „@{0}” nie został dołączony do klasy.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "Element „...” JSDoc może występować tylko w ostatnim parametrze sygnatury.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Emituj tylko pliki deklaracji „d.ts”.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Klauzula „extends” klasy obsługuje obecnie tylko identyfikatory/nazwy kwalifikowane z opcjonalnymi argumentami typu.", "Only_named_exports_may_use_export_type_1383": "Tylko nazwane eksporty mogą używać elementu „export type”.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Tylko wyliczenia numeryczne mogą mieć składowe obliczane, ale to wyrażenie ma typ „{0}”. Jeśli nie potrzebujesz sprawdzeń kompletności, rozważ użycie literału obiektu.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Tylko publiczne i chronione metody klasy bazowej są dostępne przy użyciu słowa kluczowego „super”.", "Operator_0_cannot_be_applied_to_type_1_2736": "Nie można zastosować operatora „{0}” do typu „{1}”.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Nie można zastosować operatora „{0}” do typów „{1}” i „{2}”.", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "Katalog wyjściowy dla wygenerowanych plików deklaracji.", "Output_file_0_from_project_1_does_not_exist_6309": "Plik wyjściowy „{0}” z projektu „{1}” nie istnieje", "Output_file_0_has_not_been_built_from_source_file_1_6305": "Plik wyjściowy „{0}” nie został utworzony na podstawie pliku źródłowego „{1}”.", - "Overload_0_of_1_2_gave_the_following_error_2772": "Przeciążenie {0} {1}, „{2}”, dało następujący błąd.", + "Overload_0_of_1_2_gave_the_following_error_2772": "Przeciążenie {0} z {1}, „{2}”, zwróciło następujący błąd.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Wszystkie sygnatury przeciążeń muszą być abstrakcyjne lub nieabstrakcyjne.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Wszystkie sygnatury przeciążeń muszą być otaczającymi sygnaturami lub żadna nie może być otaczającą sygnaturą.", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Wszystkie sygnatury przeciążeń muszą być wyeksportowane lub żadna nie może być wyeksportowana.", "Overload_signatures_must_all_be_optional_or_required_2386": "Wszystkie sygnatury przeciążeń muszą być opcjonalne lub wymagane.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Wszystkie sygnatury przeciążeń muszą być publiczne, prywatne lub chronione.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "Parametr „{0}” nie może być przywoływany w swoim inicjatorze.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Parametr „{0}” nie może przywoływać identyfikatora „{1}” zadeklarowanego po nim.", + "Parameter_0_cannot_reference_itself_2372": "Parametr „{0}” nie może odwoływać się do siebie samego.", "Parameter_0_implicitly_has_an_1_type_7006": "Dla parametru „{0}” niejawnie określono typ „{1}”.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Parametr „{0}” niejawnie ma typ „{1}”, ale lepszy typ można wywnioskować na podstawie użycia.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Parametr „{0}” nie znajduje się w tym samym położeniu co parametr „{1}”.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "Właściwość „{0}” nie istnieje w wyliczeniu ze specyfikatorem „const” „{1}”.", "Property_0_does_not_exist_on_type_1_2339": "Właściwość „{0}” nie istnieje w typie „{1}”.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Właściwość „{0}” nie istnieje w typie „{1}”. Czy chodziło Ci o „{2}”?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Właściwość „{0}” ma deklaracje będące w konflikcie i jest niedostępna w typie „{1}”.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „set” nie ma adnotacji typu parametru.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Ponowne eksportowanie typu, gdy podano flagę „--isolatedModules”, wymaga użycia aliasu „export type”.", "Redirect_output_structure_to_the_directory_6006": "Przekieruj strukturę wyjściową do katalogu.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Przywoływany projekt „{0}” musi mieć ustawienie „composite” o wartości true.", + "Remove_all_incorrect_body_block_braces_95115": "Usuń wszystkie niepoprawne nawiasy klamrowe bloku treści", "Remove_all_unnecessary_uses_of_await_95087": "Usuń wszystkie niepotrzebne użycia operatora „await”", "Remove_all_unreachable_code_95051": "Usuń cały nieosiągalny kod", "Remove_all_unused_labels_95054": "Usuń wszystkie nieużywane etykiety", + "Remove_block_body_braces_95112": "Usuń nawiasy klamrowe treści bloku", "Remove_braces_from_arrow_function_95060": "Usuń nawiasy klamrowe z funkcji strzałki", "Remove_destructuring_90009": "Usuń usuwanie struktury", "Remove_import_from_0_90005": "Usuń import z „{0}”", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Metawłaściwość „import.meta” jest dozwolona tylko wtedy, gdy opcja „--module” ma wartość „esnext” lub „system”.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Wywnioskowany typ „{0}” nie może być nazwany bez odwołania do elementu „{1}”. Prawdopodobnie nie jest to przenośne. Konieczna jest adnotacja typu.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Wnioskowany typ „{0}” przywołuje niedostępny typ „{1}”. Adnotacja typu jest konieczna.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Przecięcie „{0}” zostało zredukowane do wartości „never”, ponieważ właściwość „{1}” istnieje w wielu elementach składowych i w części z nich jest prywatna.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Przecięcie „{0}” zostało zredukowane do wartości „never”, ponieważ właściwość „{1}” zawiera typy powodujące konflikt w niektórych elementach składowych.", "The_last_overload_gave_the_following_error_2770": "Ostatnie przeciążenie dało następujący błąd.", "The_last_overload_is_declared_here_2771": "Ostatnie przeciążenie jest zadeklarowane tutaj.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Lewa strona instrukcji „for...in” nie może być wzorcem usuwającym strukturę.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Operand operatora „delete” nie może być identyfikatorem prywatnym.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Operand operatora „delete” nie może być właściwością tylko do odczytu.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Operand operatora „delete” musi być odwołaniem do właściwości.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Operand operatora „delete” musi być opcjonalny.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Operand operatora inkrementacji lub dekrementacji nie może być opcjonalnym dostępem do właściwości.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Operand operatora inkrementacji lub dekrementacji musi być zmienną lub dostępem do właściwości.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "Analizator oczekiwał odnalezienia elementu „}” w celu dopasowania do tokenu „{” w tym miejscu.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "To wyrażenie nie jest wywoływalne.", "This_expression_is_not_constructable_2351": "Tego wyrażenia nie można skonstruować.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Ten import nigdy nie jest używany jako wartość i musi używać aliasu „import type”, ponieważ opcja „importsNotUsedAsValues” jest ustawiona na wartość „error”.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "To jest rozszerzana deklaracja. Rozważ przeniesienie deklaracji rozszerzenia do tego samego pliku.", "This_may_be_converted_to_an_async_function_80006": "To można przekonwertować na funkcję asynchroniczną.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Do tego modułu można odwoływać się tylko za pomocą importów/eksportów języka ECMAScript, włączając flagę „{0}” i odwołując się do jego eksportu domyślnego.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Ten moduł jest zadeklarowany przy użyciu składni „export =” i może być używany tylko z importem domyślnym, gdy jest używana flaga „{0}”.", @@ -1159,7 +1174,7 @@ "Type_0_has_no_matching_index_signature_for_type_1_2537": "Typ „{0}” nie ma pasującej sygnatury indeksu dla typu „{1}”.", "Type_0_has_no_properties_in_common_with_type_1_2559": "Typy „{0}” i „{1}” nie mają żadnych wspólnych właściwości.", "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "W typie „{0}” brakuje następujących właściwości z typu „{1}”: {2}", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "W typie „{0}” brakuje następujących właściwości typu „{1}”: {2} i {3} więcej.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "W typie „{0}” brakuje następujących właściwości z typu „{1}”: {2} i jeszcze {3}.", "Type_0_is_not_a_constructor_function_type_2507": "Typ „{0}” nie jest typem funkcji konstruktora.", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Typ „{0}” nie jest prawidłowym zwracanym typem funkcji asynchronicznej w wersji ES5/ES3, ponieważ nie odwołuje się do wartości konstruktora zgodnej z elementem Promise.", "Type_0_is_not_an_array_type_2461": "Typ „{0}” nie jest typem tablicowym.", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Trwa aktualizowanie niezmienionych sygnatur czasowych danych wyjściowych projektu „{0}”...", "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "Używanie opcji kompilatora przekierowania odwołania do projektu „{0}”.", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", "VERSION_6036": "WERSJA", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Wartość typu „{0}” nie ma żadnych wspólnych właściwości z typem „{1}”. Czy jej wywołanie było zamierzone?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Nie można wywołać wartości typu „{0}”. Czy miał zostać użyty operator „new”?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Oczekiwano deklaracji zmiennej.", "Variable_declaration_list_cannot_be_empty_1123": "Lista deklaracji zmiennych nie może być pusta.", "Version_0_6029": "Wersja {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Odwiedź witrynę https://aka.ms/tsconfig.json, aby dowiedzieć się więcej o tym pliku", "Watch_input_files_6005": "Obserwuj pliki wejściowe.", "Watch_option_0_requires_a_value_of_type_1_5080": "Opcja obserwowania „{0}” wymaga wartości typu {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Określa, czy zachować nieaktualne dane wyjściowe konsoli w trybie śledzenia zamiast wyczyścić ekran.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Opakuj wszystkie nieprawidłowe znaki w kontenerze wyrażenia", + "Wrap_all_object_literal_with_parentheses_95116": "Zawijaj wszystkie literały obiektu z nawiasami", "Wrap_invalid_character_in_an_expression_container_95108": "Opakuj nieprawidłowy znak w kontenerze wyrażenia", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Zawijaj następującą treść z nawiasami, która powinna być literałem obiektu", "You_cannot_rename_a_module_via_a_global_import_8031": "Nie można zmienić nazwy modułu za pomocą importu globalnego.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Nie można zmienić nazw elementów zdefiniowanych w standardowej bibliotece TypeScript.", "You_cannot_rename_this_element_8000": "Nie można zmienić nazwy tego elementu.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "Element „{0}” akceptuje za mało argumentów, aby można go było użyć w tym miejscu jako dekorator. Czy chcesz najpierw go wywołać i zapisać tag „@{0}()”?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Operacji „{0}” i „{1}” nie można mieszać bez nawiasów.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "Element „{0}” został określony dwa razy. Atrybut o nazwie „{0}” zostanie przesłonięty.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "Element „{0}” można zaimportować tylko przez włączenie flagi „esModuleInterop” i użycie importu domyślnego.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "Element „{0}” można zaimportować tylko przy użyciu importu domyślnego.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "Element „{0}” można zaimportować za pomocą wywołania „require” lub przez włączenie flagi „esModuleInterop” i użycie importu domyślnego.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "Element „{0}” można zaimportować tylko za pomocą wywołania „require” lub przy użyciu importu domyślnego.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "Element „{0}” można zaimportować tylko przy użyciu wyrażenia „import {1} = require({2})” lub importu domyślnego.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "Element „{0}” można zaimportować tylko przy użyciu wyrażenia „import {1} = require({2})” lub przez włączenie flagi „esModuleInterop” i użycie importu domyślnego.", + "_0_cannot_be_used_as_a_JSX_component_2786": "Elementu „{0}” nie można użyć jako składnika JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "Element „{0}” nie może być używany jako wartość, ponieważ został wyeksportowany przy użyciu aliasu „export type”.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "Element „{0}” nie może być używany jako wartość, ponieważ został zaimportowany przy użyciu aliasu „import type”.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Składniki „{0}” nie akceptują tekstu jako elementów podrzędnych. Tekst w JSX ma typ „string”, ale oczekiwany typ elementu „{1}” to „{2}”.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "„#constructor” jest słowem zastrzeżonym.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Nie można wywołać elementu „delete” dla identyfikatora w trybie z ograniczeniami.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "usuń to — projekt „{0}” jest aktualny, ponieważ został wcześniej skompilowany", + "export_Asterisk_does_not_re_export_a_default_1195": "Wyrażenie „export *” nie eksportuje ponownie wartości domyślnej.", "export_can_only_be_used_in_TypeScript_files_8003": "Składnia „export =” może być używana tylko w plikach TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Modyfikator „export” nie może być stosowany do modułów otoczenia ani rozszerzeń modułów, ponieważ są one zawsze widoczne.", "extends_clause_already_seen_1172": "Napotkano już klauzulę „extends”.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 752b5931c932e..531bc4a5e8e71 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -2117,7 +2117,7 @@ declare namespace ts.server.protocol { /** * Arguments for navto request message. */ - interface NavtoRequestArgs extends FileRequestArgs { + interface NavtoRequestArgs { /** * Search term to navigate to from current location; term can * be '.*' or an identifier prefix. @@ -2127,6 +2127,10 @@ declare namespace ts.server.protocol { * Optional limit on the number of items to return. */ maxResultCount?: number; + /** + * The file for the request (absolute pathname required). + */ + file?: string; /** * Optional flag to indicate we want results for just the current file * or the entire project. @@ -2140,7 +2144,7 @@ declare namespace ts.server.protocol { * match the search term given in argument 'searchTerm'. The * context for the search is given by the named file. */ - interface NavtoRequest extends FileRequest { + interface NavtoRequest extends Request { command: CommandTypes.Navto; arguments: NavtoRequestArgs; } diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 50506014e7c44..b9e4fdd72e28f 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Uma declaração de namespace não pode estar em um arquivo diferente de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Uma expressão 'new' com argumentos de tipo precisa ser sempre seguida por uma lista de argumentos entre parênteses.", "A_non_dry_build_would_build_project_0_6357": "Um build não -dry criaria o projeto '{0}'", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "Um build não -dry excluiria os seguintes arquivos: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Um build não -dry atualizaria a saída do projeto '{0}'", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", "Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"", "Add_0_to_unresolved_variable_90008": "Adicionar '{0}.' à variável não resolvida", + "Add_a_return_statement_95111": "Adicionar uma instrução return", "Add_all_missing_async_modifiers_95041": "Adicionar todos os modificadores 'async' ausentes", "Add_all_missing_call_parentheses_95068": "Adicionar todos os parênteses de chamada ausentes", "Add_all_missing_imports_95064": "Adicionar todas as importações ausentes", "Add_all_missing_members_95022": "Adicionar todos os membros ausentes", + "Add_all_missing_return_statement_95114": "Adicionar todas as instruções return ausentes", "Add_all_missing_super_calls_95039": "Adicionar todas as chamadas super ausentes", "Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função", "Add_await_95083": "Adicionar 'await'", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Um caminho de importação não pode terminar com uma extensão '{0}'. Considere importar '{1}'.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Um argumento de expressão de índice deve ser do tipo 'string', 'number', 'symbol' ou 'any'.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Uma assinatura de índice não pode ter um parâmetro rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Uma assinatura de índice não pode ter uma vírgula à direita.", "An_index_signature_must_have_a_type_annotation_1021": "Uma assinatura de índice deve ter uma anotação de tipo.", "An_index_signature_must_have_exactly_one_parameter_1096": "Uma assinatura de índice deve ter exatamente um parâmetro.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Um parâmetro de assinatura de índice não pode ter um ponto de interrogação.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Não é possível iterar o valor porque o método 'next' de seu iterador espera o tipo '{1}', mas o array spread sempre enviará '{0}'.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Não é possível iterar o valor porque o método 'next' de seu iterador espera o tipo '{1}', mas a instrução for-of sempre enviará '{0}'.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Não é possível preceder o projeto '{0}' porque ele não tem o conjunto 'outFile'", + "Cannot_read_file_0_5083": "Não é possível ler o arquivo '{0}'.", "Cannot_read_file_0_Colon_1_5012": "Não é possível ler o arquivo '{0}': {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Não é possível declarar novamente a variável de escopo de bloco '{0}'.", "Cannot_redeclare_exported_variable_0_2323": "Não é possível redeclarar a variável exportada '{0}'.", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "Compile o projeto dando o caminho para seu arquivo de configuração ou para uma pasta com um 'tsconfig.json'.", "Compiler_option_0_expects_an_argument_6044": "A opção do compilador '{0}' espera um argumento.", "Compiler_option_0_requires_a_value_of_type_1_5024": "A opção do compilador '{0}' requer um valor do tipo {1}.", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "O compilador reserva o nome '{0}' ao emitir um nível inferior de identificador privado.", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "O compilador reserva o nome '{0}' ao emitir um identificador privado para versões anteriores.", "Composite_projects_may_not_disable_declaration_emit_6304": "Projetos compostos não podem desabilitar a emissão de declaração.", "Composite_projects_may_not_disable_incremental_compilation_6379": "Projetos compostos podem não desabilitar a compilação incremental.", "Computed_property_names_are_not_allowed_in_enums_1164": "Nomes de propriedade calculados não são permitidos em enums.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Não foi possível resolver o caminho '{0}' com as extensões: {1}.", "Could_not_write_file_0_Colon_1_5033": "Não foi possível gravar o arquivo '{0}': {1}.", "DIRECTORY_6038": "DIRETÓRIO", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "A declaração aumenta a declaração em outro arquivo. Isso não pode ser serializado.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "A emissão de declaração para esse arquivo requer o uso do nome privado '{0}'. Uma anotação de tipo explícita pode desbloquear a emissão de declaração.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "A emissão de declaração para esse arquivo requer o uso do nome privado '{0}' do módulo '{1}'. Uma anotação de tipo explícita pode desbloquear a emissão de declaração.", "Declaration_expected_1146": "Declaração esperada.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Inicializar a propriedade '{0}' no construtor", "Initialize_static_property_0_90021": "Inicializar a propriedade estática '{0}'", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "O inicializador da variável de membro de instância '{0}' não pode referenciar o identificador '{1}' declarado no construtor.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "O inicializador do parâmetro '{0}' não pode referenciar o identificador '{1}' declarado depois dele.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "O inicializador não fornece um valor para esse elemento de associação e o elemento de associação não tem valor padrão.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Inicializadores não são permitidos em contextos de ambiente.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Inicializa um projeto TypeScript e cria um arquivo tsconfig.json.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Uso inválido de '{0}' no modo estrito.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Valor inválido para 'jsxFactory'. '{0}' não é um identificador válido ou nome qualificado.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Valor inválido para '--reactNamespace'. '{0}' não é um identificador válido.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "O tipo de elemento '{0}' não é um elemento JSX válido.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "O tipo de instância '{0}' não é um elemento JSX válido.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "O tipo de retorno '{0}' não é um elemento JSX válido.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "O '@{0} {1}' do JSDoc não corresponde à cláusula 'extends {2}'.", "JSDoc_0_is_not_attached_to_a_class_8022": "O '@{0}' do JSDoc não está anexado a uma classe.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' só pode aparecer no último parâmetro de uma assinatura.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Emita somente arquivos de declaração '.d.ts'.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Somente os identificadores/nomes qualificados com argumentos de tipo opcionais tem suporte atualmente nas cláusulas de classe 'extends'.", "Only_named_exports_may_use_export_type_1383": "Somente as exportações nomeadas podem usar 'tipo de exportação'.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Somente enumerações numéricas podem ter membros computados, mas esta expressão tem o tipo '{0}'. Se você não precisar de verificações de exaustão, considere o uso de um literal de objeto.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Somente métodos protegidos e públicos da classe base são acessíveis pela palavra-chave 'super'.", "Operator_0_cannot_be_applied_to_type_1_2736": "O operador '{0}' não pode ser aplicado ao tipo '{1}'.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "O operador '{0}' não pode ser aplicado aos tipos '{1}' e '{2}'.", @@ -799,7 +808,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Assinaturas de sobrecarga devem todas ser exportadas ou não exportadas.", "Overload_signatures_must_all_be_optional_or_required_2386": "Todas as assinaturas de sobrecarga devem ser opcionais ou obrigatórias.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Todas as assinaturas de sobrecarga devem ser protegidas, privadas ou públicas.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "O parâmetro '{0}' não pode ser referenciado em seu inicializador.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "O parâmetro '{0}' não pode referenciar o identificador '{1}' declarado depois dele.", + "Parameter_0_cannot_reference_itself_2372": "O parâmetro '{0}' não pode referenciar a si mesmo.", "Parameter_0_implicitly_has_an_1_type_7006": "O parâmetro '{0}' implicitamente tem um tipo '{1}'.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "O parâmetro '{0}' implicitamente tem um tipo '{1}', mas um tipo melhor pode ser inferido do uso.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "O parâmetro '{0}' não está na mesma posição que o parâmetro '{1}'.", @@ -839,7 +849,7 @@ "Prefix_0_with_an_underscore_90025": "Prefixo '{0}' com um sublinhado", "Prefix_all_incorrect_property_declarations_with_declare_95095": "Prefixar todas as declarações de propriedade incorretas com 'declare'", "Prefix_all_unused_declarations_with_where_possible_95025": "Prefixar com '_' todas as declarações não usadas quando possível", - "Prefix_with_declare_95094": "Prefixo com 'declare'", + "Prefix_with_declare_95094": "Prefixar com 'declare'", "Print_names_of_files_part_of_the_compilation_6155": "Nomes de impressão das partes dos arquivos da compilação.", "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "Imprima nomes de arquivos que fazem parte da compilação e, em seguida, interrompa o processamento.", "Print_names_of_generated_files_part_of_the_compilation_6154": "Nomes de impressão das partes dos arquivos gerados da compilação.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "A propriedade '{0}' não existe na enumeração 'const' '{1}'.", "Property_0_does_not_exist_on_type_1_2339": "A propriedade '{0}' não existe no tipo '{1}'.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "A propriedade '{0}' não existe no tipo '{1}'. Você quis dizer '{2}'?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "A propriedade '{0}' tem declarações conflitantes e é inacessível no tipo '{1}'.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador set não tem uma anotação de tipo de parâmetro.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Exportar novamente um tipo quando o sinalizador '--isolatedModules' é fornecido requer o uso de 'export type'.", "Redirect_output_structure_to_the_directory_6006": "Redirecione a estrutura de saída para o diretório.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "O projeto referenciado '{0}' deve ter a configuração de \"composite\": true.", + "Remove_all_incorrect_body_block_braces_95115": "Remover todas as chaves incorretas do bloco de corpo", "Remove_all_unnecessary_uses_of_await_95087": "Remover todos os usos desnecessários de 'await'", "Remove_all_unreachable_code_95051": "Remover todo o código inacessível", "Remove_all_unused_labels_95054": "Remover todos os rótulos não utilizados", + "Remove_block_body_braces_95112": "Remover as chaves do corpo do bloco", "Remove_braces_from_arrow_function_95060": "Remover chaves da função de seta", "Remove_destructuring_90009": "Remover desestruturação", "Remove_import_from_0_90005": "Remover importação de '{0}'", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "A metapropriedade 'import.meta' só é permitida quando a opção '--module' é 'esnext' ou 'system'.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "O tipo inferido de '{0}' não pode ser nomeado sem uma referência a '{1}'. Isso provavelmente não é portátil. Uma anotação de tipo é necessária.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "O tipo inferido de '{0}' faz referência a um tipo '{1}' inacessível. Uma anotação de tipo é necessária.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "A interseção '{0}' foi reduzida para 'never' porque a propriedade '{1}' existe em vários constituintes e é privada em alguns.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "A interseção '{0}' foi reduzida para 'never' porque a propriedade '{1}' tem tipos conflitantes em alguns constituintes.", "The_last_overload_gave_the_following_error_2770": "A última sobrecarga gerou o seguinte erro.", "The_last_overload_is_declared_here_2771": "A última sobrecarga é declarada aqui.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "O lado esquerdo de uma instrução 'for...in' não pode ser um padrão de desestruturação.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "O operando de um operador 'delete' pode não ser um identificador privado.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "O operando de um operador 'delete' não pode ser uma propriedade somente leitura.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "O operando de um operador 'delete' deve ser uma referência de propriedade.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "O operando de um operador 'delete' precisa ser opcional.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "O operando de um operador de incremento ou decremento pode não ser um acesso opcional de propriedade.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "O operando de um operador de incremento ou decremento deve ser uma variável ou um acesso à propriedade.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "O analisador esperava localizar um '}' para corresponder ao token '{' aqui.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Essa expressão não pode ser chamada.", "This_expression_is_not_constructable_2351": "Essa expressão não pode ser construída.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Essa importação nunca é usada como um valor e deve usar 'tipo de importação' porque 'importsNotUsedAsValues' está definido como 'erro'.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Esta é a declaração que está sendo aumentada. Considere mover a declaração em aumento para o mesmo arquivo.", "This_may_be_converted_to_an_async_function_80006": "Isso pode ser convertido em uma função assíncrona.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Esse módulo só pode ser referenciado com importações/exportações de ECMAScript ligando o sinalizador '{0}' e referenciando sua exportação padrão.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Esse módulo é declarado com o uso de 'export =' e só pode ser usado com uma importação padrão ao usar o sinalizador '{0}'.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "O tipo de elementos iterados de um operando \"yield*\" deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "O tipo de propriedade '{0}' faz referência circular a si mesmo no tipo mapeado '{1}'.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "O tipo do operando \"yield\" em um gerador assíncrono deve ser uma promessa válida ou não deve conter um membro \"then\" que pode ser chamado.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "O tipo se origina nessa importação. Uma importação de estilo de namespace não pode ser chamada nem construída e causará uma falha no runtime. Considere usar uma importação padrão ou solicite uma importação aqui.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "O tipo se origina nessa importação. Uma importação de estilo de namespace não pode ser chamada nem construída e causará uma falha no runtime. Considere usar uma importação padrão ou importe require aqui.", "Type_parameter_0_has_a_circular_constraint_2313": "O parâmetro de tipo '{0}' tem uma restrição circular.", "Type_parameter_0_has_a_circular_default_2716": "O parâmetro de tipo '{0}' tem um padrão circular.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "O parâmetro de tipo '{0}' da assinatura de chamada da interface exportada tem ou está usando o nome particular '{1}'.", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Atualizando os carimbos de data/hora de saída inalterados do projeto '{0}'...", "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "Usando opções de compilador de redirecionamento de referência de projeto '{0}'.", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", "VERSION_6036": "VERSÃO", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "O valor do tipo '{0}' não tem propriedades em comum com o tipo '{1}'. Você queria chamá-lo?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "O valor do tipo '{0}' não pode ser chamado. Você pretendia incluir 'new'?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Declaração de variável esperada.", "Variable_declaration_list_cannot_be_empty_1123": "A lista de declaração de variável não pode estar vazia.", "Version_0_6029": "Versão {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Visite https://aka.ms/tsconfig.json para ler mais sobre este arquivo", "Watch_input_files_6005": "Observe os arquivos de entrada.", "Watch_option_0_requires_a_value_of_type_1_5080": "A opção do observador '{0}' requer um valor do tipo {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Se é necessário manter a saída de console desatualizada no modo de inspeção, em vez de limpar a tela.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Encapsular todos os caracteres inválidos em um contêiner de expressão", + "Wrap_all_object_literal_with_parentheses_95116": "Colocar todo o literal de objeto entre parênteses", "Wrap_invalid_character_in_an_expression_container_95108": "Encapsular caractere inválido em um contêiner de expressão", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Colocar entre parênteses o corpo a seguir, que deve ser um literal de objeto", "You_cannot_rename_a_module_via_a_global_import_8031": "Não é possível renomear um módulo por meio de uma importação global.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Não é possível renomear elementos que são definidos na biblioteca TypeScript padrão.", "You_cannot_rename_this_element_8000": "Você não pode renomear este elemento.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' aceita muito poucos argumentos para serem usados como um decorador aqui. Você quis dizer para chamá-lo primeiro e gravar '@{0}()'?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "As operações '{0}' e '{1}' não podem ser combinadas sem parênteses.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' são especificados duas vezes. O atributo chamado '{0}' será substituído.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' só pode ser importado ativando o sinalizador 'esModuleInterop' e usando uma importação padrão.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' só pode ser importado usando uma importação padrão.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' só pode ser importado usando uma chamada 'require' ou ativando o sinalizador 'esModuleInterop' e usando uma importação padrão.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' só pode ser importado usando uma chamada 'require' ou usando uma importação padrão.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' só pode ser importado usando 'import {1} = require({2})' ou uma importação padrão.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' só pode ser importado usando 'import {1} = require({2})' ou ativando o sinalizador 'esModuleInterop' e usando uma importação padrão.", + "_0_cannot_be_used_as_a_JSX_component_2786": "O módulo '{0}' não pode ser usado como um componente JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}' não pode ser usado como um valor porque foi exportado usando 'tipo de exportação'.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}' não pode ser usado como um valor porque foi importado usando 'tipo de importação'.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Os componentes '{0}' não aceitam texto como elementos filho. O texto em JSX tem o tipo 'cadeia de caracteres', mas o tipo esperado de '{1}' é '{2}'.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' é uma palavra reservada.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' não pode ser chamado em um identificador no modo estrito.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "excluir isto – o Projeto '{0}' está atualizado porque ele já foi compilado", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' não exporta novamente um padrão.", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' só pode ser usado em arquivos TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "O modificador 'export' não pode ser aplicado a módulos de ambiente e acréscimos de módulo, pois eles estão sempre visíveis.", "extends_clause_already_seen_1172": "A cláusula 'extends' já foi vista.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index af3a6ddc10ec8..18c10e5edad46 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Объявление пространства имен и класс или функция, с которыми оно объединено, не могут находится в разных файлах.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Объявление пространства имен не может располагаться раньше класса или функции, с которыми оно объединено.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Объявление пространства имен разрешено использовать только в пространстве имен или модуле.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "После выражения \"new\" с аргументами типа должен всегда следовать список аргументов в круглых скобках.", "A_non_dry_build_would_build_project_0_6357": "При сборке без флага -dry будет собран проект \"{0}\"", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "При сборке без флага -dry будут удалены следующие файлы: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "Сборка без флага -dry обновит выходные данные проекта \"{0}\"", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.", "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"", "Add_0_to_unresolved_variable_90008": "Добавить \"{0}.\" к неразрешенной переменной", + "Add_a_return_statement_95111": "Добавить оператор return", "Add_all_missing_async_modifiers_95041": "Добавить все отсутствующие модификаторы \"async\"", "Add_all_missing_call_parentheses_95068": "Добавить все недостающие скобки вызова", "Add_all_missing_imports_95064": "Добавить все отсутствующие импорты", "Add_all_missing_members_95022": "Добавить все отсутствующие элементы", + "Add_all_missing_return_statement_95114": "Добавить все отсутствующие операторы return", "Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super", "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", "Add_await_95083": "Добавить \"await\"", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "Добавление импорта \"{0}\" по умолчанию в существующее объявление импорта из \"{1}\"", "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам", - "Add_export_to_make_this_file_into_a_module_95097": "Добавить \"export {}\", чтобы сделать этот файл модулем", + "Add_export_to_make_this_file_into_a_module_95097": "Добавить \"export {}\", чтобы превратить этот файл в модуль", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "Путь импорта не может заканчиваться расширением \"{0}\". Попробуйте импортировать \"{1}\".", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Аргумент выражения индекса должен иметь тип string, number, symbol или any.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Сигнатура индекса не может иметь параметр rest.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Сигнатура индекса не может заканчиваться запятой.", "An_index_signature_must_have_a_type_annotation_1021": "У сигнатуры индекса должна быть аннотация типа.", "An_index_signature_must_have_exactly_one_parameter_1096": "У сигнатуры индекса должен быть ровно один параметр.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Параметр сигнатуры индекса не может содержать вопросительный знак.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Не удается выполнить итерацию по значению, так как метод \"next\" его итератора ожидает тип \"{1}\", но расширение массива всегда будет отправлять \"{0}\".", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Не удается выполнить итерацию по значению, так как метод \"next\" его итератора ожидает тип \"{1}\", но \"for-of\" всегда будет отправлять \"{0}\".", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "Невозможно добавить проект \"{0}\" в начало, так как для него не задан outFile", + "Cannot_read_file_0_5083": "Невозможно прочитать файл \"{0}\".", "Cannot_read_file_0_Colon_1_5012": "Не удается считать файл \"{0}\": {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Невозможно повторно объявить переменную \"{0}\" с областью видимости \"Блок\".", "Cannot_redeclare_exported_variable_0_2323": "Не удается повторно объявить экспортированную переменную \"{0}\".", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Не удалось разрешить путь \"{0}\" с расширениями: {1}.", "Could_not_write_file_0_Colon_1_5033": "Не удалось записать файл \"{0}\": \"{1}\".", "DIRECTORY_6038": "КАТАЛОГ", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Объявление дополняет объявление в другом файле. Сериализация невозможна.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Для порождения объявления для этого файла требуется использовать закрытое имя \"{0}\". Явная заметка с типом может разблокировать порождение объявления.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Для порождения объявления для этого файла требуется использовать закрытое имя \"{0}\" из модуля \"{1}\". Явная заметка с типом может разблокировать порождение объявления.", "Declaration_expected_1146": "Ожидалось объявление.", @@ -606,7 +612,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "Объявление импорта \"{0}\" использует закрытое имя \"{1}\".", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "Объявление импорта конфликтует с локальным объявлением \"{0}\".", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "Объявления импорта в пространстве имен не могут иметь ссылки на модуль.", - "Import_default_0_from_module_1_90032": "Импорт \"{0}\" по умолчанию из модуля \"{1}\"", + "Import_default_0_from_module_1_90032": "Импортировать \"{0}\" по умолчанию из модуля \"{1}\"", "Import_emit_helpers_from_tslib_6139": "Импорт вспомогательных объектов, участвующих в порождении, из \"tslib\".", "Import_may_be_converted_to_a_default_import_80003": "Импорт можно преобразовать в импорт по умолчанию.", "Import_name_cannot_be_0_2438": "Имя импорта не может иметь значение \"{0}\".", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Инициализируйте свойство \"{0}\" в конструкторе", "Initialize_static_property_0_90021": "Инициализируйте статическое свойство \"{0}\"", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "Инициализатор переменной-элемента экземпляра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный в конструкторе.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Инициализатор параметра \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный после него.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Инициализатор не предоставляет значения для элемента привязки, который не имеет значения по умолчанию.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Инициализаторы не разрешены в окружающих контекстах.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Инициализирует проект TypeScript и создает файл \"tsconfig.json\".", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Недопустимое использование \"{0}\" в строгом режиме.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "Недопустимое значение для jsxFactory. \"{0}\" не является допустимым идентификатором или полным именем.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "Недопустимое значение для \"--reactNamespace\". \"{0}\" не является допустимым идентификатором.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "Тип элемента \"{0}\" не является допустимым элементом JSX.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "Тип экземпляра \"{0}\" не является допустимым элементом JSX.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "Тип возвращаемого значения \"{0}\" не является допустимым элементом JSX.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "Параметр \"@{0} {1}\" JSDoc не соответствует предложению \"extends {2}\".", "JSDoc_0_is_not_attached_to_a_class_8022": "Параметр \"@{0}\" JSDoc не связан с классом.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" может использоваться только в последнем параметре сигнатуры.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Порождаются только файлы объявлений \".d.ts\".", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "В предложениях extends класса сейчас поддерживаются только идентификаторы или полные имена с необязательными аргументами типа.", "Only_named_exports_may_use_export_type_1383": "Только именованные экспорты могут использовать export type.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Только числовые перечисления могут иметь вычисляемые элементы, но это выражение имеет тип \"{0}\". Если вы не хотите проверять полноту, рекомендуется использовать вместо этого объектный литерал.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "Через ключевое слово super доступны только общие и защищенные методы базового класса.", "Operator_0_cannot_be_applied_to_type_1_2736": "Не удается применить операнд \"{0}\" к типу \"{1}\".", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "Оператор \"{0}\" невозможно применить к типам \"{1}\" и \"{2}\".", @@ -799,7 +808,8 @@ "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Сигнатуры перегрузки должны быть экспортированы и не экспортированы.", "Overload_signatures_must_all_be_optional_or_required_2386": "Все сигнатуры перегрузки должны быть либо необязательными, либо обязательными.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Все сигнатуры перегрузки должны быть либо общими, либо закрытыми, либо защищенными.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "На параметр \"{0}\" невозможно ссылаться в его инициализаторе.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "Параметр \"{0}\" не может ссылаться на идентификатор \"{1}\", объявленный после него.", + "Parameter_0_cannot_reference_itself_2372": "Параметр \"{0}\" не может ссылаться сам на себя.", "Parameter_0_implicitly_has_an_1_type_7006": "Параметр \"{0}\" неявно имеет тип \"{1}\".", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "Параметр \"{0}\" неявно имеет тип \"{1}\", но из использования можно определить более подходящий тип.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "Параметр \"{0}\" находится в позиции, отличной от позиции параметра \"{1}\".", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "Свойство \"{0}\" не существует в перечислении const \"{1}\".", "Property_0_does_not_exist_on_type_1_2339": "Свойство \"{0}\" не существует в типе \"{1}\".", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "Свойство \"{0}\" не существует в типе \"{1}\". Вы имели в виду \"{2}\"?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "Свойство \"{0}\" содержит конфликтующие объявления и недоступно в типе \"{1}\".", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа set не задана заметка с типом параметра.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "Для повторного экспорта типа при указании флага \"--isolatedModules\" требуется использовать \"export type\".", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Указанный в ссылке проект \"{0}\" должен иметь следующее значение параметра composite: true.", + "Remove_all_incorrect_body_block_braces_95115": "Удалить все неправильные фигурные скобки вокруг тел блоков", "Remove_all_unnecessary_uses_of_await_95087": "Удаление всех ненужных случаев использования \"await\"", "Remove_all_unreachable_code_95051": "Удалить весь недостижимый код", "Remove_all_unused_labels_95054": "Удалить все неиспользуемые метки", + "Remove_block_body_braces_95112": "Удалить фигурные скобки вокруг тела блока", "Remove_braces_from_arrow_function_95060": "Удалить скобки из стрелочной функции", "Remove_destructuring_90009": "Удалить деструктурирование", "Remove_import_from_0_90005": "Удалить импорт из \"{0}\"", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "Метасвойство \"import.meta\" разрешено, только если параметр \"--module\" имеет значение \"esnext\" или \"system\".", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "Выводимому типу \"{0}\" невозможно присвоить имя без ссылки на \"{1}\". Вероятно, оно не является переносимым. Требуется заметка с типом.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Выведенный тип \"{0}\" ссылается на недоступный тип \"{1}\". Требуется аннотация типа.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "Пересечение \"{0}\" было сокращено до \"never\", так как свойство \"{1}\" существует в нескольких составляющих и является частным в некоторых из них.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "Пересечение \"{0}\" было сокращено до \"never\", так как свойство \"{1}\" имеет конфликтующие типы в некоторых составляющих.", "The_last_overload_gave_the_following_error_2770": "Последняя перегрузка возвратила следующую ошибку.", "The_last_overload_is_declared_here_2771": "Здесь объявлена последняя перегрузка.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "Левый операнд оператора for...in не может быть шаблоном деструктурирования.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "Операнд оператора \"delete\" не может быть закрытым идентификатором.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "Операнд оператора \"delete\" не может быть свойством только для чтения.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "Операнд оператора \"delete\" должен быть ссылкой на свойство.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "Операнд оператора \"delete\" должен быть необязательным.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Операнд оператора инкремента или декремента не может быть обращением к необязательному свойству.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Операнд оператора инкремента или декремента должен быть переменной или доступом к свойству.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "Анализатор ожидал найти \"}\" для соответствия указанному здесь токену \"{\".", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Это выражение не является вызываемым.", "This_expression_is_not_constructable_2351": "Это выражение не может быть построено.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "Этот импорт никогда не используется в качестве значения и должен использовать \"import type\", так как для \"importsNotUsedAsValues\" задано значение \"error\".", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Это объявление дополняется другим объявлением. Попробуйте переместить дополняющее объявление в тот же файл.", "This_may_be_converted_to_an_async_function_80006": "Это можно преобразовать в асинхронную функцию.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "На этот модуль можно ссылаться только с помощью импортов/экспортов ECMAScript, включив флаг \"{0}\" и сославшись на его экспорт по умолчанию.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Этот модуль объявлен с помощью \"export =\" и может использоваться только с импортом по умолчанию при использовании флага \"{0}\".", @@ -1158,7 +1173,7 @@ "Type_0_has_no_construct_signatures_2761": "Тип \"{0}\" не содержит сигнатуры конструкции.", "Type_0_has_no_matching_index_signature_for_type_1_2537": "Тип \"{0}\" не содержит соответствующую сигнатуру индекса для типа \"{1}\".", "Type_0_has_no_properties_in_common_with_type_1_2559": "У типа \"{0}\" нет общих свойств с типом \"{1}\".", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "В типе \"{0}\" отсутствуют следующие свойства из типа \"{1}\": {2}.", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "В типе \"{0}\" отсутствуют следующие свойства из типа \"{1}\": {2}", "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "В типе \"{0}\" отсутствуют следующие свойства из типа \"{1}\": {2} и еще {3}.", "Type_0_is_not_a_constructor_function_type_2507": "Тип \"{0}\" не является типом функции конструктора.", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "Тип \"{0}\" не является допустимым типом возвращаемого значения асинхронной функции в ES5/ES3, так как он не ссылается на значение конструктора, совместимое с Promise.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Тип элементов итерации для операнда \"yield*\" должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "Тип свойства \"{0}\" циклически ссылается на самого себя в сопоставленном типе \"{1}\".", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Тип операнда \"yield\" в асинхронном генераторе должен быть допустимым обещанием либо не должен содержать вызываемый элемент \"then\".", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Тип происходит от этого импорта. Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения. Вместо этого рекомендуется использовать импорт по умолчанию или импорт, указанный здесь.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Тип происходит от этого импорта. Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения. Вместо этого рекомендуется использовать импорт по умолчанию или импортировать сюда \"require\".", "Type_parameter_0_has_a_circular_constraint_2313": "Параметр типа \"{0}\" содержит циклическое ограничение.", "Type_parameter_0_has_a_circular_default_2716": "Параметр типа \"{0}\" по умолчанию является циклическим.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Параметр типа \"{0}\" сигнатуры вызова из экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "Обновление меток времени в неизменившихся выходных данных проекта \"{0}\"...", "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", - "Using_compiler_options_of_project_reference_redirect_0_6215": "Использование параметров компилятора перенаправления ссылки на проект \"{0}\".", + "Using_compiler_options_of_project_reference_redirect_0_6215": "Использование параметров компилятора для перенаправления ссылки на проект \"{0}\".", "VERSION_6036": "ВЕРСИЯ", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Значение типа \"{0}\" не имеет общих свойств со значением типа \"{1}\". Вы хотели вызвать его?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "Значение типа \"{0}\" не может вызываться. Вы хотели использовать new?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Ожидалось объявление переменной.", "Variable_declaration_list_cannot_be_empty_1123": "Список объявлений переменной не может быть пустым.", "Version_0_6029": "Версия {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Дополнительные сведения об этом файле: https://aka.ms/tsconfig.json.", "Watch_input_files_6005": "Просмотр входных файлов.", "Watch_option_0_requires_a_value_of_type_1_5080": "Параметр \"{0}\" контрольного значения требует значение типа {1}.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Сохранять ли устаревшие выходные данные консоли в режиме просмотра вместо очистки экрана.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Заключение всех недопустимых символов в контейнер выражений", + "Wrap_all_object_literal_with_parentheses_95116": "Заключить все литералы объектов в круглые скобки", "Wrap_invalid_character_in_an_expression_container_95108": "Заключение недопустимого знака в контейнер выражений", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Заключить следующий текст в круглые скобки, которые должны быть литералом объекта", "You_cannot_rename_a_module_via_a_global_import_8031": "Вы не можете переименовать модуль с помощью глобального импорта.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Невозможно переименовать элементы, определенные в стандартной библиотеке TypeScript.", "You_cannot_rename_this_element_8000": "Этот элемент переименовать нельзя.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "\"{0}\" принимает слишком мало аргументов для использования в качестве декоратора. Вы хотели сначала вызвать его и записать \"@{0}()\"?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "Операции \"{0}\" и \"{1}\" невозможно использовать одновременно без скобок.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "\"{0}\" указаны дважды. Атрибут \"{0}\" будет перезаписан.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "Для импорта \"{0}\" необходимо установить флаг \"esModuleInterop\" и использовать импорт по умолчанию.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "Для импорта \"{0}\" необходимо использовать импорт по умолчанию.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "Для импорта \"{0}\" необходимо использовать вызов \"require\" или установить флаг \"esModuleInterop\" и использовать импорт по умолчанию.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "Для импорта \"{0}\" необходимо использовать вызов \"require\" или импорт по умолчанию.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "Для импорта \"{0}\" необходимо использовать \"import {1} = require({2})\" или импорт по умолчанию.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "Для импорта \"{0}\" необходимо использовать \"import {1} = require({2})\" или установить флаг \"esModuleInterop\" и использовать импорт по умолчанию.", + "_0_cannot_be_used_as_a_JSX_component_2786": "\"{0}\" невозможно использовать как компонент JSX.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "\"{0}\" невозможно использовать как значение, так как он был экспортирован с помощью \"export type\".", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "\"{0}\" невозможно использовать как значение, так как он был импортирован с помощью \"import type\".", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "Компоненты \"{0}\" не принимают текст в виде дочерних элементов. Текст в JSX-файле имеет тип \"string\", однако для \"{1}\" ожидается тип \"{2}\".", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "\"#constructor\" является зарезервированным словом.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "удалить это — проект \"{0}\" не требует обновления, так как был собран ранее", + "export_Asterisk_does_not_re_export_a_default_1195": "\"export *\" не выполняет повторный экспорт элемента по умолчанию.", "export_can_only_be_used_in_TypeScript_files_8003": "Элемент \"export =\" можно использовать только в файлах TypeScript.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "Модификатор export невозможно применить к неоднозначным модулям и улучшениям модулей, так как они всегда видимые.", "extends_clause_already_seen_1172": "Предложение extends уже существует.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 637871c57be6a..1d42b744ce6b6 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden farklı bir dosyada olamaz.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "Tür bağımsız değişkenlerine sahip bir 'new' ifadesinin arkasından her zaman parantez içine alınmış bağımsız değişken listesi gelmelidir.", "A_non_dry_build_would_build_project_0_6357": "-dry bayrağı kullanılmayan bir derleme '{0}' projesini derler", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "-dry bayrağı kullanılmayan bir derleme şu dosyaları siler: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "DRY dışı bir derleme, '{0}' projesinin çıkışını güncelleştirir", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle", "Add_0_to_unresolved_variable_90008": "Çözümlenmemiş değişkene '{0}.' ekle", + "Add_a_return_statement_95111": "Return deyimi ekleyin", "Add_all_missing_async_modifiers_95041": "Tüm eksik 'async' değiştiricileri ekle", "Add_all_missing_call_parentheses_95068": "Eksik tüm çağrı parantezlerini ekle", "Add_all_missing_imports_95064": "Tüm eksik içeri aktarmaları ekleyin", "Add_all_missing_members_95022": "Tüm eksik üyeleri ekle", + "Add_all_missing_return_statement_95114": "Tüm eksik return deyimlerini ekleyin", "Add_all_missing_super_calls_95039": "Tüm eksik süper çağrıları ekle", "Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle", "Add_await_95083": "'await' ekleyin", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "İçeri aktarma yolu '{0}' uzantısıyla bitemez. Bunun yerine '{1}' öğesini içeri aktarmayı deneyin.", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "Dizin ifadesi bağımsız değişkeni 'string', 'number', 'symbol' veya 'any' değerlerine sahip olmalıdır.", "An_index_signature_cannot_have_a_rest_parameter_1017": "Dizin imzası bir rest parametresine sahip olamaz.", + "An_index_signature_cannot_have_a_trailing_comma_1025": "Dizin imzasının sonunda virgül olamaz.", "An_index_signature_must_have_a_type_annotation_1021": "Dizin imzası bir tür açıklamasına sahip olmalıdır.", "An_index_signature_must_have_exactly_one_parameter_1096": "Dizin imzası tam olarak bir parametreye sahip olmalıdır.", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "Dizin imzası parametresi, bir soru işareti içeremez.", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "Değerin yineleyicisinin 'next' metodu '{1}' türünü beklemesine rağmen dizi yayılması her zaman '{0}' gönderdiğinden değer yinelenemiyor.", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "Değerin yineleyicisinin 'next' metodu '{1}' türünü beklemesine rağmen for-of her zaman '{0}' gönderdiğinden değer yinelenemiyor.", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "{0}' projesi için 'outFile' ayarlanmadığından başa eklenemiyor", + "Cannot_read_file_0_5083": "'{0}' dosyası okunamıyor.", "Cannot_read_file_0_Colon_1_5012": "'{0}' dosyası okunamıyor: {1}.", "Cannot_redeclare_block_scoped_variable_0_2451": "Blok kapsamlı değişken '{0}', yeniden bildirilemiyor.", "Cannot_redeclare_exported_variable_0_2323": "Dışarı aktarılan '{0}' değişkeni yeniden bildirilemiyor.", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "Uzantılara sahip '{0}' yolu çözümlenemedi: {1}.", "Could_not_write_file_0_Colon_1_5033": "'{0}' dosyası yazılamadı: {1}.", "DIRECTORY_6038": "DİZİN", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "Bildirim başka bir dosyadaki bildirimi genişlettiğinden serileştirilemez.", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "Bu dosya için bildirim gösterme, '{0}' özel adını kullanmayı gerektiriyor. Açık tür ek açıklaması, bildirim gösterme engelini kaldırabilir.", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "Bu dosya için bildirim gösterme, '{1}' modülündeki '{0}' özel adını kullanmayı gerektiriyor. Açık tür ek açıklaması, bildirim gösterme engelini kaldırabilir.", "Declaration_expected_1146": "Bildirim bekleniyor.", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "Oluşturucu içinde '{0}' özelliğini başlat", "Initialize_static_property_0_90021": "'{0}' statik özelliğini başlat", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "'{0}' örnek üyesi değişkeninin başlatıcısı, oluşturucuda bildirilen '{1}' tanımlayıcısına başvuramaz.", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "'{0}' parametresinin başlatıcısı, kendinden sonra bildirilen '{1}' tanımlayıcısına başvuramaz.", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "Başlatıcı bu bağlama öğesi için bir değer sağlamıyor ve bağlama öğesi varsayılan değere sahip değil.", "Initializers_are_not_allowed_in_ambient_contexts_1039": "Çevresel bağlamlarda başlatıcılara izin verilmez.", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "Bir TypeScript projesi başlatır ve bir tsconfig.json dosyası oluşturur.", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "Katı modda geçersiz '{0}' kullanımı.", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' değeri geçersiz. '{0}' geçerli bir tanımlayıcı veya tam ad değil.", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' için geçersiz değer. '{0}' geçerli bir tanımlayıcı değil.", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "'{0}' öğe türü geçerli bir JSX öğesi değil.", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "'{0}' örnek türü geçerli bir JSX öğesi değil.", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "'{0}' dönüş türü geçerli bir JSX öğesi değil.", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}', 'extends {2}' yan tümcesiyle eşleşmiyor.", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc '@{0}' bir sınıfa eklenmemiş.", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' yalnızca bir imzanın son parametresi içinde görünebilir.", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "Yalnızca '.d.ts' bildirim dosyalarını yayımla.", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "Sınıf 'extends' yan tümceleri içinde, şu an için yalnızca isteğe bağlı tür bağımsız değişkenlerine sahip tanımlayıcılar/tam adlar destekleniyor.", "Only_named_exports_may_use_export_type_1383": "Yalnızca adlandırılmış dışarı aktarmalarda 'dışarı aktarma türü' kullanılabilir.", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "Yalnızca sayısal sabit listelerinde hesaplanmış üyeler olabilir ancak bu ifadede '{0}' türü var. Kapsamlılık denetimleri gerekmiyorsa bunun yerine bir nesne sabit değeri kullanmayı düşünebilirsiniz.", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "'super' anahtar sözcüğüyle yalnızca temel sınıfa ait ortak ve korunan metotlara erişilebilir.", "Operator_0_cannot_be_applied_to_type_1_2736": "'{0}' işleci '{1}' türüne uygulanamıyor.", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "'{0}' işleci, '{1}' ve '{2}' türüne uygulanamaz.", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "Oluşturulan bildirim dosyaları için çıkış dizini.", "Output_file_0_from_project_1_does_not_exist_6309": "'{1}' projesinden '{0}' çıkış dosyası yok", "Output_file_0_has_not_been_built_from_source_file_1_6305": "Çıkış dosyası '{0}' '{1}' kaynak dosyasından oluşturulmamış.", - "Overload_0_of_1_2_gave_the_following_error_2772": "{1} metodunun {0} aşırı yüklemesi ('{2}'), aşağıdaki hatayı verdi.", + "Overload_0_of_1_2_gave_the_following_error_2772": "{0}/{1} aşırı yükleme '{2}' imzası, aşağıdaki hatayı verdi.", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "Aşırı yükleme imzalarının hepsi soyut veya soyut olmayan olmalıdır.", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "Aşırı yükleme imzalarının tümü çevresel veya çevresel olmayan türde olmalıdır.", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "Aşırı yükleme imzalarının hepsi dışarı aktarılmış veya dışarı aktarılmamış olmalıdır.", "Overload_signatures_must_all_be_optional_or_required_2386": "Aşırı yükleme imzalarının tümü isteğe bağlı veya gerekli olmalıdır.", "Overload_signatures_must_all_be_public_private_or_protected_2385": "Aşırı yükleme imzalarının tümü ortak, özel veya korumalı olmalıdır.", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "'{0}' parametresine başlatıcısında başvurulamaz.", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "'{0}' parametresi, kendisinden sonra bildirilen '{1}' tanımlayıcısına başvuramaz.", + "Parameter_0_cannot_reference_itself_2372": "'{0}' parametresi kendisine başvuramaz.", "Parameter_0_implicitly_has_an_1_type_7006": "'{0}' parametresi örtük olarak '{1}' türüne sahip.", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "'{0}' parametresi örtük olarak bir '{1}' türüne sahip ancak kullanımdan daha iyi bir tür çıkarsanabilir.", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "'{0}' parametresi, '{1}' parametresi ile aynı konumda değil.", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "'{0}' özelliği, '{1}' 'const' sabit listesi üzerinde değil.", "Property_0_does_not_exist_on_type_1_2339": "'{0}' özelliği, '{1}' türünde değil.", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "'{0}' özelliği '{1}' türünde yok. Bunu mu demek istediniz: '{2}'?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "'{0}' özelliği, çakışan bildirimler içeriyor ve '{1}' türü içinde erişilebilir değil.", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' özelliği, set erişimcisinin parametre türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "'--isolatedModules' bayrağı sağlandığında bir türü yeniden dışarı aktarmak için 'export type' kullanmak gerekir.", "Redirect_output_structure_to_the_directory_6006": "Çıktı yapısını dizine yeniden yönlendir.", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "Başvurulan proje '{0}' \"composite\": true ayarına sahip olmalıdır.", + "Remove_all_incorrect_body_block_braces_95115": "Tüm yanlış gövde bloğu küme ayraçlarını kaldırın", "Remove_all_unnecessary_uses_of_await_95087": "Tüm gereksiz 'await' kullanımlarını kaldırın", "Remove_all_unreachable_code_95051": "Tüm erişilemeyen kodları kaldır", "Remove_all_unused_labels_95054": "Kullanılmayan tüm etiketleri kaldır", + "Remove_block_body_braces_95112": "Blok gövdesi küme ayraçlarını kaldırın", "Remove_braces_from_arrow_function_95060": "Ok işlevinden küme ayraçlarını kaldır", "Remove_destructuring_90009": "Yıkmayı kaldır", "Remove_import_from_0_90005": "'{0}' öğesinden içeri aktarmayı kaldır", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "'import.meta' meta özelliğine yalnızca '--module' seçeneği 'esnext' veya 'system' olduğunda izin verilir.", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' öğesinin çıkarsanan türü, '{1}' başvurusu olmadan adlandırılamaz. Bu büyük olasılıkla taşınabilir değildir. Tür ek açıklaması gereklidir.", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "Çıkarsanan '{0}' türü, erişilemeyen bir '{1}' türüne başvuruyor. Tür ek açıklaması gereklidir.", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "'{1}' özelliği birden çok destekçide bulunduğundan ve bazılarında özel olduğundan, '{0}' kesişimi 'never' değerine düşürüldü.", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "'{1}' özelliği bazı bileşenlerde çakışan türlere sahip olduğundan '{0}' kesişimi 'never' değerine düşürüldü.", "The_last_overload_gave_the_following_error_2770": "Son aşırı yükleme aşağıdaki hatayı verdi.", "The_last_overload_is_declared_here_2771": "Son aşırı yükleme burada bildirilir.", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' deyiminin sol tarafı yok etme deseni olamaz.", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' operatörünün işleneni özel bir tanımlayıcı olamaz.", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' operatörünün işleneni, salt okunur bir özellik olamaz.", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' operatörünün işleneni, bir özellik başvurusu olmalıdır.", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' operatörünün işleneni isteğe bağlı olmalıdır.", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "Artırma veya eksiltme operatörünün işleneni, isteğe bağlı bir özellik erişimi olamaz.", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "Artırma veya eksiltme operatörünün işleneni, bir değişken veya özellik erişimi olmalıdır.", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "Ayrıştırıcı, buradaki '{' belirteciyle eşleştirmek için bir '}' bulmayı bekliyordu.", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "Bu ifade çağrılabilir değil.", "This_expression_is_not_constructable_2351": "Bu ifade oluşturulabilir değil.", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "'importsNotUsedAsValues', 'error' olarak ayarlandığından bu içeri aktarma hiçbir zaman bir değer olarak kullanılmaz ve 'import type' kullanmalıdır.", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "Bu, genişletilmekte olan bildirimdir. Genişleten bildirimi aynı dosyaya taşımayı düşünün.", "This_may_be_converted_to_an_async_function_80006": "Bu, asenkron bir işleve dönüştürülebilir.", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "Bu modüle yalnızca '{0}' bayrağını açıp modülün varsayılan dışarı aktarma işlemine başvurarak ECMAScript içeri/dışarı aktarma işlemleri ile başvurulabilir.", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "Bu modül, 'export =' kullanılarak bildirildi ve yalnızca '{0}' bayrağı kullanılırken varsayılan bir içeri aktarma ile kullanılabilir.", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "Bir 'yield*' işleneninin yinelenen öğelerinin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "'{0}' özelliğinin türü, '{1}' eşlenmiş türünde döngüsel olarak kendine başvuruyor.", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "Zaman uyumsuz bir oluşturucudaki 'yield' işleneninin türü, geçerli bir promise olmalı veya çağrılabilir 'then' üyesi içermemelidir.", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Tür bu içeri aktarmadan kaynaklanıyor. Bir ad alanı stili içeri aktarma işlemi çağrılamaz ya da oluşturulamaz ve çalışma zamanında hataya neden olur. Bunun yerine varsayılan içeri aktarmayı kullanmayı veya içeri aktarmayı burada gerektirmeyi deneyin.", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "Tür bu içeri aktarmadan kaynaklanıyor. Ad alanı stili içeri aktarma işlemi çağrılamaz ya da oluşturulamaz ve çalışma zamanında hataya neden olur. Bunun yerine varsayılan içeri aktarmayı kullanabilir veya burada içeri aktarma gerektirebilirsiniz.", "Type_parameter_0_has_a_circular_constraint_2313": "'{0}' tür parametresi döngüsel bir kısıtlamaya sahip.", "Type_parameter_0_has_a_circular_default_2716": "'{0}' tür parametresi döngüsel bir varsayılana sahip.", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "Dışarı aktarılan arabirimdeki çağrı imzasının '{0}' tür parametresi, '{1}' özel adına sahip veya bu adı kullanıyor.", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "Değişken bildirimi bekleniyor.", "Variable_declaration_list_cannot_be_empty_1123": "Değişken bildirim listesi boş olamaz.", "Version_0_6029": "Sürüm {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "Bu dosya hakkında daha fazla bilgi için https://aka.ms/tsconfig.json adresini ziyaret edin", "Watch_input_files_6005": "Giriş dosyalarını izleyin.", "Watch_option_0_requires_a_value_of_type_1_5080": "'{0}' izleme seçeneği, {1} türünde bir değer gerektiriyor.", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "Eski konsol çıktısının ekrandan kaldırılmak yerine izleme modunda tutulup tutulmayacağı.", "Wrap_all_invalid_characters_in_an_expression_container_95109": "Geçersiz tüm karakterleri bir ifade kapsayıcısında sarmalayın", + "Wrap_all_object_literal_with_parentheses_95116": "Tüm nesne sabit değerini parantez içine alın", "Wrap_invalid_character_in_an_expression_container_95108": "Geçersiz karakteri bir ifade kapsayıcısında sarmalayın", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "Nesne sabit değeri olması gereken aşağıdaki gövdeyi parantez içine alın", "You_cannot_rename_a_module_via_a_global_import_8031": "Genel içeri aktarma aracılığıyla bir modülü yeniden adlandıramazsınız.", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "Standart TypeScript kitaplığında tanımlanmış öğeleri yeniden adlandıramazsınız.", "You_cannot_rename_this_element_8000": "Bu öğeyi yeniden adlandıramazsınız.", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' burada dekoratör olarak kullanılmak için çok az bağımsız değişken kabul ediyor. Önce çağırıp '@{0}()' yazmak mı istediniz?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' ve '{1}' işlemleri ayraç olmadan karıştırılamaz.", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' iki kez belirtildi. '{0}' özniteliğinin üzerine yazılacak.", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "'{0}' yalnızca 'esModuleInterop' bayrağı etkinleştirilip varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_can_only_be_imported_by_using_a_default_import_2595": "'{0}' yalnızca varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "'{0}' yalnızca 'require' çağrısı kullanılarak veya 'esModuleInterop' bayrağı etkinleştirilip varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "'{0}' yalnızca 'require' çağrısı veya varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "'{0}' yalnızca 'import {1} = require({2})' veya varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "'{0}' yalnızca 'import {1} = require({2})' kullanılarak veya 'esModuleInterop' bayrağı etkinleştirilip varsayılan içeri aktarma kullanılarak içeri aktarılabilir.", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}', JSX bileşeni olarak kullanılamaz.", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "'{0}', 'export type' kullanılarak dışarı aktarıldığından değer olarak kullanılamaz.", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "'{0}', 'import type' kullanılarak içeri aktarıldığından değer olarak kullanılamaz.", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' bileşenleri, alt öğe olarak metin kabul etmez. JSX'teki metin 'string' türünde ancak beklenen '{1}' türü: '{2}'.", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' ayrılmış bir sözcüktür.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete', katı moddaki bir tanımlayıcıda çağrılamaz.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "bunu silin - '{0}' projesi önceden derlenmiş olduğundan güncel", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' varsayılanı yeniden dışarı aktarmaz.", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' yalnızca TypeScript dosyalarında kullanılabilir.", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' değiştiricisi, her zaman görünür olduğu için çevresel modüllere ve modül genişletmelerine uygulanamaz.", "extends_clause_already_seen_1172": "'extends' yan tümcesi zaten görüldü.", diff --git a/lib/tsc.js b/lib/tsc.js index f492b8b6e0fc2..3d6d3efc24fcf 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -66,7 +66,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; ts.version = ts.versionMajorMinor + ".0-dev"; function tryGetNativeMap() { return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; @@ -770,6 +770,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } @@ -1152,6 +1164,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; function isArray(value) { return Array.isArray ? Array.isArray(value) : value instanceof Array; } @@ -4152,6 +4168,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -4184,7 +4201,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -4284,6 +4301,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -4497,8 +4515,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -4664,7 +4682,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -4709,6 +4726,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4725,6 +4746,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -4859,6 +4882,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4994,6 +5023,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -5211,6 +5241,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -5408,6 +5440,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -5516,6 +5550,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -5538,6 +5579,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -5638,7 +5682,8 @@ var ts; var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500,]; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { if (code < map[0]) { return false; @@ -6860,13 +6905,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -6880,6 +6919,7 @@ var ts; tokenFlags |= 2; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { @@ -6887,11 +6927,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -7209,7 +7251,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -8055,7 +8107,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -10017,7 +10069,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -10353,6 +10405,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75: @@ -10551,6 +10607,25 @@ var ts; && node.expression.kind === 10; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -11426,10 +11501,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -11458,7 +11536,7 @@ var ts; } ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 || isBindableStaticNameExpression(node.expression, true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -11575,6 +11653,16 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 && !(valueDeclaration.flags & 8388608)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -12570,7 +12658,7 @@ var ts; ts.hasInvalidEscape = hasInvalidEscape; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -13365,14 +13453,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -13643,19 +13726,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -14937,6 +15021,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -20715,9 +20816,47 @@ var ts; var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -22218,7 +22357,8 @@ var ts; target: 1, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { @@ -22314,9 +22454,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -22482,19 +22622,10 @@ var ts; return diagnostic.messageText; } ts.getDiagnosticText = getDiagnosticText; - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -22502,7 +22633,7 @@ var ts; result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); result.resolvedPath = result.path; result.originalFileName = result.fileName; - return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), undefined, undefined, extendedConfigCache, watchOptionsToExtend); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; function readConfigFile(fileName, readFile) { @@ -22531,8 +22662,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -22662,7 +22794,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -22939,15 +23071,12 @@ var ts; } var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -22957,8 +23086,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -22966,10 +23097,12 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -24982,15 +25115,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } function getDeclarationName(node) { @@ -25063,7 +25188,7 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512); + var isDefaultExport = ts.hasModifier(node, 512) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name === undefined) { @@ -25204,7 +25329,7 @@ var ts; currentFlow.node = node; } } - currentReturnTarget = isIIFE || node.kind === 162 ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 || (ts.isInJSFile && (node.kind === 244 || node.kind === 201)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -25224,7 +25349,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162) { + if (node.kind === 162 || (ts.isInJSFile && (node.kind === 244 || node.kind === 201))) { node.returnFlowNode = currentFlow; } } @@ -26890,7 +27015,7 @@ var ts; : 4; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863); if (node.isExportEquals) { - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -26981,7 +27106,7 @@ var ts; ? 2097152 : 4 | 1048576 | 512; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -27091,7 +27216,7 @@ var ts; bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false); } function bindSpecialPropertyAssignment(node) { - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -27177,7 +27302,7 @@ var ts; : propertyAccess.parent.parent.kind === 290; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -27517,6 +27642,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195: return computeElementAccess(node, subtreeFlags); + case 267: + case 268: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -27555,6 +27683,14 @@ var ts; node.transformFlags = transformFlags | 536870912; return transformFlags & ~536879104; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2; + if (node.typeArguments) { + transformFlags |= 1; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536870912; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -27909,8 +28045,6 @@ var ts; transformFlags |= 1; break; case 266: - case 267: - case 268: case 11: case 269: case 270: @@ -28479,6 +28613,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -28637,9 +28772,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -28844,6 +28977,7 @@ var ts; }; var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; @@ -29105,11 +29239,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -29163,24 +29294,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 || ts.compareDiagnostics(r, leadingMessage) === 0; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -29201,6 +29340,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); @@ -29227,6 +29367,15 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export")) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports"); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -29264,7 +29413,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -29292,6 +29441,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -29305,7 +29455,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { if (declaration.kind === 191) { var errorBindingElement = ts.getAncestor(usage, 191); if (errorBindingElement) { @@ -29324,10 +29474,9 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); return !(compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -29337,37 +29486,39 @@ var ts; if (usage.kind === 259 && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225: case 230: case 232: - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -29424,6 +29575,53 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (target >= 2) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202: + case 201: + case 244: + case 162: + return false; + case 161: + case 163: + case 164: + case 281: + return requiresScopeChangeWorker(node.name); + case 159: + if (ts.hasStaticModifier(node)) { + return target < 99 || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) { if (excludeGlobals === void 0) { excludeGlobals = false; } return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage); @@ -29434,7 +29632,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -29452,9 +29650,7 @@ var ts; : false; } if (meaning & result.flags & 3) { - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1) { @@ -29606,15 +29802,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -29695,14 +29897,14 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551) === 111551) { + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551) === 111551) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 && result.flags & 2097152) { @@ -30055,12 +30257,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -30072,6 +30269,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export"); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default"))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -30168,7 +30384,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -30176,25 +30392,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=") - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export="); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, undefined, resolved, false); @@ -30394,9 +30633,9 @@ var ts; if (name.kind === 75) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 || name.kind === 194) { @@ -30424,7 +30663,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -30855,11 +31094,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export="); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export="); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { return symbol; @@ -30969,7 +31211,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { return { value: result }; @@ -31002,7 +31244,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -31147,7 +31389,7 @@ var ts; } } var containers = getContainersOfSymbol(symbol, enclosingDeclaration); - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -31338,7 +31580,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0; } - return flags & 277904747; + return flags & 814775659; } function createNodeBuilder() { return { @@ -31376,7 +31618,7 @@ var ts; enclosingDeclaration: enclosingDeclaration, flags: flags || 0, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -31407,10 +31649,16 @@ var ts; var inTypeAlias = context.flags & 8388608; context.flags &= ~8388608; if (!type) { - context.encounteredError = true; - return undefined; + if (!(context.flags & 262144)) { + context.encounteredError = true; + return undefined; + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125); + } + if (!(context.flags & 536870912)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1) { context.approximateLength += 3; return ts.createKeywordTypeNode(125); @@ -31747,13 +31995,13 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); var flags_2 = context.flags; @@ -31914,7 +32162,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138)] : undefined; @@ -31952,28 +32200,55 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64); + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } } } - return result; + if (seenNames) { + var saveContextFlags = context.flags; + context.flags |= 64; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; + } + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 143 : 140); @@ -31985,7 +32260,7 @@ var ts; context.approximateLength += (name.length + 4); return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(138)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256; if (suppressAny) context.flags &= ~256; @@ -31997,7 +32272,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -32017,7 +32292,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125); @@ -32040,7 +32315,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317); @@ -32049,7 +32324,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768; var dotDotDotToken = isRest ? ts.createToken(25) : undefined; @@ -32198,6 +32473,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290); + } + } if (file && file.moduleName !== undefined) { return file.moduleName; } @@ -32326,8 +32607,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968, undefined, escapedName, false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968, undefined, escapedName, false); + if (result) { + if (result.flags & 262144 && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 && context.typeParameterNames) { @@ -32344,7 +32632,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -32464,7 +32752,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -32479,6 +32767,145 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 && + type.symbol === symbol) { + context.flags |= 1048576; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + if (ts.isJSDocAllType(node) || node.kind === 302) { + return ts.createKeywordTypeNode(125); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "x", undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter(undefined, undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(undefined, undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863, true, true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863, false).accessibility !== 0) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161, true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160, false); @@ -32555,7 +32982,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ ts.createExportDeclaration(undefined, undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier) @@ -32564,7 +32991,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -32650,7 +33077,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default"; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { context.encounteredError = true; return; } @@ -32681,7 +33108,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32) { - if (symbol.flags & 4) { + if (symbol.flags & 4 && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags); } else { @@ -32771,7 +33198,7 @@ var ts; addResult(ts.createInterfaceDeclaration(undefined, undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551); }); @@ -32786,11 +33213,17 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 | 67108864))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); - var nsBody = ts.createModuleBlock([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export="; }), function (s) { + var nsBody = ts.createModuleBlock([ts.createExportDeclaration(undefined, undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export="; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -32825,7 +33258,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 : modifierFlags); if (name !== localName && !isPrivate) { @@ -32838,12 +33271,12 @@ var ts; var signatures = getSignaturesOfType(type, 0); for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; - var decl = signatureToSignatureDeclarationHelper(sig, 244, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } if (!(symbol.flags & (512 | 1024) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, true); } } @@ -32880,6 +33313,9 @@ var ts; addResult(fakespace, modifierFlags); } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -32889,24 +33325,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); var privateProperties = hasPrivateIdentifier ? [ts.createProperty(undefined, undefined, ts.createPrivateIdentifier("#private"), undefined, undefined, undefined)] : ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, false, baseTypes[0]); }); - var staticMembers = symbol.flags & (16 | 512) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, true, staticBaseType); }); var constructors = serializeSignatures(1, staticType, baseTypes[0], 162); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -33022,7 +33454,7 @@ var ts; } else { var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2)); addResult(statement, name === varName ? 1 : 0); } @@ -33041,7 +33473,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0))) && !ts.length(getSignaturesOfType(typeToSerialize, 1)) && - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -33054,10 +33486,11 @@ var ts; if (isStatic && (p.flags & (788968 | 1920 | 2097152))) { return []; } - if (p.flags & 4194304 || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256) | (isStatic ? 32 : 0); @@ -33066,16 +33499,16 @@ var ts; if (p.flags & 98304 && useAccessors) { var result = []; if (p.flags & 65536) { - result.push(ts.setTextRange(ts.createSetAccessor(undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(undefined, undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.createSetAccessor(undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(undefined, undefined, undefined, "arg", undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768) { var isPrivate_1 = modifierFlags & 8; - result.push(ts.setTextRange(ts.createGetAccessor(undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); + result.push(ts.setTextRange(ts.createGetAccessor(undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; } else if (p.flags & (4 | 3)) { - return ts.setTextRange(createProperty(undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); + return ts.setTextRange(createProperty(undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 : 0) | flag), name, p.flags & 16777216 ? ts.createToken(57) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); } if (p.flags & (8192 | 16)) { var type = getTypeOfSymbol(p); @@ -33104,98 +33537,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 && - type.symbol === symbol) { - context.flags |= 1048576; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - if (ts.isJSDocAllType(node) || node.kind === 302) { - return ts.createKeywordTypeNode(125); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature(undefined, undefined, [ts.createParameter(undefined, undefined, undefined, "x", undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter(undefined, undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(undefined, undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863, true, true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1) { @@ -33578,8 +33919,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -33657,9 +33998,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304); }); if (source.flags & 131072) { @@ -33752,7 +34090,7 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - else if (strictNullChecks && pattern.parent.initializer) { + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536)) { parentType = getTypeWithFacts(parentType, 524288); } var type; @@ -33889,6 +34227,13 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { return trueType; } @@ -33897,6 +34242,50 @@ var ts; } return undefined; } + function isConstructorDeclaredProperty(symbol) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 && + (declaration.left.kind !== 195 || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, false); + if (container && (container.kind === 162 || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); if (container) { @@ -33907,51 +34296,57 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; + } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304); }) ? constructorTypes : types; + type = getUnionType(sourceTypes, 2); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304); }) ? constructorTypes : types; - type = getUnionType(sourceTypes, 2); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304); }) === neverType) { @@ -34025,28 +34420,45 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 && kind === 2 && symbol.escapedName === "export=") { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551) { + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384); return result; } @@ -34056,6 +34468,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, false); return thisContainer.kind === 162 || @@ -34071,19 +34488,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, true, false) : unknownType; @@ -34379,7 +34783,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -34395,9 +34799,9 @@ var ts; if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 || + else if (declaration && (declaration.kind === 209 || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209) { + declaration.parent.kind === 209)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -34547,6 +34951,7 @@ var ts; return undefined; } switch (node.kind) { + case 225: case 245: case 214: case 246: @@ -34574,6 +34979,9 @@ var ts; else if (node.kind === 180) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 || node.kind === 214 || node.kind === 246 || isJSConstructor(node)) && @@ -34741,23 +35149,26 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { var outerTypeParameters = type.outerTypeParameters; @@ -35473,7 +35884,7 @@ var ts; if (!ts.length(result) && indexWithLengthOverOne !== -1) { var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -35485,7 +35896,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -35544,9 +35955,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -35600,7 +36011,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; if (!mixinFlags[i]) { var signatures = getSignaturesOfType(t, 1); @@ -35618,19 +36029,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, false, false, false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -35966,8 +36377,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -36039,8 +36450,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704) { var constraint = getConstraintOfType(t); while (constraint && constraint.flags & (262144 | 4194304 | 16777216)) { @@ -36059,8 +36470,8 @@ var ts; } if (constraints && (targetIsUnion || hasDisjointDomainType)) { if (hasDisjointDomainType) { - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908) { constraints = ts.append(constraints, t); } @@ -36133,8 +36544,8 @@ var ts; if (t.flags & 3145728) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -36218,7 +36629,7 @@ var ts; t.flags & 2097152 ? getApparentTypeOfIntersectionType(t) : t.flags & 132 ? globalStringType : t.flags & 296 ? globalNumberType : - t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 99) : + t.flags & 2112 ? getGlobalBigIntType(languageVersion >= 7) : t.flags & 528 ? globalBooleanType : t.flags & 12288 ? getGlobalESSymbolType(languageVersion >= 2) : t.flags & 67108864 ? emptyObjectType : @@ -36227,10 +36638,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576; - var excludeModifiers = isUnion ? 24 : 0; var optionalFlag = isUnion ? 0 : 16777216; var syntheticFlag = 4; var checkFlags = 0; @@ -36240,16 +36651,25 @@ var ts; if (!(type === errorType || type.flags & 131072)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | (!(modifiers & 24) ? 256 : 0) | @@ -36276,13 +36696,13 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48) && checkFlags & (1024 | 512)) { return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -36294,7 +36714,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -36357,7 +36777,7 @@ var ts; else if (type.flags & 2097152) { if (!(type.objectFlags & 268435456)) { type.objectFlags |= 268435456 | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 : 0); } return type.objectFlags & 536870912 ? neverType : type; } @@ -36374,11 +36794,30 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { return !(prop.flags & 16777216) && (ts.getCheckFlags(prop) & (192 | 131072)) === 192 && !!(getTypeOfSymbol(prop).flags & 131072); } + function isConflictingPrivateProperty(prop) { + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, undefined, 536870912), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, undefined, 536870912), symbolToString(privateProp)); + } + } + return errorInfo; + } function getPropertyOfType(type, name) { type = getApparentType(getReducedType(type)); if (type.flags & 524288) { @@ -36966,12 +37405,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -36988,8 +37427,8 @@ var ts; } function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -37466,6 +37905,8 @@ var ts; case 185: case 180: case 184: + case 174: + case 175: return isResolvedByTypeAlias(parent); case 247: return true; @@ -37634,8 +38075,8 @@ var ts; return includes; } function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -37664,8 +38105,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { var estimatedCount = (count / (len - i)) * len; @@ -37819,8 +38260,8 @@ var ts; return includes; } function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -38127,6 +38568,9 @@ var ts; if (accessFlags & 4) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 ? @@ -38439,7 +38883,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -38488,7 +38932,7 @@ var ts; return "break"; }; while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -38832,7 +39276,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 ? type.regularType : - type.flags & 1048576 ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -39295,7 +39739,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -39322,34 +39766,23 @@ var ts; } if (flags & 524288) { var objectFlags = type.objectFlags; - if (objectFlags & 16) { - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 | 16 | 32)) { + if (objectFlags & 4 && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152) || (flags & 1048576 && !(flags & 131068))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304) { return getIndexType(instantiateType(type.type, mapper)); @@ -39447,7 +39880,7 @@ var ts; return false; } function hasContextSensitiveReturnExpression(node) { - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -39617,6 +40050,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) { var reportedError = false; for (var status = iterator.next(); !status.done; status = iterator.next()) { @@ -39632,7 +40074,7 @@ var ts; } else { var resultObj = errorOutputContainer || {}; - var specificSource = next ? checkExpressionForMutableLocation(next, 0, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); @@ -39886,7 +40328,7 @@ var ts; case 3: _c.sent(); return [3, 7]; - case 4: return [4, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3, 7]; @@ -40220,13 +40662,14 @@ var ts; var overrideNextErrorInfo = 0; var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -40450,6 +40893,13 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0; } + if (originalSource.flags & 524288 && originalTarget.flags & 131068) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1; + } + reportErrorResults(originalSource, originalTarget, 0, !!(ts.getObjectFlags(originalSource) & 4096)); + return 0; + } var source = getNormalizedType(originalSource, false); var target = getNormalizedType(originalTarget, true); if (source === target) @@ -40457,6 +40907,9 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + if (source.flags & 262144 && getConstraintOfType(source) === target) { + return -1; + } if (target.flags & 1048576 && source.flags & 524288 && target.types.length <= 3 && maybeTypeOfKind(target, 98304)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304); @@ -40502,7 +40955,7 @@ var ts; if (source.flags & 1048576) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068), intersectionState & 4); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068), intersectionState); } else { if (target.flags & 1048576) { @@ -40510,16 +40963,9 @@ var ts; } else if (target.flags & 2097152) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4)) { - if (!propertiesRelatedTo(source, target, reportErrors, undefined, 4)) { - return 0; - } - } } else if (source.flags & 2097152) { - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152); })) { - result = someTypeRelatedToType(source, target, false, 1); - } + result = someTypeRelatedToType(source, target, false, 1); } if (!result && (source.flags & 66846720 || target.flags & 66846720)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -40537,42 +40983,54 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 && target.flags & 524288) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + if (result && !inPropertyCheck && (target.flags & 2097152 && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 && target.flags & 524288) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } } - } - if (source.flags & 524288 && target.flags & 131068) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + if (source.flags & 524288 && target.flags & 131068) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + return result; + } + } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -40580,11 +41038,11 @@ var ts; return 0; } if (flags & 3145728) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, false, 0); } @@ -40612,7 +41070,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -40657,7 +41115,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -40727,8 +41185,15 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 && target.types.length === sourceTypes.length) { + var related_1 = isRelatedTo(sourceType, target.types[i], false, undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, undefined, intersectionState); if (!related) { return 0; @@ -40786,7 +41251,7 @@ var ts; if (overflow) { return 0; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 && !(entry & 4)) { @@ -40861,26 +41326,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4) { + return propertiesRelatedTo(source, target, reportErrors, undefined, 0); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288)) { if (flags & 4194304) { return isRelatedTo(source.type, target.type, false); } - var result_4 = 0; + var result_6 = 0; if (flags & 8388608) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_6; } } } if (flags & 16777216) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_6; } } } @@ -41116,9 +41584,9 @@ var ts; if (source.flags & (524288 | 2097152) && target.flags & 1048576) { var objectOnlyTarget = extractTypesOfKind(target, 524288 | 2097152 | 33554432); if (objectOnlyTarget.flags & 1048576) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -41160,12 +41628,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -41195,24 +41663,24 @@ var ts; } var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) return "continue-outer"; if (sourceProperty === targetProperty) return "continue"; - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, false, 0); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, false, 0, strictNullChecks || relation === comparableRelation); if (!related) { return "continue-outer"; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -41226,7 +41694,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -41276,7 +41744,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576); - var result_7 = unionParent ? 0 : -1; + var result_9 = unionParent ? 0 : -1; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -41285,7 +41753,7 @@ var ts; if (!related) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -41293,30 +41761,23 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 && targetPropFlags & 8) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -41349,7 +41810,7 @@ var ts; } return 0; } - if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (!skipOptional && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -41463,7 +41924,7 @@ var ts; if (!(targetProp.flags & 4194304) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0; } @@ -41686,16 +42147,20 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -41753,7 +42218,7 @@ var ts; if (!variances) { cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -41778,7 +42243,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -41859,6 +42324,11 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } function isPropertyInClassDerivedFrom(prop, baseClass) { return forEachProperty(prop, function (sp) { var sourceClass = getDeclaringClass(sp); @@ -42016,8 +42486,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -42156,8 +42626,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -42472,7 +42942,7 @@ var ts; case 201: case 202: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1) { + if (wideningKind === 3) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -42481,7 +42951,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186: @@ -42495,7 +42965,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); } @@ -42609,15 +43079,22 @@ var ts; return !!(objectFlags & 134217728); } var result = !!(type.flags & 63176704 || - objectFlags & 4 && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations || - objectFlags & (32 | 131072) || - type.flags & 3145728 && !(type.flags & 1024) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 && !isNonGenericTopLevelType(type) && (objectFlags & 4 && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && type.symbol.declarations || + objectFlags & (32 | 131072)) || + type.flags & 3145728 && !(type.flags & 1024) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393) { type.objectFlags |= 67108864 | (result ? 134217728 : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 ? true : n.kind === 249 ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -42643,12 +43120,16 @@ var ts; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -42894,8 +43375,8 @@ var ts; } else if (source.flags & 1048576) { var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -42993,8 +43474,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -43516,8 +43997,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -43583,6 +44064,9 @@ var ts; if (flags & 67108864) { return strictNullChecks ? 7888800 : 16736160; } + if (flags & 131072) { + return 0; + } if (flags & 63176704) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -43788,7 +44272,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 ? type.types.length : 1; @@ -43869,8 +44353,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -43917,9 +44401,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 : 13; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, undefined); } } if (diagnostic) { @@ -44189,7 +44675,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576) { @@ -44417,14 +44903,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 ? declaredType : computedType; + if (!(type.flags & 1048576) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -44448,7 +44935,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 : 8388608); }); } return type; @@ -44487,12 +44974,6 @@ var ts; if (right_1.kind === 204 && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -44507,12 +44988,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -44576,7 +45063,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -44720,13 +45207,15 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { if (assumeTrue ? (operator !== 34 && operator !== 36) : (operator !== 35 && operator !== 37)) { return type; } - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { return type; @@ -44819,7 +45308,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536)) { type = getTypeWithFacts(type, 2097152); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -44856,7 +45345,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 : 262144); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 : 262144); }); } return type; @@ -45298,6 +45787,9 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -45591,7 +46083,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -45622,7 +46114,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2) { - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; @@ -46185,8 +46677,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -46683,7 +47175,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304) && !(maybeTypeOfKind(rightType, 1) && right.flags & 16777216)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -46821,13 +47314,13 @@ var ts; if (refKind === 1) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { @@ -46837,7 +47330,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { @@ -46904,8 +47401,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } function isKnownProperty(targetType, name, isComparingJsxAttributes) { @@ -46963,10 +47461,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 ? node.right : node.kind === 188 ? node : node.name; - if (ts.getCheckFlags(prop) & 1024) { - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { if (languageVersion < 2) { if (symbolHasNonMethodDeclaration(prop)) { @@ -47146,6 +47640,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -47218,7 +47715,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -47229,6 +47726,9 @@ var ts; prop && !(prop.flags & (3 | 4 | 98304)) && !(prop.flags & 8192 && propType.flags & 1048576)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } var assumeUninitialized = false; if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104) { var declaration = prop && prop.valueDeclaration; @@ -47352,7 +47852,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -48117,8 +48617,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -48281,7 +48781,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0, true, chain_2); if (diags_2) { @@ -48299,15 +48799,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -48420,7 +48920,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -48428,7 +48928,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0; @@ -48694,8 +49194,8 @@ var ts; if (apparentType.flags & 1048576) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -48745,9 +49245,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -49302,7 +49802,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -49466,18 +49966,16 @@ var ts; returnType = getUnionType(types, 2); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3); + if (returnType) + reportErrorsFromWidening(func, returnType, 1); + if (nextType) + reportErrorsFromWidening(func, nextType, 2); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -49651,7 +50149,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); if (type && maybeTypeOfKind(type, 1 | 16384)) { return; } @@ -49742,13 +50240,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1); - var isAsync = !!(functionFlags & 2); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -49763,7 +50254,7 @@ var ts; } else { var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3) === 2) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -49884,11 +50375,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 | 131072; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -50024,8 +50524,8 @@ var ts; } if (type.flags & 3145728) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -50081,7 +50581,8 @@ var ts; } leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 | 12288))) { + if (!(allTypesAssignableToKind(leftType, 132 | 296 | 12288) || + isTypeAssignableToKind(leftType, 4194304 | 262144))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 | 58982400)) { @@ -50429,6 +50930,12 @@ var ts; case 49: case 71: reportOperatorError(); + break; + case 42: + case 66: + if (languageVersion < 3) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -50550,8 +51057,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968, undefined, name, false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -51222,7 +51729,7 @@ var ts; error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); } } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -51574,8 +52081,9 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92); })); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement = void 0; @@ -51988,7 +52496,7 @@ var ts; } if (hasNonAmbientClass && !isConstructor && symbol.flags & 16) { ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -52087,10 +52595,10 @@ var ts; case 253: case 256: case 255: - var result_8 = 0; + var result_10 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242: case 191: case 244: @@ -52199,7 +52707,7 @@ var ts; } var globalPromiseType = getGlobalPromiseType(true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -52316,8 +52824,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182) { typeNode = typeNode.type; } @@ -52660,7 +53168,7 @@ var ts; var range = ts.isJSDocTemplateTag(parent) ? ts.rangeOfNode(parent) : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -52687,6 +53195,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { var unusedImports = ts.createMap(); var unusedDestructures = ts.createMap(); @@ -52697,8 +53215,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -53141,8 +53658,28 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + if (ts.isIdentifier(condExpr)) { + return true; + } + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 && childExpression.kind === 104) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -53265,11 +53802,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 : 13; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -53690,10 +54224,11 @@ var ts; checkGrammarBreakOrContinueStatement(node); } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1); var isAsync = !!(functionFlags & 2); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -53701,6 +54236,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 | 3); } function checkReturnStatement(node) { + var _a; if (checkGrammarStatementInAmbientContext(node)) { return; } @@ -53725,7 +54261,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -53885,6 +54421,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } if (indexKind === 1 && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; } @@ -54140,7 +54679,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -54158,7 +54697,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -54283,6 +54822,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -54291,11 +54849,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -54409,7 +54967,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -54453,7 +55011,13 @@ var ts; error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, undefined); + } } return value; function evaluate(expr) { @@ -54536,6 +55100,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -54885,13 +55452,8 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 && !node.moduleSpecifier && node.flags & 8388608; @@ -54904,6 +55466,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536); } @@ -56435,8 +57000,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 && node.parent.parent && node.parent.parent.kind === 279; } @@ -57010,9 +57601,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -57070,6 +57661,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -57989,13 +58581,13 @@ var ts; } return type; } - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 && source.flags & (2097152 | 524288)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, undefined, skipPartial); } } } @@ -59271,9 +59863,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -59395,9 +59989,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -59860,6 +60456,25 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245); node.decorators = asNodeArray(decorators); @@ -61258,11 +61873,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -61597,27 +62215,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -61745,11 +62363,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576) { + if (ts.getEmitFlags(statement) & 1048576 && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -62508,12 +63127,57 @@ var ts; ts.visitLexicalEnvironment = visitLexicalEnvironment; function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (context.getLexicalEnvironmentFlags() & 2 && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) + ]), parameter), 1 | 32 | 384 | 1536))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -63216,13 +63880,57 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -64195,7 +64903,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - ts.setEmitFlags(expression, 64); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -64286,9 +64993,6 @@ var ts; var variable = ts.createVariableDeclaration(name, undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -64855,6 +65559,10 @@ var ts; return visitModuleDeclaration(node); case 253: return visitImportEqualsDeclaration(node); + case 267: + return visitJsxSelfClosingElement(node); + case 268: + return visitJsxJsxOpeningElement(node); default: return ts.visitEachChild(node, visitor, context); } @@ -65390,6 +66098,16 @@ var ts; case 183: case 188: break; + case 295: + case 296: + case 300: + case 301: + case 302: + break; + case 297: + case 298: + case 299: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -65397,8 +66115,8 @@ var ts; } function serializeTypeList(types) { var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182) { typeNode = typeNode.type; } @@ -65713,6 +66431,12 @@ var ts; function visitTaggedTemplateExpression(node) { return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } function shouldEmitEnumDeclaration(node) { return !ts.isEnumConst(node) || compilerOptions.preserveConstEnums @@ -65894,24 +66618,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -65919,7 +66644,7 @@ var ts; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true); ts.setTextRange(block, blockLocation); - if (body.kind !== 250) { + if (!node.body || node.body.kind !== 250) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536); } return block; @@ -66637,7 +67362,7 @@ var ts; if (!body) { return undefined; } - return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters, body), constructor || node), constructor)); + return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(undefined, undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -66677,8 +67402,8 @@ var ts; return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true), constructor ? constructor.body : undefined); } function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -66692,8 +67417,8 @@ var ts; } function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -67416,13 +68141,24 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; var capturedSuperProperties; var hasSuperElementAccess; var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3; + return ancestorFacts; + } + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -67449,11 +68185,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -67484,26 +68220,30 @@ var ts; return visitVariableStatement(node); case 242: return visitVariableDeclaration(node); + case 228: + case 229: + case 231: + return doWithHierarchyFacts(visitDefault, node, 0, 2); case 232: return visitForOfStatement(node, undefined); case 230: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0, 2); case 205: return visitVoidExpression(node); case 162: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2, 1); case 161: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2, 1); case 163: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2, 1); case 164: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2, 1); case 244: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2, 1); case 201: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2, 1); case 202: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2, 0); case 156: return visitParameter(node); case 226: @@ -67524,7 +68264,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245: case 214: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2, 1); default: return ts.visitEachChild(node, visitor, context); } @@ -67559,7 +68299,7 @@ var ts; if (statement.kind === 232 && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -67613,13 +68353,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 : + 1); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -67683,15 +68427,15 @@ var ts; return ts.visitEachChild(node, visitorNoDestructuringValue, context); } function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0, 2); if (node.initializer.transformFlags & 16384) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -67737,7 +68481,7 @@ var ts; ? ts.createYield(undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(undefined); @@ -67751,8 +68495,11 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + var initializer = ancestorFacts & 2 ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, getValue)), node), 256); return ts.createTry(ts.createBlock([ @@ -67851,7 +68598,7 @@ var ts; var savedHasSuperElementAccess = hasSuperElementAccess; capturedSuperProperties = ts.createUnderscoreEscapedMap(); hasSuperElementAccess = false; - var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(41), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(undefined, ts.createToken(41), node.name && ts.getGeneratedNameForNode(node.name), undefined, [], undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1))); var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); @@ -68035,7 +68782,7 @@ var ts; }; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), ts.createIdentifier("arguments"), @@ -69577,6 +70324,8 @@ var ts; resumeLexicalEnvironment(); if (ts.isBlock(body)) { statementOffset = ts.addStandardPrologue(prologue, body.statements, false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, false) || multiLine; @@ -73384,7 +74133,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -74857,7 +75606,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -74943,6 +75693,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -75340,6 +76098,9 @@ var ts; if ((bindingList && bindingList.length) || visibleDefaultBinding) { return ts.updateImportDeclaration(decl, undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, undefined, decl.modifiers, undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } } function transformAndReplaceLatePaintedStatements(statements) { while (ts.length(lateMarkedStatements)) { @@ -76062,8 +76823,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -76079,8 +76844,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -76173,10 +76941,14 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1) { + lexicalEnvironmentFlags |= 2; + } } function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -76184,15 +76956,30 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + function addInitializationStatement(node) { + ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } function startLexicalEnvironment() { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0; } function suspendLexicalEnvironment() { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); @@ -76211,7 +76998,9 @@ var ts; ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -76225,16 +77014,36 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2, "Cannot modify the transformation context after transformation has completed."); @@ -76809,6 +77618,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -78198,16 +79008,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -78946,12 +79750,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -79262,8 +80069,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -79480,7 +80287,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153); + emitList(parentNode, decorators, 2146305); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776); @@ -79658,7 +80465,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256) { + else if (format & (2097152 | 256)) { writeSpace(); } } @@ -79790,7 +80597,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -79834,7 +80641,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -79855,6 +80662,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -81265,11 +82085,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -81702,13 +82522,13 @@ var ts; } var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } var unknownModuleNames; var result; @@ -82210,7 +83030,7 @@ var ts; if (directives.markUsed(line)) { return line; } - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -85544,9 +86364,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -85562,9 +86382,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -85581,7 +86401,7 @@ var ts; importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path); }); var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -85606,7 +86426,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -86119,17 +86939,20 @@ var ts; reportDiagnostic(diagnostic); system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -86185,12 +87008,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -86206,7 +87047,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -86523,7 +87364,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, undefined, watchOptionsToExtend)); + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, undefined, watchOptionsToExtend, extraFileExtensions)); } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -88368,15 +89209,29 @@ var ts; function createWatchStatusReporter(sys, options) { return ts.createWatchStatusReporter(sys, shouldBePretty(sys, options)); } - function createWatchOfConfigFile(sys, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend) { - var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, watchOptionsToExtend, sys, undefined, reportDiagnostic, createWatchStatusReporter(sys, configParseResult.options)); - updateWatchCompilationHost(sys, cb, watchCompilerHost); + function createWatchOfConfigFile(system, cb, reportDiagnostic, configParseResult, optionsToExtend, watchOptionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile({ + configFileName: configParseResult.options.configFilePath, + optionsToExtend: optionsToExtend, + watchOptionsToExtend: watchOptionsToExtend, + system: system, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: createWatchStatusReporter(system, configParseResult.options) + }); + updateWatchCompilationHost(system, cb, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; return ts.createWatchProgram(watchCompilerHost); } - function createWatchOfFilesAndCompilerOptions(sys, cb, reportDiagnostic, rootFiles, options, watchOptions) { - var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, sys, undefined, reportDiagnostic, createWatchStatusReporter(sys, options)); - updateWatchCompilationHost(sys, cb, watchCompilerHost); + function createWatchOfFilesAndCompilerOptions(system, cb, reportDiagnostic, rootFiles, options, watchOptions) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFiles, + options: options, + watchOptions: watchOptions, + system: system, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: createWatchStatusReporter(system, options) + }); + updateWatchCompilationHost(system, cb, watchCompilerHost); return ts.createWatchProgram(watchCompilerHost); } function canReportDiagnostics(system, compilerOptions) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 65ebef0479c9b..e9b97043b30d7 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -92,7 +92,7 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; /** @@ -880,6 +880,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1339,6 +1351,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -3549,6 +3565,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3587,6 +3604,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3598,7 +3616,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -4496,6 +4514,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4545,6 +4570,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4577,7 +4603,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -6372,6 +6398,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6651,6 +6678,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6683,7 +6711,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6783,6 +6811,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -6996,8 +7025,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7163,7 +7192,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7208,6 +7236,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -7224,6 +7256,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7358,6 +7392,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7493,6 +7533,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7710,6 +7751,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -7907,6 +7950,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8015,6 +8060,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8037,6 +8089,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8188,9 +8243,13 @@ var ts; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -9540,13 +9599,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9561,6 +9614,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9568,11 +9622,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -9901,7 +9957,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -10969,7 +11035,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -13151,7 +13217,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -13536,6 +13602,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13742,6 +13812,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -14600,7 +14689,7 @@ var ts; } /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. + * We treat the right hand side of assignments with container-like initializers as declarations. */ function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -14719,10 +14808,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14756,7 +14848,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -14885,6 +14977,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -15969,7 +16072,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -16862,14 +16965,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -17196,19 +17294,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -18641,6 +18740,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -25635,9 +25751,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -27347,7 +27505,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27449,9 +27608,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27631,19 +27790,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27652,8 +27802,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27687,6 +27836,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27695,8 +27845,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27835,7 +27986,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -28151,15 +28302,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -28169,8 +28317,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -28179,11 +28329,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -30617,16 +30769,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30717,7 +30860,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -30937,7 +31080,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -30958,7 +31101,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162 /* Constructor */) { + if (node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -32838,7 +32981,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -32940,7 +33083,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -33067,7 +33210,7 @@ var ts; } function bindSpecialPropertyAssignment(node) { // Class declarations in Typescript do not allow property declarations - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -33167,7 +33310,7 @@ var ts; : propertyAccess.parent.parent.kind === 290 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -33566,6 +33709,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33608,6 +33754,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -34042,8 +34196,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -34528,7 +34680,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34664,7 +34818,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["ExcessCheck"] = 4] = "ExcessCheck"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -34855,6 +35010,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -35016,9 +35172,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -35232,6 +35386,7 @@ var ts; /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -35511,12 +35666,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35574,24 +35725,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35612,6 +35771,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35650,6 +35810,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35689,7 +35859,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35725,6 +35895,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35741,7 +35912,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage if (declaration.kind === 191 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) @@ -35766,11 +35937,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35792,40 +35962,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -35887,6 +36059,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -35904,7 +36131,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -35932,9 +36159,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -36155,15 +36380,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -36263,17 +36494,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -36669,12 +36900,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36687,6 +36913,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36803,7 +37048,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36811,25 +37056,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -37078,9 +37346,9 @@ var ts; if (name.kind === 75 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -37108,7 +37376,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -37584,11 +37852,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37708,7 +37979,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37754,7 +38025,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -37943,7 +38214,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -38158,7 +38429,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -38197,7 +38468,7 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -38228,10 +38499,16 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38580,14 +38857,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38754,7 +39031,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38794,28 +39071,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); - } + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } + } + } + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; } - return result; + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38833,7 +39145,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38845,7 +39157,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -38865,7 +39177,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38888,7 +39200,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); @@ -38897,7 +39209,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -39064,6 +39376,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -39202,8 +39520,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -39220,7 +39545,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -39341,7 +39666,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -39368,6 +39693,163 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -39462,7 +39944,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39474,7 +39956,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39582,7 +40064,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39617,7 +40099,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39718,7 +40200,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39737,13 +40219,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39788,7 +40276,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39825,13 +40313,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -39884,6 +40373,9 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -39893,16 +40385,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -39915,9 +40411,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -40049,7 +40543,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -40092,7 +40586,7 @@ var ts; } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -40116,7 +40610,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -40131,10 +40625,11 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); @@ -40148,13 +40643,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -40163,7 +40658,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -40200,116 +40695,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40741,8 +41126,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40831,9 +41216,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -40938,8 +41320,8 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - // Filter `undefined` from the type we check against if the parent has an initializer (which handles the `undefined` case implicitly) - else if (strictNullChecks && pattern.parent.initializer) { + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; @@ -41103,6 +41485,15 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. + // Use control flow analysis of this.xxx assignments the constructor to determine the type of the property. + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for @@ -41116,6 +41507,56 @@ var ts; // No type specified and nothing can be inferred return undefined; } + function isConstructorDeclaredProperty(symbol) { + // A propery is considered a constructor declared property when all declaration sites are this.xxx assignments, + // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of + // a class constructor. + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ && + (declaration.left.kind !== 195 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + // A property is auto-typed when its declaration has no type annotation or initializer and we're in + // noImplicitAny mode or a .js file. + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); + if (container && (container.kind === 162 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + // We don't infer a type if assignments are only null or undefined. + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); @@ -41127,52 +41568,60 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + // We use control flow analysis to determine the type of the property if the property qualifies as a constructor + // declared property and the resulting control flow type isn't just undefined or null. + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; // No types from any declarations :( + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - // use only the constructor types unless they were only assigned null | undefined (including widening variants) - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; // No types from any declarations :( + } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 - type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { @@ -41247,28 +41696,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -41278,6 +41754,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41295,20 +41776,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - /** check for definition in base class if any declaration is in a class */ - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -41653,7 +42120,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41670,9 +42137,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41838,6 +42305,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -41865,6 +42333,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -42055,16 +42526,19 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -42075,7 +42549,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -42934,7 +43408,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -42946,7 +43420,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -43010,9 +43484,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -43070,7 +43544,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -43093,19 +43567,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -43478,8 +43952,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43567,8 +44041,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43593,8 +44067,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43680,8 +44154,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43783,7 +44257,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43792,10 +44266,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43806,16 +44280,25 @@ var ts; if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43842,13 +44325,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -43860,7 +44345,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -43937,7 +44422,7 @@ var ts; else if (type.flags & 2097152 /* Intersection */) { if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); } return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; } @@ -43954,11 +44439,33 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. return !(prop.flags & 16777216 /* Optional */) && (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -44616,12 +45123,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44642,8 +45149,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -45160,6 +45667,8 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: + case 174 /* ArrayType */: + case 175 /* TupleType */: return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; @@ -45341,8 +45850,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -45371,8 +45880,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -45551,8 +46060,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -45907,6 +46416,9 @@ var ts; if (accessFlags & 4 /* CacheSymbol */) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? @@ -46259,7 +46771,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -46333,7 +46845,7 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -46691,7 +47203,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -47210,7 +47722,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -47244,37 +47756,23 @@ var ts; } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; - if (objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32 /* Mapped */) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4 /* Reference */) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728 /* UnionOrIntersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152 /* Intersection */) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -47386,7 +47884,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -47583,6 +48081,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -47606,7 +48113,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -47869,7 +48376,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -48247,13 +48754,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -48510,6 +49018,15 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source @@ -48521,6 +49038,14 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -48578,7 +49103,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & 4 /* ExcessCheck */); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -48586,12 +49111,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4 /* ExcessCheck */)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 4 /* ExcessCheck */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -48607,9 +49126,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); })) { - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } + result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -48641,44 +49158,71 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } + } + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -48686,11 +49230,11 @@ var ts; return 0 /* False */; } if (flags & 3145728 /* UnionOrIntersection */) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -48718,7 +49262,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -48774,7 +49318,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -48844,8 +49388,16 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; @@ -48922,7 +49474,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -49004,26 +49556,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_4 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -49308,9 +49863,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -49377,12 +49932,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -49430,11 +49985,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -49442,7 +49997,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -49450,7 +50005,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -49464,7 +50019,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -49516,7 +50071,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_7 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -49526,7 +50081,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -49534,34 +50089,27 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -49596,7 +50144,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -49721,7 +50269,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -49969,18 +50517,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -50051,7 +50603,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -50083,7 +50635,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -50178,6 +50730,12 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return the inherited type of the given property or undefined if property doesn't exist in a base class. + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } // Return true if some underlying source property is declared in a class that derives // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { @@ -50366,8 +50924,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -50516,8 +51074,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -50888,7 +51446,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -50897,7 +51455,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -50911,7 +51469,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -51029,15 +51587,22 @@ var ts; return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); } var result = !!(type.flags & 63176704 /* Instantiable */ || - objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 /* SourceFile */ ? true : n.kind === 249 /* ModuleDeclaration */ ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -51070,12 +51635,16 @@ var ts; * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -51372,8 +51941,8 @@ var ts; else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -51481,8 +52050,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -52082,8 +52651,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -52151,6 +52720,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -52359,7 +52931,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -52451,8 +53023,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -52504,9 +53076,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, /*diagnostic*/ undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); } } if (diagnostic) { @@ -52805,7 +53379,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576 /* Union */) { @@ -53088,14 +53662,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; + if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -53119,7 +53694,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } return type; @@ -53158,12 +53733,6 @@ var ts; if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -53178,12 +53747,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -53257,7 +53832,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -53446,15 +54021,16 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { // Do not narrow when checking inequality. if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { return type; } - // In the case of `x.y`, a `x.constructor === T` type guard resets the narrowed type of `y` to its declared type. - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } // Get the type of the constructor identifier expression, if it is not a function then do not narrow. var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { @@ -53568,7 +54144,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -53608,7 +54184,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); }); } return type; @@ -54144,6 +54720,10 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + // TODO: Maybe issue a better error than 'object is possibly undefined' + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -54536,7 +55116,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -54575,7 +55155,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -55229,8 +55809,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -55821,7 +56401,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304 /* Nullable */)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 1 /* Any */) && right.flags & 16777216 /* Optional */)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -56002,14 +56583,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -56019,7 +56600,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -56100,8 +56685,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -56185,11 +56771,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -56400,6 +56981,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -56473,7 +57057,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -56487,6 +57071,9 @@ var ts; prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -56619,7 +57206,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -57521,8 +58108,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -57738,7 +58325,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -57756,15 +58343,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -57890,7 +58477,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -57898,7 +58485,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -58233,8 +58820,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -58288,9 +58875,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -58908,7 +59495,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -59091,18 +59678,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -59320,7 +59905,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -59429,13 +60014,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -59460,7 +60038,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59596,11 +60174,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -59743,8 +60330,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59810,7 +60397,8 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || + isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -60195,6 +60783,12 @@ var ts; case 49 /* GreaterThanGreaterThanGreaterThanToken */: case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: reportOperatorError(); + break; + case 42 /* AsteriskAsteriskToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -60329,8 +60923,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -61098,7 +61692,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -61500,8 +62094,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -61961,7 +62556,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -62074,10 +62669,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_8 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -62316,7 +62911,7 @@ var ts; if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -62451,8 +63046,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -62841,7 +63436,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -62868,6 +63463,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -62881,8 +63486,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -63398,8 +64002,30 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -63554,11 +64180,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -64174,10 +64797,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -64185,6 +64809,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -64210,7 +64835,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -64391,6 +65016,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -64678,7 +65306,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -64697,7 +65325,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -64856,6 +65484,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -64864,11 +65511,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -64986,7 +65633,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -65037,7 +65684,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -65120,6 +65773,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -65393,7 +66049,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -65517,15 +66173,10 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -65539,6 +66190,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } @@ -67266,8 +67920,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -67881,9 +68561,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -67942,6 +68622,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -68949,13 +69630,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -70267,9 +70948,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -70391,9 +71074,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -70864,6 +71549,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -72409,11 +73114,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -72776,7 +73484,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -72787,7 +73495,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -72799,15 +73507,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -73030,11 +73738,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -74072,18 +74781,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -74838,13 +75599,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -75978,9 +76819,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -76085,9 +76923,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -76938,6 +77773,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -77829,6 +78668,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -77838,8 +78688,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -78322,6 +79172,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -78644,24 +79502,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -78691,7 +79550,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -79644,7 +80503,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -79710,8 +80569,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79731,8 +80590,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -80642,6 +81501,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -80655,7 +81538,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ @@ -80665,6 +81548,27 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -80691,11 +81595,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -80726,26 +81630,30 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: @@ -80766,7 +81674,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -80802,7 +81710,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -80877,13 +81785,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -80964,15 +81876,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -81020,7 +81932,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -81034,9 +81946,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -81166,7 +82082,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -81380,7 +82296,7 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -81511,6 +82427,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -81546,6 +82463,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -81558,6 +82476,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -81593,6 +82512,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -83519,6 +84439,8 @@ var ts; // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -89507,7 +90429,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -91631,7 +92553,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -91722,6 +92645,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -92149,6 +93080,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -92985,8 +93922,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -93004,8 +93945,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -93135,6 +94079,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -93142,6 +94089,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -93149,6 +94097,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -93163,9 +94125,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -93190,7 +94156,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -93205,17 +94173,37 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -93849,6 +94837,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -95344,16 +96333,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -96149,12 +97132,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -96491,8 +97477,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -96719,7 +97705,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -96923,7 +97909,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -97062,7 +98048,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -97107,7 +98093,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -97143,6 +98129,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -98738,11 +99737,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -99257,13 +100256,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -99883,7 +100882,7 @@ var ts; return line; } // Stop searching if the line is not empty and not a comment - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -103760,9 +104759,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -103778,9 +104777,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -103804,7 +104803,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -103830,7 +104829,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -104404,20 +105403,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -104473,12 +105475,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -104494,7 +105514,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -104843,7 +105863,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -106811,7 +107831,11 @@ var ts; if (node.kind === 290 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) { + else if (node.parent.kind === 259 /* ExportAssignment */ + || node.parent.kind === 265 /* ExternalModuleReference */ + || node.parent.kind === 258 /* ImportSpecifier */ + || node.parent.kind === 255 /* ImportClause */ + || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -108230,10 +109254,28 @@ var ts; var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } + function getReplacementSpanForContextToken(contextToken) { + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return createTextSpanFromStringLiteralLikeContent(contextToken); + default: + return createTextSpanFromNode(contextToken); + } + } + ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken; function createTextSpanFromNode(node, sourceFile, endNode) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromStringLiteralLikeContent(node) { + if (node.isUnterminated) + return undefined; + return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); + } + ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent; function createTextRangeFromNode(node, sourceFile) { return ts.createRange(node.getStart(sourceFile), node.end); } @@ -108471,17 +109513,26 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + function insertImports(changes, sourceFile, imports, blankLineBetween) { + var decl = ts.isArray(imports) ? imports[0] : imports; + var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { - changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + if (ts.isArray(imports)) { + changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports); + } + else { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports); + } + } + else if (ts.isArray(imports)) { + changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween); } else { - changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween); + changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween); } } - ts.insertImport = insertImport; + ts.insertImports = insertImports; function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); @@ -108886,6 +109937,27 @@ var ts; addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } ts.suppressTrailingTrivia = suppressTrailingTrivia; + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + } + ts.copyComments = copyComments; + function hasLeadingLineBreak(node, text) { + var start = node.getFullStart(); + var end = node.getStart(); + for (var i = start; i < end; i++) { + if (text.charCodeAt(i) === 10 /* lineFeed */) + return true; + } + return false; + } function addEmitFlagsRecursively(node, flag, getChild) { ts.addEmitFlags(node, flag); var child = getChild(node); @@ -108979,6 +110051,11 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + /* @internal */ + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { @@ -109387,10 +110464,54 @@ var ts; return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + /** + * Useful to check whether a string contains another string at a specific index + * without allocating another string or traversing the entire contents of the outer string. + * + * This function is useful in place of either of the following: + * + * ```ts + * // Allocates + * haystack.substr(startIndex, needle.length) === needle + * + * // Full traversal + * haystack.indexOf(needle, startIndex) === startIndex + * ``` + * + * @param haystack The string that potentially contains `needle`. + * @param needle The string whose content might sit within `haystack`. + * @param startIndex The index within `haystack` to start searching for `needle`. + */ + function stringContainsAt(haystack, needle, startIndex) { + var needleLength = needle.length; + if (needleLength + startIndex > haystack.length) { + return false; + } + for (var i = 0; i < needleLength; i++) { + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) + return false; + } + return true; + } + ts.stringContainsAt = stringContainsAt; function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } ts.startsWithUnderscore = startsWithUnderscore; + function isGlobalDeclaration(declaration) { + return !isNonGlobalDeclaration(declaration); + } + ts.isGlobalDeclaration = isGlobalDeclaration; + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } + ts.isNonGlobalDeclaration = isNonGlobalDeclaration; // #endregion })(ts || (ts = {})); var ts; @@ -110367,11 +111488,11 @@ var ts; if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -110380,11 +111501,17 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ + name: type.value, + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: "0", + replacementSpan: ts.getReplacementSpanForContextToken(contextToken) + }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -110551,7 +111678,9 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }), + symbols: type.getApparentProperties().filter(function (prop) { + return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration); + }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -110983,6 +112112,22 @@ var ts; SortText["AutoImportSuggestions"] = "5"; SortText["JavascriptIdentifiers"] = "6"; })(SortText = Completions.SortText || (Completions.SortText = {})); + /** + * Special values for `CompletionInfo['source']` used to disambiguate + * completion items with the same `name`. (Each completion item must + * have a unique name/source combination, because those two fields + * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`. + * + * When the completion item is an auto-import suggestion, the source + * is the module specifier of the suggestion. To avoid collisions, + * the values here should not be a module specifier we would ever + * generate for an auto-import. + */ + var CompletionSource; + (function (CompletionSource) { + /** Completions that require `this.` insertion text */ + CompletionSource["ThisProperty"] = "ThisProperty/"; + })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType"; @@ -111130,14 +112275,16 @@ var ts; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); @@ -111174,7 +112321,8 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { + uniqueNames.add(realName); entries.push({ name: realName, kind: "warning" /* warning */, @@ -111192,9 +112340,9 @@ var ts; function createCompletionEntryForLiteral(literal, preferences) { return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var insertText; - var replacementSpan; + var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -111271,13 +112419,18 @@ var ts; !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; } function getSourceFromOrigin(origin) { - return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + if (originIsExport(origin)) { + return ts.stripQuotes(origin.moduleSymbol.name); + } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { + return CompletionSource.ThisProperty; + } } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); // Tracks unique names. - // We don't set this for global variables or completions from external module exports, because we can have multiple of those. - // Based on the order we add things we will always see locals first, then globals, then module exports. + // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; + // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { @@ -111288,21 +112441,26 @@ var ts; continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.has(name)) { + if (uniques.get(name)) { continue; } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 - uniques.set(name, true); - } + /** True for locals; false for globals, module exports from other files, `this.` completions. */ + var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + uniques.set(name, shouldShadowLaterSymbols); entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniques; + // Prevent consumers of this map from having to worry about + // the boolean value. Externally, it should be seen as the + // set of all names. + return { + has: function (name) { return uniques.has(name); }, + add: function (name) { return uniques.set(name, true); }, + }; } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -111931,6 +113089,7 @@ var ts; function tryGetGlobalSymbols() { var result = tryGetObjectLikeCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() + || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() @@ -112012,7 +113171,7 @@ var ts; // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); - if (thisType) { + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; @@ -112220,7 +113379,7 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -112489,8 +113648,6 @@ var ts; * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` @@ -112498,9 +113655,10 @@ var ts; ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; - // cursor is in an import clause - // try to show exported member for imported module + // try to show exported member for imported/re-exported module var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + if (!moduleSpecifier) + return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -112511,6 +113669,35 @@ var ts; symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); return 1 /* Success */; } + /** + * Adds local declarations for completions in named exports: + * + * export { | }; + * + * Does not check for the absence of a module specifier (`export {} from "./other"`) + * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that, + * preventing this function from running. + */ + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedExports) + : undefined; + if (!namedExports) { + return 0 /* Continue */; + } + var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration)); + completionKind = 5 /* None */; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) { + var _a, _b; + symbols.push(symbol); + if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) { + symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember; + } + }); + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. @@ -112861,7 +114048,7 @@ var ts; }); } } - // Set SortText to OptionalMember if it is an optinoal member + // Set SortText to OptionalMember if it is an optional member function setSortTextToOptionalMember() { symbols.forEach(function (m) { if (m.flags & 16777216 /* Optional */) { @@ -112917,7 +114104,8 @@ var ts; return baseSymbols.filter(function (propertySymbol) { return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && + !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration); }); } /** @@ -113144,10 +114332,16 @@ var ts; return cls; } break; - case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| } + case 75 /* Identifier */: { + // class c { public prop = c| } + if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return undefined; + } + // class c extends React.Component { a: () => 1\n compon| } if (isFromObjectTypeDeclaration(location)) { return ts.findAncestor(location, ts.isObjectTypeDeclaration); } + } } if (!contextToken) return undefined; @@ -113215,14 +114409,23 @@ var ts; } } } - function isNonGlobalDeclaration(declaration) { - var sourceFile = declaration.getSourceFile(); - // If the file is not a module, the declaration is global - if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { - return false; + /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ + function isProbablyGlobalType(type, sourceFile, checker) { + // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in + // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists. + var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { + return true; + } + var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { + return true; + } + var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { + return true; } - // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation - return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + return false; } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -114551,7 +115754,29 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var referenceEntries; + var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 194 /* PropertyAccessExpression */ + || node.parent.kind === 191 /* BindingElement */ + || node.parent.kind === 195 /* ElementAccessExpression */ + || node.kind === 102 /* SuperKeyword */) { + referenceEntries = entries && __spreadArrays(entries); + } + else { + var queue = entries && __spreadArrays(entries); + var seenNodes = ts.createMap(); + while (queue && queue.length) { + var entry = queue.shift(); + if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { + continue; + } + referenceEntries = ts.append(referenceEntries, entry); + var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries_1) { + queue.push.apply(queue, entries_1); + } + } + } var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } @@ -117542,6 +118767,8 @@ var ts; // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 226 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression); case 209 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { @@ -119085,7 +120312,10 @@ var ts; case 246 /* InterfaceDeclaration */: case 248 /* EnumDeclaration */: case 251 /* CaseBlock */: + case 173 /* TypeLiteral */: return spanForNode(n); + case 175 /* TupleType */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); case 277 /* CaseClause */: case 278 /* DefaultClause */: return spanForNodeArray(n.statements); @@ -119103,6 +120333,8 @@ var ts; case 211 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); + case 190 /* ArrayBindingPattern */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -120891,7 +122123,7 @@ var ts; var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); })); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); @@ -120908,7 +122140,7 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; @@ -121211,7 +122443,18 @@ var ts; } ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) || + ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + function hasSupportedNumberOfArguments(node) { + if (node.arguments.length > 2) + return false; + if (node.arguments.length < 2) + return true; + return ts.some(node.arguments, function (arg) { + return arg.kind === 100 /* NullKeyword */ || + ts.isIdentifier(arg) && arg.text === "undefined"; + }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { @@ -121252,6 +122495,7 @@ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -121696,7 +122940,7 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -121838,7 +123082,7 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122459,7 +123703,7 @@ var ts; rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), // Async-await rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // JSX opening elements @@ -124891,6 +126135,15 @@ var ts; * include all trivia between the node and the previous token */ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + /** + * Include attached JSDoc comments + */ + LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc"; + /** + * Only delete trivia on the same line as getStart(). + * Used to avoid deleting leading comments + */ + LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine"; })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); var TrailingTriviaOption; (function (TrailingTriviaOption) { @@ -124933,6 +126186,15 @@ var ts; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } + if (leadingTriviaOption === LeadingTriviaOption.StartLine) { + return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile); + } + if (leadingTriviaOption === LeadingTriviaOption.JSDoc) { + var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) { + return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile); + } + } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); if (fullStart === start) { @@ -125081,11 +126343,23 @@ var ts; this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween); + }; + ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween); + }; + ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); - this.insertNodeAt(sourceFile, pos, newNode, { + var options = { prefix: pos === 0 ? undefined : this.newLineCharacter, suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), - }); + }; + if (ts.isArray(insert)) { + this.insertNodesAt(sourceFile, pos, insert, options); + } + else { + this.insertNodeAt(sourceFile, pos, insert, options); + } }; ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) { var p0 = ts.firstOrUndefined(parameters); @@ -125148,6 +126422,7 @@ var ts; }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var _a; var endNode; if (ts.isFunctionLike(node)) { endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); @@ -125159,7 +126434,7 @@ var ts; } } else { - endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -125564,7 +126839,7 @@ var ts; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. @@ -125578,10 +126853,16 @@ var ts; for (var i = 0; i < normalized.length - 1; i++) { _loop_10(i); } - var textChanges = normalized.map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + var textChanges = ts.mapDefined(normalized, function (c) { + var span = ts.createTextSpanFromRange(c.range); + var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); + // Filter out redundant changes. + if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) { + return undefined; + } + return ts.createTextChange(span, newText); }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; + return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; @@ -125942,10 +127223,10 @@ var ts; break; } case 254 /* ImportDeclaration */: - var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration); - deleteNode(changes, sourceFile, node, - // For first import, leave header comment in place - isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); + case 253 /* ImportEqualsDeclaration */: + var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); + // For first import, leave header comment in place, otherwise only delete JSDoc comments + deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; case 191 /* BindingElement */: var pattern = node.parent; @@ -125981,6 +127262,10 @@ var ts; case 94 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; + case 245 /* ClassDeclaration */: + case 244 /* FunctionDeclaration */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + break; default: if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); @@ -126050,7 +127335,7 @@ var ts; deleteNode(changes, sourceFile, parent); break; case 225 /* VariableStatement */: - deleteNode(changes, sourceFile, gp); + deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: ts.Debug.assertNever(gp); @@ -126523,7 +127808,7 @@ var ts; reference; var diagnostic = ts.find(diagnostics, function (diagnostic) { return diagnostic.start === errorNode.getStart(sourceFile) && - diagnostic.start + diagnostic.length === errorNode.getEnd(); + (diagnostic.start + diagnostic.length) === errorNode.getEnd(); }); return diagnostic && ts.contains(errorCodes, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid @@ -127000,90 +128285,161 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node. + if (ts.hasJSDocNodes(ctorDeclaration)) { + ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol if (symbol.members) { - symbol.members.forEach(function (member) { + symbol.members.forEach(function (member, key) { + if (key === "constructor") { + // fn.prototype.constructor = fn + changes.delete(sourceFile, member.valueDeclaration.parent); + return; + } var memberElement = createClassElement(member, /*modifiers*/ undefined); if (memberElement) { - memberElements.push(memberElement); + memberElements.push.apply(memberElements, memberElement); } }); } // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); + if (member.name === "prototype") { + var firstDeclaration = member.declarations[0]; + // only one "x.prototype = { ... }" will pass + if (member.declarations.length === 1 && + ts.isPropertyAccessExpression(firstDeclaration) && + ts.isBinaryExpression(firstDeclaration.parent) && + firstDeclaration.parent.operatorToken.kind === 62 /* EqualsToken */ && + ts.isObjectLiteralExpression(firstDeclaration.parent.right)) { + var prototypes = firstDeclaration.parent.right; + var memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } + } + } + else { + var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } } }); } return memberElements; function shouldConvertDeclaration(_target, source) { - // Right now the only thing we can convert are function expressions - other values shouldn't get - // transformed. We can update this once ES public class properties are available. - return ts.isFunctionLike(source); + // Right now the only thing we can convert are function expressions, get/set accessors and methods + // other values like normal value fields ({a: 1}) shouldn't get transformed. + // We can update this once ES public class properties are available. + if (ts.isPropertyAccessExpression(_target)) { + if (isConstructorAssignment(_target)) + return true; + return ts.isFunctionLike(source); + } + else { + return ts.every(_target.properties, function (property) { + // a() {} + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) + return true; + // a: function() {} + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer) && !!property.name) + return true; + // x.prototype.constructor = fn + if (isConstructorAssignment(property)) + return true; + return false; + }); + } } function createClassElement(symbol, modifiers) { // Right now the only thing we can convert are function expressions, which are marked as methods - if (!(symbol.flags & 8192 /* Method */)) { - return; + // or { x: y } type prototype assignments, which are marked as ObjectLiteral + var members = []; + if (!(symbol.flags & 8192 /* Method */) && !(symbol.flags & 4096 /* ObjectLiteral */)) { + return members; } var memberDeclaration = symbol.valueDeclaration; var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var assignmentExpr = assignmentBinaryExpression.right; + if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { + return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 201 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - case 202 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 223 /* Block */) { - bodyBlock = arrowFunctionBody; - } - // case 2: () => [1,2,3] - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJS(sourceFile)) { - return; - } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); - return prop; + if (!assignmentExpr) { + members.push(ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined)); + return members; + } + // f.x = expr + if (ts.isPropertyAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) { + return createFunctionLikeExpressionMember(members, assignmentExpr, memberDeclaration.name); + } + // f.prototype = { ... } + else if (ts.isObjectLiteralExpression(assignmentExpr)) { + return ts.flatMap(assignmentExpr.properties, function (property) { + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) { + // MethodDeclaration and AccessorDeclaration can appear in a class directly + return members.concat(property); + } + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer)) { + return createFunctionLikeExpressionMember(members, property.initializer, property.name); + } + // Drop constructor assignments + if (isConstructorAssignment(property)) + return members; + return []; + }); + } + else { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) + return members; + if (!ts.isPropertyAccessExpression(memberDeclaration)) + return members; + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); + members.push(prop); + return members; + } + function createFunctionLikeExpressionMember(members, expression, name) { + if (ts.isFunctionExpression(expression)) + return createFunctionExpressionMember(members, expression, name); + else + return createArrowFunctionExpressionMember(members, expression, name); + } + function createFunctionExpressionMember(members, functionExpression, name) { + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); + } + function createArrowFunctionExpressionMember(members, arrowFunction, name) { + var arrowFunctionBody = arrowFunction.body; + var bodyBlock; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 223 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); } } } @@ -127120,6 +128476,13 @@ var ts; function getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } + function isConstructorAssignment(x) { + if (!x.name) + return false; + if (ts.isIdentifier(x.name) && x.name.text === "constructor") + return true; + return false; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -127230,10 +128593,6 @@ var ts; var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } - function isParameterOfPromiseCallback(node, checker) { - return ts.isParameter(node) && (isPromiseReturningCallExpression(node.parent.parent, checker, "then") || - isPromiseReturningCallExpression(node.parent.parent, checker, "catch")); - } function isPromiseTypedExpression(node, checker) { if (!ts.isExpression(node)) return false; @@ -127248,7 +128607,6 @@ var ts; It then checks for any collisions and renames them through getSynthesizedDeepClone */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) { - var variableNames = []; var identsToRenameMap = ts.createMap(); // key is the symbol id var collidingSymbolMap = ts.createMultiMap(); ts.forEachChild(nodeToRename, function visit(node) { @@ -127273,7 +128631,6 @@ var ts; var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - variableNames.push({ identifier: synthName.identifier, symbol: symbol }); collidingSymbolMap.add(ident.text, symbol); } // We only care about identifiers that are parameters, variable declarations, or binding elements @@ -127285,17 +128642,12 @@ var ts; var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - variableNames.push({ identifier: newName.identifier, symbol: symbol }); collidingSymbolMap.add(originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); - identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); - if (isParameterOfPromiseCallback(node.parent, checker) || ts.isVariableDeclaration(node.parent)) { - variableNames.push({ identifier: identifier, symbol: symbol }); - collidingSymbolMap.add(originalName, symbol); - } + collidingSymbolMap.add(originalName, symbol); } } } @@ -127375,7 +128727,7 @@ var ts; varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier); var typeArray = possibleNameForVarDecl.types; var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); } @@ -128349,7 +129701,6 @@ var ts; // Keys are import clause node IDs. var addToExisting = ts.createMap(); var newImports = ts.createMap(); - var lastModuleSpecifier; return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start); @@ -128399,7 +129750,6 @@ var ts; var entry = newImports.get(moduleSpecifier); if (!entry) { newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); - lastModuleSpecifier = moduleSpecifier; } else { // An import clause can only be type-only if every import fix contributing to it can be type-only. @@ -128439,11 +129789,15 @@ var ts; var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); + var newDeclarations; newImports.forEach(function (_a, moduleSpecifier) { var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); - var addDeclarations = useRequire ? addNewRequires : addNewImports; - addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + var getDeclarations = useRequire ? getNewRequires : getNewImports; + newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports)); }); + if (newDeclarations) { + ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); + } } } codefix.createImportAdder = createImportAdder; @@ -128840,11 +130194,11 @@ var ts; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; - var addDeclarations = useRequire ? addNewRequires : addNewImports; + var getDeclarations = useRequire ? getNewRequires : getNewImports; var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; - addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); + ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -128912,11 +130266,12 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewImports(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { - ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly)); } var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { @@ -128928,12 +130283,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause( /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } - function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewRequires(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; // const { default: foo, bar, etc } = require('./mod'); if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; @@ -128941,13 +130298,14 @@ var ts; bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); } var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } // const foo = require('./mod'); if (imports.namespaceLikeImport) { var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { return ts.createVariableStatement( @@ -129320,6 +130678,192 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "returnValueCorrect"; + var fixIdAddReturnStatement = "fixAddReturnStatement"; + var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace"; + var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + var errorCodes = [ + ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + ]; + var ProblemKind; + (function (ProblemKind) { + ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement"; + ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses"; + })(ProblemKind || (ProblemKind = {})); + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen], + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; + var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) + return undefined; + if (info.kind === ProblemKind.MissingReturnStatement) { + return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined); + } + else { + return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; + } + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) + return undefined; + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixIdRemoveBlockBodyBrace: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); + break; + case fixIdWrapTheBlockWithParen: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1) + return undefined; + var firstStatement = ts.first(declaration.body.statements); + if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + } + else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return ts.isArrowFunction(declaration) ? { + declaration: declaration, + kind: ProblemKind.MissingParentheses, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } + } + else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) { + var firstBlockStatement = ts.first(firstStatement.statements); + if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; + } + } + } + return undefined; + } + function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) { + return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type); + } + function getInfo(checker, sourceFile, position, errorCode) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (!node.parent) + return undefined; + var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); + switch (errorCode) { + case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node)) + return undefined; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); + case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body) + return undefined; + var pos = declaration.parent.arguments.indexOf(declaration); + var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) + return undefined; + return getFixInfo(checker, declaration, type, /* isFunctionType */ true); + case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent)) + return undefined; + var initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body) + return undefined; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); + } + return undefined; + } + function getVariableLikeInitializer(declaration) { + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + return declaration.initializer; + case 273 /* JsxAttribute */: + return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); + case 282 /* ShorthandPropertyAssignment */: + case 158 /* PropertySignature */: + case 284 /* EnumMember */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + return undefined; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + ts.suppressLeadingAndTrailingTrivia(expression); + var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, ts.createReturn(expression), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : undefined + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression; + ts.suppressLeadingAndTrailingTrivia(commentSource); + ts.copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement); + } + function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -129344,7 +130888,7 @@ var ts; return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); @@ -129352,7 +130896,7 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { - var program = context.program, preferences = context.preferences; + var program = context.program; var checker = program.getTypeChecker(); var seen = ts.createMap(); var typeDeclToMembers = new ts.NodeMap(); @@ -129388,7 +130932,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call && !ts.isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); } else { if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { @@ -129528,11 +131072,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */); } @@ -129584,16 +131128,17 @@ var ts; // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { // Private methods are not implemented yet. if (ts.isPrivateIdentifier(token)) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) { + var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -129601,6 +131146,7 @@ var ts; else { changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } + importAdder.writeFixes(changeTracker); } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { /** @@ -130260,6 +131806,13 @@ var ts; } if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + if (ts.isParameter(token.parent)) { + ts.getJSDocParameterTags(token.parent).forEach(function (tag) { + if (ts.isIdentifier(tag.name)) { + changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text)); + } + }); + } } } function canPrefix(token) { @@ -130497,7 +132050,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); @@ -131157,7 +132710,7 @@ var ts; } switch (node.parent.kind) { case 226 /* ExpressionStatement */: - addCandidateType(usage, checker.getVoidType()); + inferTypeFromExpressionStatement(node, usage); break; case 208 /* PostfixUnaryExpression */: usage.isNumber = true; @@ -131213,6 +132766,9 @@ var ts; addCandidateType(usage, checker.getContextualType(node)); } } + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); + } function inferTypeFromPrefixUnaryExpression(node, usage) { switch (node.operator) { case 45 /* PlusPlusToken */: @@ -131466,6 +133022,7 @@ var ts; return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); } function inferTypes(usage) { + var _a, _b, _c; var types = []; if (usage.isNumber) { types.push(checker.getNumberType()); @@ -131479,10 +133036,7 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - if (usage.properties && usage.properties.size - || usage.calls && usage.calls.length - || usage.constructs && usage.constructs.length - || usage.stringIndex) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); @@ -131636,6 +133190,59 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixReturnTypeInAsyncFunction"; + var errorCodes = [ + ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + var checker = program.getTypeChecker(); + var info = getInfo(sourceFile, program.getTypeChecker(), span.start); + if (!info) { + return undefined; + } + var returnTypeNode = info.returnTypeNode, returnType = info.returnType, promisedTypeNode = info.promisedTypeNode, promisedType = info.promisedType; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, returnTypeNode, promisedTypeNode); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Replace_0_with_Promise_1, + checker.typeToString(returnType), checker.typeToString(promisedType)], fixId, ts.Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); + if (info) { + doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); + } + }); } + }); + function getInfo(sourceFile, checker, pos) { + if (ts.isInJSFile(sourceFile)) { + return undefined; + } + var token = ts.getTokenAtPosition(sourceFile, pos); + var func = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var returnTypeNode = func === null || func === void 0 ? void 0 : func.type; + if (!returnTypeNode) { + return undefined; + } + var returnType = checker.getTypeFromTypeNode(returnTypeNode); + var promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); + var promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined); + if (promisedTypeNode) { + return { returnTypeNode: returnTypeNode, returnType: returnType, promisedTypeNode: promisedTypeNode, promisedType: promisedType }; + } + } + function doChange(changes, sourceFile, returnTypeNode, promisedTypeNode) { + changes.replaceNode(sourceFile, returnTypeNode, ts.createTypeReferenceNode("Promise", [promisedTypeNode])); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -131652,12 +133259,13 @@ var ts; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options); var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -131869,14 +133477,14 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) { var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { - // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); + return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; @@ -131892,9 +133500,21 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && ts.isImportTypeNode(typeNode)) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { @@ -132048,6 +133668,7 @@ var ts; function importSymbols(importAdder, symbols) { symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); } + codefix.importSymbols = importSymbols; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -133530,6 +135151,8 @@ var ts; function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); + var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); @@ -133545,7 +135168,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -133604,6 +135227,7 @@ var ts; else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); var newNodes = []; // replace range with function call var called = getCalledExpression(scope, range, functionNameText); @@ -134692,6 +136316,7 @@ var ts; var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(accessorName); ts.suppressLeadingAndTrailingTrivia(declaration); ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); @@ -134937,7 +136562,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -135586,19 +137211,20 @@ var ts; } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); - body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); + ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); } - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { + t.replaceNode(file, func.body, body); + }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } - function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); - } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); @@ -135955,7 +137581,7 @@ var ts; ts.suppressLeadingAndTrailingTrivia(property.name); if (ts.isPropertyAssignment(property)) ts.suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); + ts.copyComments(arg, property); return property; }); if (hasRestParameter && functionArguments.length >= parameters.length) { @@ -135990,10 +137616,10 @@ var ts; /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); + ts.copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + ts.copyComments(thisParameter.type, newThisParameter.type); } return ts.createNodeArray([newThisParameter, objectParameter]); } @@ -136004,7 +137630,7 @@ var ts; /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); ts.suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + ts.copyComments(parameterDeclaration.initializer, element.initializer); } return element; } @@ -136022,9 +137648,9 @@ var ts; /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); + ts.copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); + ts.copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; } @@ -136040,26 +137666,6 @@ var ts; return checker.isOptionalParameter(parameterDeclaration); } } - function copyComments(sourceNode, targetNode) { - var sourceFile = sourceNode.getSourceFile(); - var text = sourceFile.text; - if (hasLeadingLineBreak(sourceNode, text)) { - ts.copyLeadingComments(sourceNode, targetNode, sourceFile); - } - else { - ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); - } - ts.copyTrailingComments(sourceNode, targetNode, sourceFile); - } - function hasLeadingLineBreak(node, text) { - var start = node.getFullStart(); - var end = node.getStart(); - for (var i = start; i < end; i++) { - if (text.charCodeAt(i) === 10 /* lineFeed */) - return true; - } - return false; - } function getParameterName(paramDeclaration) { return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name); } @@ -136228,7 +137834,6 @@ var ts; indexes.push(index); index++; } - text = ts.escapeString(text); return [index, text, indexes]; } function nodesToTemplate(_a, file) { @@ -144293,15 +145898,18 @@ var ts; */ /* @internal */ ProjectService.prototype.loadConfiguredProject = function (project, reason) { + var _this = this; this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk var configFilename = ts.normalizePath(project.getConfigFilePath()); - var configFileContent = this.host.readFile(configFilename) || ""; - var result = ts.parseJsonText(configFilename, configFileContent); + var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); + var result = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); if (!result.endOfFileToken) { result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; } var configFileErrors = result.parseDiagnostics; + if (!ts.isString(configFileContent)) + configFileErrors.push(configFileContent); var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), /*existingOptions*/ {}, configFilename, /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, @@ -146097,10 +147705,9 @@ var ts; function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, - /*initialLocation*/ undefined, function (_a, tryAddToTodo) { - var project = _a.project; - for (var _i = 0, _b = action(project); _i < _b.length; _i++) { - var output = _b[_i]; + /*initialLocation*/ undefined, function (project, _, tryAddToTodo) { + for (var _i = 0, _a = action(project); _i < _a.length; _i++) { + var output = _a[_i]; if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { outputs.push(output); } @@ -146110,10 +147717,9 @@ var ts; } function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { - var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _b.length; _i++) { - var output = _b[_i]; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, tryAddToTodo) { + for (var _i = 0, _a = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _a.length; _i++) { + var output = _a[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); } @@ -146128,8 +147734,7 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { - var project = _a.project, location = _a.location; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, getMappedLocation) { var _loop_9 = function (outputReferencedSymbol) { var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); var definition = mappedDefinitionFile === undefined ? @@ -146147,8 +147752,8 @@ var ts; } } }; - for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { - var outputReferencedSymbol = _b[_i]; + for (var _i = 0, _a = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _a.length; _i++) { + var outputReferencedSymbol = _a[_i]; _loop_9(outputReferencedSymbol); } }); @@ -146173,9 +147778,9 @@ var ts; var toDo; var seenProjects = ts.createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + // TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); - toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + toDo = callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb); }); // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. if (initialLocation) { @@ -146193,13 +147798,15 @@ var ts; return; var definition = mapDefinitionInProject(defaultDefinition_1, project, getGeneratedDefinition_1, getSourceDefinition_1); if (definition) { - toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + toDo = callbackProjectAndLocation(project, definition, projectService, toDo, seenProjects, cb); } }); } } while (toDo && toDo.length) { - toDo = callbackProjectAndLocation(ts.Debug.checkDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + var next = toDo.pop(); + ts.Debug.assertIsDefined(next); + toDo = callbackProjectAndLocation(next.project, next.location, projectService, toDo, seenProjects, cb); } } function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { @@ -146230,30 +147837,29 @@ var ts; sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); } - function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { - var project = projectAndLocation.project, location = projectAndLocation.location; + function callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb) { if (project.getCancellationToken().isCancellationRequested()) return undefined; // Skip rest of toDo if cancelled // If this is not the file we were actually looking, return rest of the toDo if (isLocationProjectReferenceRedirect(project, location)) return toDo; - cb(projectAndLocation, function (project, location) { - addToSeen(seenProjects, projectAndLocation.project); - var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + cb(project, location, function (innerProject, location) { + addToSeen(seenProjects, project); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(innerProject, location); if (!originalLocation) return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { var project_1 = _a[_i]; - addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + addToTodo(project_1, originalLocation, toDo, seenProjects); } var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); if (symlinkedProjectsMap) { symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { var symlinkedProject = symlinkedProjects_2[_i]; - addToTodo({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }, toDo, seenProjects); + addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos }, toDo, seenProjects); } }); } @@ -146261,9 +147867,9 @@ var ts; }); return toDo; } - function addToTodo(projectAndLocation, toDo, seenProjects) { - if (addToSeen(seenProjects, projectAndLocation.project)) - toDo.push(projectAndLocation); + function addToTodo(project, location, toDo, seenProjects) { + if (addToSeen(seenProjects, project)) + toDo.push({ project: project, location: location }); } function addToSeen(seenProjects, project) { return ts.addToSeen(seenProjects, getProjectKey(project)); @@ -147233,6 +148839,7 @@ var ts; return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { + var _a; var projects; var symLinkedProjects; if (args.projectFileName) { @@ -147257,7 +148864,7 @@ var ts; // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { - this.projectService.logErrorForScriptInfoNotFound(args.file); + this.projectService.logErrorForScriptInfoNotFound((_a = args.file) !== null && _a !== void 0 ? _a : args.projectFileName); return server.Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 @@ -147268,6 +148875,9 @@ var ts; if (project) { return project; } + if (!args.file) { + return server.Errors.ThrowNoProject(); + } } var info = this.projectService.getScriptInfo(args.file); return info.getDefaultProject(); @@ -147752,16 +149362,17 @@ var ts; }); }; Session.prototype.getFullNavigateToItems = function (args) { - var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount, projectFileName = args.projectFileName; if (currentFileOnly) { + ts.Debug.assertDefined(args.file); var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } - else { - return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { - return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); - }, documentSpanLocation, navigateToItemIsEqualTo); + else if (!args.file && !projectFileName) { + return combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*filename*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, navigateToItemIsEqualTo); } + var fileArgs = args; + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(fileArgs), this.getDefaultProject(fileArgs), function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, documentSpanLocation, navigateToItemIsEqualTo); function navigateToItemIsEqualTo(a, b) { if (a === b) { return true; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 545fac4f8a159..c9c2c066f8361 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.9"; + const versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -2040,23 +2040,23 @@ declare namespace ts { getNonNullableType(type: Type): Type; getTypeArguments(type: TypeReference): readonly Type[]; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): (SignatureDeclaration & { typeArguments?: NodeArray; }) | undefined; /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -2135,6 +2135,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowThisInObjectLiteral = 32768, AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, @@ -2163,6 +2164,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2171,7 +2173,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 277904747 + NodeBuilderFlagsMask = 814775659 } export enum SymbolFormatFlags { None = 0, @@ -3225,6 +3227,7 @@ declare namespace ts { NoInterveningComments = 262144, NoSpaceIfEmpty = 524288, SingleElement = 1048576, + SpaceAfterList = 2097152, Modifiers = 262656, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, @@ -3256,7 +3259,7 @@ declare namespace ts { CaseOrDefaultClauseStatements = 163969, HeritageClauseTypes = 528, SourceFileStatements = 131073, - Decorators = 49153, + Decorators = 2146305, TypeArguments = 53776, TypeParameters = 53776, Parameters = 2576, @@ -3860,7 +3863,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4457,7 +4460,8 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray | undefined): NodeArray | undefined; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4785,6 +4789,7 @@ declare namespace ts { /** Options to extend */ optionsToExtend?: CompilerOptions; watchOptionsToExtend?: WatchOptions; + extraFileExtensions?: readonly FileExtensionInfo[]; /** * Used to generate source file names from the config file and its include, exclude, files rules * and also to cache the directory stucture @@ -4812,7 +4817,7 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): WatchCompilerHostOfConfigFile; function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[], watchOptions?: WatchOptions): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options @@ -4955,6 +4960,7 @@ declare namespace ts.server { interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; + readonly stack?: string; } interface ProjectResponse extends TypingInstallerResponse { readonly projectName: string; @@ -8315,7 +8321,7 @@ declare namespace ts.server.protocol { /** * Arguments for navto request message. */ - interface NavtoRequestArgs extends FileRequestArgs { + interface NavtoRequestArgs { /** * Search term to navigate to from current location; term can * be '.*' or an identifier prefix. @@ -8325,6 +8331,10 @@ declare namespace ts.server.protocol { * Optional limit on the number of items to return. */ maxResultCount?: number; + /** + * The file for the request (absolute pathname required). + */ + file?: string; /** * Optional flag to indicate we want results for just the current file * or the entire project. @@ -8338,7 +8348,7 @@ declare namespace ts.server.protocol { * match the search term given in argument 'searchTerm'. The * context for the search is given by the named file. */ - interface NavtoRequest extends FileRequest { + interface NavtoRequest extends Request { command: CommandTypes.Navto; arguments: NavtoRequestArgs; } diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 344ae4236d636..41618feb3bab0 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -242,7 +242,7 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; /** @@ -1030,6 +1030,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1489,6 +1501,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -3699,6 +3715,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3737,6 +3754,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3748,7 +3766,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -4646,6 +4664,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4695,6 +4720,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4727,7 +4753,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -6522,6 +6548,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6801,6 +6828,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6833,7 +6861,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6933,6 +6961,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -7146,8 +7175,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7313,7 +7342,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7358,6 +7386,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -7374,6 +7406,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7508,6 +7542,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7643,6 +7683,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7860,6 +7901,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8057,6 +8100,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8165,6 +8210,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8187,6 +8239,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8338,9 +8393,13 @@ var ts; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -9690,13 +9749,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9711,6 +9764,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9718,11 +9772,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -10051,7 +10107,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -11119,7 +11185,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -13301,7 +13367,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -13686,6 +13752,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13892,6 +13962,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -14750,7 +14839,7 @@ var ts; } /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. + * We treat the right hand side of assignments with container-like initializers as declarations. */ function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -14869,10 +14958,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14906,7 +14998,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -15035,6 +15127,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -16119,7 +16222,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -17012,14 +17115,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -17346,19 +17444,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -18791,6 +18890,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -25785,9 +25901,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -27497,7 +27655,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27599,9 +27758,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27781,19 +27940,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27802,8 +27952,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27837,6 +27986,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27845,8 +27995,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27985,7 +28136,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -28301,15 +28452,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -28319,8 +28467,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -28329,11 +28479,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -30767,16 +30919,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30867,7 +31010,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -31087,7 +31230,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -31108,7 +31251,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162 /* Constructor */) { + if (node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -32988,7 +33131,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -33090,7 +33233,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -33217,7 +33360,7 @@ var ts; } function bindSpecialPropertyAssignment(node) { // Class declarations in Typescript do not allow property declarations - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -33317,7 +33460,7 @@ var ts; : propertyAccess.parent.parent.kind === 290 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -33716,6 +33859,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33758,6 +33904,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -34192,8 +34346,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -34678,7 +34830,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34814,7 +34968,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["ExcessCheck"] = 4] = "ExcessCheck"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -35005,6 +35160,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -35166,9 +35322,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -35382,6 +35536,7 @@ var ts; /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -35661,12 +35816,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35724,24 +35875,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35762,6 +35921,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35800,6 +35960,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35839,7 +36009,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35875,6 +36045,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35891,7 +36062,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage if (declaration.kind === 191 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) @@ -35916,11 +36087,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35942,40 +36112,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -36037,6 +36209,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -36054,7 +36281,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -36082,9 +36309,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -36305,15 +36530,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -36413,17 +36644,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -36819,12 +37050,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36837,6 +37063,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36953,7 +37198,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36961,25 +37206,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -37228,9 +37496,9 @@ var ts; if (name.kind === 75 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -37258,7 +37526,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -37734,11 +38002,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37858,7 +38129,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37904,7 +38175,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -38093,7 +38364,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -38308,7 +38579,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -38347,7 +38618,7 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -38378,10 +38649,16 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38730,14 +39007,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38904,7 +39181,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38944,28 +39221,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); - } + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } + } + } + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; } - return result; + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38983,7 +39295,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38995,7 +39307,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -39015,7 +39327,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39038,7 +39350,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); @@ -39047,7 +39359,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -39214,6 +39526,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -39352,8 +39670,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -39370,7 +39695,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -39491,7 +39816,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -39518,6 +39843,163 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -39612,7 +40094,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39624,7 +40106,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39732,7 +40214,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39767,7 +40249,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39868,7 +40350,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39887,13 +40369,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39938,7 +40426,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39975,13 +40463,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -40034,6 +40523,9 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -40043,16 +40535,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -40065,9 +40561,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -40199,7 +40693,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -40242,7 +40736,7 @@ var ts; } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -40266,7 +40760,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -40281,10 +40775,11 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); @@ -40298,13 +40793,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -40313,7 +40808,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -40350,116 +40845,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40891,8 +41276,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40981,9 +41366,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -41088,8 +41470,8 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - // Filter `undefined` from the type we check against if the parent has an initializer (which handles the `undefined` case implicitly) - else if (strictNullChecks && pattern.parent.initializer) { + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; @@ -41253,6 +41635,15 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. + // Use control flow analysis of this.xxx assignments the constructor to determine the type of the property. + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for @@ -41266,6 +41657,56 @@ var ts; // No type specified and nothing can be inferred return undefined; } + function isConstructorDeclaredProperty(symbol) { + // A propery is considered a constructor declared property when all declaration sites are this.xxx assignments, + // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of + // a class constructor. + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ && + (declaration.left.kind !== 195 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + // A property is auto-typed when its declaration has no type annotation or initializer and we're in + // noImplicitAny mode or a .js file. + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); + if (container && (container.kind === 162 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + // We don't infer a type if assignments are only null or undefined. + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); @@ -41277,52 +41718,60 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + // We use control flow analysis to determine the type of the property if the property qualifies as a constructor + // declared property and the resulting control flow type isn't just undefined or null. + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; // No types from any declarations :( + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - // use only the constructor types unless they were only assigned null | undefined (including widening variants) - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; // No types from any declarations :( + } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 - type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { @@ -41397,28 +41846,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -41428,6 +41904,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41445,20 +41926,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - /** check for definition in base class if any declaration is in a class */ - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -41803,7 +42270,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41820,9 +42287,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41988,6 +42455,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -42015,6 +42483,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -42205,16 +42676,19 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -42225,7 +42699,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -43084,7 +43558,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -43096,7 +43570,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -43160,9 +43634,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -43220,7 +43694,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -43243,19 +43717,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -43628,8 +44102,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43717,8 +44191,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43743,8 +44217,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43830,8 +44304,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43933,7 +44407,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43942,10 +44416,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43956,16 +44430,25 @@ var ts; if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43992,13 +44475,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -44010,7 +44495,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -44087,7 +44572,7 @@ var ts; else if (type.flags & 2097152 /* Intersection */) { if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); } return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; } @@ -44104,11 +44589,33 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. return !(prop.flags & 16777216 /* Optional */) && (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -44766,12 +45273,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44792,8 +45299,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -45310,6 +45817,8 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: + case 174 /* ArrayType */: + case 175 /* TupleType */: return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; @@ -45491,8 +46000,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -45521,8 +46030,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -45701,8 +46210,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -46057,6 +46566,9 @@ var ts; if (accessFlags & 4 /* CacheSymbol */) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? @@ -46409,7 +46921,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -46483,7 +46995,7 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -46841,7 +47353,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -47360,7 +47872,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -47394,37 +47906,23 @@ var ts; } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; - if (objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32 /* Mapped */) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4 /* Reference */) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728 /* UnionOrIntersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152 /* Intersection */) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -47536,7 +48034,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -47733,6 +48231,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -47756,7 +48263,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -48019,7 +48526,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -48397,13 +48904,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -48660,6 +49168,15 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source @@ -48671,6 +49188,14 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -48728,7 +49253,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & 4 /* ExcessCheck */); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -48736,12 +49261,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4 /* ExcessCheck */)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 4 /* ExcessCheck */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -48757,9 +49276,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); })) { - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } + result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -48791,44 +49308,71 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } + } + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -48836,11 +49380,11 @@ var ts; return 0 /* False */; } if (flags & 3145728 /* UnionOrIntersection */) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -48868,7 +49412,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -48924,7 +49468,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -48994,8 +49538,16 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; @@ -49072,7 +49624,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -49154,26 +49706,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_4 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -49458,9 +50013,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -49527,12 +50082,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -49580,11 +50135,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -49592,7 +50147,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -49600,7 +50155,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -49614,7 +50169,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -49666,7 +50221,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_7 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -49676,7 +50231,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -49684,34 +50239,27 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -49746,7 +50294,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -49871,7 +50419,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -50119,18 +50667,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -50201,7 +50753,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -50233,7 +50785,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -50328,6 +50880,12 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return the inherited type of the given property or undefined if property doesn't exist in a base class. + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } // Return true if some underlying source property is declared in a class that derives // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { @@ -50516,8 +51074,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -50666,8 +51224,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -51038,7 +51596,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -51047,7 +51605,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -51061,7 +51619,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -51179,15 +51737,22 @@ var ts; return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); } var result = !!(type.flags & 63176704 /* Instantiable */ || - objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 /* SourceFile */ ? true : n.kind === 249 /* ModuleDeclaration */ ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -51220,12 +51785,16 @@ var ts; * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -51522,8 +52091,8 @@ var ts; else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -51631,8 +52200,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -52232,8 +52801,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -52301,6 +52870,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -52509,7 +53081,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -52601,8 +53173,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -52654,9 +53226,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, /*diagnostic*/ undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); } } if (diagnostic) { @@ -52955,7 +53529,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576 /* Union */) { @@ -53238,14 +53812,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; + if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -53269,7 +53844,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } return type; @@ -53308,12 +53883,6 @@ var ts; if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -53328,12 +53897,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -53407,7 +53982,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -53596,15 +54171,16 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { // Do not narrow when checking inequality. if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { return type; } - // In the case of `x.y`, a `x.constructor === T` type guard resets the narrowed type of `y` to its declared type. - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } // Get the type of the constructor identifier expression, if it is not a function then do not narrow. var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { @@ -53718,7 +54294,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -53758,7 +54334,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); }); } return type; @@ -54294,6 +54870,10 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + // TODO: Maybe issue a better error than 'object is possibly undefined' + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -54686,7 +55266,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -54725,7 +55305,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -55379,8 +55959,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -55971,7 +56551,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304 /* Nullable */)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 1 /* Any */) && right.flags & 16777216 /* Optional */)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -56152,14 +56733,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -56169,7 +56750,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -56250,8 +56835,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -56335,11 +56921,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -56550,6 +57131,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -56623,7 +57207,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -56637,6 +57221,9 @@ var ts; prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -56769,7 +57356,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -57671,8 +58258,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -57888,7 +58475,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -57906,15 +58493,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -58040,7 +58627,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -58048,7 +58635,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -58383,8 +58970,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -58438,9 +59025,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -59058,7 +59645,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -59241,18 +59828,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -59470,7 +60055,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -59579,13 +60164,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -59610,7 +60188,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59746,11 +60324,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -59893,8 +60480,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59960,7 +60547,8 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || + isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -60345,6 +60933,12 @@ var ts; case 49 /* GreaterThanGreaterThanGreaterThanToken */: case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: reportOperatorError(); + break; + case 42 /* AsteriskAsteriskToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -60479,8 +61073,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -61248,7 +61842,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -61650,8 +62244,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -62111,7 +62706,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -62224,10 +62819,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_8 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -62466,7 +63061,7 @@ var ts; if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -62601,8 +63196,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -62991,7 +63586,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -63018,6 +63613,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -63031,8 +63636,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -63548,8 +64152,30 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -63704,11 +64330,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -64324,10 +64947,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -64335,6 +64959,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -64360,7 +64985,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -64541,6 +65166,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -64828,7 +65456,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -64847,7 +65475,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -65006,6 +65634,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -65014,11 +65661,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -65136,7 +65783,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -65187,7 +65834,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -65270,6 +65923,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -65543,7 +66199,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -65667,15 +66323,10 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -65689,6 +66340,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } @@ -67416,8 +68070,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -68031,9 +68711,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -68092,6 +68772,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -69099,13 +69780,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -70417,9 +71098,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -70541,9 +71224,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -71014,6 +71699,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -72559,11 +73264,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -72926,7 +73634,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -72937,7 +73645,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -72949,15 +73657,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -73180,11 +73888,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -74222,18 +74931,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -74988,13 +75749,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -76128,9 +76969,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -76235,9 +77073,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -77088,6 +77923,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -77979,6 +78818,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -77988,8 +78838,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -78472,6 +79322,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -78794,24 +79652,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -78841,7 +79700,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -79794,7 +80653,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -79860,8 +80719,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79881,8 +80740,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -80792,6 +81651,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -80805,7 +81688,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ @@ -80815,6 +81698,27 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -80841,11 +81745,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -80876,26 +81780,30 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: @@ -80916,7 +81824,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -80952,7 +81860,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -81027,13 +81935,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -81114,15 +82026,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -81170,7 +82082,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -81184,9 +82096,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -81316,7 +82232,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -81530,7 +82446,7 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -81661,6 +82577,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -81696,6 +82613,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -81708,6 +82626,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -81743,6 +82662,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -83669,6 +84589,8 @@ var ts; // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -89657,7 +90579,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -91781,7 +92703,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -91872,6 +92795,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -92299,6 +93230,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -93135,8 +94072,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -93154,8 +94095,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -93285,6 +94229,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -93292,6 +94239,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -93299,6 +94247,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -93313,9 +94275,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -93340,7 +94306,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -93355,17 +94323,37 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -93999,6 +94987,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -95494,16 +96483,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -96299,12 +97282,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -96641,8 +97627,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -96869,7 +97855,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -97073,7 +98059,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -97212,7 +98198,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -97257,7 +98243,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -97293,6 +98279,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -98888,11 +99887,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -99407,13 +100406,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -100033,7 +101032,7 @@ var ts; return line; } // Stop searching if the line is not empty and not a comment - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -103910,9 +104909,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -103928,9 +104927,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -103954,7 +104953,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -103980,7 +104979,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -104554,20 +105553,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -104623,12 +105625,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -104644,7 +105664,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -104993,7 +106013,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -107334,7 +108354,11 @@ var ts; if (node.kind === 290 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) { + else if (node.parent.kind === 259 /* ExportAssignment */ + || node.parent.kind === 265 /* ExternalModuleReference */ + || node.parent.kind === 258 /* ImportSpecifier */ + || node.parent.kind === 255 /* ImportClause */ + || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -108753,10 +109777,28 @@ var ts; var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } + function getReplacementSpanForContextToken(contextToken) { + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return createTextSpanFromStringLiteralLikeContent(contextToken); + default: + return createTextSpanFromNode(contextToken); + } + } + ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken; function createTextSpanFromNode(node, sourceFile, endNode) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromStringLiteralLikeContent(node) { + if (node.isUnterminated) + return undefined; + return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); + } + ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent; function createTextRangeFromNode(node, sourceFile) { return ts.createRange(node.getStart(sourceFile), node.end); } @@ -108994,17 +110036,26 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + function insertImports(changes, sourceFile, imports, blankLineBetween) { + var decl = ts.isArray(imports) ? imports[0] : imports; + var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { - changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + if (ts.isArray(imports)) { + changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports); + } + else { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports); + } + } + else if (ts.isArray(imports)) { + changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween); } else { - changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween); + changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween); } } - ts.insertImport = insertImport; + ts.insertImports = insertImports; function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); @@ -109409,6 +110460,27 @@ var ts; addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } ts.suppressTrailingTrivia = suppressTrailingTrivia; + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + } + ts.copyComments = copyComments; + function hasLeadingLineBreak(node, text) { + var start = node.getFullStart(); + var end = node.getStart(); + for (var i = start; i < end; i++) { + if (text.charCodeAt(i) === 10 /* lineFeed */) + return true; + } + return false; + } function addEmitFlagsRecursively(node, flag, getChild) { ts.addEmitFlags(node, flag); var child = getChild(node); @@ -109502,6 +110574,11 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + /* @internal */ + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { @@ -109910,10 +110987,54 @@ var ts; return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + /** + * Useful to check whether a string contains another string at a specific index + * without allocating another string or traversing the entire contents of the outer string. + * + * This function is useful in place of either of the following: + * + * ```ts + * // Allocates + * haystack.substr(startIndex, needle.length) === needle + * + * // Full traversal + * haystack.indexOf(needle, startIndex) === startIndex + * ``` + * + * @param haystack The string that potentially contains `needle`. + * @param needle The string whose content might sit within `haystack`. + * @param startIndex The index within `haystack` to start searching for `needle`. + */ + function stringContainsAt(haystack, needle, startIndex) { + var needleLength = needle.length; + if (needleLength + startIndex > haystack.length) { + return false; + } + for (var i = 0; i < needleLength; i++) { + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) + return false; + } + return true; + } + ts.stringContainsAt = stringContainsAt; function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } ts.startsWithUnderscore = startsWithUnderscore; + function isGlobalDeclaration(declaration) { + return !isNonGlobalDeclaration(declaration); + } + ts.isGlobalDeclaration = isGlobalDeclaration; + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } + ts.isNonGlobalDeclaration = isNonGlobalDeclaration; // #endregion })(ts || (ts = {})); var ts; @@ -110890,11 +112011,11 @@ var ts; if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -110903,11 +112024,17 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ + name: type.value, + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: "0", + replacementSpan: ts.getReplacementSpanForContextToken(contextToken) + }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -111074,7 +112201,9 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }), + symbols: type.getApparentProperties().filter(function (prop) { + return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration); + }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -111506,6 +112635,22 @@ var ts; SortText["AutoImportSuggestions"] = "5"; SortText["JavascriptIdentifiers"] = "6"; })(SortText = Completions.SortText || (Completions.SortText = {})); + /** + * Special values for `CompletionInfo['source']` used to disambiguate + * completion items with the same `name`. (Each completion item must + * have a unique name/source combination, because those two fields + * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`. + * + * When the completion item is an auto-import suggestion, the source + * is the module specifier of the suggestion. To avoid collisions, + * the values here should not be a module specifier we would ever + * generate for an auto-import. + */ + var CompletionSource; + (function (CompletionSource) { + /** Completions that require `this.` insertion text */ + CompletionSource["ThisProperty"] = "ThisProperty/"; + })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType"; @@ -111653,14 +112798,16 @@ var ts; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); @@ -111697,7 +112844,8 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { + uniqueNames.add(realName); entries.push({ name: realName, kind: "warning" /* warning */, @@ -111715,9 +112863,9 @@ var ts; function createCompletionEntryForLiteral(literal, preferences) { return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var insertText; - var replacementSpan; + var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -111794,13 +112942,18 @@ var ts; !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; } function getSourceFromOrigin(origin) { - return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + if (originIsExport(origin)) { + return ts.stripQuotes(origin.moduleSymbol.name); + } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { + return CompletionSource.ThisProperty; + } } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); // Tracks unique names. - // We don't set this for global variables or completions from external module exports, because we can have multiple of those. - // Based on the order we add things we will always see locals first, then globals, then module exports. + // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; + // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { @@ -111811,21 +112964,26 @@ var ts; continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.has(name)) { + if (uniques.get(name)) { continue; } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 - uniques.set(name, true); - } + /** True for locals; false for globals, module exports from other files, `this.` completions. */ + var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + uniques.set(name, shouldShadowLaterSymbols); entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniques; + // Prevent consumers of this map from having to worry about + // the boolean value. Externally, it should be seen as the + // set of all names. + return { + has: function (name) { return uniques.has(name); }, + add: function (name) { return uniques.set(name, true); }, + }; } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -112454,6 +113612,7 @@ var ts; function tryGetGlobalSymbols() { var result = tryGetObjectLikeCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() + || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() @@ -112535,7 +113694,7 @@ var ts; // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); - if (thisType) { + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; @@ -112743,7 +113902,7 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -113012,8 +114171,6 @@ var ts; * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` @@ -113021,9 +114178,10 @@ var ts; ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; - // cursor is in an import clause - // try to show exported member for imported module + // try to show exported member for imported/re-exported module var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + if (!moduleSpecifier) + return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -113034,6 +114192,35 @@ var ts; symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); return 1 /* Success */; } + /** + * Adds local declarations for completions in named exports: + * + * export { | }; + * + * Does not check for the absence of a module specifier (`export {} from "./other"`) + * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that, + * preventing this function from running. + */ + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedExports) + : undefined; + if (!namedExports) { + return 0 /* Continue */; + } + var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration)); + completionKind = 5 /* None */; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) { + var _a, _b; + symbols.push(symbol); + if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) { + symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember; + } + }); + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. @@ -113384,7 +114571,7 @@ var ts; }); } } - // Set SortText to OptionalMember if it is an optinoal member + // Set SortText to OptionalMember if it is an optional member function setSortTextToOptionalMember() { symbols.forEach(function (m) { if (m.flags & 16777216 /* Optional */) { @@ -113440,7 +114627,8 @@ var ts; return baseSymbols.filter(function (propertySymbol) { return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && + !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration); }); } /** @@ -113667,10 +114855,16 @@ var ts; return cls; } break; - case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| } + case 75 /* Identifier */: { + // class c { public prop = c| } + if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return undefined; + } + // class c extends React.Component { a: () => 1\n compon| } if (isFromObjectTypeDeclaration(location)) { return ts.findAncestor(location, ts.isObjectTypeDeclaration); } + } } if (!contextToken) return undefined; @@ -113738,14 +114932,23 @@ var ts; } } } - function isNonGlobalDeclaration(declaration) { - var sourceFile = declaration.getSourceFile(); - // If the file is not a module, the declaration is global - if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { - return false; + /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ + function isProbablyGlobalType(type, sourceFile, checker) { + // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in + // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists. + var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { + return true; + } + var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { + return true; + } + var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { + return true; } - // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation - return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + return false; } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -115074,7 +116277,29 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var referenceEntries; + var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 194 /* PropertyAccessExpression */ + || node.parent.kind === 191 /* BindingElement */ + || node.parent.kind === 195 /* ElementAccessExpression */ + || node.kind === 102 /* SuperKeyword */) { + referenceEntries = entries && __spreadArrays(entries); + } + else { + var queue = entries && __spreadArrays(entries); + var seenNodes = ts.createMap(); + while (queue && queue.length) { + var entry = queue.shift(); + if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { + continue; + } + referenceEntries = ts.append(referenceEntries, entry); + var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries_1) { + queue.push.apply(queue, entries_1); + } + } + } var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } @@ -118065,6 +119290,8 @@ var ts; // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 226 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression); case 209 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { @@ -119608,7 +120835,10 @@ var ts; case 246 /* InterfaceDeclaration */: case 248 /* EnumDeclaration */: case 251 /* CaseBlock */: + case 173 /* TypeLiteral */: return spanForNode(n); + case 175 /* TupleType */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); case 277 /* CaseClause */: case 278 /* DefaultClause */: return spanForNodeArray(n.statements); @@ -119626,6 +120856,8 @@ var ts; case 211 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); + case 190 /* ArrayBindingPattern */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -121414,7 +122646,7 @@ var ts; var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); })); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); @@ -121431,7 +122663,7 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; @@ -121734,7 +122966,18 @@ var ts; } ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) || + ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + function hasSupportedNumberOfArguments(node) { + if (node.arguments.length > 2) + return false; + if (node.arguments.length < 2) + return true; + return ts.some(node.arguments, function (arg) { + return arg.kind === 100 /* NullKeyword */ || + ts.isIdentifier(arg) && arg.text === "undefined"; + }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { @@ -121775,6 +123018,7 @@ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -122219,7 +123463,7 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122361,7 +123605,7 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122982,7 +124226,7 @@ var ts; rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), // Async-await rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // JSX opening elements @@ -125414,6 +126658,15 @@ var ts; * include all trivia between the node and the previous token */ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + /** + * Include attached JSDoc comments + */ + LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc"; + /** + * Only delete trivia on the same line as getStart(). + * Used to avoid deleting leading comments + */ + LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine"; })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); var TrailingTriviaOption; (function (TrailingTriviaOption) { @@ -125456,6 +126709,15 @@ var ts; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } + if (leadingTriviaOption === LeadingTriviaOption.StartLine) { + return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile); + } + if (leadingTriviaOption === LeadingTriviaOption.JSDoc) { + var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) { + return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile); + } + } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); if (fullStart === start) { @@ -125604,11 +126866,23 @@ var ts; this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween); + }; + ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween); + }; + ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); - this.insertNodeAt(sourceFile, pos, newNode, { + var options = { prefix: pos === 0 ? undefined : this.newLineCharacter, suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), - }); + }; + if (ts.isArray(insert)) { + this.insertNodesAt(sourceFile, pos, insert, options); + } + else { + this.insertNodeAt(sourceFile, pos, insert, options); + } }; ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) { var p0 = ts.firstOrUndefined(parameters); @@ -125671,6 +126945,7 @@ var ts; }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var _a; var endNode; if (ts.isFunctionLike(node)) { endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); @@ -125682,7 +126957,7 @@ var ts; } } else { - endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -126087,7 +127362,7 @@ var ts; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. @@ -126101,10 +127376,16 @@ var ts; for (var i = 0; i < normalized.length - 1; i++) { _loop_10(i); } - var textChanges = normalized.map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + var textChanges = ts.mapDefined(normalized, function (c) { + var span = ts.createTextSpanFromRange(c.range); + var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); + // Filter out redundant changes. + if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) { + return undefined; + } + return ts.createTextChange(span, newText); }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; + return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; @@ -126465,10 +127746,10 @@ var ts; break; } case 254 /* ImportDeclaration */: - var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration); - deleteNode(changes, sourceFile, node, - // For first import, leave header comment in place - isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); + case 253 /* ImportEqualsDeclaration */: + var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); + // For first import, leave header comment in place, otherwise only delete JSDoc comments + deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; case 191 /* BindingElement */: var pattern = node.parent; @@ -126504,6 +127785,10 @@ var ts; case 94 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; + case 245 /* ClassDeclaration */: + case 244 /* FunctionDeclaration */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + break; default: if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); @@ -126573,7 +127858,7 @@ var ts; deleteNode(changes, sourceFile, parent); break; case 225 /* VariableStatement */: - deleteNode(changes, sourceFile, gp); + deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: ts.Debug.assertNever(gp); @@ -127046,7 +128331,7 @@ var ts; reference; var diagnostic = ts.find(diagnostics, function (diagnostic) { return diagnostic.start === errorNode.getStart(sourceFile) && - diagnostic.start + diagnostic.length === errorNode.getEnd(); + (diagnostic.start + diagnostic.length) === errorNode.getEnd(); }); return diagnostic && ts.contains(errorCodes, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid @@ -127523,90 +128808,161 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node. + if (ts.hasJSDocNodes(ctorDeclaration)) { + ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol if (symbol.members) { - symbol.members.forEach(function (member) { + symbol.members.forEach(function (member, key) { + if (key === "constructor") { + // fn.prototype.constructor = fn + changes.delete(sourceFile, member.valueDeclaration.parent); + return; + } var memberElement = createClassElement(member, /*modifiers*/ undefined); if (memberElement) { - memberElements.push(memberElement); + memberElements.push.apply(memberElements, memberElement); } }); } // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); + if (member.name === "prototype") { + var firstDeclaration = member.declarations[0]; + // only one "x.prototype = { ... }" will pass + if (member.declarations.length === 1 && + ts.isPropertyAccessExpression(firstDeclaration) && + ts.isBinaryExpression(firstDeclaration.parent) && + firstDeclaration.parent.operatorToken.kind === 62 /* EqualsToken */ && + ts.isObjectLiteralExpression(firstDeclaration.parent.right)) { + var prototypes = firstDeclaration.parent.right; + var memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } + } + } + else { + var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } } }); } return memberElements; function shouldConvertDeclaration(_target, source) { - // Right now the only thing we can convert are function expressions - other values shouldn't get - // transformed. We can update this once ES public class properties are available. - return ts.isFunctionLike(source); + // Right now the only thing we can convert are function expressions, get/set accessors and methods + // other values like normal value fields ({a: 1}) shouldn't get transformed. + // We can update this once ES public class properties are available. + if (ts.isPropertyAccessExpression(_target)) { + if (isConstructorAssignment(_target)) + return true; + return ts.isFunctionLike(source); + } + else { + return ts.every(_target.properties, function (property) { + // a() {} + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) + return true; + // a: function() {} + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer) && !!property.name) + return true; + // x.prototype.constructor = fn + if (isConstructorAssignment(property)) + return true; + return false; + }); + } } function createClassElement(symbol, modifiers) { // Right now the only thing we can convert are function expressions, which are marked as methods - if (!(symbol.flags & 8192 /* Method */)) { - return; + // or { x: y } type prototype assignments, which are marked as ObjectLiteral + var members = []; + if (!(symbol.flags & 8192 /* Method */) && !(symbol.flags & 4096 /* ObjectLiteral */)) { + return members; } var memberDeclaration = symbol.valueDeclaration; var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var assignmentExpr = assignmentBinaryExpression.right; + if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { + return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 201 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - case 202 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 223 /* Block */) { - bodyBlock = arrowFunctionBody; - } - // case 2: () => [1,2,3] - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); - } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJS(sourceFile)) { - return; - } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); - return prop; + if (!assignmentExpr) { + members.push(ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined)); + return members; + } + // f.x = expr + if (ts.isPropertyAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) { + return createFunctionLikeExpressionMember(members, assignmentExpr, memberDeclaration.name); + } + // f.prototype = { ... } + else if (ts.isObjectLiteralExpression(assignmentExpr)) { + return ts.flatMap(assignmentExpr.properties, function (property) { + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) { + // MethodDeclaration and AccessorDeclaration can appear in a class directly + return members.concat(property); + } + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer)) { + return createFunctionLikeExpressionMember(members, property.initializer, property.name); + } + // Drop constructor assignments + if (isConstructorAssignment(property)) + return members; + return []; + }); + } + else { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) + return members; + if (!ts.isPropertyAccessExpression(memberDeclaration)) + return members; + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); + members.push(prop); + return members; + } + function createFunctionLikeExpressionMember(members, expression, name) { + if (ts.isFunctionExpression(expression)) + return createFunctionExpressionMember(members, expression, name); + else + return createArrowFunctionExpressionMember(members, expression, name); + } + function createFunctionExpressionMember(members, functionExpression, name) { + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); + } + function createArrowFunctionExpressionMember(members, arrowFunction, name) { + var arrowFunctionBody = arrowFunction.body; + var bodyBlock; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 223 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); } } } @@ -127643,6 +128999,13 @@ var ts; function getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } + function isConstructorAssignment(x) { + if (!x.name) + return false; + if (ts.isIdentifier(x.name) && x.name.text === "constructor") + return true; + return false; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -127753,10 +129116,6 @@ var ts; var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } - function isParameterOfPromiseCallback(node, checker) { - return ts.isParameter(node) && (isPromiseReturningCallExpression(node.parent.parent, checker, "then") || - isPromiseReturningCallExpression(node.parent.parent, checker, "catch")); - } function isPromiseTypedExpression(node, checker) { if (!ts.isExpression(node)) return false; @@ -127771,7 +129130,6 @@ var ts; It then checks for any collisions and renames them through getSynthesizedDeepClone */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) { - var variableNames = []; var identsToRenameMap = ts.createMap(); // key is the symbol id var collidingSymbolMap = ts.createMultiMap(); ts.forEachChild(nodeToRename, function visit(node) { @@ -127796,7 +129154,6 @@ var ts; var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - variableNames.push({ identifier: synthName.identifier, symbol: symbol }); collidingSymbolMap.add(ident.text, symbol); } // We only care about identifiers that are parameters, variable declarations, or binding elements @@ -127808,17 +129165,12 @@ var ts; var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - variableNames.push({ identifier: newName.identifier, symbol: symbol }); collidingSymbolMap.add(originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); - identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); - if (isParameterOfPromiseCallback(node.parent, checker) || ts.isVariableDeclaration(node.parent)) { - variableNames.push({ identifier: identifier, symbol: symbol }); - collidingSymbolMap.add(originalName, symbol); - } + collidingSymbolMap.add(originalName, symbol); } } } @@ -127898,7 +129250,7 @@ var ts; varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier); var typeArray = possibleNameForVarDecl.types; var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); } @@ -128872,7 +130224,6 @@ var ts; // Keys are import clause node IDs. var addToExisting = ts.createMap(); var newImports = ts.createMap(); - var lastModuleSpecifier; return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start); @@ -128922,7 +130273,6 @@ var ts; var entry = newImports.get(moduleSpecifier); if (!entry) { newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); - lastModuleSpecifier = moduleSpecifier; } else { // An import clause can only be type-only if every import fix contributing to it can be type-only. @@ -128962,11 +130312,15 @@ var ts; var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); + var newDeclarations; newImports.forEach(function (_a, moduleSpecifier) { var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); - var addDeclarations = useRequire ? addNewRequires : addNewImports; - addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + var getDeclarations = useRequire ? getNewRequires : getNewImports; + newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports)); }); + if (newDeclarations) { + ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); + } } } codefix.createImportAdder = createImportAdder; @@ -129363,11 +130717,11 @@ var ts; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; - var addDeclarations = useRequire ? addNewRequires : addNewImports; + var getDeclarations = useRequire ? getNewRequires : getNewImports; var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; - addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); + ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129435,11 +130789,12 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewImports(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { - ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly)); } var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { @@ -129451,12 +130806,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause( /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } - function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewRequires(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; // const { default: foo, bar, etc } = require('./mod'); if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; @@ -129464,13 +130821,14 @@ var ts; bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); } var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } // const foo = require('./mod'); if (imports.namespaceLikeImport) { var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { return ts.createVariableStatement( @@ -129843,6 +131201,192 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "returnValueCorrect"; + var fixIdAddReturnStatement = "fixAddReturnStatement"; + var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace"; + var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + var errorCodes = [ + ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + ]; + var ProblemKind; + (function (ProblemKind) { + ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement"; + ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses"; + })(ProblemKind || (ProblemKind = {})); + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen], + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; + var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) + return undefined; + if (info.kind === ProblemKind.MissingReturnStatement) { + return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined); + } + else { + return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; + } + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) + return undefined; + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixIdRemoveBlockBodyBrace: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); + break; + case fixIdWrapTheBlockWithParen: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1) + return undefined; + var firstStatement = ts.first(declaration.body.statements); + if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + } + else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return ts.isArrowFunction(declaration) ? { + declaration: declaration, + kind: ProblemKind.MissingParentheses, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } + } + else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) { + var firstBlockStatement = ts.first(firstStatement.statements); + if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; + } + } + } + return undefined; + } + function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) { + return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type); + } + function getInfo(checker, sourceFile, position, errorCode) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (!node.parent) + return undefined; + var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); + switch (errorCode) { + case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node)) + return undefined; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); + case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body) + return undefined; + var pos = declaration.parent.arguments.indexOf(declaration); + var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) + return undefined; + return getFixInfo(checker, declaration, type, /* isFunctionType */ true); + case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent)) + return undefined; + var initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body) + return undefined; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); + } + return undefined; + } + function getVariableLikeInitializer(declaration) { + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + return declaration.initializer; + case 273 /* JsxAttribute */: + return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); + case 282 /* ShorthandPropertyAssignment */: + case 158 /* PropertySignature */: + case 284 /* EnumMember */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + return undefined; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + ts.suppressLeadingAndTrailingTrivia(expression); + var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, ts.createReturn(expression), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : undefined + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression; + ts.suppressLeadingAndTrailingTrivia(commentSource); + ts.copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement); + } + function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -129867,7 +131411,7 @@ var ts; return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); @@ -129875,7 +131419,7 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { - var program = context.program, preferences = context.preferences; + var program = context.program; var checker = program.getTypeChecker(); var seen = ts.createMap(); var typeDeclToMembers = new ts.NodeMap(); @@ -129911,7 +131455,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call && !ts.isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); } else { if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { @@ -130051,11 +131595,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */); } @@ -130107,16 +131651,17 @@ var ts; // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { // Private methods are not implemented yet. if (ts.isPrivateIdentifier(token)) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) { + var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -130124,6 +131669,7 @@ var ts; else { changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } + importAdder.writeFixes(changeTracker); } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { /** @@ -130783,6 +132329,13 @@ var ts; } if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + if (ts.isParameter(token.parent)) { + ts.getJSDocParameterTags(token.parent).forEach(function (tag) { + if (ts.isIdentifier(tag.name)) { + changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text)); + } + }); + } } } function canPrefix(token) { @@ -131020,7 +132573,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); @@ -131680,7 +133233,7 @@ var ts; } switch (node.parent.kind) { case 226 /* ExpressionStatement */: - addCandidateType(usage, checker.getVoidType()); + inferTypeFromExpressionStatement(node, usage); break; case 208 /* PostfixUnaryExpression */: usage.isNumber = true; @@ -131736,6 +133289,9 @@ var ts; addCandidateType(usage, checker.getContextualType(node)); } } + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); + } function inferTypeFromPrefixUnaryExpression(node, usage) { switch (node.operator) { case 45 /* PlusPlusToken */: @@ -131989,6 +133545,7 @@ var ts; return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); } function inferTypes(usage) { + var _a, _b, _c; var types = []; if (usage.isNumber) { types.push(checker.getNumberType()); @@ -132002,10 +133559,7 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - if (usage.properties && usage.properties.size - || usage.calls && usage.calls.length - || usage.constructs && usage.constructs.length - || usage.stringIndex) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); @@ -132159,6 +133713,59 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixReturnTypeInAsyncFunction"; + var errorCodes = [ + ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + var checker = program.getTypeChecker(); + var info = getInfo(sourceFile, program.getTypeChecker(), span.start); + if (!info) { + return undefined; + } + var returnTypeNode = info.returnTypeNode, returnType = info.returnType, promisedTypeNode = info.promisedTypeNode, promisedType = info.promisedType; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, returnTypeNode, promisedTypeNode); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Replace_0_with_Promise_1, + checker.typeToString(returnType), checker.typeToString(promisedType)], fixId, ts.Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); + if (info) { + doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); + } + }); } + }); + function getInfo(sourceFile, checker, pos) { + if (ts.isInJSFile(sourceFile)) { + return undefined; + } + var token = ts.getTokenAtPosition(sourceFile, pos); + var func = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var returnTypeNode = func === null || func === void 0 ? void 0 : func.type; + if (!returnTypeNode) { + return undefined; + } + var returnType = checker.getTypeFromTypeNode(returnTypeNode); + var promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); + var promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined); + if (promisedTypeNode) { + return { returnTypeNode: returnTypeNode, returnType: returnType, promisedTypeNode: promisedTypeNode, promisedType: promisedType }; + } + } + function doChange(changes, sourceFile, returnTypeNode, promisedTypeNode) { + changes.replaceNode(sourceFile, returnTypeNode, ts.createTypeReferenceNode("Promise", [promisedTypeNode])); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -132175,12 +133782,13 @@ var ts; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options); var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -132392,14 +134000,14 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) { var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { - // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); + return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; @@ -132415,9 +134023,21 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && ts.isImportTypeNode(typeNode)) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { @@ -132571,6 +134191,7 @@ var ts; function importSymbols(importAdder, symbols) { symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); } + codefix.importSymbols = importSymbols; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -134053,6 +135674,8 @@ var ts; function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); + var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); @@ -134068,7 +135691,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -134127,6 +135750,7 @@ var ts; else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); var newNodes = []; // replace range with function call var called = getCalledExpression(scope, range, functionNameText); @@ -135215,6 +136839,7 @@ var ts; var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(accessorName); ts.suppressLeadingAndTrailingTrivia(declaration); ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); @@ -135460,7 +137085,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -136109,19 +137734,20 @@ var ts; } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); - body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); + ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); } - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { + t.replaceNode(file, func.body, body); + }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } - function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); - } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); @@ -136478,7 +138104,7 @@ var ts; ts.suppressLeadingAndTrailingTrivia(property.name); if (ts.isPropertyAssignment(property)) ts.suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); + ts.copyComments(arg, property); return property; }); if (hasRestParameter && functionArguments.length >= parameters.length) { @@ -136513,10 +138139,10 @@ var ts; /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); + ts.copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + ts.copyComments(thisParameter.type, newThisParameter.type); } return ts.createNodeArray([newThisParameter, objectParameter]); } @@ -136527,7 +138153,7 @@ var ts; /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); ts.suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + ts.copyComments(parameterDeclaration.initializer, element.initializer); } return element; } @@ -136545,9 +138171,9 @@ var ts; /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); + ts.copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); + ts.copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; } @@ -136563,26 +138189,6 @@ var ts; return checker.isOptionalParameter(parameterDeclaration); } } - function copyComments(sourceNode, targetNode) { - var sourceFile = sourceNode.getSourceFile(); - var text = sourceFile.text; - if (hasLeadingLineBreak(sourceNode, text)) { - ts.copyLeadingComments(sourceNode, targetNode, sourceFile); - } - else { - ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); - } - ts.copyTrailingComments(sourceNode, targetNode, sourceFile); - } - function hasLeadingLineBreak(node, text) { - var start = node.getFullStart(); - var end = node.getStart(); - for (var i = start; i < end; i++) { - if (text.charCodeAt(i) === 10 /* lineFeed */) - return true; - } - return false; - } function getParameterName(paramDeclaration) { return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name); } @@ -136751,7 +138357,6 @@ var ts; indexes.push(index); index++; } - text = ts.escapeString(text); return [index, text, indexes]; } function nodesToTemplate(_a, file) { @@ -144443,15 +146048,18 @@ var ts; */ /* @internal */ ProjectService.prototype.loadConfiguredProject = function (project, reason) { + var _this = this; this.sendProjectLoadingStartEvent(project, reason); // Read updated contents from disk var configFilename = ts.normalizePath(project.getConfigFilePath()); - var configFileContent = this.host.readFile(configFilename) || ""; - var result = ts.parseJsonText(configFilename, configFileContent); + var configFileContent = ts.tryReadFile(configFilename, function (fileName) { return _this.host.readFile(fileName); }); + var result = ts.parseJsonText(configFilename, ts.isString(configFileContent) ? configFileContent : ""); if (!result.endOfFileToken) { result.endOfFileToken = { kind: 1 /* EndOfFileToken */ }; } var configFileErrors = result.parseDiagnostics; + if (!ts.isString(configFileContent)) + configFileErrors.push(configFileContent); var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), /*existingOptions*/ {}, configFilename, /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions, @@ -146247,10 +147855,9 @@ var ts; function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, - /*initialLocation*/ undefined, function (_a, tryAddToTodo) { - var project = _a.project; - for (var _i = 0, _b = action(project); _i < _b.length; _i++) { - var output = _b[_i]; + /*initialLocation*/ undefined, function (project, _, tryAddToTodo) { + for (var _i = 0, _a = action(project); _i < _a.length; _i++) { + var output = _a[_i]; if (!ts.contains(outputs, output, resultsEqual) && !tryAddToTodo(project, getLocation(output))) { outputs.push(output); } @@ -146260,10 +147867,9 @@ var ts; } function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { - var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _b.length; _i++) { - var output = _b[_i]; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, tryAddToTodo) { + for (var _i = 0, _a = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _a.length; _i++) { + var output = _a[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); } @@ -146278,8 +147884,7 @@ var ts; } function combineProjectOutputForReferences(projects, defaultProject, initialLocation) { var outputs = []; - combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { - var project = _a.project, location = _a.location; + combineProjectOutputWorker(projects, defaultProject, initialLocation, function (project, location, getMappedLocation) { var _loop_9 = function (outputReferencedSymbol) { var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); var definition = mappedDefinitionFile === undefined ? @@ -146297,8 +147902,8 @@ var ts; } } }; - for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { - var outputReferencedSymbol = _b[_i]; + for (var _i = 0, _a = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _a.length; _i++) { + var outputReferencedSymbol = _a[_i]; _loop_9(outputReferencedSymbol); } }); @@ -146323,9 +147928,9 @@ var ts; var toDo; var seenProjects = ts.createMap(); forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) { - // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. + // TLocation should be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid. var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined); - toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb); + toDo = callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb); }); // After initial references are collected, go over every other project and see if it has a reference for the symbol definition. if (initialLocation) { @@ -146343,13 +147948,15 @@ var ts; return; var definition = mapDefinitionInProject(defaultDefinition_1, project, getGeneratedDefinition_1, getSourceDefinition_1); if (definition) { - toDo = callbackProjectAndLocation({ project: project, location: definition }, projectService, toDo, seenProjects, cb); + toDo = callbackProjectAndLocation(project, definition, projectService, toDo, seenProjects, cb); } }); } } while (toDo && toDo.length) { - toDo = callbackProjectAndLocation(ts.Debug.checkDefined(toDo.pop()), projectService, toDo, seenProjects, cb); + var next = toDo.pop(); + ts.Debug.assertIsDefined(next); + toDo = callbackProjectAndLocation(next.project, next.location, projectService, toDo, seenProjects, cb); } } function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { @@ -146380,30 +147987,29 @@ var ts; sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); } - function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) { - var project = projectAndLocation.project, location = projectAndLocation.location; + function callbackProjectAndLocation(project, location, projectService, toDo, seenProjects, cb) { if (project.getCancellationToken().isCancellationRequested()) return undefined; // Skip rest of toDo if cancelled // If this is not the file we were actually looking, return rest of the toDo if (isLocationProjectReferenceRedirect(project, location)) return toDo; - cb(projectAndLocation, function (project, location) { - addToSeen(seenProjects, projectAndLocation.project); - var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location); + cb(project, location, function (innerProject, location) { + addToSeen(seenProjects, project); + var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(innerProject, location); if (!originalLocation) return undefined; var originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); toDo = toDo || []; for (var _i = 0, _a = originalScriptInfo.containingProjects; _i < _a.length; _i++) { var project_1 = _a[_i]; - addToTodo({ project: project_1, location: originalLocation }, toDo, seenProjects); + addToTodo(project_1, originalLocation, toDo, seenProjects); } var symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); if (symlinkedProjectsMap) { symlinkedProjectsMap.forEach(function (symlinkedProjects, symlinkedPath) { for (var _i = 0, symlinkedProjects_2 = symlinkedProjects; _i < symlinkedProjects_2.length; _i++) { var symlinkedProject = symlinkedProjects_2[_i]; - addToTodo({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }, toDo, seenProjects); + addToTodo(symlinkedProject, { fileName: symlinkedPath, pos: originalLocation.pos }, toDo, seenProjects); } }); } @@ -146411,9 +148017,9 @@ var ts; }); return toDo; } - function addToTodo(projectAndLocation, toDo, seenProjects) { - if (addToSeen(seenProjects, projectAndLocation.project)) - toDo.push(projectAndLocation); + function addToTodo(project, location, toDo, seenProjects) { + if (addToSeen(seenProjects, project)) + toDo.push({ project: project, location: location }); } function addToSeen(seenProjects, project) { return ts.addToSeen(seenProjects, getProjectKey(project)); @@ -147383,6 +148989,7 @@ var ts; return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { + var _a; var projects; var symLinkedProjects; if (args.projectFileName) { @@ -147407,7 +149014,7 @@ var ts; // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); }); if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { - this.projectService.logErrorForScriptInfoNotFound(args.file); + this.projectService.logErrorForScriptInfoNotFound((_a = args.file) !== null && _a !== void 0 ? _a : args.projectFileName); return server.Errors.ThrowNoProject(); } return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217 @@ -147418,6 +149025,9 @@ var ts; if (project) { return project; } + if (!args.file) { + return server.Errors.ThrowNoProject(); + } } var info = this.projectService.getScriptInfo(args.file); return info.getDefaultProject(); @@ -147902,16 +149512,17 @@ var ts; }); }; Session.prototype.getFullNavigateToItems = function (args) { - var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount; + var currentFileOnly = args.currentFileOnly, searchValue = args.searchValue, maxResultCount = args.maxResultCount, projectFileName = args.projectFileName; if (currentFileOnly) { + ts.Debug.assertDefined(args.file); var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file); } - else { - return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) { - return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); - }, documentSpanLocation, navigateToItemIsEqualTo); + else if (!args.file && !projectFileName) { + return combineProjectOutputFromEveryProject(this.projectService, function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*filename*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, navigateToItemIsEqualTo); } + var fileArgs = args; + return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(fileArgs), this.getDefaultProject(fileArgs), function (project) { return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject()); }, documentSpanLocation, navigateToItemIsEqualTo); function navigateToItemIsEqualTo(a, b) { if (a === b) { return true; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 45bb3f9913c8d..e1a34cf708250 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.9"; + const versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -2040,23 +2040,23 @@ declare namespace ts { getNonNullableType(type: Type): Type; getTypeArguments(type: TypeReference): readonly Type[]; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): (SignatureDeclaration & { typeArguments?: NodeArray; }) | undefined; /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -2135,6 +2135,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowThisInObjectLiteral = 32768, AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, @@ -2163,6 +2164,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2171,7 +2173,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 277904747 + NodeBuilderFlagsMask = 814775659 } export enum SymbolFormatFlags { None = 0, @@ -3225,6 +3227,7 @@ declare namespace ts { NoInterveningComments = 262144, NoSpaceIfEmpty = 524288, SingleElement = 1048576, + SpaceAfterList = 2097152, Modifiers = 262656, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, @@ -3256,7 +3259,7 @@ declare namespace ts { CaseOrDefaultClauseStatements = 163969, HeritageClauseTypes = 528, SourceFileStatements = 131073, - Decorators = 49153, + Decorators = 2146305, TypeArguments = 53776, TypeParameters = 53776, Parameters = 2576, @@ -3860,7 +3863,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4457,7 +4460,8 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray | undefined): NodeArray | undefined; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4785,6 +4789,7 @@ declare namespace ts { /** Options to extend */ optionsToExtend?: CompilerOptions; watchOptionsToExtend?: WatchOptions; + extraFileExtensions?: readonly FileExtensionInfo[]; /** * Used to generate source file names from the config file and its include, exclude, files rules * and also to cache the directory stucture @@ -4812,7 +4817,7 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): WatchCompilerHostOfConfigFile; function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[], watchOptions?: WatchOptions): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options @@ -4955,6 +4960,7 @@ declare namespace ts.server { interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; + readonly stack?: string; } interface ProjectResponse extends TypingInstallerResponse { readonly projectName: string; diff --git a/lib/typescript.js b/lib/typescript.js index b58197c99c668..63718c68e7134 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -242,7 +242,7 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; /** @@ -1030,6 +1030,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1489,6 +1501,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -3699,6 +3715,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3737,6 +3754,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3748,7 +3766,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -4646,6 +4664,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4695,6 +4720,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4727,7 +4753,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -6522,6 +6548,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6801,6 +6828,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6833,7 +6861,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6933,6 +6961,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -7146,8 +7175,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7313,7 +7342,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7358,6 +7386,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -7374,6 +7406,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7508,6 +7542,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7643,6 +7683,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7860,6 +7901,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8057,6 +8100,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8165,6 +8210,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8187,6 +8239,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8338,9 +8393,13 @@ var ts; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -9690,13 +9749,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9711,6 +9764,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9718,11 +9772,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -10051,7 +10107,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -11119,7 +11185,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -13301,7 +13367,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -13686,6 +13752,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13892,6 +13962,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -14750,7 +14839,7 @@ var ts; } /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. + * We treat the right hand side of assignments with container-like initializers as declarations. */ function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -14869,10 +14958,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14906,7 +14998,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -15035,6 +15127,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -16119,7 +16222,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -17012,14 +17115,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -17346,19 +17444,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -18791,6 +18890,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -25785,9 +25901,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -27497,7 +27655,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27599,9 +27758,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27781,19 +27940,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27802,8 +27952,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27837,6 +27986,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27845,8 +27995,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27985,7 +28136,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -28301,15 +28452,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -28319,8 +28467,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -28329,11 +28479,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -30767,16 +30919,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30867,7 +31010,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -31087,7 +31230,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -31108,7 +31251,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162 /* Constructor */) { + if (node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -32988,7 +33131,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -33090,7 +33233,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -33217,7 +33360,7 @@ var ts; } function bindSpecialPropertyAssignment(node) { // Class declarations in Typescript do not allow property declarations - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -33317,7 +33460,7 @@ var ts; : propertyAccess.parent.parent.kind === 290 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -33716,6 +33859,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33758,6 +33904,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -34192,8 +34346,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -34678,7 +34830,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34814,7 +34968,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["ExcessCheck"] = 4] = "ExcessCheck"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -35005,6 +35160,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -35166,9 +35322,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -35382,6 +35536,7 @@ var ts; /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -35661,12 +35816,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35724,24 +35875,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35762,6 +35921,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35800,6 +35960,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35839,7 +36009,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35875,6 +36045,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35891,7 +36062,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage if (declaration.kind === 191 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) @@ -35916,11 +36087,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35942,40 +36112,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -36037,6 +36209,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -36054,7 +36281,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -36082,9 +36309,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -36305,15 +36530,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -36413,17 +36644,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -36819,12 +37050,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36837,6 +37063,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36953,7 +37198,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36961,25 +37206,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -37228,9 +37496,9 @@ var ts; if (name.kind === 75 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -37258,7 +37526,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -37734,11 +38002,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37858,7 +38129,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37904,7 +38175,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -38093,7 +38364,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -38308,7 +38579,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -38347,7 +38618,7 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -38378,10 +38649,16 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38730,14 +39007,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38904,7 +39181,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38944,28 +39221,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } } } - return result; + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; + } + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38983,7 +39295,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38995,7 +39307,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -39015,7 +39327,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39038,7 +39350,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); @@ -39047,7 +39359,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -39214,6 +39526,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -39352,8 +39670,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -39370,7 +39695,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -39491,7 +39816,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -39518,6 +39843,163 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -39612,7 +40094,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39624,7 +40106,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39732,7 +40214,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39767,7 +40249,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39868,7 +40350,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39887,13 +40369,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39938,7 +40426,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39975,13 +40463,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -40034,6 +40523,9 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -40043,16 +40535,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -40065,9 +40561,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -40199,7 +40693,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -40242,7 +40736,7 @@ var ts; } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -40266,7 +40760,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -40281,10 +40775,11 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); @@ -40298,13 +40793,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -40313,7 +40808,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -40350,116 +40845,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40891,8 +41276,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40981,9 +41366,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -41088,8 +41470,8 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - // Filter `undefined` from the type we check against if the parent has an initializer (which handles the `undefined` case implicitly) - else if (strictNullChecks && pattern.parent.initializer) { + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; @@ -41253,6 +41635,15 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. + // Use control flow analysis of this.xxx assignments the constructor to determine the type of the property. + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for @@ -41266,6 +41657,56 @@ var ts; // No type specified and nothing can be inferred return undefined; } + function isConstructorDeclaredProperty(symbol) { + // A propery is considered a constructor declared property when all declaration sites are this.xxx assignments, + // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of + // a class constructor. + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ && + (declaration.left.kind !== 195 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + // A property is auto-typed when its declaration has no type annotation or initializer and we're in + // noImplicitAny mode or a .js file. + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); + if (container && (container.kind === 162 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + // We don't infer a type if assignments are only null or undefined. + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); @@ -41277,52 +41718,60 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + // We use control flow analysis to determine the type of the property if the property qualifies as a constructor + // declared property and the resulting control flow type isn't just undefined or null. + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; // No types from any declarations :( + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - // use only the constructor types unless they were only assigned null | undefined (including widening variants) - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; // No types from any declarations :( + } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 - type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { @@ -41397,28 +41846,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -41428,6 +41904,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41445,20 +41926,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - /** check for definition in base class if any declaration is in a class */ - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -41803,7 +42270,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41820,9 +42287,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41988,6 +42455,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -42015,6 +42483,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -42205,16 +42676,19 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -42225,7 +42699,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -43084,7 +43558,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -43096,7 +43570,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -43160,9 +43634,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -43220,7 +43694,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -43243,19 +43717,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -43628,8 +44102,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43717,8 +44191,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43743,8 +44217,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43830,8 +44304,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43933,7 +44407,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43942,10 +44416,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43956,16 +44430,25 @@ var ts; if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43992,13 +44475,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -44010,7 +44495,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -44087,7 +44572,7 @@ var ts; else if (type.flags & 2097152 /* Intersection */) { if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); } return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; } @@ -44104,11 +44589,33 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. return !(prop.flags & 16777216 /* Optional */) && (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -44766,12 +45273,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44792,8 +45299,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -45310,6 +45817,8 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: + case 174 /* ArrayType */: + case 175 /* TupleType */: return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; @@ -45491,8 +46000,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -45521,8 +46030,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -45701,8 +46210,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -46057,6 +46566,9 @@ var ts; if (accessFlags & 4 /* CacheSymbol */) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? @@ -46409,7 +46921,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -46483,7 +46995,7 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -46841,7 +47353,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -47360,7 +47872,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -47394,37 +47906,23 @@ var ts; } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; - if (objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32 /* Mapped */) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4 /* Reference */) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728 /* UnionOrIntersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152 /* Intersection */) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -47536,7 +48034,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -47733,6 +48231,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -47756,7 +48263,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -48019,7 +48526,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -48397,13 +48904,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -48660,6 +49168,15 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source @@ -48671,6 +49188,14 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -48728,7 +49253,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & 4 /* ExcessCheck */); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -48736,12 +49261,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4 /* ExcessCheck */)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 4 /* ExcessCheck */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -48757,9 +49276,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); })) { - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } + result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -48791,44 +49308,71 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -48836,11 +49380,11 @@ var ts; return 0 /* False */; } if (flags & 3145728 /* UnionOrIntersection */) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -48868,7 +49412,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -48924,7 +49468,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -48994,8 +49538,16 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; @@ -49072,7 +49624,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -49154,26 +49706,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_4 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -49458,9 +50013,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -49527,12 +50082,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -49580,11 +50135,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -49592,7 +50147,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -49600,7 +50155,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -49614,7 +50169,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -49666,7 +50221,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_7 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -49676,7 +50231,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -49684,34 +50239,27 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -49746,7 +50294,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -49871,7 +50419,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -50119,18 +50667,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -50201,7 +50753,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -50233,7 +50785,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -50328,6 +50880,12 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return the inherited type of the given property or undefined if property doesn't exist in a base class. + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } // Return true if some underlying source property is declared in a class that derives // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { @@ -50516,8 +51074,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -50666,8 +51224,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -51038,7 +51596,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -51047,7 +51605,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -51061,7 +51619,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -51179,15 +51737,22 @@ var ts; return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); } var result = !!(type.flags & 63176704 /* Instantiable */ || - objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 /* SourceFile */ ? true : n.kind === 249 /* ModuleDeclaration */ ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -51220,12 +51785,16 @@ var ts; * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -51522,8 +52091,8 @@ var ts; else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -51631,8 +52200,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -52232,8 +52801,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -52301,6 +52870,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -52509,7 +53081,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -52601,8 +53173,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -52654,9 +53226,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, /*diagnostic*/ undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); } } if (diagnostic) { @@ -52955,7 +53529,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576 /* Union */) { @@ -53238,14 +53812,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; + if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -53269,7 +53844,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } return type; @@ -53308,12 +53883,6 @@ var ts; if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -53328,12 +53897,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -53407,7 +53982,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -53596,15 +54171,16 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { // Do not narrow when checking inequality. if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { return type; } - // In the case of `x.y`, a `x.constructor === T` type guard resets the narrowed type of `y` to its declared type. - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } // Get the type of the constructor identifier expression, if it is not a function then do not narrow. var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { @@ -53718,7 +54294,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -53758,7 +54334,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); }); } return type; @@ -54294,6 +54870,10 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + // TODO: Maybe issue a better error than 'object is possibly undefined' + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -54686,7 +55266,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -54725,7 +55305,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -55379,8 +55959,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -55971,7 +56551,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304 /* Nullable */)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 1 /* Any */) && right.flags & 16777216 /* Optional */)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -56152,14 +56733,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -56169,7 +56750,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -56250,8 +56835,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -56335,11 +56921,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -56550,6 +57131,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -56623,7 +57207,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -56637,6 +57221,9 @@ var ts; prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -56769,7 +57356,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -57671,8 +58258,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -57888,7 +58475,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -57906,15 +58493,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -58040,7 +58627,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -58048,7 +58635,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -58383,8 +58970,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -58438,9 +59025,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -59058,7 +59645,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -59241,18 +59828,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -59470,7 +60055,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -59579,13 +60164,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -59610,7 +60188,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59746,11 +60324,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -59893,8 +60480,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59960,7 +60547,8 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || + isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -60345,6 +60933,12 @@ var ts; case 49 /* GreaterThanGreaterThanGreaterThanToken */: case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: reportOperatorError(); + break; + case 42 /* AsteriskAsteriskToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -60479,8 +61073,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -61248,7 +61842,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -61650,8 +62244,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -62111,7 +62706,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -62224,10 +62819,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_8 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -62466,7 +63061,7 @@ var ts; if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -62601,8 +63196,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -62991,7 +63586,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -63018,6 +63613,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -63031,8 +63636,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -63548,8 +64152,30 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -63704,11 +64330,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -64324,10 +64947,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -64335,6 +64959,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -64360,7 +64985,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -64541,6 +65166,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -64828,7 +65456,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -64847,7 +65475,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -65006,6 +65634,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -65014,11 +65661,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -65136,7 +65783,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -65187,7 +65834,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -65270,6 +65923,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -65543,7 +66199,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -65667,15 +66323,10 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -65689,6 +66340,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } @@ -67416,8 +68070,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -68031,9 +68711,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -68092,6 +68772,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -69099,13 +69780,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -70417,9 +71098,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -70541,9 +71224,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -71014,6 +71699,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -72559,11 +73264,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -72926,7 +73634,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -72937,7 +73645,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -72949,15 +73657,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -73180,11 +73888,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -74222,18 +74931,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -74988,13 +75749,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -76128,9 +76969,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -76235,9 +77073,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -77088,6 +77923,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -77979,6 +78818,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -77988,8 +78838,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -78472,6 +79322,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -78794,24 +79652,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -78841,7 +79700,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -79794,7 +80653,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -79860,8 +80719,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79881,8 +80740,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -80792,6 +81651,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -80805,7 +81688,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ @@ -80815,6 +81698,27 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -80841,11 +81745,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -80876,26 +81780,30 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: @@ -80916,7 +81824,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -80952,7 +81860,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -81027,13 +81935,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -81114,15 +82026,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -81170,7 +82082,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -81184,9 +82096,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -81316,7 +82232,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -81530,7 +82446,7 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -81661,6 +82577,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -81696,6 +82613,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -81708,6 +82626,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -81743,6 +82662,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -83669,6 +84589,8 @@ var ts; // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -89657,7 +90579,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -91781,7 +92703,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -91872,6 +92795,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -92299,6 +93230,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -93135,8 +94072,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -93154,8 +94095,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -93285,6 +94229,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -93292,6 +94239,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -93299,6 +94247,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -93313,9 +94275,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -93340,7 +94306,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -93355,17 +94323,37 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -93999,6 +94987,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -95494,16 +96483,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -96299,12 +97282,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -96641,8 +97627,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -96869,7 +97855,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -97073,7 +98059,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -97212,7 +98198,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -97257,7 +98243,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -97293,6 +98279,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -98888,11 +99887,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -99407,13 +100406,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -100033,7 +101032,7 @@ var ts; return line; } // Stop searching if the line is not empty and not a comment - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -103910,9 +104909,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -103928,9 +104927,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -103954,7 +104953,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -103980,7 +104979,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -104554,20 +105553,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -104623,12 +105625,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -104644,7 +105664,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -104993,7 +106013,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -107334,7 +108354,11 @@ var ts; if (node.kind === 290 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) { + else if (node.parent.kind === 259 /* ExportAssignment */ + || node.parent.kind === 265 /* ExternalModuleReference */ + || node.parent.kind === 258 /* ImportSpecifier */ + || node.parent.kind === 255 /* ImportClause */ + || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -108753,10 +109777,28 @@ var ts; var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } + function getReplacementSpanForContextToken(contextToken) { + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return createTextSpanFromStringLiteralLikeContent(contextToken); + default: + return createTextSpanFromNode(contextToken); + } + } + ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken; function createTextSpanFromNode(node, sourceFile, endNode) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromStringLiteralLikeContent(node) { + if (node.isUnterminated) + return undefined; + return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); + } + ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent; function createTextRangeFromNode(node, sourceFile) { return ts.createRange(node.getStart(sourceFile), node.end); } @@ -108994,17 +110036,26 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + function insertImports(changes, sourceFile, imports, blankLineBetween) { + var decl = ts.isArray(imports) ? imports[0] : imports; + var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { - changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + if (ts.isArray(imports)) { + changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports); + } + else { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports); + } + } + else if (ts.isArray(imports)) { + changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween); } else { - changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween); + changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween); } } - ts.insertImport = insertImport; + ts.insertImports = insertImports; function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); @@ -109409,6 +110460,27 @@ var ts; addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } ts.suppressTrailingTrivia = suppressTrailingTrivia; + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + } + ts.copyComments = copyComments; + function hasLeadingLineBreak(node, text) { + var start = node.getFullStart(); + var end = node.getStart(); + for (var i = start; i < end; i++) { + if (text.charCodeAt(i) === 10 /* lineFeed */) + return true; + } + return false; + } function addEmitFlagsRecursively(node, flag, getChild) { ts.addEmitFlags(node, flag); var child = getChild(node); @@ -109502,6 +110574,11 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + /* @internal */ + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { @@ -109910,10 +110987,54 @@ var ts; return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + /** + * Useful to check whether a string contains another string at a specific index + * without allocating another string or traversing the entire contents of the outer string. + * + * This function is useful in place of either of the following: + * + * ```ts + * // Allocates + * haystack.substr(startIndex, needle.length) === needle + * + * // Full traversal + * haystack.indexOf(needle, startIndex) === startIndex + * ``` + * + * @param haystack The string that potentially contains `needle`. + * @param needle The string whose content might sit within `haystack`. + * @param startIndex The index within `haystack` to start searching for `needle`. + */ + function stringContainsAt(haystack, needle, startIndex) { + var needleLength = needle.length; + if (needleLength + startIndex > haystack.length) { + return false; + } + for (var i = 0; i < needleLength; i++) { + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) + return false; + } + return true; + } + ts.stringContainsAt = stringContainsAt; function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } ts.startsWithUnderscore = startsWithUnderscore; + function isGlobalDeclaration(declaration) { + return !isNonGlobalDeclaration(declaration); + } + ts.isGlobalDeclaration = isGlobalDeclaration; + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } + ts.isNonGlobalDeclaration = isNonGlobalDeclaration; // #endregion })(ts || (ts = {})); var ts; @@ -110890,11 +112011,11 @@ var ts; if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -110903,11 +112024,17 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ + name: type.value, + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: "0", + replacementSpan: ts.getReplacementSpanForContextToken(contextToken) + }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -111074,7 +112201,9 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }), + symbols: type.getApparentProperties().filter(function (prop) { + return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration); + }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -111506,6 +112635,22 @@ var ts; SortText["AutoImportSuggestions"] = "5"; SortText["JavascriptIdentifiers"] = "6"; })(SortText = Completions.SortText || (Completions.SortText = {})); + /** + * Special values for `CompletionInfo['source']` used to disambiguate + * completion items with the same `name`. (Each completion item must + * have a unique name/source combination, because those two fields + * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`. + * + * When the completion item is an auto-import suggestion, the source + * is the module specifier of the suggestion. To avoid collisions, + * the values here should not be a module specifier we would ever + * generate for an auto-import. + */ + var CompletionSource; + (function (CompletionSource) { + /** Completions that require `this.` insertion text */ + CompletionSource["ThisProperty"] = "ThisProperty/"; + })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType"; @@ -111653,14 +112798,16 @@ var ts; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); @@ -111697,7 +112844,8 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { + uniqueNames.add(realName); entries.push({ name: realName, kind: "warning" /* warning */, @@ -111715,9 +112863,9 @@ var ts; function createCompletionEntryForLiteral(literal, preferences) { return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var insertText; - var replacementSpan; + var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -111794,13 +112942,18 @@ var ts; !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; } function getSourceFromOrigin(origin) { - return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + if (originIsExport(origin)) { + return ts.stripQuotes(origin.moduleSymbol.name); + } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { + return CompletionSource.ThisProperty; + } } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); // Tracks unique names. - // We don't set this for global variables or completions from external module exports, because we can have multiple of those. - // Based on the order we add things we will always see locals first, then globals, then module exports. + // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; + // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { @@ -111811,21 +112964,26 @@ var ts; continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.has(name)) { + if (uniques.get(name)) { continue; } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 - uniques.set(name, true); - } + /** True for locals; false for globals, module exports from other files, `this.` completions. */ + var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + uniques.set(name, shouldShadowLaterSymbols); entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniques; + // Prevent consumers of this map from having to worry about + // the boolean value. Externally, it should be seen as the + // set of all names. + return { + has: function (name) { return uniques.has(name); }, + add: function (name) { return uniques.set(name, true); }, + }; } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -112454,6 +113612,7 @@ var ts; function tryGetGlobalSymbols() { var result = tryGetObjectLikeCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() + || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() @@ -112535,7 +113694,7 @@ var ts; // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); - if (thisType) { + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; @@ -112743,7 +113902,7 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -113012,8 +114171,6 @@ var ts; * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` @@ -113021,9 +114178,10 @@ var ts; ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; - // cursor is in an import clause - // try to show exported member for imported module + // try to show exported member for imported/re-exported module var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + if (!moduleSpecifier) + return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -113034,6 +114192,35 @@ var ts; symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); return 1 /* Success */; } + /** + * Adds local declarations for completions in named exports: + * + * export { | }; + * + * Does not check for the absence of a module specifier (`export {} from "./other"`) + * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that, + * preventing this function from running. + */ + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedExports) + : undefined; + if (!namedExports) { + return 0 /* Continue */; + } + var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration)); + completionKind = 5 /* None */; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) { + var _a, _b; + symbols.push(symbol); + if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) { + symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember; + } + }); + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. @@ -113384,7 +114571,7 @@ var ts; }); } } - // Set SortText to OptionalMember if it is an optinoal member + // Set SortText to OptionalMember if it is an optional member function setSortTextToOptionalMember() { symbols.forEach(function (m) { if (m.flags & 16777216 /* Optional */) { @@ -113440,7 +114627,8 @@ var ts; return baseSymbols.filter(function (propertySymbol) { return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && + !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration); }); } /** @@ -113667,10 +114855,16 @@ var ts; return cls; } break; - case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| } + case 75 /* Identifier */: { + // class c { public prop = c| } + if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return undefined; + } + // class c extends React.Component { a: () => 1\n compon| } if (isFromObjectTypeDeclaration(location)) { return ts.findAncestor(location, ts.isObjectTypeDeclaration); } + } } if (!contextToken) return undefined; @@ -113738,14 +114932,23 @@ var ts; } } } - function isNonGlobalDeclaration(declaration) { - var sourceFile = declaration.getSourceFile(); - // If the file is not a module, the declaration is global - if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { - return false; + /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ + function isProbablyGlobalType(type, sourceFile, checker) { + // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in + // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists. + var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { + return true; + } + var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { + return true; } - // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation - return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { + return true; + } + return false; } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -115074,7 +116277,29 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var referenceEntries; + var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 194 /* PropertyAccessExpression */ + || node.parent.kind === 191 /* BindingElement */ + || node.parent.kind === 195 /* ElementAccessExpression */ + || node.kind === 102 /* SuperKeyword */) { + referenceEntries = entries && __spreadArrays(entries); + } + else { + var queue = entries && __spreadArrays(entries); + var seenNodes = ts.createMap(); + while (queue && queue.length) { + var entry = queue.shift(); + if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { + continue; + } + referenceEntries = ts.append(referenceEntries, entry); + var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries_1) { + queue.push.apply(queue, entries_1); + } + } + } var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } @@ -118065,6 +119290,8 @@ var ts; // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 226 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression); case 209 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { @@ -119608,7 +120835,10 @@ var ts; case 246 /* InterfaceDeclaration */: case 248 /* EnumDeclaration */: case 251 /* CaseBlock */: + case 173 /* TypeLiteral */: return spanForNode(n); + case 175 /* TupleType */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); case 277 /* CaseClause */: case 278 /* DefaultClause */: return spanForNodeArray(n.statements); @@ -119626,6 +120856,8 @@ var ts; case 211 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); + case 190 /* ArrayBindingPattern */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -121414,7 +122646,7 @@ var ts; var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); })); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); @@ -121431,7 +122663,7 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; @@ -121734,7 +122966,18 @@ var ts; } ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) || + ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + function hasSupportedNumberOfArguments(node) { + if (node.arguments.length > 2) + return false; + if (node.arguments.length < 2) + return true; + return ts.some(node.arguments, function (arg) { + return arg.kind === 100 /* NullKeyword */ || + ts.isIdentifier(arg) && arg.text === "undefined"; + }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { @@ -121775,6 +123018,7 @@ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -122219,7 +123463,7 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122361,7 +123605,7 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122982,7 +124226,7 @@ var ts; rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), // Async-await rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // JSX opening elements @@ -125414,6 +126658,15 @@ var ts; * include all trivia between the node and the previous token */ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + /** + * Include attached JSDoc comments + */ + LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc"; + /** + * Only delete trivia on the same line as getStart(). + * Used to avoid deleting leading comments + */ + LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine"; })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); var TrailingTriviaOption; (function (TrailingTriviaOption) { @@ -125456,6 +126709,15 @@ var ts; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } + if (leadingTriviaOption === LeadingTriviaOption.StartLine) { + return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile); + } + if (leadingTriviaOption === LeadingTriviaOption.JSDoc) { + var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) { + return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile); + } + } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); if (fullStart === start) { @@ -125604,11 +126866,23 @@ var ts; this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween); + }; + ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween); + }; + ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); - this.insertNodeAt(sourceFile, pos, newNode, { + var options = { prefix: pos === 0 ? undefined : this.newLineCharacter, suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), - }); + }; + if (ts.isArray(insert)) { + this.insertNodesAt(sourceFile, pos, insert, options); + } + else { + this.insertNodeAt(sourceFile, pos, insert, options); + } }; ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) { var p0 = ts.firstOrUndefined(parameters); @@ -125671,6 +126945,7 @@ var ts; }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var _a; var endNode; if (ts.isFunctionLike(node)) { endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); @@ -125682,7 +126957,7 @@ var ts; } } else { - endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -126087,7 +127362,7 @@ var ts; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. @@ -126101,10 +127376,16 @@ var ts; for (var i = 0; i < normalized.length - 1; i++) { _loop_10(i); } - var textChanges = normalized.map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + var textChanges = ts.mapDefined(normalized, function (c) { + var span = ts.createTextSpanFromRange(c.range); + var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); + // Filter out redundant changes. + if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) { + return undefined; + } + return ts.createTextChange(span, newText); }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; + return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; @@ -126465,10 +127746,10 @@ var ts; break; } case 254 /* ImportDeclaration */: - var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration); - deleteNode(changes, sourceFile, node, - // For first import, leave header comment in place - isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); + case 253 /* ImportEqualsDeclaration */: + var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); + // For first import, leave header comment in place, otherwise only delete JSDoc comments + deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; case 191 /* BindingElement */: var pattern = node.parent; @@ -126504,6 +127785,10 @@ var ts; case 94 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; + case 245 /* ClassDeclaration */: + case 244 /* FunctionDeclaration */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + break; default: if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); @@ -126573,7 +127858,7 @@ var ts; deleteNode(changes, sourceFile, parent); break; case 225 /* VariableStatement */: - deleteNode(changes, sourceFile, gp); + deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: ts.Debug.assertNever(gp); @@ -127046,7 +128331,7 @@ var ts; reference; var diagnostic = ts.find(diagnostics, function (diagnostic) { return diagnostic.start === errorNode.getStart(sourceFile) && - diagnostic.start + diagnostic.length === errorNode.getEnd(); + (diagnostic.start + diagnostic.length) === errorNode.getEnd(); }); return diagnostic && ts.contains(errorCodes, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid @@ -127523,90 +128808,161 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node. + if (ts.hasJSDocNodes(ctorDeclaration)) { + ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol if (symbol.members) { - symbol.members.forEach(function (member) { + symbol.members.forEach(function (member, key) { + if (key === "constructor") { + // fn.prototype.constructor = fn + changes.delete(sourceFile, member.valueDeclaration.parent); + return; + } var memberElement = createClassElement(member, /*modifiers*/ undefined); if (memberElement) { - memberElements.push(memberElement); + memberElements.push.apply(memberElements, memberElement); } }); } // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); + if (member.name === "prototype") { + var firstDeclaration = member.declarations[0]; + // only one "x.prototype = { ... }" will pass + if (member.declarations.length === 1 && + ts.isPropertyAccessExpression(firstDeclaration) && + ts.isBinaryExpression(firstDeclaration.parent) && + firstDeclaration.parent.operatorToken.kind === 62 /* EqualsToken */ && + ts.isObjectLiteralExpression(firstDeclaration.parent.right)) { + var prototypes = firstDeclaration.parent.right; + var memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } + } + } + else { + var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } } }); } return memberElements; function shouldConvertDeclaration(_target, source) { - // Right now the only thing we can convert are function expressions - other values shouldn't get - // transformed. We can update this once ES public class properties are available. - return ts.isFunctionLike(source); + // Right now the only thing we can convert are function expressions, get/set accessors and methods + // other values like normal value fields ({a: 1}) shouldn't get transformed. + // We can update this once ES public class properties are available. + if (ts.isPropertyAccessExpression(_target)) { + if (isConstructorAssignment(_target)) + return true; + return ts.isFunctionLike(source); + } + else { + return ts.every(_target.properties, function (property) { + // a() {} + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) + return true; + // a: function() {} + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer) && !!property.name) + return true; + // x.prototype.constructor = fn + if (isConstructorAssignment(property)) + return true; + return false; + }); + } } function createClassElement(symbol, modifiers) { // Right now the only thing we can convert are function expressions, which are marked as methods - if (!(symbol.flags & 8192 /* Method */)) { - return; + // or { x: y } type prototype assignments, which are marked as ObjectLiteral + var members = []; + if (!(symbol.flags & 8192 /* Method */) && !(symbol.flags & 4096 /* ObjectLiteral */)) { + return members; } var memberDeclaration = symbol.valueDeclaration; var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var assignmentExpr = assignmentBinaryExpression.right; + if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { + return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 201 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - case 202 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 223 /* Block */) { - bodyBlock = arrowFunctionBody; - } - // case 2: () => [1,2,3] - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + if (!assignmentExpr) { + members.push(ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined)); + return members; + } + // f.x = expr + if (ts.isPropertyAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) { + return createFunctionLikeExpressionMember(members, assignmentExpr, memberDeclaration.name); + } + // f.prototype = { ... } + else if (ts.isObjectLiteralExpression(assignmentExpr)) { + return ts.flatMap(assignmentExpr.properties, function (property) { + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) { + // MethodDeclaration and AccessorDeclaration can appear in a class directly + return members.concat(property); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJS(sourceFile)) { - return; + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer)) { + return createFunctionLikeExpressionMember(members, property.initializer, property.name); } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); - return prop; + // Drop constructor assignments + if (isConstructorAssignment(property)) + return members; + return []; + }); + } + else { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) + return members; + if (!ts.isPropertyAccessExpression(memberDeclaration)) + return members; + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); + members.push(prop); + return members; + } + function createFunctionLikeExpressionMember(members, expression, name) { + if (ts.isFunctionExpression(expression)) + return createFunctionExpressionMember(members, expression, name); + else + return createArrowFunctionExpressionMember(members, expression, name); + } + function createFunctionExpressionMember(members, functionExpression, name) { + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); + } + function createArrowFunctionExpressionMember(members, arrowFunction, name) { + var arrowFunctionBody = arrowFunction.body; + var bodyBlock; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 223 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); } } } @@ -127643,6 +128999,13 @@ var ts; function getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } + function isConstructorAssignment(x) { + if (!x.name) + return false; + if (ts.isIdentifier(x.name) && x.name.text === "constructor") + return true; + return false; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -127753,10 +129116,6 @@ var ts; var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } - function isParameterOfPromiseCallback(node, checker) { - return ts.isParameter(node) && (isPromiseReturningCallExpression(node.parent.parent, checker, "then") || - isPromiseReturningCallExpression(node.parent.parent, checker, "catch")); - } function isPromiseTypedExpression(node, checker) { if (!ts.isExpression(node)) return false; @@ -127771,7 +129130,6 @@ var ts; It then checks for any collisions and renames them through getSynthesizedDeepClone */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) { - var variableNames = []; var identsToRenameMap = ts.createMap(); // key is the symbol id var collidingSymbolMap = ts.createMultiMap(); ts.forEachChild(nodeToRename, function visit(node) { @@ -127796,7 +129154,6 @@ var ts; var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - variableNames.push({ identifier: synthName.identifier, symbol: symbol }); collidingSymbolMap.add(ident.text, symbol); } // We only care about identifiers that are parameters, variable declarations, or binding elements @@ -127808,17 +129165,12 @@ var ts; var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - variableNames.push({ identifier: newName.identifier, symbol: symbol }); collidingSymbolMap.add(originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); - identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); - if (isParameterOfPromiseCallback(node.parent, checker) || ts.isVariableDeclaration(node.parent)) { - variableNames.push({ identifier: identifier, symbol: symbol }); - collidingSymbolMap.add(originalName, symbol); - } + collidingSymbolMap.add(originalName, symbol); } } } @@ -127898,7 +129250,7 @@ var ts; varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier); var typeArray = possibleNameForVarDecl.types; var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); } @@ -128872,7 +130224,6 @@ var ts; // Keys are import clause node IDs. var addToExisting = ts.createMap(); var newImports = ts.createMap(); - var lastModuleSpecifier; return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start); @@ -128922,7 +130273,6 @@ var ts; var entry = newImports.get(moduleSpecifier); if (!entry) { newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); - lastModuleSpecifier = moduleSpecifier; } else { // An import clause can only be type-only if every import fix contributing to it can be type-only. @@ -128962,11 +130312,15 @@ var ts; var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); + var newDeclarations; newImports.forEach(function (_a, moduleSpecifier) { var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); - var addDeclarations = useRequire ? addNewRequires : addNewImports; - addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + var getDeclarations = useRequire ? getNewRequires : getNewImports; + newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports)); }); + if (newDeclarations) { + ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); + } } } codefix.createImportAdder = createImportAdder; @@ -129363,11 +130717,11 @@ var ts; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; - var addDeclarations = useRequire ? addNewRequires : addNewImports; + var getDeclarations = useRequire ? getNewRequires : getNewImports; var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; - addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); + ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129435,11 +130789,12 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewImports(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { - ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly)); } var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { @@ -129451,12 +130806,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause( /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } - function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewRequires(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; // const { default: foo, bar, etc } = require('./mod'); if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; @@ -129464,13 +130821,14 @@ var ts; bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); } var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } // const foo = require('./mod'); if (imports.namespaceLikeImport) { var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { return ts.createVariableStatement( @@ -129843,6 +131201,192 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "returnValueCorrect"; + var fixIdAddReturnStatement = "fixAddReturnStatement"; + var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace"; + var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + var errorCodes = [ + ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + ]; + var ProblemKind; + (function (ProblemKind) { + ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement"; + ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses"; + })(ProblemKind || (ProblemKind = {})); + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen], + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; + var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) + return undefined; + if (info.kind === ProblemKind.MissingReturnStatement) { + return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined); + } + else { + return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; + } + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) + return undefined; + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixIdRemoveBlockBodyBrace: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); + break; + case fixIdWrapTheBlockWithParen: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1) + return undefined; + var firstStatement = ts.first(declaration.body.statements); + if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + } + else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return ts.isArrowFunction(declaration) ? { + declaration: declaration, + kind: ProblemKind.MissingParentheses, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } + } + else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) { + var firstBlockStatement = ts.first(firstStatement.statements); + if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; + } + } + } + return undefined; + } + function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) { + return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type); + } + function getInfo(checker, sourceFile, position, errorCode) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (!node.parent) + return undefined; + var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); + switch (errorCode) { + case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node)) + return undefined; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); + case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body) + return undefined; + var pos = declaration.parent.arguments.indexOf(declaration); + var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) + return undefined; + return getFixInfo(checker, declaration, type, /* isFunctionType */ true); + case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent)) + return undefined; + var initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body) + return undefined; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); + } + return undefined; + } + function getVariableLikeInitializer(declaration) { + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + return declaration.initializer; + case 273 /* JsxAttribute */: + return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); + case 282 /* ShorthandPropertyAssignment */: + case 158 /* PropertySignature */: + case 284 /* EnumMember */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + return undefined; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + ts.suppressLeadingAndTrailingTrivia(expression); + var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, ts.createReturn(expression), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : undefined + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression; + ts.suppressLeadingAndTrailingTrivia(commentSource); + ts.copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement); + } + function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -129867,7 +131411,7 @@ var ts; return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); @@ -129875,7 +131419,7 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { - var program = context.program, preferences = context.preferences; + var program = context.program; var checker = program.getTypeChecker(); var seen = ts.createMap(); var typeDeclToMembers = new ts.NodeMap(); @@ -129911,7 +131455,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call && !ts.isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); } else { if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { @@ -130051,11 +131595,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */); } @@ -130107,16 +131651,17 @@ var ts; // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { // Private methods are not implemented yet. if (ts.isPrivateIdentifier(token)) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) { + var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -130124,6 +131669,7 @@ var ts; else { changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } + importAdder.writeFixes(changeTracker); } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { /** @@ -130783,6 +132329,13 @@ var ts; } if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + if (ts.isParameter(token.parent)) { + ts.getJSDocParameterTags(token.parent).forEach(function (tag) { + if (ts.isIdentifier(tag.name)) { + changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text)); + } + }); + } } } function canPrefix(token) { @@ -131020,7 +132573,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); @@ -131680,7 +133233,7 @@ var ts; } switch (node.parent.kind) { case 226 /* ExpressionStatement */: - addCandidateType(usage, checker.getVoidType()); + inferTypeFromExpressionStatement(node, usage); break; case 208 /* PostfixUnaryExpression */: usage.isNumber = true; @@ -131736,6 +133289,9 @@ var ts; addCandidateType(usage, checker.getContextualType(node)); } } + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); + } function inferTypeFromPrefixUnaryExpression(node, usage) { switch (node.operator) { case 45 /* PlusPlusToken */: @@ -131989,6 +133545,7 @@ var ts; return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); } function inferTypes(usage) { + var _a, _b, _c; var types = []; if (usage.isNumber) { types.push(checker.getNumberType()); @@ -132002,10 +133559,7 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - if (usage.properties && usage.properties.size - || usage.calls && usage.calls.length - || usage.constructs && usage.constructs.length - || usage.stringIndex) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); @@ -132159,6 +133713,59 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixReturnTypeInAsyncFunction"; + var errorCodes = [ + ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + var checker = program.getTypeChecker(); + var info = getInfo(sourceFile, program.getTypeChecker(), span.start); + if (!info) { + return undefined; + } + var returnTypeNode = info.returnTypeNode, returnType = info.returnType, promisedTypeNode = info.promisedTypeNode, promisedType = info.promisedType; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, returnTypeNode, promisedTypeNode); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Replace_0_with_Promise_1, + checker.typeToString(returnType), checker.typeToString(promisedType)], fixId, ts.Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); + if (info) { + doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); + } + }); } + }); + function getInfo(sourceFile, checker, pos) { + if (ts.isInJSFile(sourceFile)) { + return undefined; + } + var token = ts.getTokenAtPosition(sourceFile, pos); + var func = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var returnTypeNode = func === null || func === void 0 ? void 0 : func.type; + if (!returnTypeNode) { + return undefined; + } + var returnType = checker.getTypeFromTypeNode(returnTypeNode); + var promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); + var promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined); + if (promisedTypeNode) { + return { returnTypeNode: returnTypeNode, returnType: returnType, promisedTypeNode: promisedTypeNode, promisedType: promisedType }; + } + } + function doChange(changes, sourceFile, returnTypeNode, promisedTypeNode) { + changes.replaceNode(sourceFile, returnTypeNode, ts.createTypeReferenceNode("Promise", [promisedTypeNode])); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -132175,12 +133782,13 @@ var ts; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options); var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -132392,14 +134000,14 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) { var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { - // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); + return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; @@ -132415,9 +134023,21 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && ts.isImportTypeNode(typeNode)) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { @@ -132571,6 +134191,7 @@ var ts; function importSymbols(importAdder, symbols) { symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); } + codefix.importSymbols = importSymbols; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -134053,6 +135674,8 @@ var ts; function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); + var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); @@ -134068,7 +135691,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -134127,6 +135750,7 @@ var ts; else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); var newNodes = []; // replace range with function call var called = getCalledExpression(scope, range, functionNameText); @@ -135215,6 +136839,7 @@ var ts; var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(accessorName); ts.suppressLeadingAndTrailingTrivia(declaration); ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); @@ -135460,7 +137085,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -136109,19 +137734,20 @@ var ts; } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); - body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); + ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); } - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { + t.replaceNode(file, func.body, body); + }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } - function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); - } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); @@ -136478,7 +138104,7 @@ var ts; ts.suppressLeadingAndTrailingTrivia(property.name); if (ts.isPropertyAssignment(property)) ts.suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); + ts.copyComments(arg, property); return property; }); if (hasRestParameter && functionArguments.length >= parameters.length) { @@ -136513,10 +138139,10 @@ var ts; /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); + ts.copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + ts.copyComments(thisParameter.type, newThisParameter.type); } return ts.createNodeArray([newThisParameter, objectParameter]); } @@ -136527,7 +138153,7 @@ var ts; /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); ts.suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + ts.copyComments(parameterDeclaration.initializer, element.initializer); } return element; } @@ -136545,9 +138171,9 @@ var ts; /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); + ts.copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); + ts.copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; } @@ -136563,26 +138189,6 @@ var ts; return checker.isOptionalParameter(parameterDeclaration); } } - function copyComments(sourceNode, targetNode) { - var sourceFile = sourceNode.getSourceFile(); - var text = sourceFile.text; - if (hasLeadingLineBreak(sourceNode, text)) { - ts.copyLeadingComments(sourceNode, targetNode, sourceFile); - } - else { - ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); - } - ts.copyTrailingComments(sourceNode, targetNode, sourceFile); - } - function hasLeadingLineBreak(node, text) { - var start = node.getFullStart(); - var end = node.getStart(); - for (var i = start; i < end; i++) { - if (text.charCodeAt(i) === 10 /* lineFeed */) - return true; - } - return false; - } function getParameterName(paramDeclaration) { return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name); } @@ -136751,7 +138357,6 @@ var ts; indexes.push(index); index++; } - text = ts.escapeString(text); return [index, text, indexes]; } function nodesToTemplate(_a, file) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 28197812a4ba3..39ea8a4089d9b 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.9"; + const versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -2040,23 +2040,23 @@ declare namespace ts { getNonNullableType(type: Type): Type; getTypeArguments(type: TypeReference): readonly Type[]; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; + typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): (SignatureDeclaration & { typeArguments?: NodeArray; }) | undefined; /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; + indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined; + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression | undefined; + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration | undefined; + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration | undefined; + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -2135,6 +2135,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowThisInObjectLiteral = 32768, AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, @@ -2163,6 +2164,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2171,7 +2173,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 277904747 + NodeBuilderFlagsMask = 814775659 } export enum SymbolFormatFlags { None = 0, @@ -3225,6 +3227,7 @@ declare namespace ts { NoInterveningComments = 262144, NoSpaceIfEmpty = 524288, SingleElement = 1048576, + SpaceAfterList = 2097152, Modifiers = 262656, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, @@ -3256,7 +3259,7 @@ declare namespace ts { CaseOrDefaultClauseStatements = 163969, HeritageClauseTypes = 528, SourceFileStatements = 131073, - Decorators = 49153, + Decorators = 2146305, TypeArguments = 53776, TypeParameters = 53776, Parameters = 2576, @@ -3860,7 +3863,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4457,7 +4460,8 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray | undefined): NodeArray | undefined; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4785,6 +4789,7 @@ declare namespace ts { /** Options to extend */ optionsToExtend?: CompilerOptions; watchOptionsToExtend?: WatchOptions; + extraFileExtensions?: readonly FileExtensionInfo[]; /** * Used to generate source file names from the config file and its include, exclude, files rules * and also to cache the directory stucture @@ -4812,7 +4817,7 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): WatchCompilerHostOfConfigFile; function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[], watchOptions?: WatchOptions): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options @@ -4955,6 +4960,7 @@ declare namespace ts.server { interface InitializationFailedResponse extends TypingInstallerResponse { readonly kind: EventInitializationFailed; readonly message: string; + readonly stack?: string; } interface ProjectResponse extends TypingInstallerResponse { readonly projectName: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 073bea0fb6f9a..f666b85f161dc 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -242,7 +242,7 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; /** @@ -1030,6 +1030,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1489,6 +1501,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -3699,6 +3715,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3737,6 +3754,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3748,7 +3766,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -4646,6 +4664,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4695,6 +4720,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4727,7 +4753,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -6522,6 +6548,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6801,6 +6828,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6833,7 +6861,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6933,6 +6961,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -7146,8 +7175,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7313,7 +7342,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7358,6 +7386,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -7374,6 +7406,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7508,6 +7542,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7643,6 +7683,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7860,6 +7901,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -8057,6 +8100,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8165,6 +8210,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8187,6 +8239,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8338,9 +8393,13 @@ var ts; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -9690,13 +9749,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9711,6 +9764,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9718,11 +9772,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -10051,7 +10107,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -11119,7 +11185,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -13301,7 +13367,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -13686,6 +13752,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13892,6 +13962,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -14750,7 +14839,7 @@ var ts; } /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. + * We treat the right hand side of assignments with container-like initializers as declarations. */ function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -14869,10 +14958,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14906,7 +14998,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -15035,6 +15127,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -16119,7 +16222,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -17012,14 +17115,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -17346,19 +17444,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -18791,6 +18890,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -25785,9 +25901,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -27497,7 +27655,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27599,9 +27758,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27781,19 +27940,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27802,8 +27952,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27837,6 +27986,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27845,8 +27995,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27985,7 +28136,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -28301,15 +28452,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -28319,8 +28467,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -28329,11 +28479,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -30767,16 +30919,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30867,7 +31010,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -31087,7 +31230,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -31108,7 +31251,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162 /* Constructor */) { + if (node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -32988,7 +33131,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -33090,7 +33233,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -33217,7 +33360,7 @@ var ts; } function bindSpecialPropertyAssignment(node) { // Class declarations in Typescript do not allow property declarations - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -33317,7 +33460,7 @@ var ts; : propertyAccess.parent.parent.kind === 290 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -33716,6 +33859,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33758,6 +33904,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -34192,8 +34346,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -34678,7 +34830,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34814,7 +34968,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["ExcessCheck"] = 4] = "ExcessCheck"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -35005,6 +35160,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -35166,9 +35322,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -35382,6 +35536,7 @@ var ts; /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -35661,12 +35816,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35724,24 +35875,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35762,6 +35921,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35800,6 +35960,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35839,7 +36009,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35875,6 +36045,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35891,7 +36062,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage if (declaration.kind === 191 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) @@ -35916,11 +36087,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35942,40 +36112,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -36037,6 +36209,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -36054,7 +36281,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -36082,9 +36309,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -36305,15 +36530,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -36413,17 +36644,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -36819,12 +37050,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36837,6 +37063,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36953,7 +37198,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36961,25 +37206,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -37228,9 +37496,9 @@ var ts; if (name.kind === 75 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -37258,7 +37526,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -37734,11 +38002,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37858,7 +38129,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37904,7 +38175,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -38093,7 +38364,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -38308,7 +38579,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -38347,7 +38618,7 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -38378,10 +38649,16 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38730,14 +39007,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38904,7 +39181,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38944,28 +39221,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } } } - return result; + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; + } + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38983,7 +39295,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38995,7 +39307,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -39015,7 +39327,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -39038,7 +39350,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); @@ -39047,7 +39359,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -39214,6 +39526,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -39352,8 +39670,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -39370,7 +39695,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -39491,7 +39816,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -39518,6 +39843,163 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -39612,7 +40094,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39624,7 +40106,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39732,7 +40214,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39767,7 +40249,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39868,7 +40350,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39887,13 +40369,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39938,7 +40426,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39975,13 +40463,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -40034,6 +40523,9 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -40043,16 +40535,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -40065,9 +40561,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -40199,7 +40693,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -40242,7 +40736,7 @@ var ts; } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -40266,7 +40760,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -40281,10 +40775,11 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); @@ -40298,13 +40793,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -40313,7 +40808,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -40350,116 +40845,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40891,8 +41276,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40981,9 +41366,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -41088,8 +41470,8 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - // Filter `undefined` from the type we check against if the parent has an initializer (which handles the `undefined` case implicitly) - else if (strictNullChecks && pattern.parent.initializer) { + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; @@ -41253,6 +41635,15 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. + // Use control flow analysis of this.xxx assignments the constructor to determine the type of the property. + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for @@ -41266,6 +41657,56 @@ var ts; // No type specified and nothing can be inferred return undefined; } + function isConstructorDeclaredProperty(symbol) { + // A propery is considered a constructor declared property when all declaration sites are this.xxx assignments, + // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of + // a class constructor. + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ && + (declaration.left.kind !== 195 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + // A property is auto-typed when its declaration has no type annotation or initializer and we're in + // noImplicitAny mode or a .js file. + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); + if (container && (container.kind === 162 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + // We don't infer a type if assignments are only null or undefined. + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); @@ -41277,52 +41718,60 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + // We use control flow analysis to determine the type of the property if the property qualifies as a constructor + // declared property and the resulting control flow type isn't just undefined or null. + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; // No types from any declarations :( + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - // use only the constructor types unless they were only assigned null | undefined (including widening variants) - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; // No types from any declarations :( + } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 - type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { @@ -41397,28 +41846,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -41428,6 +41904,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41445,20 +41926,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - /** check for definition in base class if any declaration is in a class */ - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -41803,7 +42270,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41820,9 +42287,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41988,6 +42455,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -42015,6 +42483,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -42205,16 +42676,19 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -42225,7 +42699,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -43084,7 +43558,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -43096,7 +43570,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -43160,9 +43634,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -43220,7 +43694,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -43243,19 +43717,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -43628,8 +44102,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43717,8 +44191,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43743,8 +44217,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43830,8 +44304,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43933,7 +44407,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43942,10 +44416,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43956,16 +44430,25 @@ var ts; if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43992,13 +44475,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -44010,7 +44495,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -44087,7 +44572,7 @@ var ts; else if (type.flags & 2097152 /* Intersection */) { if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); } return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; } @@ -44104,11 +44589,33 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. return !(prop.flags & 16777216 /* Optional */) && (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -44766,12 +45273,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44792,8 +45299,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -45310,6 +45817,8 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: + case 174 /* ArrayType */: + case 175 /* TupleType */: return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; @@ -45491,8 +46000,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -45521,8 +46030,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -45701,8 +46210,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -46057,6 +46566,9 @@ var ts; if (accessFlags & 4 /* CacheSymbol */) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? @@ -46409,7 +46921,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -46483,7 +46995,7 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -46841,7 +47353,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -47360,7 +47872,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -47394,37 +47906,23 @@ var ts; } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; - if (objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32 /* Mapped */) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4 /* Reference */) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728 /* UnionOrIntersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152 /* Intersection */) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -47536,7 +48034,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -47733,6 +48231,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -47756,7 +48263,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -48019,7 +48526,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -48397,13 +48904,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -48660,6 +49168,15 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source @@ -48671,6 +49188,14 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -48728,7 +49253,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & 4 /* ExcessCheck */); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -48736,12 +49261,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4 /* ExcessCheck */)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 4 /* ExcessCheck */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -48757,9 +49276,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); })) { - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } + result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -48791,44 +49308,71 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -48836,11 +49380,11 @@ var ts; return 0 /* False */; } if (flags & 3145728 /* UnionOrIntersection */) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -48868,7 +49412,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -48924,7 +49468,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -48994,8 +49538,16 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; @@ -49072,7 +49624,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -49154,26 +49706,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_4 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -49458,9 +50013,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -49527,12 +50082,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -49580,11 +50135,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -49592,7 +50147,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -49600,7 +50155,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -49614,7 +50169,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -49666,7 +50221,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_7 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -49676,7 +50231,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -49684,34 +50239,27 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -49746,7 +50294,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -49871,7 +50419,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -50119,18 +50667,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -50201,7 +50753,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -50233,7 +50785,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -50328,6 +50880,12 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return the inherited type of the given property or undefined if property doesn't exist in a base class. + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } // Return true if some underlying source property is declared in a class that derives // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { @@ -50516,8 +51074,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -50666,8 +51224,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -51038,7 +51596,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -51047,7 +51605,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -51061,7 +51619,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -51179,15 +51737,22 @@ var ts; return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); } var result = !!(type.flags & 63176704 /* Instantiable */ || - objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 /* SourceFile */ ? true : n.kind === 249 /* ModuleDeclaration */ ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -51220,12 +51785,16 @@ var ts; * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -51522,8 +52091,8 @@ var ts; else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -51631,8 +52200,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -52232,8 +52801,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -52301,6 +52870,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -52509,7 +53081,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -52601,8 +53173,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -52654,9 +53226,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, /*diagnostic*/ undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); } } if (diagnostic) { @@ -52955,7 +53529,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576 /* Union */) { @@ -53238,14 +53812,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; + if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -53269,7 +53844,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } return type; @@ -53308,12 +53883,6 @@ var ts; if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -53328,12 +53897,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -53407,7 +53982,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -53596,15 +54171,16 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { // Do not narrow when checking inequality. if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { return type; } - // In the case of `x.y`, a `x.constructor === T` type guard resets the narrowed type of `y` to its declared type. - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } // Get the type of the constructor identifier expression, if it is not a function then do not narrow. var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { @@ -53718,7 +54294,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -53758,7 +54334,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); }); } return type; @@ -54294,6 +54870,10 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + // TODO: Maybe issue a better error than 'object is possibly undefined' + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -54686,7 +55266,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -54725,7 +55305,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -55379,8 +55959,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -55971,7 +56551,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304 /* Nullable */)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 1 /* Any */) && right.flags & 16777216 /* Optional */)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -56152,14 +56733,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -56169,7 +56750,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -56250,8 +56835,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -56335,11 +56921,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -56550,6 +57131,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -56623,7 +57207,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -56637,6 +57221,9 @@ var ts; prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -56769,7 +57356,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -57671,8 +58258,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -57888,7 +58475,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -57906,15 +58493,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -58040,7 +58627,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -58048,7 +58635,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -58383,8 +58970,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -58438,9 +59025,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -59058,7 +59645,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -59241,18 +59828,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -59470,7 +60055,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -59579,13 +60164,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -59610,7 +60188,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59746,11 +60324,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -59893,8 +60480,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59960,7 +60547,8 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || + isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -60345,6 +60933,12 @@ var ts; case 49 /* GreaterThanGreaterThanGreaterThanToken */: case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: reportOperatorError(); + break; + case 42 /* AsteriskAsteriskToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -60479,8 +61073,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -61248,7 +61842,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -61650,8 +62244,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -62111,7 +62706,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -62224,10 +62819,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_8 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -62466,7 +63061,7 @@ var ts; if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -62601,8 +63196,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -62991,7 +63586,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -63018,6 +63613,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -63031,8 +63636,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -63548,8 +64152,30 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -63704,11 +64330,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -64324,10 +64947,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -64335,6 +64959,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -64360,7 +64985,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -64541,6 +65166,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -64828,7 +65456,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -64847,7 +65475,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -65006,6 +65634,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -65014,11 +65661,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -65136,7 +65783,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -65187,7 +65834,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -65270,6 +65923,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -65543,7 +66199,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -65667,15 +66323,10 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -65689,6 +66340,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } @@ -67416,8 +68070,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -68031,9 +68711,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -68092,6 +68772,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -69099,13 +69780,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -70417,9 +71098,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -70541,9 +71224,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -71014,6 +71699,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -72559,11 +73264,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -72926,7 +73634,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -72937,7 +73645,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -72949,15 +73657,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -73180,11 +73888,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -74222,18 +74931,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -74988,13 +75749,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -76128,9 +76969,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -76235,9 +77073,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -77088,6 +77923,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -77979,6 +78818,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -77988,8 +78838,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -78472,6 +79322,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -78794,24 +79652,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -78841,7 +79700,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -79794,7 +80653,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -79860,8 +80719,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79881,8 +80740,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -80792,6 +81651,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -80805,7 +81688,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ @@ -80815,6 +81698,27 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -80841,11 +81745,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -80876,26 +81780,30 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: @@ -80916,7 +81824,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -80952,7 +81860,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -81027,13 +81935,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -81114,15 +82026,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -81170,7 +82082,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -81184,9 +82096,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -81316,7 +82232,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -81530,7 +82446,7 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -81661,6 +82577,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -81696,6 +82613,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -81708,6 +82626,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -81743,6 +82662,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -83669,6 +84589,8 @@ var ts; // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -89657,7 +90579,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -91781,7 +92703,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -91872,6 +92795,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -92299,6 +93230,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -93135,8 +94072,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -93154,8 +94095,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -93285,6 +94229,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -93292,6 +94239,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -93299,6 +94247,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -93313,9 +94275,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -93340,7 +94306,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -93355,17 +94323,37 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -93999,6 +94987,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -95494,16 +96483,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -96299,12 +97282,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -96641,8 +97627,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -96869,7 +97855,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -97073,7 +98059,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -97212,7 +98198,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -97257,7 +98243,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -97293,6 +98279,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -98888,11 +99887,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -99407,13 +100406,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -100033,7 +101032,7 @@ var ts; return line; } // Stop searching if the line is not empty and not a comment - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -103910,9 +104909,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -103928,9 +104927,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -103954,7 +104953,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -103980,7 +104979,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -104554,20 +105553,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -104623,12 +105625,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -104644,7 +105664,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -104993,7 +106013,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -107334,7 +108354,11 @@ var ts; if (node.kind === 290 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) { + else if (node.parent.kind === 259 /* ExportAssignment */ + || node.parent.kind === 265 /* ExternalModuleReference */ + || node.parent.kind === 258 /* ImportSpecifier */ + || node.parent.kind === 255 /* ImportClause */ + || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -108753,10 +109777,28 @@ var ts; var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } + function getReplacementSpanForContextToken(contextToken) { + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return createTextSpanFromStringLiteralLikeContent(contextToken); + default: + return createTextSpanFromNode(contextToken); + } + } + ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken; function createTextSpanFromNode(node, sourceFile, endNode) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromStringLiteralLikeContent(node) { + if (node.isUnterminated) + return undefined; + return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); + } + ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent; function createTextRangeFromNode(node, sourceFile) { return ts.createRange(node.getStart(sourceFile), node.end); } @@ -108994,17 +110036,26 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var importKindPredicate = importDecl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + function insertImports(changes, sourceFile, imports, blankLineBetween) { + var decl = ts.isArray(imports) ? imports[0] : imports; + var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { - changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + if (ts.isArray(imports)) { + changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports); + } + else { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports); + } + } + else if (ts.isArray(imports)) { + changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween); } else { - changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween); + changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween); } } - ts.insertImport = insertImport; + ts.insertImports = insertImports; function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); @@ -109409,6 +110460,27 @@ var ts; addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } ts.suppressTrailingTrivia = suppressTrailingTrivia; + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + } + ts.copyComments = copyComments; + function hasLeadingLineBreak(node, text) { + var start = node.getFullStart(); + var end = node.getStart(); + for (var i = start; i < end; i++) { + if (text.charCodeAt(i) === 10 /* lineFeed */) + return true; + } + return false; + } function addEmitFlagsRecursively(node, flag, getChild) { ts.addEmitFlags(node, flag); var child = getChild(node); @@ -109502,6 +110574,11 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + /* @internal */ + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { @@ -109910,10 +110987,54 @@ var ts; return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + /** + * Useful to check whether a string contains another string at a specific index + * without allocating another string or traversing the entire contents of the outer string. + * + * This function is useful in place of either of the following: + * + * ```ts + * // Allocates + * haystack.substr(startIndex, needle.length) === needle + * + * // Full traversal + * haystack.indexOf(needle, startIndex) === startIndex + * ``` + * + * @param haystack The string that potentially contains `needle`. + * @param needle The string whose content might sit within `haystack`. + * @param startIndex The index within `haystack` to start searching for `needle`. + */ + function stringContainsAt(haystack, needle, startIndex) { + var needleLength = needle.length; + if (needleLength + startIndex > haystack.length) { + return false; + } + for (var i = 0; i < needleLength; i++) { + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) + return false; + } + return true; + } + ts.stringContainsAt = stringContainsAt; function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } ts.startsWithUnderscore = startsWithUnderscore; + function isGlobalDeclaration(declaration) { + return !isNonGlobalDeclaration(declaration); + } + ts.isGlobalDeclaration = isGlobalDeclaration; + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } + ts.isNonGlobalDeclaration = isNonGlobalDeclaration; // #endregion })(ts || (ts = {})); var ts; @@ -110890,11 +112011,11 @@ var ts; if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -110903,11 +112024,17 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ + name: type.value, + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: "0", + replacementSpan: ts.getReplacementSpanForContextToken(contextToken) + }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -111074,7 +112201,9 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }), + symbols: type.getApparentProperties().filter(function (prop) { + return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration); + }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -111506,6 +112635,22 @@ var ts; SortText["AutoImportSuggestions"] = "5"; SortText["JavascriptIdentifiers"] = "6"; })(SortText = Completions.SortText || (Completions.SortText = {})); + /** + * Special values for `CompletionInfo['source']` used to disambiguate + * completion items with the same `name`. (Each completion item must + * have a unique name/source combination, because those two fields + * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`. + * + * When the completion item is an auto-import suggestion, the source + * is the module specifier of the suggestion. To avoid collisions, + * the values here should not be a module specifier we would ever + * generate for an auto-import. + */ + var CompletionSource; + (function (CompletionSource) { + /** Completions that require `this.` insertion text */ + CompletionSource["ThisProperty"] = "ThisProperty/"; + })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType"; @@ -111653,14 +112798,16 @@ var ts; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); @@ -111697,7 +112844,8 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { + uniqueNames.add(realName); entries.push({ name: realName, kind: "warning" /* warning */, @@ -111715,9 +112863,9 @@ var ts; function createCompletionEntryForLiteral(literal, preferences) { return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var insertText; - var replacementSpan; + var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -111794,13 +112942,18 @@ var ts; !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; } function getSourceFromOrigin(origin) { - return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + if (originIsExport(origin)) { + return ts.stripQuotes(origin.moduleSymbol.name); + } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { + return CompletionSource.ThisProperty; + } } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); // Tracks unique names. - // We don't set this for global variables or completions from external module exports, because we can have multiple of those. - // Based on the order we add things we will always see locals first, then globals, then module exports. + // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; + // true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { @@ -111811,21 +112964,26 @@ var ts; continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.has(name)) { + if (uniques.get(name)) { continue; } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 - uniques.set(name, true); - } + /** True for locals; false for globals, module exports from other files, `this.` completions. */ + var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + uniques.set(name, shouldShadowLaterSymbols); entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniques; + // Prevent consumers of this map from having to worry about + // the boolean value. Externally, it should be seen as the + // set of all names. + return { + has: function (name) { return uniques.has(name); }, + add: function (name) { return uniques.set(name, true); }, + }; } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -112454,6 +113612,7 @@ var ts; function tryGetGlobalSymbols() { var result = tryGetObjectLikeCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() + || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() @@ -112535,7 +113694,7 @@ var ts; // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); - if (thisType) { + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; @@ -112743,7 +113902,7 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, isNonGlobalDeclaration)) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -113012,8 +114171,6 @@ var ts; * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` @@ -113021,9 +114178,10 @@ var ts; ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; - // cursor is in an import clause - // try to show exported member for imported module + // try to show exported member for imported/re-exported module var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + if (!moduleSpecifier) + return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -113034,6 +114192,35 @@ var ts; symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); return 1 /* Success */; } + /** + * Adds local declarations for completions in named exports: + * + * export { | }; + * + * Does not check for the absence of a module specifier (`export {} from "./other"`) + * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that, + * preventing this function from running. + */ + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedExports) + : undefined; + if (!namedExports) { + return 0 /* Continue */; + } + var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration)); + completionKind = 5 /* None */; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) { + var _a, _b; + symbols.push(symbol); + if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) { + symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember; + } + }); + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. @@ -113384,7 +114571,7 @@ var ts; }); } } - // Set SortText to OptionalMember if it is an optinoal member + // Set SortText to OptionalMember if it is an optional member function setSortTextToOptionalMember() { symbols.forEach(function (m) { if (m.flags & 16777216 /* Optional */) { @@ -113440,7 +114627,8 @@ var ts; return baseSymbols.filter(function (propertySymbol) { return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && + !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration); }); } /** @@ -113667,10 +114855,16 @@ var ts; return cls; } break; - case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| } + case 75 /* Identifier */: { + // class c { public prop = c| } + if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return undefined; + } + // class c extends React.Component { a: () => 1\n compon| } if (isFromObjectTypeDeclaration(location)) { return ts.findAncestor(location, ts.isObjectTypeDeclaration); } + } } if (!contextToken) return undefined; @@ -113738,14 +114932,23 @@ var ts; } } } - function isNonGlobalDeclaration(declaration) { - var sourceFile = declaration.getSourceFile(); - // If the file is not a module, the declaration is global - if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { - return false; + /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ + function isProbablyGlobalType(type, sourceFile, checker) { + // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in + // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists. + var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { + return true; + } + var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { + return true; } - // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation - return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { + return true; + } + return false; } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -115074,7 +116277,29 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var referenceEntries; + var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 194 /* PropertyAccessExpression */ + || node.parent.kind === 191 /* BindingElement */ + || node.parent.kind === 195 /* ElementAccessExpression */ + || node.kind === 102 /* SuperKeyword */) { + referenceEntries = entries && __spreadArrays(entries); + } + else { + var queue = entries && __spreadArrays(entries); + var seenNodes = ts.createMap(); + while (queue && queue.length) { + var entry = queue.shift(); + if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { + continue; + } + referenceEntries = ts.append(referenceEntries, entry); + var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries_1) { + queue.push.apply(queue, entries_1); + } + } + } var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } @@ -118065,6 +119290,8 @@ var ts; // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 226 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression); case 209 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { @@ -119608,7 +120835,10 @@ var ts; case 246 /* InterfaceDeclaration */: case 248 /* EnumDeclaration */: case 251 /* CaseBlock */: + case 173 /* TypeLiteral */: return spanForNode(n); + case 175 /* TupleType */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isTupleTypeNode(n.parent), 22 /* OpenBracketToken */); case 277 /* CaseClause */: case 278 /* DefaultClause */: return spanForNodeArray(n.statements); @@ -119626,6 +120856,8 @@ var ts; case 211 /* TemplateExpression */: case 14 /* NoSubstitutionTemplateLiteral */: return spanForTemplateLiteral(n); + case 190 /* ArrayBindingPattern */: + return spanForNode(n, /*autoCollapse*/ false, /*useFullStart*/ !ts.isBindingElement(n.parent), 22 /* OpenBracketToken */); } function spanForJSXElement(node) { var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); @@ -121414,7 +122646,7 @@ var ts; var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); })); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); @@ -121431,7 +122663,7 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; @@ -121734,7 +122966,18 @@ var ts; } ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) || + ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + function hasSupportedNumberOfArguments(node) { + if (node.arguments.length > 2) + return false; + if (node.arguments.length < 2) + return true; + return ts.some(node.arguments, function (arg) { + return arg.kind === 100 /* NullKeyword */ || + ts.isIdentifier(arg) && arg.text === "undefined"; + }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { @@ -121775,6 +123018,7 @@ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -122219,7 +123463,7 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122361,7 +123605,7 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -122982,7 +124226,7 @@ var ts; rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), // Async-await rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // JSX opening elements @@ -125414,6 +126658,15 @@ var ts; * include all trivia between the node and the previous token */ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + /** + * Include attached JSDoc comments + */ + LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc"; + /** + * Only delete trivia on the same line as getStart(). + * Used to avoid deleting leading comments + */ + LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine"; })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); var TrailingTriviaOption; (function (TrailingTriviaOption) { @@ -125456,6 +126709,15 @@ var ts; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } + if (leadingTriviaOption === LeadingTriviaOption.StartLine) { + return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile); + } + if (leadingTriviaOption === LeadingTriviaOption.JSDoc) { + var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) { + return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile); + } + } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); if (fullStart === start) { @@ -125604,11 +126866,23 @@ var ts; this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween); + }; + ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween); + }; + ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); - this.insertNodeAt(sourceFile, pos, newNode, { + var options = { prefix: pos === 0 ? undefined : this.newLineCharacter, suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), - }); + }; + if (ts.isArray(insert)) { + this.insertNodesAt(sourceFile, pos, insert, options); + } + else { + this.insertNodeAt(sourceFile, pos, insert, options); + } }; ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) { var p0 = ts.firstOrUndefined(parameters); @@ -125671,6 +126945,7 @@ var ts; }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var _a; var endNode; if (ts.isFunctionLike(node)) { endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); @@ -125682,7 +126957,7 @@ var ts; } } else { - endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -126087,7 +127362,7 @@ var ts; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. @@ -126101,10 +127376,16 @@ var ts; for (var i = 0; i < normalized.length - 1; i++) { _loop_10(i); } - var textChanges = normalized.map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + var textChanges = ts.mapDefined(normalized, function (c) { + var span = ts.createTextSpanFromRange(c.range); + var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); + // Filter out redundant changes. + if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) { + return undefined; + } + return ts.createTextChange(span, newText); }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; + return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; @@ -126465,10 +127746,10 @@ var ts; break; } case 254 /* ImportDeclaration */: - var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration); - deleteNode(changes, sourceFile, node, - // For first import, leave header comment in place - isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); + case 253 /* ImportEqualsDeclaration */: + var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); + // For first import, leave header comment in place, otherwise only delete JSDoc comments + deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; case 191 /* BindingElement */: var pattern = node.parent; @@ -126504,6 +127785,10 @@ var ts; case 94 /* FunctionKeyword */: deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); break; + case 245 /* ClassDeclaration */: + case 244 /* FunctionDeclaration */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + break; default: if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); @@ -126573,7 +127858,7 @@ var ts; deleteNode(changes, sourceFile, parent); break; case 225 /* VariableStatement */: - deleteNode(changes, sourceFile, gp); + deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: ts.Debug.assertNever(gp); @@ -127046,7 +128331,7 @@ var ts; reference; var diagnostic = ts.find(diagnostics, function (diagnostic) { return diagnostic.start === errorNode.getStart(sourceFile) && - diagnostic.start + diagnostic.length === errorNode.getEnd(); + (diagnostic.start + diagnostic.length) === errorNode.getEnd(); }); return diagnostic && ts.contains(errorCodes, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid @@ -127523,90 +128808,161 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node. + if (ts.hasJSDocNodes(ctorDeclaration)) { + ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol if (symbol.members) { - symbol.members.forEach(function (member) { + symbol.members.forEach(function (member, key) { + if (key === "constructor") { + // fn.prototype.constructor = fn + changes.delete(sourceFile, member.valueDeclaration.parent); + return; + } var memberElement = createClassElement(member, /*modifiers*/ undefined); if (memberElement) { - memberElements.push(memberElement); + memberElements.push.apply(memberElements, memberElement); } }); } // all static members are stored in the "exports" array of symbol if (symbol.exports) { symbol.exports.forEach(function (member) { - var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); - if (memberElement) { - memberElements.push(memberElement); + if (member.name === "prototype") { + var firstDeclaration = member.declarations[0]; + // only one "x.prototype = { ... }" will pass + if (member.declarations.length === 1 && + ts.isPropertyAccessExpression(firstDeclaration) && + ts.isBinaryExpression(firstDeclaration.parent) && + firstDeclaration.parent.operatorToken.kind === 62 /* EqualsToken */ && + ts.isObjectLiteralExpression(firstDeclaration.parent.right)) { + var prototypes = firstDeclaration.parent.right; + var memberElement = createClassElement(prototypes.symbol, /** modifiers */ undefined); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } + } + } + else { + var memberElement = createClassElement(member, [ts.createToken(120 /* StaticKeyword */)]); + if (memberElement) { + memberElements.push.apply(memberElements, memberElement); + } } }); } return memberElements; function shouldConvertDeclaration(_target, source) { - // Right now the only thing we can convert are function expressions - other values shouldn't get - // transformed. We can update this once ES public class properties are available. - return ts.isFunctionLike(source); + // Right now the only thing we can convert are function expressions, get/set accessors and methods + // other values like normal value fields ({a: 1}) shouldn't get transformed. + // We can update this once ES public class properties are available. + if (ts.isPropertyAccessExpression(_target)) { + if (isConstructorAssignment(_target)) + return true; + return ts.isFunctionLike(source); + } + else { + return ts.every(_target.properties, function (property) { + // a() {} + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) + return true; + // a: function() {} + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer) && !!property.name) + return true; + // x.prototype.constructor = fn + if (isConstructorAssignment(property)) + return true; + return false; + }); + } } function createClassElement(symbol, modifiers) { // Right now the only thing we can convert are function expressions, which are marked as methods - if (!(symbol.flags & 8192 /* Method */)) { - return; + // or { x: y } type prototype assignments, which are marked as ObjectLiteral + var members = []; + if (!(symbol.flags & 8192 /* Method */) && !(symbol.flags & 4096 /* ObjectLiteral */)) { + return members; } var memberDeclaration = symbol.valueDeclaration; var assignmentBinaryExpression = memberDeclaration.parent; - if (!shouldConvertDeclaration(memberDeclaration, assignmentBinaryExpression.right)) { - return; + var assignmentExpr = assignmentBinaryExpression.right; + if (!shouldConvertDeclaration(memberDeclaration, assignmentExpr)) { + return members; } // delete the entire statement if this expression is the sole expression to take care of the semicolon at the end var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 226 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; changes.delete(sourceFile, nodeToDelete); - if (!assignmentBinaryExpression.right) { - return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, - /*type*/ undefined, /*initializer*/ undefined); - } - switch (assignmentBinaryExpression.right.kind) { - case 201 /* FunctionExpression */: { - var functionExpression = assignmentBinaryExpression.right; - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - case 202 /* ArrowFunction */: { - var arrowFunction = assignmentBinaryExpression.right; - var arrowFunctionBody = arrowFunction.body; - var bodyBlock = void 0; - // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 223 /* Block */) { - bodyBlock = arrowFunctionBody; - } - // case 2: () => [1,2,3] - else { - bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); + if (!assignmentExpr) { + members.push(ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, + /*type*/ undefined, /*initializer*/ undefined)); + return members; + } + // f.x = expr + if (ts.isPropertyAccessExpression(memberDeclaration) && (ts.isFunctionExpression(assignmentExpr) || ts.isArrowFunction(assignmentExpr))) { + return createFunctionLikeExpressionMember(members, assignmentExpr, memberDeclaration.name); + } + // f.prototype = { ... } + else if (ts.isObjectLiteralExpression(assignmentExpr)) { + return ts.flatMap(assignmentExpr.properties, function (property) { + if (ts.isMethodDeclaration(property) || ts.isGetOrSetAccessorDeclaration(property)) { + // MethodDeclaration and AccessorDeclaration can appear in a class directly + return members.concat(property); } - var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); - var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, - /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); - return method; - } - default: { - // Don't try to declare members in JavaScript files - if (ts.isSourceFileJS(sourceFile)) { - return; + if (ts.isPropertyAssignment(property) && ts.isFunctionExpression(property.initializer)) { + return createFunctionLikeExpressionMember(members, property.initializer, property.name); } - var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, - /*type*/ undefined, assignmentBinaryExpression.right); - ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); - return prop; + // Drop constructor assignments + if (isConstructorAssignment(property)) + return members; + return []; + }); + } + else { + // Don't try to declare members in JavaScript files + if (ts.isSourceFileJS(sourceFile)) + return members; + if (!ts.isPropertyAccessExpression(memberDeclaration)) + return members; + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentExpr); + ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); + members.push(prop); + return members; + } + function createFunctionLikeExpressionMember(members, expression, name) { + if (ts.isFunctionExpression(expression)) + return createFunctionExpressionMember(members, expression, name); + else + return createArrowFunctionExpressionMember(members, expression, name); + } + function createFunctionExpressionMember(members, functionExpression, name) { + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); + } + function createArrowFunctionExpressionMember(members, arrowFunction, name) { + var arrowFunctionBody = arrowFunction.body; + var bodyBlock; + // case 1: () => { return [1,2,3] } + if (arrowFunctionBody.kind === 223 /* Block */) { + bodyBlock = arrowFunctionBody; + } + // case 2: () => [1,2,3] + else { + bodyBlock = ts.createBlock([ts.createReturn(arrowFunctionBody)]); } + var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 126 /* AsyncKeyword */)); + var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, name, /*questionToken*/ undefined, + /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); + return members.concat(method); } } } @@ -127643,6 +128999,13 @@ var ts; function getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } + function isConstructorAssignment(x) { + if (!x.name) + return false; + if (ts.isIdentifier(x.name) && x.name.text === "constructor") + return true; + return false; + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -127753,10 +129116,6 @@ var ts; var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } - function isParameterOfPromiseCallback(node, checker) { - return ts.isParameter(node) && (isPromiseReturningCallExpression(node.parent.parent, checker, "then") || - isPromiseReturningCallExpression(node.parent.parent, checker, "catch")); - } function isPromiseTypedExpression(node, checker) { if (!ts.isExpression(node)) return false; @@ -127771,7 +129130,6 @@ var ts; It then checks for any collisions and renames them through getSynthesizedDeepClone */ function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) { - var variableNames = []; var identsToRenameMap = ts.createMap(); // key is the symbol id var collidingSymbolMap = ts.createMultiMap(); ts.forEachChild(nodeToRename, function visit(node) { @@ -127796,7 +129154,6 @@ var ts; var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - variableNames.push({ identifier: synthName.identifier, symbol: symbol }); collidingSymbolMap.add(ident.text, symbol); } // We only care about identifiers that are parameters, variable declarations, or binding elements @@ -127808,17 +129165,12 @@ var ts; var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - variableNames.push({ identifier: newName.identifier, symbol: symbol }); collidingSymbolMap.add(originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); - identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); - if (isParameterOfPromiseCallback(node.parent, checker) || ts.isVariableDeclaration(node.parent)) { - variableNames.push({ identifier: identifier, symbol: symbol }); - collidingSymbolMap.add(originalName, symbol); - } + collidingSymbolMap.add(originalName, symbol); } } } @@ -127898,7 +129250,7 @@ var ts; varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier); var typeArray = possibleNameForVarDecl.types; var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); } @@ -128872,7 +130224,6 @@ var ts; // Keys are import clause node IDs. var addToExisting = ts.createMap(); var newImports = ts.createMap(); - var lastModuleSpecifier; return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; function addImportFromDiagnostic(diagnostic, context) { var info = getFixesInfo(context, diagnostic.code, diagnostic.start); @@ -128922,7 +130273,6 @@ var ts; var entry = newImports.get(moduleSpecifier); if (!entry) { newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); - lastModuleSpecifier = moduleSpecifier; } else { // An import clause can only be type-only if every import fix contributing to it can be type-only. @@ -128962,11 +130312,15 @@ var ts; var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); }); + var newDeclarations; newImports.forEach(function (_a, moduleSpecifier) { var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); - var addDeclarations = useRequire ? addNewRequires : addNewImports; - addDeclarations(changeTracker, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); + var getDeclarations = useRequire ? getNewRequires : getNewImports; + newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports)); }); + if (newDeclarations) { + ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); + } } } codefix.createImportAdder = createImportAdder; @@ -129363,11 +130717,11 @@ var ts; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; - var addDeclarations = useRequire ? addNewRequires : addNewImports; + var getDeclarations = useRequire ? getNewRequires : getNewImports; var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; - addDeclarations(changes, sourceFile, moduleSpecifier, quotePreference, importsCollection, /*blankLineBetween*/ true); + ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -129435,11 +130789,12 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewImports(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { - ts.insertImport(changes, sourceFile, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly), /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly)); } var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { @@ -129451,12 +130806,14 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause( /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, /*blankLineBetween*/ blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } - function addNewRequires(changes, sourceFile, moduleSpecifier, quotePreference, imports, blankLineBetween) { + function getNewRequires(moduleSpecifier, quotePreference, imports) { var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; // const { default: foo, bar, etc } = require('./mod'); if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; @@ -129464,13 +130821,14 @@ var ts; bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); } var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } // const foo = require('./mod'); if (imports.namespaceLikeImport) { var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); - ts.insertImport(changes, sourceFile, declaration, blankLineBetween); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { return ts.createVariableStatement( @@ -129843,6 +131201,192 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "returnValueCorrect"; + var fixIdAddReturnStatement = "fixAddReturnStatement"; + var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace"; + var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + var errorCodes = [ + ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + ]; + var ProblemKind; + (function (ProblemKind) { + ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement"; + ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses"; + })(ProblemKind || (ProblemKind = {})); + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen], + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; + var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) + return undefined; + if (info.kind === ProblemKind.MissingReturnStatement) { + return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined); + } + else { + return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; + } + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) + return undefined; + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixIdRemoveBlockBodyBrace: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); + break; + case fixIdWrapTheBlockWithParen: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1) + return undefined; + var firstStatement = ts.first(declaration.body.statements); + if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + } + else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return ts.isArrowFunction(declaration) ? { + declaration: declaration, + kind: ProblemKind.MissingParentheses, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } + } + else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) { + var firstBlockStatement = ts.first(firstStatement.statements); + if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; + } + } + } + return undefined; + } + function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) { + return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type); + } + function getInfo(checker, sourceFile, position, errorCode) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (!node.parent) + return undefined; + var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); + switch (errorCode) { + case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node)) + return undefined; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); + case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body) + return undefined; + var pos = declaration.parent.arguments.indexOf(declaration); + var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) + return undefined; + return getFixInfo(checker, declaration, type, /* isFunctionType */ true); + case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent)) + return undefined; + var initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body) + return undefined; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); + } + return undefined; + } + function getVariableLikeInitializer(declaration) { + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + return declaration.initializer; + case 273 /* JsxAttribute */: + return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); + case 282 /* ShorthandPropertyAssignment */: + case 158 /* PropertySignature */: + case 284 /* EnumMember */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + return undefined; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + ts.suppressLeadingAndTrailingTrivia(expression); + var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, ts.createReturn(expression), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : undefined + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression; + ts.suppressLeadingAndTrailingTrivia(commentSource); + ts.copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement); + } + function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -129867,7 +131411,7 @@ var ts; return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); @@ -129875,7 +131419,7 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { - var program = context.program, preferences = context.preferences; + var program = context.program; var checker = program.getTypeChecker(); var seen = ts.createMap(); var typeDeclToMembers = new ts.NodeMap(); @@ -129911,7 +131455,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call && !ts.isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); } else { if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { @@ -130051,11 +131595,11 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */); } @@ -130107,16 +131651,17 @@ var ts; // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { // Private methods are not implemented yet. if (ts.isPrivateIdentifier(token)) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) { + var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -130124,6 +131669,7 @@ var ts; else { changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } + importAdder.writeFixes(changeTracker); } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { /** @@ -130783,6 +132329,13 @@ var ts; } if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + if (ts.isParameter(token.parent)) { + ts.getJSDocParameterTags(token.parent).forEach(function (tag) { + if (ts.isIdentifier(tag.name)) { + changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text)); + } + }); + } } } function canPrefix(token) { @@ -131020,7 +132573,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); @@ -131680,7 +133233,7 @@ var ts; } switch (node.parent.kind) { case 226 /* ExpressionStatement */: - addCandidateType(usage, checker.getVoidType()); + inferTypeFromExpressionStatement(node, usage); break; case 208 /* PostfixUnaryExpression */: usage.isNumber = true; @@ -131736,6 +133289,9 @@ var ts; addCandidateType(usage, checker.getContextualType(node)); } } + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); + } function inferTypeFromPrefixUnaryExpression(node, usage) { switch (node.operator) { case 45 /* PlusPlusToken */: @@ -131989,6 +133545,7 @@ var ts; return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); } function inferTypes(usage) { + var _a, _b, _c; var types = []; if (usage.isNumber) { types.push(checker.getNumberType()); @@ -132002,10 +133559,7 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - if (usage.properties && usage.properties.size - || usage.calls && usage.calls.length - || usage.constructs && usage.constructs.length - || usage.stringIndex) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); @@ -132159,6 +133713,59 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixReturnTypeInAsyncFunction"; + var errorCodes = [ + ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + var checker = program.getTypeChecker(); + var info = getInfo(sourceFile, program.getTypeChecker(), span.start); + if (!info) { + return undefined; + } + var returnTypeNode = info.returnTypeNode, returnType = info.returnType, promisedTypeNode = info.promisedTypeNode, promisedType = info.promisedType; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, returnTypeNode, promisedTypeNode); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Replace_0_with_Promise_1, + checker.typeToString(returnType), checker.typeToString(promisedType)], fixId, ts.Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions)]; + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, context.program.getTypeChecker(), diag.start); + if (info) { + doChange(changes, diag.file, info.returnTypeNode, info.promisedTypeNode); + } + }); } + }); + function getInfo(sourceFile, checker, pos) { + if (ts.isInJSFile(sourceFile)) { + return undefined; + } + var token = ts.getTokenAtPosition(sourceFile, pos); + var func = ts.findAncestor(token, ts.isFunctionLikeDeclaration); + var returnTypeNode = func === null || func === void 0 ? void 0 : func.type; + if (!returnTypeNode) { + return undefined; + } + var returnType = checker.getTypeFromTypeNode(returnTypeNode); + var promisedType = checker.getAwaitedType(returnType) || checker.getVoidType(); + var promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined); + if (promisedTypeNode) { + return { returnTypeNode: returnTypeNode, returnType: returnType, promisedTypeNode: promisedTypeNode, promisedType: promisedType }; + } + } + function doChange(changes, sourceFile, returnTypeNode, promisedTypeNode) { + changes.replaceNode(sourceFile, returnTypeNode, ts.createTypeReferenceNode("Promise", [promisedTypeNode])); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -132175,12 +133782,13 @@ var ts; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options); var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -132392,14 +134000,14 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) { var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { - // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); + return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; @@ -132415,9 +134023,21 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && ts.isImportTypeNode(typeNode)) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { @@ -132571,6 +134191,7 @@ var ts; function importSymbols(importAdder, symbols) { symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); } + codefix.importSymbols = importSymbols; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -134053,6 +135674,8 @@ var ts; function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); + var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); @@ -134068,7 +135691,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -134127,6 +135750,7 @@ var ts; else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); var newNodes = []; // replace range with function call var called = getCalledExpression(scope, range, functionNameText); @@ -135215,6 +136839,7 @@ var ts; var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(accessorName); ts.suppressLeadingAndTrailingTrivia(declaration); ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); @@ -135460,7 +137085,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -136109,19 +137734,20 @@ var ts; } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); - body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); + ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); } - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { + t.replaceNode(file, func.body, body); + }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } - function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); - } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); @@ -136478,7 +138104,7 @@ var ts; ts.suppressLeadingAndTrailingTrivia(property.name); if (ts.isPropertyAssignment(property)) ts.suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); + ts.copyComments(arg, property); return property; }); if (hasRestParameter && functionArguments.length >= parameters.length) { @@ -136513,10 +138139,10 @@ var ts; /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); + ts.copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + ts.copyComments(thisParameter.type, newThisParameter.type); } return ts.createNodeArray([newThisParameter, objectParameter]); } @@ -136527,7 +138153,7 @@ var ts; /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); ts.suppressLeadingAndTrailingTrivia(element); if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + ts.copyComments(parameterDeclaration.initializer, element.initializer); } return element; } @@ -136545,9 +138171,9 @@ var ts; /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); + ts.copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); + ts.copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; } @@ -136563,26 +138189,6 @@ var ts; return checker.isOptionalParameter(parameterDeclaration); } } - function copyComments(sourceNode, targetNode) { - var sourceFile = sourceNode.getSourceFile(); - var text = sourceFile.text; - if (hasLeadingLineBreak(sourceNode, text)) { - ts.copyLeadingComments(sourceNode, targetNode, sourceFile); - } - else { - ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); - } - ts.copyTrailingComments(sourceNode, targetNode, sourceFile); - } - function hasLeadingLineBreak(node, text) { - var start = node.getFullStart(); - var end = node.getStart(); - for (var i = start; i < end; i++) { - if (text.charCodeAt(i) === 10 /* lineFeed */) - return true; - } - return false; - } function getParameterName(paramDeclaration) { return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name); } @@ -136751,7 +138357,6 @@ var ts; indexes.push(index); index++; } - text = ts.escapeString(text); return [index, text, indexes]; } function nodesToTemplate(_a, file) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 7c1911bd76edd..aec6e4ed0c096 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -81,7 +81,7 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.9"; + ts.versionMajorMinor = "4.0"; /** The version of the TypeScript compiler release */ ts.version = ts.versionMajorMinor + ".0-dev"; /** @@ -869,6 +869,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1328,6 +1340,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -3538,6 +3554,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3576,6 +3593,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3587,7 +3605,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -4485,6 +4503,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4534,6 +4559,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4566,7 +4592,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -6361,6 +6387,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6640,6 +6667,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6672,7 +6700,7 @@ var ts; Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{0}>'?"), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), @@ -6772,6 +6800,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -6985,8 +7014,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7152,7 +7181,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7197,6 +7225,10 @@ var ts; Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -7213,6 +7245,8 @@ var ts; Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7347,6 +7381,12 @@ var ts; _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), + The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."), + Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -7482,6 +7522,7 @@ var ts; Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7699,6 +7740,8 @@ var ts; Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -7896,6 +7939,8 @@ var ts; Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), + Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), + Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8004,6 +8049,13 @@ var ts; Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8026,6 +8078,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8177,9 +8232,13 @@ var ts; var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; /** - * Test for whether a comment's text contains a `@ts-expect-error` or `@ts-ignore` directive. + * Test for whether a single line comment's text contains a directive. */ - var commentDirectiveRegEx = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -9529,13 +9588,7 @@ var ts; } pos++; } - var type = getDirectiveFromComment(text.slice(tokenPos, pos)); - if (type !== undefined) { - commentDirectives = ts.append(commentDirectives, { - range: { pos: tokenPos, end: pos }, - type: type, - }); - } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9550,6 +9603,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9557,11 +9611,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -9890,7 +9946,17 @@ var ts; } return token; } - function getDirectiveFromComment(text) { + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { var match = commentDirectiveRegEx.exec(text); if (!match) { return undefined; @@ -10958,7 +11024,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -13140,7 +13206,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.pos).line, + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, commentDirective, ]); })); var usedLines = ts.createMap(); @@ -13525,6 +13591,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13731,6 +13801,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -14589,7 +14678,7 @@ var ts; } /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). - * We treat the right hand side of assignments with container-like initalizers as declarations. + * We treat the right hand side of assignments with container-like initializers as declarations. */ function getAssignedExpandoInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) { @@ -14708,10 +14797,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14745,7 +14837,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -14874,6 +14966,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -15958,7 +16061,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -16851,14 +16954,9 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; - function isConstructorAccessExpression(expr) { - return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || - ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"); - } - ts.isConstructorAccessExpression = isConstructorAccessExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { if (ts.isPropertyAccessExpression(expr)) { var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -17185,19 +17283,20 @@ var ts; return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; - function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - var prevPos = getPreviousNonWhitespacePosition(startPos, sourceFile); - return ts.getLinesBetweenPositions(sourceFile, prevPos || 0, startPos); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); } ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; - function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, sourceFile, includeComments) { + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); - return ts.getLinesBetweenPositions(sourceFile, pos, nextPos); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; - function getPreviousNonWhitespacePosition(pos, sourceFile) { - while (pos-- > 0) { + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { return pos; } @@ -18630,6 +18729,23 @@ var ts; }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -25624,9 +25740,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -27336,7 +27494,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27438,9 +27597,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27620,19 +27779,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27641,8 +27791,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27676,6 +27825,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27684,8 +27834,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27824,7 +27975,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -28140,15 +28291,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -28158,8 +28306,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -28168,11 +28318,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -30606,16 +30758,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30706,7 +30849,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -30926,7 +31069,7 @@ var ts; } // We create a return control flow graph for IIFEs and constructors. For constructors // we use the return control flow graph in strict property initialization checks. - currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined; + currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) ? createBranchLabel() : undefined; currentExceptionTarget = undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -30947,7 +31090,7 @@ var ts; if (currentReturnTarget) { addAntecedent(currentReturnTarget, currentFlow); currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 162 /* Constructor */) { + if (node.kind === 162 /* Constructor */ || (ts.isInJSFile && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */))) { node.returnFlowNode = currentFlow; } } @@ -32827,7 +32970,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -32929,7 +33072,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -33056,7 +33199,7 @@ var ts; } function bindSpecialPropertyAssignment(node) { // Class declarations in Typescript do not allow property declarations - var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression); + var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer); if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) { return; } @@ -33156,7 +33299,7 @@ var ts; : propertyAccess.parent.parent.kind === 290 /* SourceFile */; } function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) { - var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer); var isToplevel = isTopLevelNamespaceAssignment(propertyAccess); namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); @@ -33555,6 +33698,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33597,6 +33743,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -34031,8 +34185,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -34517,7 +34669,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34653,7 +34807,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["ExcessCheck"] = 4] = "ExcessCheck"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -34844,6 +34999,7 @@ var ts; }, getParameterType: getTypeAtPosition, getPromisedTypeOfPromise: getPromisedTypeOfPromise, + getAwaitedType: function (type) { return getAwaitedType(type); }, getReturnTypeOfSignature: getReturnTypeOfSignature, isNullableType: isNullableType, getNullableType: getNullableType, @@ -35005,9 +35161,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -35221,6 +35375,7 @@ var ts; /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); + var inInferTypeForHomomorphicMappedType = false; var ambientModulesCache; /** * List of every ambient module with a "*" wildcard. @@ -35500,12 +35655,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35563,24 +35714,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35601,6 +35760,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35639,6 +35799,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35678,7 +35848,7 @@ var ts; } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35714,6 +35884,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35730,7 +35901,7 @@ var ts; var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } - if (declaration.pos <= usage.pos) { + if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) { // declaration is before usage if (declaration.kind === 191 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) @@ -35755,11 +35926,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35781,40 +35951,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration)) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -35876,6 +36048,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -35893,7 +36120,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -35921,9 +36148,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -36144,15 +36369,21 @@ var ts; location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -36252,17 +36483,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -36658,12 +36889,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36676,6 +36902,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36792,7 +37037,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36800,25 +37045,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -37067,9 +37335,9 @@ var ts; if (name.kind === 75 /* Identifier */) { var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -37097,7 +37365,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -37573,11 +37841,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37697,7 +37968,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37743,7 +38014,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -37932,7 +38203,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -38147,7 +38418,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -38186,7 +38457,7 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), @@ -38217,10 +38488,16 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } - type = getReducedType(type); if (type.flags & 1 /* Any */) { context.approximateLength += 3; return ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38569,14 +38846,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38743,7 +39020,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38783,28 +39060,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } } } - return result; + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; + } + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38822,7 +39134,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38834,7 +39146,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -38854,7 +39166,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38877,7 +39189,7 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); @@ -38886,7 +39198,7 @@ var ts; if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -39053,6 +39365,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -39191,8 +39509,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -39209,7 +39534,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -39330,7 +39655,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -39357,6 +39682,163 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -39451,7 +39933,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39463,7 +39945,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39571,7 +40053,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39606,7 +40088,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39707,7 +40189,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39726,13 +40208,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39777,7 +40265,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39814,13 +40302,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -39873,6 +40362,9 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); @@ -39882,16 +40374,20 @@ var ts; var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); - var symbolProps = getPropertiesOfType(classType); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertIsDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -39904,9 +40400,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -40038,7 +40532,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -40081,7 +40575,7 @@ var ts; } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -40105,7 +40599,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -40120,10 +40614,11 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); @@ -40137,13 +40632,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -40152,7 +40647,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -40189,116 +40684,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - // We don't _actually_ support jsdoc namepath types, emit `any` instead - if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40730,8 +41115,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40820,9 +41205,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -40927,8 +41309,8 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - // Filter `undefined` from the type we check against if the parent has an initializer (which handles the `undefined` case implicitly) - else if (strictNullChecks && pattern.parent.initializer) { + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } var type; @@ -41092,6 +41474,15 @@ var ts; var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); return addOptionality(type, isOptional); } + if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { + // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file. + // Use control flow analysis of this.xxx assignments the constructor to determine the type of the property. + var constructor = findConstructorDeclaration(declaration.parent); + var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) : + ts.getModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) : + undefined; + return type && addOptionality(type, isOptional); + } if (ts.isJsxAttribute(declaration)) { // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. // I.e is sugar for @@ -41105,6 +41496,56 @@ var ts; // No type specified and nothing can be inferred return undefined; } + function isConstructorDeclaredProperty(symbol) { + // A propery is considered a constructor declared property when all declaration sites are this.xxx assignments, + // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of + // a class constructor. + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) { + var links = getSymbolLinks(symbol); + if (links.isConstructorDeclaredProperty === undefined) { + links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) { + return ts.isBinaryExpression(declaration) && + ts.getAssignmentDeclarationKind(declaration) === 4 /* ThisProperty */ && + (declaration.left.kind !== 195 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && + !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration); + }); + } + return links.isConstructorDeclaredProperty; + } + return false; + } + function isAutoTypedProperty(symbol) { + // A property is auto-typed when its declaration has no type annotation or initializer and we're in + // noImplicitAny mode or a .js file. + var declaration = symbol.valueDeclaration; + return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) && + !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration)); + } + function getDeclaringConstructor(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false); + if (container && (container.kind === 162 /* Constructor */ || isJSConstructor(container))) { + return container; + } + } + } + function getFlowTypeInConstructor(symbol, constructor) { + var reference = ts.createPropertyAccess(ts.createThis(), ts.unescapeLeadingUnderscores(symbol.escapedName)); + reference.expression.parent = reference; + reference.parent = constructor; + reference.flowNode = constructor.returnFlowNode; + var flowType = getFlowTypeOfProperty(reference, symbol); + if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) { + error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); + } + // We don't infer a type if assignments are only null or undefined. + return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType); + } + function getFlowTypeOfProperty(reference, prop) { + var initialType = prop && (!isAutoTypedProperty(prop) || ts.getModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType; + return getFlowTypeOfReference(reference, autoType, initialType); + } function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) { // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration); @@ -41116,52 +41557,60 @@ var ts; var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } + var type; var definedInConstructor = false; var definedInMethod = false; - var jsdocType; - var types; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : - ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : - undefined; - if (!expression) { - continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere - } - var kind = ts.isAccessExpression(expression) - ? ts.getAssignmentDeclarationPropertyAccessKind(expression) - : ts.getAssignmentDeclarationKind(expression); - if (kind === 4 /* ThisProperty */) { - if (isDeclarationInConstructor(expression)) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - if (!ts.isCallExpression(expression)) { - jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); - } - if (!jsdocType) { - (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); - } + // We use control flow analysis to determine the type of the property if the property qualifies as a constructor + // declared property and the resulting control flow type isn't just undefined or null. + if (isConstructorDeclaredProperty(symbol)) { + type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol)); } - var type = jsdocType; if (!type) { - if (!ts.length(types)) { - return errorType; // No types from any declarations :( + var jsdocType = void 0; + var types = void 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration : + ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : + undefined; + if (!expression) { + continue; // Non-assignment declaration merged in (eg, an Identifier to mark the thing as a namespace) - skip over it and pull type info from elsewhere + } + var kind = ts.isAccessExpression(expression) + ? ts.getAssignmentDeclarationPropertyAccessKind(expression) + : ts.getAssignmentDeclarationKind(expression); + if (kind === 4 /* ThisProperty */) { + if (isDeclarationInConstructor(expression)) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + if (!ts.isCallExpression(expression)) { + jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } + if (!jsdocType) { + (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + } } - var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; - // use only the constructor types unless they were only assigned null | undefined (including widening variants) - if (definedInMethod) { - var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); - if (propType) { - (constructorTypes || (constructorTypes = [])).push(propType); - definedInConstructor = true; + type = jsdocType; + if (!type) { + if (!ts.length(types)) { + return errorType; // No types from any declarations :( } + var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined; + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfPropertyInBaseClass(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 - type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) { @@ -41236,28 +41685,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -41267,6 +41743,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41284,20 +41765,6 @@ var ts; return expression && isDeclarationInConstructor(expression); }); } - /** check for definition in base class if any declaration is in a class */ - function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) { - var parentDeclaration = ts.forEach(property.declarations, function (d) { - var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; - return ts.isClassLike(parent) && parent; - }); - if (parentDeclaration) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, property.escapedName); - } - } - } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -41642,7 +42109,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41659,9 +42126,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41827,6 +42294,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -41854,6 +42322,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -42044,16 +42515,19 @@ var ts; error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return type.resolvedBaseTypes = ts.emptyArray; } - baseType = getReducedType(getReturnTypeOfSignature(constructors[0])); + baseType = getReturnTypeOfSignature(constructors[0]); } if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -42064,7 +42538,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -42923,7 +43397,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -42935,7 +43409,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -42999,9 +43473,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -43059,7 +43533,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -43082,19 +43556,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -43467,8 +43941,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43556,8 +44030,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43582,8 +44056,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43669,8 +44143,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43772,7 +44246,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43781,10 +44255,10 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43795,16 +44269,25 @@ var ts; if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43831,13 +44314,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -43849,7 +44334,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -43926,7 +44411,7 @@ var ts; else if (type.flags & 2097152 /* Intersection */) { if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | - (ts.some(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType) ? 536870912 /* IsNeverIntersection */ : 0); + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); } return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; } @@ -43943,11 +44428,33 @@ var ts; } return reduced; } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. return !(prop.flags & 16777216 /* Optional */) && (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -44605,12 +45112,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44631,8 +45138,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -45149,6 +45656,8 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: + case 174 /* ArrayType */: + case 175 /* TupleType */: return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; @@ -45330,8 +45839,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -45360,8 +45869,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -45540,8 +46049,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -45896,6 +46405,9 @@ var ts; if (accessFlags & 4 /* CacheSymbol */) { getNodeLinks(accessNode).resolvedSymbol = prop; } + if (isThisPropertyAccessInConstructor(accessExpression, prop)) { + return autoType; + } } var propType = getTypeOfSymbol(prop); return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ? @@ -46248,7 +46760,7 @@ var ts; function getConditionalType(root, mapper) { var result; var extraTypes; - var _loop_11 = function () { + var _loop_12 = function () { var checkType = instantiateType(root.checkType, mapper); var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); var extendsType = instantiateType(root.extendsType, mapper); @@ -46322,7 +46834,7 @@ var ts; // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. while (true) { - var state_4 = _loop_11(); + var state_4 = _loop_12(); if (typeof state_4 === "object") return state_4.value; if (state_4 === "break") @@ -46680,7 +47192,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -47199,7 +47711,7 @@ var ts; return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper) { + if (!(type && mapper && couldContainTypeVariables(type))) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -47233,37 +47745,23 @@ var ts; } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; - if (objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. - return couldContainTypeVariables(type) ? - getObjectTypeInstantiation(type, mapper) : type; - } - if (objectFlags & 32 /* Mapped */) { - return getObjectTypeInstantiation(type, mapper); - } - if (objectFlags & 4 /* Reference */) { - if (type.node) { - return getObjectTypeInstantiation(type, mapper); + if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) { + if (objectFlags & 4 /* Reference */ && !(type.node)) { + var resolvedTypeArguments = type.resolvedTypeArguments; + var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); + return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; } - var resolvedTypeArguments = type.resolvedTypeArguments; - var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper); - return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type; + return getObjectTypeInstantiation(type, mapper); } return type; } - if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { - if (!couldContainTypeVariables(type)) { - return type; - } + if (flags & 3145728 /* UnionOrIntersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes === types - ? type - : (flags & 2097152 /* Intersection */) - ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) - : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + return newTypes === types ? type : + flags & 2097152 /* Intersection */ ? + getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : + getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -47375,7 +47873,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -47572,6 +48070,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -47595,7 +48102,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -47858,7 +48365,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -48236,13 +48743,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -48499,6 +49007,15 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source @@ -48510,6 +49027,14 @@ var ts; if (relation === identityRelation) { return isIdenticalTo(source, target); } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -48567,7 +49092,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & 4 /* ExcessCheck */); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -48575,12 +49100,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) && !(intersectionState & 4 /* ExcessCheck */)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 4 /* ExcessCheck */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -48596,9 +49115,7 @@ var ts; // // - For a primitive type or type parameter (such as 'number = A & B') there is no point in // breaking the intersection apart. - if (!isNonGenericObjectType(target) || !ts.every(source.types, function (t) { return isNonGenericObjectType(t) && !(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); })) { - result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } + result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); } if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) { @@ -48630,44 +49147,71 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { var flags = source.flags & target.flags; @@ -48675,11 +49219,11 @@ var ts; return 0 /* False */; } if (flags & 3145728 /* UnionOrIntersection */) { - var result_3 = eachTypeRelatedToSomeType(source, target); - if (result_3) { - result_3 &= eachTypeRelatedToSomeType(target, source); + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } - return result_3; + return result_5; } return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } @@ -48707,7 +49251,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_12 = function (prop) { + var _loop_13 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -48763,7 +49307,7 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_5 = _loop_12(prop); + var state_5 = _loop_13(prop); if (typeof state_5 === "object") return state_5.value; } @@ -48833,8 +49377,16 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; @@ -48911,7 +49463,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -48993,26 +49545,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_4 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_4 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_4 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_4 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_4; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -49297,9 +49852,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_5 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_5) { - return result_5; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -49366,12 +49921,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_6; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); - if (result_6 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_6 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -49419,11 +49974,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_13 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_14 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -49431,7 +49986,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -49439,7 +49994,7 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_7 = _loop_14(i); + var state_7 = _loop_15(i); switch (state_7) { case "continue-outer": continue outer; } @@ -49453,7 +50008,7 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_6 = _loop_13(combination); + var state_6 = _loop_14(combination); if (typeof state_6 === "object") return state_6.value; } @@ -49505,7 +50060,7 @@ var ts; ts.Debug.assertIsDefined(links.deferralParent); ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_7 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -49515,7 +50070,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_7 &= related; + result_9 &= related; } else { if (related) { @@ -49523,34 +50078,27 @@ var ts; } } } - if (unionParent && !result_7 && targetIsOptional) { - result_7 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_7 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_7; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -49585,7 +50133,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -49710,7 +50258,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -49958,18 +50506,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -50040,7 +50592,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_15 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -50072,7 +50624,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_15(tp); + _loop_16(tp); } cache.variances = variances; } @@ -50167,6 +50719,12 @@ var ts; function getDeclaringClass(prop) { return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; } + // Return the inherited type of the given property or undefined if property doesn't exist in a base class. + function getTypeOfPropertyInBaseClass(property) { + var classType = getDeclaringClass(property); + var baseClassType = classType && getBaseTypes(classType)[0]; + return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName); + } // Return true if some underlying source property is declared in a class that derives // from the given base class. function isPropertyInClassDerivedFrom(prop, baseClass) { @@ -50355,8 +50913,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -50505,8 +51063,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -50877,7 +51435,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -50886,7 +51444,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -50900,7 +51458,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -51018,15 +51576,22 @@ var ts; return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); } var result = !!(type.flags & 63176704 /* Instantiable */ || - objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || - objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || + objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) || + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables)); if (type.flags & 3899393 /* ObjectFlagsType */) { type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } return result; } + function isNonGenericTopLevelType(type) { + if (type.aliasSymbol && !type.aliasTypeArguments) { + var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 247 /* TypeAliasDeclaration */); + return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 290 /* SourceFile */ ? true : n.kind === 249 /* ModuleDeclaration */ ? false : "quit"; })); + } + return false; + } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) || @@ -51059,12 +51624,16 @@ var ts; * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). */ function inferTypeForHomomorphicMappedType(source, target, constraint) { + if (inInferTypeForHomomorphicMappedType) { + return undefined; + } var key = source.id + "," + target.id + "," + constraint.id; if (reverseMappedCache.has(key)) { return reverseMappedCache.get(key); } - reverseMappedCache.set(key, undefined); + inInferTypeForHomomorphicMappedType = true; var type = createReverseMappedType(source, target, constraint); + inInferTypeForHomomorphicMappedType = false; reverseMappedCache.set(key, type); return type; } @@ -51361,8 +51930,8 @@ var ts; else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } @@ -51470,8 +52039,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -52071,8 +52640,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -52140,6 +52709,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -52348,7 +52920,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -52440,8 +53012,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -52493,9 +53065,11 @@ var ts; return getTypeOfSymbol(symbol); } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { - var expressionType = getTypeOfDottedName(declaration.parent.parent.expression, /*diagnostic*/ undefined); + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); if (expressionType) { - return getForOfIterationType(declaration.parent.parent, expressionType); + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); } } if (diagnostic) { @@ -52794,7 +53368,7 @@ var ts; if (isEmptyArrayAssignment(node)) { return getEvolvingArrayType(neverType); } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow)); + var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } if (declaredType.flags & 1048576 /* Union */) { @@ -53077,14 +53651,15 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { + var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; + if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } var name = getAccessedPropertyName(expr); if (name === undefined) { return false; } - return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -53108,7 +53683,7 @@ var ts; if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } return type; @@ -53147,12 +53722,6 @@ var ts; if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } - if (ts.isConstructorAccessExpression(left_1)) { - return narrowTypeByConstructor(type, left_1, operator_1, right_1, assumeTrue); - } - if (ts.isConstructorAccessExpression(right_1)) { - return narrowTypeByConstructor(type, right_1, operator_1, left_1, assumeTrue); - } if (isMatchingReference(reference, left_1)) { return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); } @@ -53167,12 +53736,18 @@ var ts; type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); } } - if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + if (isMatchingReferenceDiscriminant(left_1, type)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } - if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + if (isMatchingReferenceDiscriminant(right_1, type)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -53246,7 +53821,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -53435,15 +54010,16 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } - function narrowTypeByConstructor(type, constructorAccessExpr, operator, identifier, assumeTrue) { + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { // Do not narrow when checking inequality. if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { return type; } - // In the case of `x.y`, a `x.constructor === T` type guard resets the narrowed type of `y` to its declared type. - if (!isMatchingReference(reference, constructorAccessExpr.expression)) { - return declaredType; - } // Get the type of the constructor identifier expression, if it is not a function then do not narrow. var identifierType = getTypeOfExpression(identifier); if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { @@ -53557,7 +54133,7 @@ var ts; !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + if (isMatchingReferenceDiscriminant(predicateArgument, type)) { return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } @@ -53597,7 +54173,7 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); } - if (isMatchingReferenceDiscriminant(expr, declaredType)) { + if (isMatchingReferenceDiscriminant(expr, type)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); }); } return type; @@ -54133,6 +54709,10 @@ var ts; var fileSymbol = getSymbolOfNode(container); return fileSymbol && getTypeOfSymbol(fileSymbol); } + else if (container.externalModuleIndicator) { + // TODO: Maybe issue a better error than 'object is possibly undefined' + return undefinedType; + } else if (includeGlobalThis) { return getTypeOfSymbol(globalThisSymbol); } @@ -54525,7 +55105,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -54564,7 +55144,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -55218,8 +55798,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -55810,7 +56390,8 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { var right = _a[_i]; var left = props.get(right.escapedName); - if (left && !maybeTypeOfKind(getTypeOfSymbol(right), 98304 /* Nullable */)) { + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 1 /* Any */) && right.flags & 16777216 /* Optional */)) { var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); } @@ -55991,14 +56572,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -56008,7 +56589,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -56089,8 +56674,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -56174,11 +56760,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -56389,6 +56970,9 @@ var ts; } return false; } + function isThisPropertyAccessInConstructor(node, prop) { + return ts.isThisProperty(node) && (isAutoTypedProperty(prop) || isConstructorDeclaredProperty(prop)) && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop); + } function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); @@ -56462,7 +57046,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = getConstraintForLocation(getTypeOfSymbol(prop), node); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node); } return getFlowTypeOfAccessExpression(node, prop, propType, right); } @@ -56476,6 +57060,9 @@ var ts; prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) { return propType; } + if (propType === autoType) { + return getFlowTypeOfProperty(node, prop); + } // If strict null checks and strict property initialization checks are enabled, if we have // a this.xxx property access, if the property is an instance property without an initializer, // and if we are in a constructor of the same class as the property declaration, assume that @@ -56608,7 +57195,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -57510,8 +58097,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -57727,7 +58314,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_16 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -57745,15 +58332,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_16(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -57879,7 +58466,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_17 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -57887,7 +58474,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_17(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -58222,8 +58809,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -58277,9 +58864,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -58897,7 +59484,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -59080,18 +59667,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -59309,7 +59894,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -59418,13 +60003,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -59449,7 +60027,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -59585,11 +60163,20 @@ var ts; } var links = getNodeLinks(expr); var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + if (symbol) { + if (isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol)); } return booleanType; } + function checkDeleteExpressionMustBeOptional(expr, type) { + var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */; + if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional); + } + } function checkTypeOfExpression(node) { checkExpression(node.expression); return typeofType; @@ -59732,8 +60319,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59799,7 +60386,8 @@ var ts; // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type, // and the right operand to be of type Any, an object type, or a type parameter type. // The result is always of the Boolean primitive type. - if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) { + if (!(allTypesAssignableToKind(leftType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) || + isTypeAssignableToKind(leftType, 4194304 /* Index */ | 262144 /* TypeParameter */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) { @@ -60184,6 +60772,12 @@ var ts; case 49 /* GreaterThanGreaterThanGreaterThanToken */: case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: reportOperatorError(); + break; + case 42 /* AsteriskAsteriskToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + if (languageVersion < 3 /* ES2016 */) { + error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later); + } } resultType_1 = bigintType; } @@ -60318,8 +60912,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -61087,7 +61681,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -61489,8 +62083,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -61950,7 +62545,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -62063,10 +62658,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_8 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_8 |= getDeclarationSpaces(d); }); - return result_8; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -62305,7 +62900,7 @@ var ts; if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. - error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType)); return; } } @@ -62440,8 +63035,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -62830,7 +63425,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -62857,6 +63452,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -62870,8 +63475,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -63387,8 +63991,30 @@ var ts; var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); @@ -63543,11 +64169,8 @@ var ts; } } function checkRightHandSideOfForOf(statement) { - return getForOfIterationType(statement, checkNonNullExpression(statement.expression)); - } - function getForOfIterationType(statement, expressionType) { var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, statement.expression); + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -64163,10 +64786,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -64174,6 +64798,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -64199,7 +64824,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -64380,6 +65005,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -64667,7 +65295,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_18 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -64686,7 +65314,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_18(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -64845,6 +65473,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -64853,11 +65500,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -64975,7 +65622,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -65026,7 +65673,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -65109,6 +65762,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -65382,7 +66038,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -65506,15 +66162,10 @@ var ts; } checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -65528,6 +66179,9 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } @@ -67255,8 +67909,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -67870,9 +68550,9 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken) { + else if (isOptionalParameter(parameter)) { seenOptionalParameter = true; - if (parameter.initializer) { + if (parameter.questionToken && parameter.initializer) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } @@ -67931,6 +68611,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -68938,13 +69619,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -70256,9 +70937,11 @@ var ts; } ts.createBinary = createBinary; function updateBinary(node, left, right, operator) { + if (operator === void 0) { operator = node.operatorToken; } return node.left !== left || node.right !== right - ? updateNode(createBinary(left, operator || node.operatorToken, right), node) + || node.operatorToken !== operator + ? updateNode(createBinary(left, operator, right), node) : node; } ts.updateBinary = updateBinary; @@ -70380,9 +71063,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -70853,6 +71538,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -72398,11 +73103,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -72765,7 +73473,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -72776,7 +73484,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -72788,15 +73496,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -73019,11 +73727,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -74061,18 +74770,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -74827,13 +75588,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -75967,9 +76808,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -76074,9 +76912,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -76927,6 +77762,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -77818,6 +78657,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -77827,8 +78677,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -78311,6 +79161,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -78633,24 +79491,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -78680,7 +79539,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -79633,7 +80492,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -79699,8 +80558,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79720,8 +80579,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -80631,6 +81490,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -80644,7 +81527,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; var currentSourceFile; var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ @@ -80654,6 +81537,27 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } function recordTaggedTemplateString(temp) { taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); } @@ -80680,11 +81584,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -80715,26 +81619,30 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: @@ -80755,7 +81663,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -80791,7 +81699,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -80866,13 +81774,17 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); var visited = ts.visitEachChild(node, visitor, context); var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) ]); - return ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; } function visitTaggedTemplateExpression(node) { return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); @@ -80953,15 +81865,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -81009,7 +81921,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -81023,9 +81935,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -81155,7 +82071,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -81369,7 +82285,7 @@ var ts; function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) { context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -81500,6 +82416,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -81535,6 +82452,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -81547,6 +82465,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -81582,6 +82501,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -83508,6 +84428,8 @@ var ts; // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -89496,7 +90418,7 @@ var ts; scoped: false, dependencies: [ts.createBindingHelper], priority: 2, - text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n }" }; function createExportStarHelper(context, module) { context.requestEmitHelper(exportStarHelper); @@ -91620,7 +92542,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -91711,6 +92634,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -92138,6 +93069,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -92974,8 +93911,12 @@ var ts; var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -92993,8 +93934,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -93124,6 +94068,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -93131,6 +94078,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -93138,6 +94086,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -93152,9 +94114,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -93179,7 +94145,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -93194,17 +94162,37 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); @@ -93838,6 +94826,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -95333,16 +96322,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); - var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); - } + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); - var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(node, [node.expression], 0 /* None */); - if (trailingNewlines) { - writeLine(trailingNewlines); - } - decreaseIndentIf(leadingNewlines); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -96138,12 +97121,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -96480,8 +97466,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -96708,7 +97694,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -96912,7 +97898,7 @@ var ts; if (closingLineTerminatorCount) { writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -97051,7 +98037,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); } return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; } @@ -97096,7 +98082,7 @@ var ts; } if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { if (preserveSourceNewlines) { - return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, currentSourceFile, includeComments); }); + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); } return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } @@ -97132,6 +98118,19 @@ var ts; } return lines; } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); + } + } function synthesizedNodeStartsOnNewLine(node, format) { if (ts.nodeIsSynthesized(node)) { var startsOnNewLine = ts.getStartsOnNewLine(node); @@ -98727,11 +99726,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -99246,13 +100245,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_9 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_9.push(resolvedModule); + result_11.push(resolvedModule); } - return result_9; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -99872,7 +100871,7 @@ var ts; return line; } // Stop searching if the line is not empty and not a comment - var lineText = file.text.slice(lineStarts[line - 1], lineStarts[line]).trim(); + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { return -1; } @@ -103749,9 +104748,9 @@ var ts; var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); if (!preferSymlinks) { - var result_10 = ts.forEach(targets, cb); - if (result_10) - return result_10; + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; } var links = host.getProbableSymlinks ? host.getProbableSymlinks(host.getSourceFiles()) @@ -103767,9 +104766,9 @@ var ts; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); var option = ts.resolvePath(path, relative); if (!host.fileExists || host.fileExists(option)) { - var result_11 = cb(option); - if (result_11) - return result_11; + var result_13 = cb(option); + if (result_13) + return result_13; } }); return result || @@ -103793,7 +104792,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_19 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { @@ -103819,7 +104818,7 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_8 = _loop_19(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; if (state_8 === "break") break; @@ -104393,20 +105392,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -104462,12 +105464,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -104483,7 +105503,7 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; @@ -104832,7 +105852,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -107375,7 +108395,8 @@ var ts; } _this.delayedInitializationError = { kind: "event::initializationFailed", - message: e.message + message: e.message, + stack: e.stack, }; } _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log); @@ -107494,7 +108515,9 @@ var ts; var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log); installer.listen(); function indent(newline, str) { - return newline + " " + str.replace(/\r?\n/, newline + " "); + return str && str.length + ? newline + " " + str.replace(/\r?\n/, newline + " ") + : ""; } })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 856c7e1c01757..ee773c076cc42 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空间声明必须位于与之合并的类或函数所在的相同文件内。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空间声明不能位于与之合并的类或函数前", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只允许在命名空间或模块中使用命名空间声明。", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "具有类型参数的 \"new\" 表达式的后面必须始终是带括号的参数列表。", "A_non_dry_build_would_build_project_0_6357": "非 -dry 生成将生成项目“{0}”", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry 生成将删除以下文件: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "非干燥生成将更新项目 \"{0}\" 的输出", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", "Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明", "Add_0_to_unresolved_variable_90008": "将“{0}.”添加到未解析的变量", + "Add_a_return_statement_95111": "添加 return 语句", "Add_all_missing_async_modifiers_95041": "添加所有缺失的 \"async\" 修饰符", "Add_all_missing_call_parentheses_95068": "添加所有缺失的调用括号", "Add_all_missing_imports_95064": "添加所有缺少的导入", "Add_all_missing_members_95022": "添加所有缺少的成员", + "Add_all_missing_return_statement_95114": "添加所有缺少的 return 语句", "Add_all_missing_super_calls_95039": "添加所有缺失的超级调用", "Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数", "Add_await_95083": "添加 \"await\"", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "将默认导入 \"{0}\" 从 \"{1}\" 添加到现有导入声明。", "Add_definite_assignment_assertion_to_property_0_95020": "向属性“{0}”添加明确的赋值断言", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "将明确赋值断言添加到未初始化的所有属性", - "Add_export_to_make_this_file_into_a_module_95097": "添加 \"export {}\" 以将此文件变为模块", + "Add_export_to_make_this_file_into_a_module_95097": "添加 \"export {}\",将此文件变为模块", "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", "Add_initializer_to_property_0_95019": "向属性“{0}”添加初始值设定项", "Add_initializers_to_all_uninitialized_properties_95027": "将初始化表达式添加到未初始化的所有属性", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "导入路径不能以“{0}”扩展名结束。考虑改为导入“{1}”。", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引表达式参数必须为 \"string\"、\"number\"、\"symbol\" 或 \"any\" 类型。", "An_index_signature_cannot_have_a_rest_parameter_1017": "索引签名不能包含 rest 参数。", + "An_index_signature_cannot_have_a_trailing_comma_1025": "索引签名不能包含尾随逗号。", "An_index_signature_must_have_a_type_annotation_1021": "索引签名必须具有类型批注。", "An_index_signature_must_have_exactly_one_parameter_1096": "索引签名必须正好具有一个参数。", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引签名参数不能包含问号。", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "无法迭代值,因为其迭代器的 \"next\" 方法需要类型 \"{1}\",但数组扩张将始终发送 \"{0}\"。", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "无法迭代值,因为其迭代器的 \"next\" 方法需要类型 \"{1}\",但 for-of 将始终发送 \"{0}\"。", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"", + "Cannot_read_file_0_5083": "无法读取文件“{0}”。", "Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。", "Cannot_redeclare_exported_variable_0_2323": "无法重新声明导出的变量“{0}”。", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。", "Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。", "Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "当发出专用标识符下层时,编译器预留名称 \"{0}\"。", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "当发出专用标识符下层时,编译器会预留名称“{0}”。", "Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。", "Composite_projects_may_not_disable_incremental_compilation_6379": "复合项目不能禁用增量编译。", "Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "无法解析具有表达式的路径“{0}”: {1}。", "Could_not_write_file_0_Colon_1_5033": "无法写入文件“{0}”: {1}。", "DIRECTORY_6038": "目录", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "该声明扩充了另一文件中的声明。这无法被序列化。", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "此文件的声明发出要求使用专用名称 \"{0}\"。显式类型注释可能取消阻止声明发出。", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "此文件的声明发出要求使用模块 \"{1}\" 中的专用名称 \"{0}\"。显式类型注释可能取消阻止声明发出。", "Declaration_expected_1146": "应为声明。", @@ -537,7 +543,7 @@ "Fallthrough_case_in_switch_7029": "switch 语句中的 Fallthrough 情况。", "File_0_does_not_exist_6096": "文件“{0}”不存在。", "File_0_exist_use_it_as_a_name_resolution_result_6097": "文件“{0}”存在 - 将其用作名称解析结果。", - "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "文件 \"{0}\" 具有不受支持的扩展名。支持的扩展名只有 {1}。", + "File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1_6054": "文件“{0}”具有不受支持的扩展名。仅支持 {1} 扩展名。", "File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。", "File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option_6504": "文件 \"{0}\" 是 JavaScript 文件。你是想启用 \"allowJs\" 选项吗?", "File_0_is_not_a_module_2306": "文件“{0}”不是模块。", @@ -606,7 +612,7 @@ "Import_declaration_0_is_using_private_name_1_4000": "导入声明“{0}”使用的是专用名称“{1}”。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "导入声明与“{0}”的局部声明冲突。", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "命名空间中的导入声明不能引用模块。", - "Import_default_0_from_module_1_90032": "从模块 \"{1}\" 导入默认的 \"{0}\"", + "Import_default_0_from_module_1_90032": "从模块“{1}”导入默认的“{0}”", "Import_emit_helpers_from_tslib_6139": "从 \"tslib\" 导入发出帮助程序。", "Import_may_be_converted_to_a_default_import_80003": "导入可能会转换为默认导入。", "Import_name_cannot_be_0_2438": "导入名称不能为“{0}”。", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "初始化构造函数中的属性“{0}”", "Initialize_static_property_0_90021": "初始化静态属性“{0}”", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "实例成员变量“{0}”的初始化表达式不能引用构造函数中声明的标识符“{1}”。", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "参数“{0}”的初始化表达式不能引用在它之后声明的标识符“{1}”。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始化表达式没有为此绑定元素提供此任何值,且该绑定元素没有默认值。", "Initializers_are_not_allowed_in_ambient_contexts_1039": "不允许在环境上下文中使用初始化表达式。", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 项目并创建 tsconfig.json 文件。", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "严格模式下“{0}”的使用无效。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "\"jsxFactory\" 的值无效。“{0}”不是有效的标识符或限定名称。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "\"--reactNamespace\" 的值无效。“{0}”不是有效的标识符。", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "其元素类型“{0}”不是有效的 JSX 元素。", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "其实例类型“{0}”不是有效的 JSX 元素。", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "其返回类型“{0}”不是有效的 JSX 元素。", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc \"@{0} {1}\" 不匹配 \"extends {2}\" 子句。", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc \"@{0}\" 未附加到类。", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc \"...\" 可能仅出现在签名的最后一个参数中。", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "仅发出 \".d.ts\" 声明文件。 ", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "类 \"extends\" 子句当前仅支持具有可选类型参数的标识符/限定名称。", "Only_named_exports_may_use_export_type_1383": "只有已命名的导出可使用“导出类型”。", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "只有数字枚举可具有计算成员,但此表达式的类型为“{0}”。如果不需要全面性检查,请考虑改用对象文本。", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "通过 \"super\" 关键字只能访问基类的公共方法和受保护方法。", "Operator_0_cannot_be_applied_to_type_1_2736": "运算符 \"{0}\" 不能应用于类型 \"{1}\"。", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "运算符“{0}”不能应用于类型“{1}”和“{2}”。", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。", "Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在", "Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。", - "Overload_0_of_1_2_gave_the_following_error_2772": "{1} 个重载 中的第 {0} 个(\"{2}\")出现了以下错误。", + "Overload_0_of_1_2_gave_the_following_error_2772": "第 {0} 个重载(共 {1} 个),“{2}”,出现以下错误。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "重载签名必须均导出或均不导出。", "Overload_signatures_must_all_be_optional_or_required_2386": "重载签名必须全部为可选签名或必需签名。", "Overload_signatures_must_all_be_public_private_or_protected_2385": "重载签名必须全部是公共签名、私有签名或受保护签名。", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "参数“{0}”的初始化表达式中不能引用该参数自身。", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "参数“{0}”不能引用在它之后声明的标识符“{1}”。", + "Parameter_0_cannot_reference_itself_2372": "参数“{0}”不能引用它自身。", "Parameter_0_implicitly_has_an_1_type_7006": "参数“{0}”隐式具有“{1}”类型。", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "参数 \"{0}\" 隐式具有 \"{1}\" 类型,但可以从用法中推断出更好的类型。", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "参数“{0}”和参数“{1}”的位置不一样。", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "属性“{0}”在类型“{1}”上不存在。你是否指的是“{2}”?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "属性“{0}”的声明发生冲突,并且在类型“{1}”中不可访问此属性。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "属性“{0}”隐式具有类型 \"any\",因为其 set 访问器缺少参数类型批注。", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "提供 \"--isolatedModules\" 标志时,需要使用 \"export type\" 才能重新导出类型。", "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。", + "Remove_all_incorrect_body_block_braces_95115": "删除所有错误的正文块括号", "Remove_all_unnecessary_uses_of_await_95087": "删除 \"await\" 的所有不必要的使用", "Remove_all_unreachable_code_95051": "删除所有无法访问的代码", "Remove_all_unused_labels_95054": "删除所有未使用的标签", + "Remove_block_body_braces_95112": "删除块正文括号", "Remove_braces_from_arrow_function_95060": "从箭头函数中删除大括号", "Remove_destructuring_90009": "删除解构", "Remove_import_from_0_90005": "从“{0}”删除导入", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "仅当 \"--module\" 选项为 \"esnext\" 或 \"system\" 时,才允许使用 \"import. meta\" 元属性。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "如果没有引用 \"{1}\",则无法命名 \"{0}\" 的推断类型。这很可能不可移植。需要类型注释。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "由于属性“{1}”存在于多个要素中,但在某些要素中是专用属性,因此已将交集“{0}”缩减为“绝不”。", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "由于属性“{1}”在某些要素中具有存在冲突的类型,因此已将交集“{0}”缩减为“绝不”。", "The_last_overload_gave_the_following_error_2770": "最后一个重载给出了以下错误。", "The_last_overload_is_declared_here_2771": "在此处声明最后一个重载。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "\"delete\" 运算符的操作数不能是专用标识符。", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "\"delete\" 运算符的操作数不能是只读属性。", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "\"delete\" 运算符的操作数必须是属性引用。", + "The_operand_of_a_delete_operator_must_be_optional_2790": "\"delete\" 运算符的操作数必须是可选的。", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "增量或减量运算符的操作数不能是可选属性访问。", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "递增或递减运算符的操作数必须是变量或属性访问。", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "分析器预期在这里找到与 \"{\" 标记匹配的 \"}\"。", @@ -1109,7 +1123,7 @@ "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "算术运算右侧必须是 \"any\"、\"number\"、\"bigint\" 或枚举类型。", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "\"in\" 表达式的右侧必须是 \"any\" 类型、对象类型或类型参数。", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "\"instanceof\" 表达式的右侧必须属于类型 \"any\",或属于可分配给 \"Function\" 接口类型的类型。", - "The_shadowing_declaration_of_0_is_defined_here_18017": "在此处定义了 \"{0}\" 的隐藏声明", + "The_shadowing_declaration_of_0_is_defined_here_18017": "在此处定义了“{0}”的阴影声明", "The_specified_path_does_not_exist_Colon_0_5058": "指定的路径不存在:“{0}”。", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "赋值的目标必须是变量或属性访问。", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "对象 rest 分配的目标不能是可选属性访问。", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "此表达式不可调用。", "This_expression_is_not_constructable_2351": "此表达式不可构造。", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "此导入从不用作值,必须使用 \"import type\" ,因为 \"importsNotUsedAsValues\" 设置为 \"error\"。", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "这是正在扩充的声明。请考虑将扩充声明移到同一个文件中。", "This_may_be_converted_to_an_async_function_80006": "可将此转换为异步函数。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "只能通过启用 \"{0}\" 标志并引用其默认导出,使用 ECMAScript 导入/导出来引用此模块。", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "此模块是使用 \"export =\" 声明的,在使用 \"{0}\" 标志时只能与默认导入一起使用。", @@ -1158,8 +1173,8 @@ "Type_0_has_no_construct_signatures_2761": "类型 \"{0}\" 没有构造签名。", "Type_0_has_no_matching_index_signature_for_type_1_2537": "类型“{0}”没有匹配的类型“{1}”的索引签名。", "Type_0_has_no_properties_in_common_with_type_1_2559": "类型“{0}”与类型“{1}”不具有相同的属性。", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "类型 \"{0}\" 缺少类型 \"{1}\" 中的以下属性: {2}", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "类型 \"{0}\" 缺少类型 \"{1}\" 的以下属性: {2} 及其他 {3} 项。", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "类型“{0}”缺少类型“{1}”中的以下属性: {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "类型“{0}”缺少类型“{1}”的以下属性: {2} 及其他 {3} 项。", "Type_0_is_not_a_constructor_function_type_2507": "类型“{0}”不是构造函数类型。", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "类型“{0}”不是 ES5/ES3 中的有效异步函数返回类型,因为其未引用与 Promise 相符的构造函数值。", "Type_0_is_not_an_array_type_2461": "类型“{0}”不是数组类型。", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "\"yield*\" 操作数的迭代元素的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "属性“{0}”的类型在已映射的类型“{1}”中循环引用其自身。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "异步生成器中 \"yield\" 操作数的类型必须是有效承诺,或不得包含可调用的 \"then\" 成员。", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "此导入产生的类型。无法调用或构造命名空间样式的导入,这类导入将在运行时导致失败。请考虑改为使用默认导入或这里需要的导入。", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "此导入产生的类型。无法调用或构造命名空间样式的导入,这类导入将在运行时导致失败。请考虑改为使用默认导入或此处需要的导入。", "Type_parameter_0_has_a_circular_constraint_2313": "类型参数“{0}”具有循环约束。", "Type_parameter_0_has_a_circular_default_2716": "类型参数“{0}”具有循环默认值。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "导出接口中的调用签名的类型参数“{0}”具有或正在使用专用名称“{1}”。", @@ -1258,7 +1273,7 @@ "Updating_unchanged_output_timestamps_of_project_0_6371": "正在更新项目 \"{0}\" 未更改的输出时间戳…", "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", - "Using_compiler_options_of_project_reference_redirect_0_6215": "使用项目引用重定向 \"{0}\" 的编译器选项。", + "Using_compiler_options_of_project_reference_redirect_0_6215": "使用项目引用重定向“{0}”的编译器选项。", "VERSION_6036": "版本", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "类型“{0}”的值没有与类型“{1}”相同的属性。你是想调用它吗?", "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348": "类型“{0}”的值不可调用。是否希望包括 \"new\"?", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "应为变量声明。", "Variable_declaration_list_cannot_be_empty_1123": "变量声明列表不能为空。", "Version_0_6029": "版本 {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "请访问 https://aka.ms/tsconfig.json,了解有关此文件的详细信息", "Watch_input_files_6005": "监视输入文件。", "Watch_option_0_requires_a_value_of_type_1_5080": "观察选项 \"{0}\" 需要 {1} 类型的值。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否在监视模式下保留过时的控制台输出,而不是清除屏幕。", "Wrap_all_invalid_characters_in_an_expression_container_95109": "包装表达式容器中的所有无效字符", + "Wrap_all_object_literal_with_parentheses_95116": "用括号将所有对象文字括起来", "Wrap_invalid_character_in_an_expression_container_95108": "包装表达式容器中的无效字符", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "用括号将以下应为对象文字的正文括起来", "You_cannot_rename_a_module_via_a_global_import_8031": "不能通过全局导入对模块进行重命名。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "不能重命名标准 TypeScript 库中定义的元素。", "You_cannot_rename_this_element_8000": "无法重命名此元素。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "“{0}”收到的参数过少,无法在此处充当修饰器。你是要先调用它,然后再写入 \"@{0}()\" 吗?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "不能在不使用括号的情况下混用 \"{0}\" 和 \"{1}\" 操作。", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "“{0}”被指定了两次。将覆盖名为“{0}”的特性。", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "只能通过启用 \"esModuleInterop\" 标志并使用默认导入来导入“{0}”。", + "_0_can_only_be_imported_by_using_a_default_import_2595": "仅可使用默认导入来导入“{0}”。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "只能通过使用 \"require\" 调用或启用 \"esModuleInterop\" 标志并使用默认导入来导入“{0}”。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "只能使用 \"require\" 调用或使用默认导入来导入“{0}”。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "仅可使用 \"import {1} = require({2})\" 或默认导入来导入“{0}”。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "仅可使用 \"import {1} = require({2})\" 或通过启用 \"esModuleInterop\" 标志并使用默认导入来导入“{0}”。", + "_0_cannot_be_used_as_a_JSX_component_2786": "“{0}”不能用作 JSX 组件。", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "\"{0}\" 是使用 \"export type\" 导出的,因此不能用作值。", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "\"{0}\" 是使用 \"import type\" 导入的,因此不能用作值。", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "\"{0}\" 组件不接受文本作为子元素。JSX 中的文本类型为 \"string\",但 \"{1}\" 的预期类型为 \"{2}\"。", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "\"#constructor\" 是保留字。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "在严格模式下,无法对标识符调用 \"delete\"。", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "删除此 - 项目“{0}”已是最新,因为它是以前生成的", + "export_Asterisk_does_not_re_export_a_default_1195": "\"export *\" 不会重新导出默认值。", "export_can_only_be_used_in_TypeScript_files_8003": "\"export =\" 只能在 TypeScript 文件中使用。", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "\"export\" 修饰符不可用于环境模块和模块扩大,因为它们始终可见。", "extends_clause_already_seen_1172": "已看到 \"extends\" 子句。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index 24d78becd11ef..43c3bd2b02bd0 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -52,6 +52,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空間宣告的所在檔案位置,不得與其要合併的類別或函式不同。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空間宣告的位置不得先於其要合併的類別或函式。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只有命名空間或模組才允許命名空間宣告。", + "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384": "具有型別引數的 'new' 運算式後面必須永遠接著以括號括住的引數清單。", "A_non_dry_build_would_build_project_0_6357": "非 -dry 組建會建置專案 '{0}'", "A_non_dry_build_would_delete_the_following_files_Colon_0_6356": "非 -dry 組建會刪除下列檔案: {0}", "A_non_dry_build_would_update_output_of_project_0_6375": "非 DRY 組建將會更新專案 '{0}' 的輸出", @@ -106,10 +107,12 @@ "Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。", "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告", "Add_0_to_unresolved_variable_90008": "對未解析的變數新增 '{0}.'", + "Add_a_return_statement_95111": "新增 return 陳述式", "Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾元", "Add_all_missing_call_parentheses_95068": "新增所有缺少的呼叫括號", "Add_all_missing_imports_95064": "新增所有缺少的匯入", "Add_all_missing_members_95022": "新增遺漏的所有成員", + "Add_all_missing_return_statement_95114": "新增所有遺漏的 return 陳述式", "Add_all_missing_super_calls_95039": "新增缺少的所有 super 呼叫", "Add_async_modifier_to_containing_function_90029": "將 async 修飾元新增至包含的函式", "Add_await_95083": "新增 'await'", @@ -122,7 +125,7 @@ "Add_default_import_0_to_existing_import_declaration_from_1_90033": "從 \"{1}\" 將預設匯入 '{0}' 新增至現有的匯入宣告", "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示", - "Add_export_to_make_this_file_into_a_module_95097": "新增 'export {}' 以將此檔案設為模組", + "Add_export_to_make_this_file_into_a_module_95097": "新增 'export {}' 以將此檔案轉為模組", "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", "Add_initializer_to_property_0_95019": "將初始設定式新增至屬性 '{0}'", "Add_initializers_to_all_uninitialized_properties_95027": "為所有未初始化的屬性新增初始設定式", @@ -196,6 +199,7 @@ "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引運算式引數必須是 'string'、'number'、'symbol' 或 'any' 類型。", "An_index_signature_cannot_have_a_rest_parameter_1017": "索引簽章不得有剩餘參數。", + "An_index_signature_cannot_have_a_trailing_comma_1025": "索引簽章結尾不可有逗號。", "An_index_signature_must_have_a_type_annotation_1021": "索引簽章必須有類型註釋。", "An_index_signature_must_have_exactly_one_parameter_1096": "索引簽章只可有一個參數。", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引簽章參數不得有問號。", @@ -298,6 +302,7 @@ "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_al_2764": "因為值的迭代器 'next' 方法需要類型 '{1}',但陣列擴張永遠會傳送 '{0}',所以無法逐一查看值。", "Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_s_2763": "因為值的迭代器 'next' 方法需要類型 '{1}',但 for-of 永遠會傳送 '{0}',所以無法逐一查看值。", "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容", + "Cannot_read_file_0_5083": "無法讀取檔案 '{0}'。", "Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。", "Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。", "Cannot_redeclare_exported_variable_0_2323": "無法重新宣告匯出的變數 '{0}'。", @@ -340,7 +345,7 @@ "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。", "Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。", "Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。", - "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "在下層發出私人識別碼時,編譯器會保留名稱 '{0}'。", + "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027": "降級發出私人識別碼時,編譯器會保留名稱 '{0}'。", "Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。", "Composite_projects_may_not_disable_incremental_compilation_6379": "複合專案可能不會停用累加編譯。", "Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。", @@ -390,6 +395,7 @@ "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231": "無法解析具有下列延伸模組的路徑 '{0}': {1}。", "Could_not_write_file_0_Colon_1_5033": "無法編寫檔案 '{0}': {1}。", "DIRECTORY_6038": "目錄", + "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232": "宣告會讓另一個檔案中的宣告增加。這無法序列化。", "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005": "此檔案的宣告發出必須使用私人名稱 '{0}'。明確的型別註解可能會解除封鎖宣告發出。", "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006": "此檔案的宣告發出必須使用來自模組 '{1}' 的私人名稱 '{0}'。明確的型別註解可能會解除封鎖宣告發出。", "Declaration_expected_1146": "必須是宣告。", @@ -626,7 +632,6 @@ "Initialize_property_0_in_the_constructor_90020": "將建構函式中的屬性 '{0}' 初始化", "Initialize_static_property_0_90021": "將靜態屬性 '{0}' 初始化", "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301": "執行個體成員變數 '{0}' 的初始設定式不得參考建構函式中所宣告的識別碼 '{1}'。", - "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "參數 '{0}' 的初始設定式不得參考在其之後宣告的識別碼 '{1}'。", "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525": "初始設定式未提供任何值給這個繫結項目,且該繫結項目沒有預設值。", "Initializers_are_not_allowed_in_ambient_contexts_1039": "環境內容中不得有初始設定式。", "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070": "初始化 TypeScript 專案並建立 tsconfig.json 檔案。", @@ -646,6 +651,9 @@ "Invalid_use_of_0_in_strict_mode_1100": "在 strict 模式中使用 '{0}' 無效。", "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067": "'jsxFactory' 的值無效。'{0}' 不是有效的識別碼或限定名稱。", "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059": "'--reactNamespace' 的值無效。'{0}' 不是有效的識別碼。", + "Its_element_type_0_is_not_a_valid_JSX_element_2789": "其元素類型 '{0}' 不是有效的 JSX 元素。", + "Its_instance_type_0_is_not_a_valid_JSX_element_2788": "其執行個體類型 '{0}' 不是有效的 JSX 元素。", + "Its_return_type_0_is_not_a_valid_JSX_element_2787": "其傳回型別 '{0}' 不是有效的 JSX 元素。", "JSDoc_0_1_does_not_match_the_extends_2_clause_8023": "JSDoc '@{0} {1}' 不符合 'extends {2}' 子句。", "JSDoc_0_is_not_attached_to_a_class_8022": "JSDoc ''@{0}' 未連結到類別。", "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028": "JSDoc '...' 只能出現在特徵標記的最後一個參數中。", @@ -770,6 +778,7 @@ "Only_emit_d_ts_declaration_files_6014": "只發出 '.d.ts' 宣告檔案。", "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002": "類別 'extends' 子句中,目前只支援具有選擇性型別引數的識別碼/限定名稱。", "Only_named_exports_may_use_export_type_1383": "只有具名的匯出可以使用「匯出類型」。", + "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033": "只有數值列舉才可以有計算成員,但此運算式的類型為 '{0}'。若您不需要詳細檢查,請考慮改用物件常值。", "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340": "只有基底類別之公開且受保護的方法,才可透過 'super' 關鍵字存取。", "Operator_0_cannot_be_applied_to_type_1_2736": "無法將運算子 '{0}' 套用至類型 '{1}'。", "Operator_0_cannot_be_applied_to_types_1_and_2_2365": "無法將運算子 '{0}' 套用至類型 '{1}' 和 '{2}'。", @@ -793,13 +802,14 @@ "Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。", "Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'", "Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。", - "Overload_0_of_1_2_gave_the_following_error_2772": "{1} 的多載 {0},'{2}',發生下列錯誤。", + "Overload_0_of_1_2_gave_the_following_error_2772": "多載 {0} (共 {1}),'{2}',發生下列錯誤。", "Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。", "Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。", "Overload_signatures_must_all_be_exported_or_non_exported_2383": "多載簽章必須全部匯出或不匯出。", "Overload_signatures_must_all_be_optional_or_required_2386": "多載簽章都必須是選擇性或必要簽章。", "Overload_signatures_must_all_be_public_private_or_protected_2385": "多載簽章必須是公用、私用或受保護。", - "Parameter_0_cannot_be_referenced_in_its_initializer_2372": "無法在參數 '{0}' 的初始設定式中參考此參數。", + "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373": "參數 '{0}' 不得參考在其之後宣告的識別碼 '{1}'。", + "Parameter_0_cannot_reference_itself_2372": "參數 '{0}' 不得參考自身。", "Parameter_0_implicitly_has_an_1_type_7006": "參數 '{0}' 隱含了 '{1}' 類型。", "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044": "參數 '{0}' 隱含 '{1}' 類型,但可從使用方式推斷更適合的類型。", "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227": "參數 '{0}' 與參數 '{1}' 不在同一個位置。", @@ -839,7 +849,7 @@ "Prefix_0_with_an_underscore_90025": "具有底線的前置詞 '{0}'", "Prefix_all_incorrect_property_declarations_with_declare_95095": "在所有不正確屬性宣告的開頭放置 'declare'", "Prefix_all_unused_declarations_with_where_possible_95025": "若可行,為所有未使用的宣告加上前置詞 '_'", - "Prefix_with_declare_95094": "在開頭放置 'declare'", + "Prefix_with_declare_95094": "以 'declare' 開頭", "Print_names_of_files_part_of_the_compilation_6155": "列印編譯時檔案部分的名稱。", "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503": "列印屬於編譯一部分的檔案名稱,然後停止處理。", "Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。", @@ -867,7 +877,6 @@ "Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。", "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551": "類型 '{1}' 沒有屬性 '{0}'。您指的是 '{2}' 嗎?", - "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546": "屬性 '{0}' 有衝突的宣告,在類型 '{1}' 中無法存取。", "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "因為屬性 '{0}' 的 set 存取子沒有參數類型註釋,致使該屬性意味著類型 'any'。", @@ -923,9 +932,11 @@ "Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type_1205": "提供 '--isolatedModules' 旗標時,必須使用 'export type' 重新匯出類型。", "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。", + "Remove_all_incorrect_body_block_braces_95115": "移除所有不正確的主體區塊大括弧", "Remove_all_unnecessary_uses_of_await_95087": "移除所有不必要的 'await' 使用方式", "Remove_all_unreachable_code_95051": "移除所有無法連線的程式碼", "Remove_all_unused_labels_95054": "移除所有未使用的標籤", + "Remove_block_body_braces_95112": "移除區塊主體大括弧", "Remove_braces_from_arrow_function_95060": "從箭號函式移除大括號", "Remove_destructuring_90009": "移除解構", "Remove_import_from_0_90005": "從 '{0}' 移除匯入", @@ -1076,6 +1087,8 @@ "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343": "只有當 '--module' 選項為 'esnext' 或 'system' 時,才允許 'import.meta' 中繼屬性。", "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742": "'{0}' 的推斷類型無法在沒有 '{1}' 參考的情況下命名。其可能非可攜式。必須有型別註解。", "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。", + "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032": "因為屬性 '{1}' 存在於多個部分,而且在某些部分為私人性質,所以交集 '{0}' 已縮減為 'never'。", + "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031": "因為屬性 '{1}' 在某些部分有衝突的類型,所以交集 '{0}' 已縮減為 'never'。", "The_last_overload_gave_the_following_error_2770": "最後一個多載出現下列錯誤。", "The_last_overload_is_declared_here_2771": "最後一個多載宣告於此處。", "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。", @@ -1096,6 +1109,7 @@ "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011": "'delete' 運算子的運算元不可為私人識別碼。", "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704": "'delete' 運算子的運算元不可為唯讀屬性。", "The_operand_of_a_delete_operator_must_be_a_property_reference_2703": "'delete' 運算子的運算元必須為屬性參考。", + "The_operand_of_a_delete_operator_must_be_optional_2790": "'delete' 運算子的運算元必須是非必須。", "The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access_2777": "遞增或遞減運算子的運算元不可為選擇性屬性存取。", "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357": "遞增或遞減運算子的運算元必須是變數或屬性存取。", "The_parser_expected_to_find_a_to_match_the_token_here_1007": "剖析器需找到可與此處 '{' 語彙基元搭配的 '}'。", @@ -1109,7 +1123,7 @@ "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "算術運算的右側內容必須屬於 'any'、'number'、'bigint' 或列舉類型。", "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361": "'in' 運算式的右側必須是類型 'any'、物件類型或型別參數。", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "'instanceof' 運算式的右側必須是 'any' 類型,或是可指派給 'Function' 介面類型的類型。", - "The_shadowing_declaration_of_0_is_defined_here_18017": "'{0}' 的陰影宣告定義於此處", + "The_shadowing_declaration_of_0_is_defined_here_18017": "'{0}' 的隱蔽宣告定義於此處", "The_specified_path_does_not_exist_Colon_0_5058": "指定的路徑不存在: '{0}'。", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "指派的目標必須是變數或屬性存取。", "The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access_2778": "物件其餘指派的目標不可為選擇性屬性存取。", @@ -1134,6 +1148,7 @@ "This_expression_is_not_callable_2349": "無法呼叫此運算式。", "This_expression_is_not_constructable_2351": "無法建構此運算式。", "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371": "因為 'importsNotUsedAsValues' 設定為 'error',所以此匯入永遠不會作為值使用,而且必須使用 'import type'。", + "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233": "此宣告正在增加中。請考慮將正在增加的宣告移至相同的檔案中。", "This_may_be_converted_to_an_async_function_80006": "這可以轉換為非同步函式。", "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497": "只能以 ECMAScript 匯入/匯出來參考此模組,方法為開啟 '{0}' 旗標並參考其預設匯出。", "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594": "此模組使用 'export =' 宣告,而且在使用 '{0}' 旗標時,只能搭配預設匯入使用。", @@ -1158,8 +1173,8 @@ "Type_0_has_no_construct_signatures_2761": "類型 '{0}' 沒有任何建構簽章。", "Type_0_has_no_matching_index_signature_for_type_1_2537": "類型 '{0}' 沒有與類型 '{1}' 相符的索引簽章。", "Type_0_has_no_properties_in_common_with_type_1_2559": "類型 '{0}' 與類型 '{1}' 沒有任何共通的屬性。", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "類型 '{0}' 缺少類型 '{1}' 中的下列屬性: {2}", - "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "類型 '{0}' 缺少類型 '{1}' 中的下列屬性: {2},以及另外 {3} 個。", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739": "類型 '{0}' 在類型 '{1}' 中缺少下列屬性: {2}", + "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740": "類型 '{0}' 在類型 '{1}' 中缺少下列屬性: {2},以及另外 {3} 個。", "Type_0_is_not_a_constructor_function_type_2507": "類型 '{0}' 不是建構函式類型。", "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055": "類型 '{0}' 不是 ES5/ES3 中的有效非同步函式傳回型別,因為它不是指與 Promise 相容的建構函式值。", "Type_0_is_not_an_array_type_2461": "類型 '{0}' 不是陣列類型。", @@ -1196,7 +1211,7 @@ "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322": "'yield*' 運算元的反覆項目類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615": "屬性 '{0}' 的類型在對應的類型 '{1}' 中會循環參考自己。", "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321": "非同步產生器中的 'yield' 運算元類型必須是有效的 Promise,或不得包含可呼叫的 'then' 成員。", - "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "類型源自此匯入。無法呼叫或建構命名空間樣式的匯入,而且可能會在執行階段導致失敗。請考慮改用預設匯入或此處要求的匯入。", + "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038": "類型源自此匯入。無法呼叫或建構命名空間樣式的匯入,而且可能會在執行階段導致失敗。請考慮改用預設匯入或於此處匯入 require。", "Type_parameter_0_has_a_circular_constraint_2313": "類型參數 '{0}' 具有循環條件約束。", "Type_parameter_0_has_a_circular_default_2716": "型別參數 '{0}' 包含循環的預設值。", "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008": "匯出介面中呼叫簽章的型別參數 '{0}' 具有或使用私用名稱 '{1}'。", @@ -1270,17 +1285,27 @@ "Variable_declaration_expected_1134": "必須是變數宣告。", "Variable_declaration_list_cannot_be_empty_1123": "變數宣告清單不得為空白。", "Version_0_6029": "版本 {0}", + "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110": "瀏覽 https://aka.ms/tsconfig.json 以閱讀此檔案的詳細資訊", "Watch_input_files_6005": "監看輸入檔。", "Watch_option_0_requires_a_value_of_type_1_5080": "監看選項 '{0}' 需要 {1} 類型的值。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否要將已過期的主控台輸出,維持在監看模式下,而非清除螢幕。", "Wrap_all_invalid_characters_in_an_expression_container_95109": "將所有無效字元包裝在運算式容器中", + "Wrap_all_object_literal_with_parentheses_95116": "使用括弧括住所有物件常值", "Wrap_invalid_character_in_an_expression_container_95108": "包裝在運算式容器中的字元無效", + "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113": "使用括弧括住下列必須是物件常值的主體", "You_cannot_rename_a_module_via_a_global_import_8031": "您無法透過全域匯入重新命名模組。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。", "_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329": "'{0}' 在此只接受極少數的引數用為裝飾項目。要先呼叫此項目,然後再寫入 '@{0}()' 嗎?", "_0_and_1_operations_cannot_be_mixed_without_parentheses_5076": "'{0}' 與 '{1}' 作業無法在沒有括號的情況下同時使用。", "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710": "'{0}' 指定了兩次。將會覆寫名為 '{0}' 的屬性。", + "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596": "只能透過開啟 'esModuleInterop' 旗標並使用預設匯入來匯入 '{0}'。", + "_0_can_only_be_imported_by_using_a_default_import_2595": "只能使用預設匯入來匯入 '{0}'。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598": "只能使用 'require' 呼叫,或透過開啟 'esModuleInterop' 旗標並使用預設匯入,來匯入 '{0}'。", + "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597": "只能使用 'require' 呼叫或預設匯入來匯入 '{0}'。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616": "只能使用 'import {1} = require({2})' 或預設匯入來匯入 '{0}'。", + "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617": "只能使用 'import {1} = require({2})',或透過開啟 'esModuleInterop' 旗標並使用預設匯入,來匯入 '{0}'。", + "_0_cannot_be_used_as_a_JSX_component_2786": "'{0}' 不能用作 JSX 元件。", "_0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type_1362": "因為 '{0}' 是使用 'export type' 匯出的,所以無法作為值使用。", "_0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type_1361": "因為 '{0}' 是使用 'import type' 匯入的,所以無法作為值使用。", "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747": "'{0}' 元件不接受文字作為子項目。JSX 中的文字具有類型 'string',但 '{1}' 需要的類型為 '{2}'。", @@ -1350,6 +1375,7 @@ "constructor_is_a_reserved_word_18012": "'#constructor' 為保留字。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "不得在 strict 模式中對識別碼呼叫 'delete'。", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "刪除此項目 - 因為先前已建置專案 '{0}',所以其為最新狀態", + "export_Asterisk_does_not_re_export_a_default_1195": "'export *' 不會重新匯出預設值。", "export_can_only_be_used_in_TypeScript_files_8003": "'export =' 只可用於 TypeScript 檔案中。", "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾元無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。", "extends_clause_already_seen_1172": "已經有 'extends' 子句。", diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 529c5c1884e56..cb6c0c51b6d9e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -27780,7 +27780,7 @@ namespace ts { error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } - if (expr.kind === SyntaxKind.PropertyAccessExpression && isPrivateIdentifier((expr as PropertyAccessExpression).name)) { + if (expr.kind === SyntaxKind.PropertyAccessExpression && isPrivateIdentifier(expr.name)) { error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier); } const links = getNodeLinks(expr); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 8ecac56c8f93a..07613e301fa38 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4029,11 +4029,11 @@ namespace ts { } if (member.kind === SyntaxKind.GetAccessor && !getAccessor) { - getAccessor = member; + getAccessor = member; } if (member.kind === SyntaxKind.SetAccessor && !setAccessor) { - setAccessor = member; + setAccessor = member; } } } From 8d78984558b73ecb67d7437e91946a4f9500a166 Mon Sep 17 00:00:00 2001 From: Wenlu Wang Date: Thu, 7 May 2020 06:05:31 +0800 Subject: [PATCH 18/28] Add support of contextual quick info (#37451) * Add support of contextual quick info * Avoid document comment map * Make lint happy Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> --- src/services/services.ts | 22 ++++++++++++++++++ src/services/symbolDisplay.ts | 2 +- src/services/types.ts | 2 ++ tests/cases/fourslash/commentsClassMembers.ts | 12 +++++----- .../fourslash/quickInfoForGetterAndSetter.ts | 23 +++++++++++++++++++ 5 files changed, 54 insertions(+), 7 deletions(-) create mode 100644 tests/cases/fourslash/quickInfoForGetterAndSetter.ts diff --git a/src/services/services.ts b/src/services/services.ts index c0d386291a5a6..0ad6ea996e7e5 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -293,6 +293,9 @@ namespace ts { // symbol has no doc comment, then the empty array will be returned. documentationComment?: SymbolDisplayPart[]; + contextualGetAccessorDocumentationComment?: SymbolDisplayPart[]; + contextualSetAccessorDocumentationComment?: SymbolDisplayPart[]; + // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no JSDoc tags, then the empty array will be returned. tags?: JSDocTagInfo[]; @@ -330,6 +333,25 @@ namespace ts { return this.documentationComment; } + getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { + switch (context?.kind) { + case SyntaxKind.GetAccessor: + if (!this.contextualGetAccessorDocumentationComment) { + this.contextualGetAccessorDocumentationComment = emptyArray; + this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker); + } + return this.contextualGetAccessorDocumentationComment; + case SyntaxKind.SetAccessor: + if (!this.contextualSetAccessorDocumentationComment) { + this.contextualSetAccessorDocumentationComment = emptyArray; + this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker); + } + return this.contextualSetAccessorDocumentationComment; + default: + return this.getDocumentationComment(checker); + } + } + getJsDocTags(): JSDocTagInfo[] { if (this.tags === undefined) { this.tags = JsDoc.getJsDocTagsFromDeclarations(this.declarations); diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index b8122428e4196..c9af01faef896 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -502,7 +502,7 @@ namespace ts.SymbolDisplay { } if (documentation.length === 0 && !hasMultipleSignatures) { - documentation = symbol.getDocumentationComment(typeChecker); + documentation = symbol.getContextualDocumentationComment(enclosingDeclaration, typeChecker); } if (documentation.length === 0 && symbolFlags & SymbolFlags.Property) { diff --git a/src/services/types.ts b/src/services/types.ts index 24d04fb438e2f..13c68364664d8 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -41,6 +41,8 @@ namespace ts { getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; + /* @internal */ + getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] getJsDocTags(): JSDocTagInfo[]; } diff --git a/tests/cases/fourslash/commentsClassMembers.ts b/tests/cases/fourslash/commentsClassMembers.ts index 4457dc617cddc..718b9e7816e81 100644 --- a/tests/cases/fourslash/commentsClassMembers.ts +++ b/tests/cases/fourslash/commentsClassMembers.ts @@ -248,22 +248,22 @@ verify.quickInfos({ 1: ["class c1", "This is comment for c1"], 2: ["(property) c1.p1: number", "p1 is property of c1"], 3: ["(method) c1.p2(b: number): number", "sum with property"], - 6: ["(property) c1.p3: number", "getter property 1\nsetter property 1"], + 6: ["(property) c1.p3: number", "getter property 1"], "8q": ["(method) c1.p2(b: number): number", "sum with property"], - 10: ["(property) c1.p3: number", "getter property 1\nsetter property 1"], + 10: ["(property) c1.p3: number", "setter property 1"], "13q": ["(method) c1.p2(b: number): number", "sum with property"], 14: ["(property) c1.pp1: number", "pp1 is property of c1"], 15: ["(method) c1.pp2(b: number): number", "sum with property"], - 18: ["(property) c1.pp3: number", "getter property 2\nsetter property 2"], + 18: ["(property) c1.pp3: number", "getter property 2"], "20q": ["(method) c1.pp2(b: number): number", "sum with property"], - 22: ["(property) c1.pp3: number", "getter property 2\nsetter property 2"], + 22: ["(property) c1.pp3: number", "setter property 2"], "25q": ["(method) c1.pp2(b: number): number", "sum with property"], 26: ["constructor c1(): c1", "Constructor method"], 27: ["(property) c1.s1: number", "s1 is static property of c1"], 28: ["(method) c1.s2(b: number): number", "static sum with property"], - 32: ["(property) c1.s3: number", "static getter property\nsetter property 3"], + 32: ["(property) c1.s3: number", "static getter property"], "35q": ["(method) c1.s2(b: number): number", "static sum with property"], - 37: ["(property) c1.s3: number", "static getter property\nsetter property 3"], + 37: ["(property) c1.s3: number", "setter property 3"], "42q": ["(method) c1.s2(b: number): number", "static sum with property"], 43: "(property) c1.nc_p1: number", 44: "(method) c1.nc_p2(b: number): number", diff --git a/tests/cases/fourslash/quickInfoForGetterAndSetter.ts b/tests/cases/fourslash/quickInfoForGetterAndSetter.ts new file mode 100644 index 0000000000000..723836488c235 --- /dev/null +++ b/tests/cases/fourslash/quickInfoForGetterAndSetter.ts @@ -0,0 +1,23 @@ +/// + +//// class Test { +//// constructor() { +//// this.value; +//// } +//// +//// /** Getter text */ +//// get val/*1*/ue() { +//// return this.value; +//// } +//// +//// /** Setter text */ +//// set val/*2*/ue(value) { +//// this.value = value; +//// } +//// } + +goTo.marker("1"); +verify.quickInfoIs("(property) Test.value: any", "Getter text"); + +goTo.marker("2"); +verify.quickInfoIs("(property) Test.value: any", "Setter text"); From e66ce879a97c43dd2be110d6905c36ff3eca579b Mon Sep 17 00:00:00 2001 From: Wenlu Wang Date: Thu, 7 May 2020 06:06:12 +0800 Subject: [PATCH 19/28] expose jsdoc factory (#29539) * expose jsdoc factory * refactor jsdoc factory * correctly jsdoc factory types * update jsdoc factory * Add check for delete expression must be optional * accept new basseline * Revert "Add check for delete expression must be optional" This reverts commit 76937c3b1a5c3acbb3da8e449f5f88978be4eed0. * remove newline * make linter happy * Add deprecated comment Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> --- src/compiler/factoryPublic.ts | 125 +++++++++++++++--- src/services/codefixes/inferFromUsage.ts | 4 +- .../reference/api/tsserverlibrary.d.ts | 27 ++++ tests/baselines/reference/api/typescript.d.ts | 27 ++++ 4 files changed, 164 insertions(+), 19 deletions(-) diff --git a/src/compiler/factoryPublic.ts b/src/compiler/factoryPublic.ts index d78fdfc4dac3a..ac1dcbb0435a6 100644 --- a/src/compiler/factoryPublic.ts +++ b/src/compiler/factoryPublic.ts @@ -2464,53 +2464,46 @@ namespace ts { // JSDoc - /* @internal */ export function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression { const node = createSynthesizedNode(SyntaxKind.JSDocTypeExpression) as JSDocTypeExpression; node.type = type; return node; } - /* @internal */ export function createJSDocTypeTag(typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag { - const tag = createJSDocTag(SyntaxKind.JSDocTypeTag, "type"); + const tag = createJSDocTag(SyntaxKind.JSDocTypeTag, "type", comment); tag.typeExpression = typeExpression; - tag.comment = comment; return tag; } - /* @internal */ export function createJSDocReturnTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag { - const tag = createJSDocTag(SyntaxKind.JSDocReturnTag, "returns"); + const tag = createJSDocTag(SyntaxKind.JSDocReturnTag, "returns", comment); tag.typeExpression = typeExpression; - tag.comment = comment; return tag; } - /** @internal */ export function createJSDocThisTag(typeExpression?: JSDocTypeExpression): JSDocThisTag { const tag = createJSDocTag(SyntaxKind.JSDocThisTag, "this"); tag.typeExpression = typeExpression; return tag; } - /* @internal */ + /** + * @deprecated Use `createJSDocParameterTag` to create jsDoc param tag. + */ export function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag { - const tag = createJSDocTag(SyntaxKind.JSDocParameterTag, "param"); + const tag = createJSDocTag(SyntaxKind.JSDocParameterTag, "param", comment); tag.typeExpression = typeExpression; tag.name = name; tag.isBracketed = isBracketed; - tag.comment = comment; return tag; } - /* @internal */ - export function createJSDocClassTag(): JSDocClassTag { - return createJSDocTag(SyntaxKind.JSDocClassTag, "class"); + export function createJSDocClassTag(comment?: string): JSDocClassTag { + return createJSDocTag(SyntaxKind.JSDocClassTag, "class", comment); } - /* @internal */ export function createJSDocComment(comment?: string | undefined, tags?: NodeArray | undefined) { const node = createSynthesizedNode(SyntaxKind.JSDocComment) as JSDoc; node.comment = comment; @@ -2518,10 +2511,108 @@ namespace ts { return node; } - /* @internal */ - function createJSDocTag(kind: T["kind"], tagName: string): T { + export function createJSDocTag(kind: T["kind"], tagName: string, comment?: string): T { const node = createSynthesizedNode(kind) as T; node.tagName = createIdentifier(tagName); + node.comment = comment; + return node; + } + + export function createJSDocAugmentsTag(classExpression: JSDocAugmentsTag["class"], comment?: string) { + const tag = createJSDocTag(SyntaxKind.JSDocAugmentsTag, "augments", comment); + tag.class = classExpression; + return tag; + } + + export function createJSDocEnumTag(typeExpression?: JSDocTypeExpression, comment?: string) { + const tag = createJSDocTag(SyntaxKind.JSDocEnumTag, "enum", comment); + tag.typeExpression = typeExpression; + return tag; + } + + export function createJSDocTemplateTag(constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string) { + const tag = createJSDocTag(SyntaxKind.JSDocTemplateTag, "template", comment); + tag.constraint = constraint; + tag.typeParameters = asNodeArray(typeParameters); + return tag; + } + + export function createJSDocTypedefTag(fullName?: JSDocNamespaceDeclaration | Identifier, name?: Identifier, comment?: string, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral) { + const tag = createJSDocTag(SyntaxKind.JSDocTypedefTag, "typedef", comment); + tag.fullName = fullName; + tag.name = name; + tag.typeExpression = typeExpression; + return tag; + } + + export function createJSDocCallbackTag(fullName: JSDocNamespaceDeclaration | Identifier | undefined, name: Identifier | undefined, comment: string | undefined, typeExpression: JSDocSignature) { + const tag = createJSDocTag(SyntaxKind.JSDocCallbackTag, "callback", comment); + tag.fullName = fullName; + tag.name = name; + tag.typeExpression = typeExpression; + return tag; + } + + export function createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag) { + const tag = createSynthesizedNode(SyntaxKind.JSDocSignature) as JSDocSignature; + tag.typeParameters = typeParameters; + tag.parameters = parameters; + tag.type = type; + return tag; + } + + function createJSDocPropertyLikeTag(kind: T["kind"], tagName: "arg" | "argument" | "param", typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string) { + const tag = createJSDocTag(kind, tagName, comment); + tag.typeExpression = typeExpression; + tag.name = name; + tag.isNameFirst = isNameFirst; + tag.isBracketed = isBracketed; + return tag; + } + + export function createJSDocPropertyTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string) { + return createJSDocPropertyLikeTag(SyntaxKind.JSDocPropertyTag, "param", typeExpression, name, isNameFirst, isBracketed, comment); + } + + export function createJSDocParameterTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string) { + return createJSDocPropertyLikeTag(SyntaxKind.JSDocParameterTag, "param", typeExpression, name, isNameFirst, isBracketed, comment); + } + + export function createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean) { + const tag = createSynthesizedNode(SyntaxKind.JSDocTypeLiteral) as JSDocTypeLiteral; + tag.jsDocPropertyTags = jsDocPropertyTags; + tag.isArrayType = isArrayType; + return tag; + } + + export function createJSDocImplementsTag(classExpression: JSDocImplementsTag["class"], comment?: string) { + const tag = createJSDocTag(SyntaxKind.JSDocImplementsTag, "implements", comment); + tag.class = classExpression; + return tag; + } + + export function createJSDocAuthorTag(comment?: string) { + return createJSDocTag(SyntaxKind.JSDocAuthorTag, "author", comment); + } + + export function createJSDocPublicTag() { + return createJSDocTag(SyntaxKind.JSDocPublicTag, "public"); + } + + export function createJSDocPrivateTag() { + return createJSDocTag(SyntaxKind.JSDocPrivateTag, "private"); + } + + export function createJSDocProtectedTag() { + return createJSDocTag(SyntaxKind.JSDocProtectedTag, "protected"); + } + + export function createJSDocReadonlyTag() { + return createJSDocTag(SyntaxKind.JSDocReadonlyTag, "readonly"); + } + + export function appendJSDocToContainer(node: JSDocContainer, jsdoc: JSDoc) { + node.jsDoc = append(node.jsDoc, jsdoc); return node; } diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 7fa01819d2297..bf6b918086041 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -346,7 +346,7 @@ namespace ts.codefix { const typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); const name = getSynthesizedClone(param.name); setEmitFlags(name, EmitFlags.NoComments | EmitFlags.NoNestedComments); - return typeNode && createJSDocParamTag(name, !!inference.isOptional, createJSDocTypeExpression(typeNode), ""); + return typeNode && createJSDocParameterTag(createJSDocTypeExpression(typeNode), name, /* isNameFirst */ false, !!inference.isOptional, ""); }); addJSDocTags(changes, sourceFile, signature, paramTags); } @@ -382,7 +382,7 @@ namespace ts.codefix { const oldParam = oldTag as JSDocParameterTag; const newParam = newTag as JSDocParameterTag; return isIdentifier(oldParam.name) && isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText - ? createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) + ? createJSDocParameterTag(newParam.typeExpression, newParam.name, newParam.isNameFirst, newParam.isBracketed, oldParam.comment) : undefined; } case SyntaxKind.JSDocReturnTag: diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index c9c2c066f8361..b898d160f4845 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4247,6 +4247,33 @@ declare namespace ts { function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; function createExternalModuleReference(expression: Expression): ExternalModuleReference; function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression; + function createJSDocTypeTag(typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; + function createJSDocReturnTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; + function createJSDocThisTag(typeExpression?: JSDocTypeExpression): JSDocThisTag; + /** + * @deprecated Use `createJSDocParameterTag` to create jsDoc param tag. + */ + function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag; + function createJSDocClassTag(comment?: string): JSDocClassTag; + function createJSDocComment(comment?: string | undefined, tags?: NodeArray | undefined): JSDoc; + function createJSDocTag(kind: T["kind"], tagName: string, comment?: string): T; + function createJSDocAugmentsTag(classExpression: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; + function createJSDocEnumTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocEnumTag; + function createJSDocTemplateTag(constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; + function createJSDocTypedefTag(fullName?: JSDocNamespaceDeclaration | Identifier, name?: Identifier, comment?: string, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral): JSDocTypedefTag; + function createJSDocCallbackTag(fullName: JSDocNamespaceDeclaration | Identifier | undefined, name: Identifier | undefined, comment: string | undefined, typeExpression: JSDocSignature): JSDocCallbackTag; + function createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; + function createJSDocPropertyTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string): JSDocPropertyTag; + function createJSDocParameterTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string): JSDocParameterTag; + function createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; + function createJSDocImplementsTag(classExpression: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; + function createJSDocAuthorTag(comment?: string): JSDocTag; + function createJSDocPublicTag(): JSDocTag; + function createJSDocPrivateTag(): JSDocTag; + function createJSDocProtectedTag(): JSDocTag; + function createJSDocReadonlyTag(): JSDocTag; + function appendJSDocToContainer(node: JSDocContainer, jsdoc: JSDoc): JSDocContainer; function createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index e1a34cf708250..f1a808da72863 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4247,6 +4247,33 @@ declare namespace ts { function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; function createExternalModuleReference(expression: Expression): ExternalModuleReference; function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression; + function createJSDocTypeTag(typeExpression: JSDocTypeExpression, comment?: string): JSDocTypeTag; + function createJSDocReturnTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocReturnTag; + function createJSDocThisTag(typeExpression?: JSDocTypeExpression): JSDocThisTag; + /** + * @deprecated Use `createJSDocParameterTag` to create jsDoc param tag. + */ + function createJSDocParamTag(name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, comment?: string): JSDocParameterTag; + function createJSDocClassTag(comment?: string): JSDocClassTag; + function createJSDocComment(comment?: string | undefined, tags?: NodeArray | undefined): JSDoc; + function createJSDocTag(kind: T["kind"], tagName: string, comment?: string): T; + function createJSDocAugmentsTag(classExpression: JSDocAugmentsTag["class"], comment?: string): JSDocAugmentsTag; + function createJSDocEnumTag(typeExpression?: JSDocTypeExpression, comment?: string): JSDocEnumTag; + function createJSDocTemplateTag(constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string): JSDocTemplateTag; + function createJSDocTypedefTag(fullName?: JSDocNamespaceDeclaration | Identifier, name?: Identifier, comment?: string, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral): JSDocTypedefTag; + function createJSDocCallbackTag(fullName: JSDocNamespaceDeclaration | Identifier | undefined, name: Identifier | undefined, comment: string | undefined, typeExpression: JSDocSignature): JSDocCallbackTag; + function createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; + function createJSDocPropertyTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string): JSDocPropertyTag; + function createJSDocParameterTag(typeExpression: JSDocTypeExpression | undefined, name: EntityName, isNameFirst: boolean, isBracketed: boolean, comment?: string): JSDocParameterTag; + function createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; + function createJSDocImplementsTag(classExpression: JSDocImplementsTag["class"], comment?: string): JSDocImplementsTag; + function createJSDocAuthorTag(comment?: string): JSDocTag; + function createJSDocPublicTag(): JSDocTag; + function createJSDocPrivateTag(): JSDocTag; + function createJSDocProtectedTag(): JSDocTag; + function createJSDocReadonlyTag(): JSDocTag; + function appendJSDocToContainer(node: JSDocContainer, jsdoc: JSDoc): JSDocContainer; function createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; From 683b3ec058142c1b2af87775d4e99253c0884532 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 7 May 2020 01:10:02 +0300 Subject: [PATCH 20/28] feat(37782): 'declare method' quick fix for adding a private method (#37806) * feat(37782): add quick-fix action to declare a private method for names that start from underscore * better merge order in messages json Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> --- src/compiler/diagnosticMessages.json | 4 + src/services/codefixes/fixAddMissingMember.ts | 130 +++++++++--------- src/services/codefixes/helpers.ts | 8 +- ...AddMissingMember18_declarePrivateMethod.ts | 29 ++++ ...AddMissingMember19_declarePrivateMethod.ts | 29 ++++ .../fourslash/codeFixUndeclaredMethod.ts | 32 ++--- .../codeFixUndeclaredMethodFunctionArgs.ts | 7 +- ...odeFixUndeclaredMethodObjectLiteralArgs.ts | 7 +- 8 files changed, 158 insertions(+), 88 deletions(-) create mode 100644 tests/cases/fourslash/codeFixAddMissingMember18_declarePrivateMethod.ts create mode 100644 tests/cases/fourslash/codeFixAddMissingMember19_declarePrivateMethod.ts diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 47f9b792054c6..78c047a5e4a95 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -5205,6 +5205,10 @@ "category": "Message", "code": 90037 }, + "Declare private method '{0}'": { + "category": "Message", + "code": 90038 + }, "Declare a private field named '{0}'.": { "category": "Message", "code": 90053 diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index ad7b115f5742d..27c73306693f8 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -13,19 +13,15 @@ namespace ts.codefix { errorCodes, getCodeActions(context) { const info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker(), context.program); - if (!info) return undefined; - + if (!info) { + return undefined; + } if (info.kind === InfoKind.Enum) { const { token, parentDeclaration } = info; const changes = textChanges.ChangeTracker.with(context, t => addEnumMemberDeclaration(t, context.program.getTypeChecker(), token, parentDeclaration)); return [createCodeFixAction(fixName, changes, [Diagnostics.Add_missing_enum_member_0, token.text], fixId, Diagnostics.Add_all_missing_members)]; } - const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info; - const methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); - const addMember = inJs && !isInterfaceDeclaration(parentDeclaration) ? - singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); - return concatenate(singleElementArray(methodCodeAction), addMember); + return concatenate(getActionsForMissingMethodDeclaration(context, info), getActionsForMissingMemberDeclaration(context, info)); }, fixIds: [fixId], getAllCodeActions: context => { @@ -62,19 +58,18 @@ namespace ts.codefix { return !!superInfos && superInfos.some(({ token }) => token.text === info.token.text); })) continue; - const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info; - + const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; // Always prefer to add a method declaration if possible. if (call && !isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); + addMethodDeclaration(context, changes, call, token.text, modifierFlags & ModifierFlags.Static, parentDeclaration, declSourceFile, isJSFile); } else { - if (inJs && !isInterfaceDeclaration(parentDeclaration)) { - addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, makeStatic); + if (isJSFile && !isInterfaceDeclaration(parentDeclaration)) { + addMissingMemberInJs(changes, declSourceFile, parentDeclaration, token, !!(modifierFlags & ModifierFlags.Static)); } else { const typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); - addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic ? ModifierFlags.Static : 0); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, modifierFlags & ModifierFlags.Static); } } } @@ -104,12 +99,12 @@ namespace ts.codefix { } interface ClassOrInterfaceInfo { readonly kind: InfoKind.ClassOrInterface; + readonly call: CallExpression | undefined; readonly token: Identifier | PrivateIdentifier; + readonly modifierFlags: ModifierFlags; readonly parentDeclaration: ClassOrInterface; - readonly makeStatic: boolean; readonly declSourceFile: SourceFile; - readonly inJs: boolean; - readonly call: CallExpression | undefined; + readonly isJSFile: boolean; } type Info = EnumInfo | ClassOrInterfaceInfo; @@ -144,9 +139,10 @@ namespace ts.codefix { } const declSourceFile = classOrInterface.getSourceFile(); - const inJs = isSourceFileJS(declSourceFile); + const modifierFlags = (makeStatic ? ModifierFlags.Static : 0) | (startsWithUnderscore(token.text) ? ModifierFlags.Private : 0); + const isJSFile = isSourceFileJS(declSourceFile); const call = tryCast(parent.parent, isCallExpression); - return { kind: InfoKind.ClassOrInterface, token, parentDeclaration: classOrInterface, makeStatic, declSourceFile, inJs, call }; + return { kind: InfoKind.ClassOrInterface, token, call, modifierFlags, parentDeclaration: classOrInterface, declSourceFile, isJSFile }; } const enumDeclaration = find(symbol.declarations, isEnumDeclaration); @@ -156,13 +152,22 @@ namespace ts.codefix { return undefined; } - function getActionsForAddMissingMemberInJavascriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, token: Identifier | PrivateIdentifier, makeStatic: boolean): CodeFixAction | undefined { - const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, classDeclaration, token, makeStatic)); + function getActionsForMissingMemberDeclaration(context: CodeFixContext, info: ClassOrInterfaceInfo): CodeFixAction[] | undefined { + return info.isJSFile ? singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : + createActionsForAddMissingMemberInTypeScriptFile(context, info); + } + + function createActionForAddMissingMemberInJavascriptFile(context: CodeFixContext, { parentDeclaration, declSourceFile, modifierFlags, token }: ClassOrInterfaceInfo): CodeFixAction | undefined { + if (isInterfaceDeclaration(parentDeclaration)) { + return undefined; + } + + const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, parentDeclaration, token, !!(modifierFlags & ModifierFlags.Static))); if (changes.length === 0) { return undefined; } - const diagnostic = makeStatic ? Diagnostics.Initialize_static_property_0 : + const diagnostic = modifierFlags & ModifierFlags.Static ? Diagnostics.Initialize_static_property_0 : isPrivateIdentifier(token) ? Diagnostics.Declare_a_private_field_named_0 : Diagnostics.Initialize_property_0_in_the_constructor; return createCodeFixAction(fixName, changes, [diagnostic, token.text], fixId, Diagnostics.Add_all_missing_members); @@ -209,18 +214,22 @@ namespace ts.codefix { return createStatement(createAssignment(createPropertyAccess(obj, propertyName), createIdentifier("undefined"))); } - function getActionsForAddMissingMemberInTypeScriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassOrInterface, token: Identifier | PrivateIdentifier, makeStatic: boolean): CodeFixAction[] | undefined { - const typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - const actions: CodeFixAction[] = [createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, makeStatic ? ModifierFlags.Static : 0)]; - if (makeStatic || isPrivateIdentifier(token)) { + function createActionsForAddMissingMemberInTypeScriptFile(context: CodeFixContext, { parentDeclaration, declSourceFile, modifierFlags, token }: ClassOrInterfaceInfo): CodeFixAction[] | undefined { + const memberName = token.text; + const isStatic = modifierFlags & ModifierFlags.Static; + const typeNode = getTypeNode(context.program.getTypeChecker(), parentDeclaration, token); + const addPropertyDeclarationChanges = (modifierFlags: ModifierFlags) => textChanges.ChangeTracker.with(context, t => addPropertyDeclaration(t, declSourceFile, parentDeclaration, memberName, typeNode, modifierFlags)); + + const actions = [createCodeFixAction(fixName, addPropertyDeclarationChanges(modifierFlags & ModifierFlags.Static), [isStatic ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, memberName], fixId, Diagnostics.Add_all_missing_members)]; + if (isStatic || isPrivateIdentifier(token)) { return actions; } - if (startsWithUnderscore(token.text)) { - actions.unshift(createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, ModifierFlags.Private)); + if (modifierFlags & ModifierFlags.Private) { + actions.unshift(createCodeFixActionWithoutFixAll(fixName, addPropertyDeclarationChanges(ModifierFlags.Private), [Diagnostics.Declare_private_property_0, memberName])); } - actions.push(createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)); + actions.push(createAddIndexSignatureAction(context, declSourceFile, parentDeclaration, token.text, typeNode)); return actions; } @@ -239,14 +248,6 @@ namespace ts.codefix { return typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword); } - function createAddPropertyDeclarationAction(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassOrInterface, tokenName: string, typeNode: TypeNode, modifierFlags: ModifierFlags): CodeFixAction { - const changes = textChanges.ChangeTracker.with(context, t => addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags)); - if (modifierFlags & ModifierFlags.Private) { - return createCodeFixActionWithoutFixAll(fixName, changes, [Diagnostics.Declare_private_property_0, tokenName]); - } - return createCodeFixAction(fixName, changes, [modifierFlags & ModifierFlags.Static ? Diagnostics.Declare_static_property_0 : Diagnostics.Declare_property_0, tokenName], fixId, Diagnostics.Add_all_missing_members); - } - function addPropertyDeclaration(changeTracker: textChanges.ChangeTracker, declSourceFile: SourceFile, classDeclaration: ClassOrInterface, tokenName: string, typeNode: TypeNode, modifierFlags: ModifierFlags): void { const property = createProperty( /*decorators*/ undefined, @@ -297,41 +298,46 @@ namespace ts.codefix { return createCodeFixActionWithoutFixAll(fixName, changes, [Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration( - context: CodeFixContext, - declSourceFile: SourceFile, - classDeclaration: ClassOrInterface, - token: Identifier | PrivateIdentifier, - callExpression: CallExpression, - makeStatic: boolean, - inJs: boolean - ): CodeFixAction | undefined { + function getActionsForMissingMethodDeclaration(context: CodeFixContext, info: ClassOrInterfaceInfo): CodeFixAction[] | undefined { + const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; + if (call === undefined) { + return undefined; + } + // Private methods are not implemented yet. - if (isPrivateIdentifier(token)) { return undefined; } - const changes = textChanges.ChangeTracker.with(context, t => addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs)); - return createCodeFixAction(fixName, changes, [makeStatic ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, token.text], fixId, Diagnostics.Add_all_missing_members); + if (isPrivateIdentifier(token)) { + return undefined; + } + + const methodName = token.text; + const addMethodDeclarationChanges = (modifierFlags: ModifierFlags) => textChanges.ChangeTracker.with(context, t => addMethodDeclaration(context, t, call, methodName, modifierFlags, parentDeclaration, declSourceFile, isJSFile)); + const actions = [createCodeFixAction(fixName, addMethodDeclarationChanges(modifierFlags & ModifierFlags.Static), [modifierFlags & ModifierFlags.Static ? Diagnostics.Declare_static_method_0 : Diagnostics.Declare_method_0, methodName], fixId, Diagnostics.Add_all_missing_members)]; + if (modifierFlags & ModifierFlags.Private) { + actions.unshift(createCodeFixActionWithoutFixAll(fixName, addMethodDeclarationChanges(ModifierFlags.Private), [Diagnostics.Declare_private_method_0, methodName])); + } + return actions; } function addMethodDeclaration( context: CodeFixContextBase, - changeTracker: textChanges.ChangeTracker, - declSourceFile: SourceFile, - typeDecl: ClassOrInterface, - token: Identifier, + changes: textChanges.ChangeTracker, callExpression: CallExpression, - makeStatic: boolean, - inJs: boolean + methodName: string, + modifierFlags: ModifierFlags, + parentDeclaration: ClassOrInterface, + sourceFile: SourceFile, + isJSFile: boolean ): void { - const importAdder = createImportAdder(declSourceFile, context.program, context.preferences, context.host); - const methodDeclaration = createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); - const containingMethodDeclaration = getAncestor(callExpression, SyntaxKind.MethodDeclaration); - if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { - changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); + const importAdder = createImportAdder(sourceFile, context.program, context.preferences, context.host); + const methodDeclaration = createMethodFromCallExpression(context, importAdder, callExpression, methodName, modifierFlags, parentDeclaration, isJSFile); + const containingMethodDeclaration = findAncestor(callExpression, n => isMethodDeclaration(n) || isConstructorDeclaration(n)); + if (containingMethodDeclaration && containingMethodDeclaration.parent === parentDeclaration) { + changes.insertNodeAfter(sourceFile, containingMethodDeclaration, methodDeclaration); } else { - changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); + changes.insertNodeAtClassStart(sourceFile, parentDeclaration, methodDeclaration); } - importAdder.writeFixes(changeTracker); + importAdder.writeFixes(changes); } function addEnumMemberDeclaration(changes: textChanges.ChangeTracker, checker: TypeChecker, token: Identifier, enumDeclaration: EnumDeclaration) { diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 51fe5b8fad25e..4e9c3a9c5a7b7 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -214,12 +214,12 @@ namespace ts.codefix { export function createMethodFromCallExpression( context: CodeFixContextBase, + importAdder: ImportAdder, call: CallExpression, methodName: string, - inJs: boolean, - makeStatic: boolean, + modifierFlags: ModifierFlags, contextNode: Node, - importAdder: ImportAdder + inJs: boolean ): MethodDeclaration { const body = !isInterfaceDeclaration(contextNode); const { typeArguments, arguments: args, parent } = call; @@ -234,7 +234,7 @@ namespace ts.codefix { const returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); return createMethod( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, + /*modifiers*/ modifierFlags ? createNodeArray(createModifiersFromModifierFlags(modifierFlags)) : undefined, /*asteriskToken*/ isYieldExpression(parent) ? createToken(SyntaxKind.AsteriskToken) : undefined, methodName, /*questionToken*/ undefined, diff --git a/tests/cases/fourslash/codeFixAddMissingMember18_declarePrivateMethod.ts b/tests/cases/fourslash/codeFixAddMissingMember18_declarePrivateMethod.ts new file mode 100644 index 0000000000000..d0fa87d6a0d95 --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingMember18_declarePrivateMethod.ts @@ -0,0 +1,29 @@ +/// + +////class A { +//// constructor() { +//// this._foo(); +//// } +////} + +verify.codeFixAvailable([ + { description: "Declare private method '_foo'" }, + { description: "Declare method '_foo'" }, + { description: "Declare private property '_foo'" }, + { description: "Declare property '_foo'" }, + { description: "Add index signature for property '_foo'" } +]) + +verify.codeFix({ + description: [ts.Diagnostics.Declare_private_method_0.message, "_foo"], + index: 0, + newFileContent: +`class A { + constructor() { + this._foo(); + } + private _foo() { + throw new Error("Method not implemented."); + } +}` +}); diff --git a/tests/cases/fourslash/codeFixAddMissingMember19_declarePrivateMethod.ts b/tests/cases/fourslash/codeFixAddMissingMember19_declarePrivateMethod.ts new file mode 100644 index 0000000000000..72f4e27b5fe36 --- /dev/null +++ b/tests/cases/fourslash/codeFixAddMissingMember19_declarePrivateMethod.ts @@ -0,0 +1,29 @@ +/// + +////class A { +//// foo() { +//// this._bar(); +//// } +////} + +verify.codeFixAvailable([ + { description: "Declare private method '_bar'" }, + { description: "Declare method '_bar'" }, + { description: "Declare private property '_bar'" }, + { description: "Declare property '_bar'" }, + { description: "Add index signature for property '_bar'" } +]) + +verify.codeFix({ + description: [ts.Diagnostics.Declare_private_method_0.message, "_bar"], + index: 0, + newFileContent: +`class A { + foo() { + this._bar(); + } + private _bar() { + throw new Error("Method not implemented."); + } +}` +}); diff --git a/tests/cases/fourslash/codeFixUndeclaredMethod.ts b/tests/cases/fourslash/codeFixUndeclaredMethod.ts index 32713e5dd19b8..ac7a8b32b2f51 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethod.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethod.ts @@ -15,9 +15,6 @@ verify.codeFix({ index: 0, newFileContent: `class A { - foo1(arg0: number, arg1: number, arg2: number) { - throw new Error("Method not implemented."); - } constructor() { this.foo1(1,2,3); // 7 type args @@ -25,6 +22,9 @@ verify.codeFix({ // 8 type args this.foo3<1,2,3,4,5,6,7,8>(); } + foo1(arg0: number, arg1: number, arg2: number) { + throw new Error("Method not implemented."); + } }`, applyChanges: true, }); @@ -34,12 +34,6 @@ verify.codeFix({ index: 0, newFileContent: `class A { - foo2() { - throw new Error("Method not implemented."); - } - foo1(arg0: number, arg1: number, arg2: number) { - throw new Error("Method not implemented."); - } constructor() { this.foo1(1,2,3); // 7 type args @@ -47,6 +41,12 @@ verify.codeFix({ // 8 type args this.foo3<1,2,3,4,5,6,7,8>(); } + foo2() { + throw new Error("Method not implemented."); + } + foo1(arg0: number, arg1: number, arg2: number) { + throw new Error("Method not implemented."); + } }`, applyChanges: true, }); @@ -56,6 +56,13 @@ verify.codeFix({ index: 0, newFileContent: `class A { + constructor() { + this.foo1(1,2,3); + // 7 type args + this.foo2<1,2,3,4,5,6,7>(); + // 8 type args + this.foo3<1,2,3,4,5,6,7,8>(); + } foo3() { throw new Error("Method not implemented."); } @@ -65,12 +72,5 @@ verify.codeFix({ foo1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } - constructor() { - this.foo1(1,2,3); - // 7 type args - this.foo2<1,2,3,4,5,6,7>(); - // 8 type args - this.foo3<1,2,3,4,5,6,7,8>(); - } }` }); diff --git a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts index c4056625b70b9..faa5a165ace73 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts @@ -1,10 +1,11 @@ /// -//// class A {[| -//// |]constructor() { +//// class A { +//// constructor() { //// this.foo1(() => 1, () => "2", () => false); //// this.foo2((a: number) => a, (b: string) => b, (c: boolean) => c); -//// } +//// }[| +//// |] //// } verify.codeFix({ diff --git a/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts b/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts index 5c0698ad653e9..9d339c50fae04 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts @@ -1,11 +1,12 @@ /// -//// class A {[| -//// |]constructor() { +//// class A { +//// constructor() { //// this.foo1(null, {}, { a: 1, b: "2"}); //// const bar = this.foo2(null, {}, { a: 1, b: "2"}); //// const baz: number = this.foo3(null, {}, { a: 1, b: "2"}); -//// } +//// }[| +//// |] //// } verify.codeFix({ From c08b020ae9092e9c36bde847d2b12941bfd8f2cd Mon Sep 17 00:00:00 2001 From: csigs Date: Wed, 6 May 2020 22:10:57 +0000 Subject: [PATCH 21/28] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 79ab9ca04d779..aa1a21e275f13 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -4694,6 +4694,15 @@ + + + + + + + + + @@ -5144,6 +5153,15 @@ + + + + + + + + + @@ -8711,6 +8729,15 @@ + + + ']]> + + ']]> + + + + @@ -10277,11 +10304,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - Promessa global.]]> + global. Você quis escrever 'Promise<{0}>'?]]> From 05d59a1f1a408968aab7ae5dda9eef5881643cf7 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 6 May 2020 23:15:24 +0100 Subject: [PATCH 22/28] Unify logic in typeof narrowing (#33434) --- src/compiler/checker.ts | 55 +++---- .../reference/narrowingByTypeofInSwitch.js | 49 +++++- .../narrowingByTypeofInSwitch.symbols | 150 ++++++++++++------ .../reference/narrowingByTypeofInSwitch.types | 67 ++++++++ .../compiler/narrowingByTypeofInSwitch.ts | 19 ++- 5 files changed, 249 insertions(+), 91 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cb6c0c51b6d9e..0872ee38e2b35 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20806,29 +20806,8 @@ namespace ts { const facts = assumeTrue ? typeofEQFacts.get(literal.text) || TypeFacts.TypeofEQHostObject : typeofNEFacts.get(literal.text) || TypeFacts.TypeofNEHostObject; - return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); - - function narrowTypeForTypeof(type: Type) { - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(type, targetType)) { - return type; - } - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - return type; - } + const impliedType = getImpliedTypeFromTypeofGuard(type, literal.text); + return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts); } function narrowTypeBySwitchOptionalChainContainment(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number, clauseCheck: (type: Type) => boolean) { @@ -20879,19 +20858,28 @@ namespace ts { return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } - function getImpliedTypeFromTypeofCase(type: Type, text: string) { + function getImpliedTypeFromTypeofGuard(type: Type, text: string) { switch (text) { case "function": return type.flags & TypeFlags.Any ? type : globalFunctionType; case "object": return type.flags & TypeFlags.Unknown ? getUnionType([nonPrimitiveType, nullType]) : type; default: - return typeofTypesByName.get(text) || type; + return typeofTypesByName.get(text); } } - function narrowTypeForTypeofSwitch(candidate: Type) { + // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are + // super-types of the implied guard will be retained in the final type: this is because type-facts only + // filter. Instead, we would like to replace those union constituents with the more precise type implied by + // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not + // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to + // filtering by type-facts. + function narrowUnionMemberByTypeof(candidate: Type) { return (type: Type) => { + if (isTypeSubtypeOf(type, candidate)) { + return type; + } if (isTypeSubtypeOf(candidate, type)) { return candidate; } @@ -20916,11 +20904,9 @@ namespace ts { let clauseWitnesses: string[]; let switchFacts: TypeFacts; if (defaultCaseLocation > -1) { - // We no longer need the undefined denoting an - // explicit default case. Remove the undefined and - // fix-up clauseStart and clauseEnd. This means - // that we don't have to worry about undefined - // in the witness array. + // We no longer need the undefined denoting an explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means that we don't have to worry about undefined in the + // witness array. const witnesses = switchWitnesses.filter(witness => witness !== undefined); // The adjusted clause start and end after removing the `default` statement. const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; @@ -20963,11 +20949,8 @@ namespace ts { boolean. We know that number cannot be selected because it is caught in the first clause. */ - let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => getImpliedTypeFromTypeofCase(type, text))), switchFacts); - if (impliedType.flags & TypeFlags.Union) { - impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOrType(type)); - } - return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); + const impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => getImpliedTypeFromTypeofGuard(type, text) || type)), switchFacts); + return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts); } function isMatchingConstructorReference(expr: Expression) { diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.js b/tests/baselines/reference/narrowingByTypeofInSwitch.js index f2b4d26c56e54..234829a4b5aed 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.js +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.js @@ -250,6 +250,20 @@ function narrowingNarrows(x: {} | undefined) { } } +function narrowingNarrows2(x: true | 3 | 'hello' | undefined) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertNever(x); return; + case 'symbol': assertNever(x); return; + case 'object': const _: {} = assertNever(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + case 'number': assertNever(x); return; + default: const _y: {} = assertNever(x); return; + } +} + /* Template literals */ function testUnionWithTempalte(x: Basic) { @@ -298,9 +312,11 @@ function multipleGenericFuseWithBoth case 'object': return [xy, 'two']; case `number`: return [xy] } -} +} + //// [narrowingByTypeofInSwitch.js] +"use strict"; function assertNever(x) { return x; } @@ -634,6 +650,37 @@ function narrowingNarrows(x) { return; } } +function narrowingNarrows2(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertNever(x); + return; + case 'symbol': + assertNever(x); + return; + case 'object': + var _ = assertNever(x); + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + case 'number': + assertNever(x); + return; + default: + var _y = assertNever(x); + return; + } +} /* Template literals */ function testUnionWithTempalte(x) { switch (typeof x) { diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols index 052bacf17a1c6..ea1282393fca1 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols @@ -715,144 +715,192 @@ function narrowingNarrows(x: {} | undefined) { } } +function narrowingNarrows2(x: true | 3 | 'hello' | undefined) { +>narrowingNarrows2 : Symbol(narrowingNarrows2, Decl(narrowingByTypeofInSwitch.ts, 249, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'function': assertNever(x); return; +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'symbol': assertNever(x); return; +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'object': const _: {} = assertNever(x); return; +>_ : Symbol(_, Decl(narrowingByTypeofInSwitch.ts, 257, 28)) +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + case 'number': assertNever(x); return; +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + + default: const _y: {} = assertNever(x); return; +>_y : Symbol(_y, Decl(narrowingByTypeofInSwitch.ts, 261, 22)) +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 251, 27)) + } +} + /* Template literals */ function testUnionWithTempalte(x: Basic) { ->testUnionWithTempalte : Symbol(testUnionWithTempalte, Decl(narrowingByTypeofInSwitch.ts, 249, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>testUnionWithTempalte : Symbol(testUnionWithTempalte, Decl(narrowingByTypeofInSwitch.ts, 263, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) >Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 46, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `number`: assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `boolean`: assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `function`: assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `symbol`: assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `object`: assertObject(x); return; >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `string`: assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) case `undefined`: assertUndefined(x); return; >assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) } assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 253, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 267, 31)) } function fallThroughTestWithTempalte(x: string | number | boolean | object) { ->fallThroughTestWithTempalte : Symbol(fallThroughTestWithTempalte, Decl(narrowingByTypeofInSwitch.ts, 264, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>fallThroughTestWithTempalte : Symbol(fallThroughTestWithTempalte, Decl(narrowingByTypeofInSwitch.ts, 278, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) case `number`: assertNumber(x) >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) case `string`: assertStringOrNumber(x) >assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) break; default: assertObject(x); >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) case `number`: case `boolean`: assertBooleanOrObject(x); >assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 266, 37)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 280, 37)) break; } } function keyofNarrowingWithTemplate(k: keyof S) { ->keyofNarrowingWithTemplate : Symbol(keyofNarrowingWithTemplate, Decl(narrowingByTypeofInSwitch.ts, 280, 1)) ->S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 282, 36)) ->K : Symbol(K, Decl(narrowingByTypeofInSwitch.ts, 282, 49)) ->S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 282, 36)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) ->S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 282, 36)) +>keyofNarrowingWithTemplate : Symbol(keyofNarrowingWithTemplate, Decl(narrowingByTypeofInSwitch.ts, 294, 1)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 296, 36)) +>K : Symbol(K, Decl(narrowingByTypeofInSwitch.ts, 296, 49)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 296, 36)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 296, 36)) function assertKeyofS(k1: keyof S) { } ->assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 282, 87)) ->k1 : Symbol(k1, Decl(narrowingByTypeofInSwitch.ts, 283, 26)) ->S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 282, 36)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 296, 87)) +>k1 : Symbol(k1, Decl(narrowingByTypeofInSwitch.ts, 297, 26)) +>S : Symbol(S, Decl(narrowingByTypeofInSwitch.ts, 296, 36)) switch (typeof k) { ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) case `number`: assertNumber(k); assertKeyofS(k); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) ->assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 282, 87)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 296, 87)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) case `symbol`: assertSymbol(k); assertKeyofS(k); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) ->assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 282, 87)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 296, 87)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) case `string`: assertString(k); assertKeyofS(k); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) ->assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 282, 87)) ->k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 282, 74)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) +>assertKeyofS : Symbol(assertKeyofS, Decl(narrowingByTypeofInSwitch.ts, 296, 87)) +>k : Symbol(k, Decl(narrowingByTypeofInSwitch.ts, 296, 74)) } } /* Both string literals and template literals */ function multipleGenericFuseWithBoth(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { ->multipleGenericFuseWithBoth : Symbol(multipleGenericFuseWithBoth, Decl(narrowingByTypeofInSwitch.ts, 289, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 293, 37)) +>multipleGenericFuseWithBoth : Symbol(multipleGenericFuseWithBoth, Decl(narrowingByTypeofInSwitch.ts, 303, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 307, 37)) >L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 293, 58)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 307, 58)) >R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 134, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 293, 81)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 293, 37)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 293, 58)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 293, 37)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 293, 58)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 293, 37)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 293, 58)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 307, 81)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 307, 37)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 307, 58)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 307, 37)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 307, 58)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 307, 37)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 307, 58)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 293, 81)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 307, 81)) case `function`: return [xy, 1]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 293, 81)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 307, 81)) case 'object': return [xy, 'two']; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 293, 81)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 307, 81)) case `number`: return [xy] ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 293, 81)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 307, 81)) } } + diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index 90126810527f8..570f77e7a872f 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -869,6 +869,72 @@ function narrowingNarrows(x: {} | undefined) { } } +function narrowingNarrows2(x: true | 3 | 'hello' | undefined) { +>narrowingNarrows2 : (x: true | 3 | 'hello' | undefined) => void +>x : true | 3 | "hello" | undefined +>true : true + + switch (typeof x) { +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : true | 3 | "hello" | undefined + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : 3 + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : true + + case 'function': assertNever(x); return; +>'function' : "function" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + case 'symbol': assertNever(x); return; +>'symbol' : "symbol" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + case 'object': const _: {} = assertNever(x); return; +>'object' : "object" +>_ : {} +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : "hello" + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : undefined + + case 'number': assertNever(x); return; +>'number' : "number" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + default: const _y: {} = assertNever(x); return; +>_y : {} +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + } +} + /* Template literals */ function testUnionWithTempalte(x: Basic) { @@ -1042,3 +1108,4 @@ function multipleGenericFuseWithBoth >xy : (X & number) | (Y & number) } } + diff --git a/tests/cases/compiler/narrowingByTypeofInSwitch.ts b/tests/cases/compiler/narrowingByTypeofInSwitch.ts index cd726827456e3..8f6e23e1b1f9b 100644 --- a/tests/cases/compiler/narrowingByTypeofInSwitch.ts +++ b/tests/cases/compiler/narrowingByTypeofInSwitch.ts @@ -1,5 +1,4 @@ -// @strictNullChecks: true -// @strictFunctionTypes: true +// @strict: true function assertNever(x: never) { return x; @@ -252,6 +251,20 @@ function narrowingNarrows(x: {} | undefined) { } } +function narrowingNarrows2(x: true | 3 | 'hello' | undefined) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertNever(x); return; + case 'symbol': assertNever(x); return; + case 'object': const _: {} = assertNever(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + case 'number': assertNever(x); return; + default: const _y: {} = assertNever(x); return; + } +} + /* Template literals */ function testUnionWithTempalte(x: Basic) { @@ -300,4 +313,4 @@ function multipleGenericFuseWithBoth case 'object': return [xy, 'two']; case `number`: return [xy] } -} \ No newline at end of file +} From 29cf049e61fccbc237771f13be775a92a9b55f41 Mon Sep 17 00:00:00 2001 From: Eli Barzilay Date: Wed, 6 May 2020 17:23:03 -0400 Subject: [PATCH 23/28] moveToNewFile: handle namespace imports too Fixes #35591 --- src/services/refactors/moveToNewFile.ts | 1 + .../fourslash/moveToNewFile_moveNamedImport.ts | 18 ++++++++++++++++++ .../moveToNewFile_moveNamespaceImport.ts | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 tests/cases/fourslash/moveToNewFile_moveNamedImport.ts create mode 100644 tests/cases/fourslash/moveToNewFile_moveNamespaceImport.ts diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 6a9e8df6bd701..e714315f31395 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -533,6 +533,7 @@ namespace ts.refactor { case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ImportSpecifier: case SyntaxKind.ImportClause: + case SyntaxKind.NamespaceImport: return true; case SyntaxKind.VariableDeclaration: return isVariableDeclarationInImport(decl as VariableDeclaration); diff --git a/tests/cases/fourslash/moveToNewFile_moveNamedImport.ts b/tests/cases/fourslash/moveToNewFile_moveNamedImport.ts new file mode 100644 index 0000000000000..63100d05f9379 --- /dev/null +++ b/tests/cases/fourslash/moveToNewFile_moveNamedImport.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /a.ts +////import { foo as oFoo } from './other'; +////[|export const x = oFoo();|] +////export const a = 0; + +verify.moveToNewFile({ + newFileContents: { +"/a.ts": +`export const a = 0;`, + +"/x.ts": +`import { foo as oFoo } from './other'; +export const x = oFoo(); +` + }, +}); diff --git a/tests/cases/fourslash/moveToNewFile_moveNamespaceImport.ts b/tests/cases/fourslash/moveToNewFile_moveNamespaceImport.ts new file mode 100644 index 0000000000000..4d5ee7ffbf0f4 --- /dev/null +++ b/tests/cases/fourslash/moveToNewFile_moveNamespaceImport.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /a.ts +////import * as o from './other'; +////[|export const x = o.foo();|] +////export const a = 0; + +verify.moveToNewFile({ + newFileContents: { +"/a.ts": +`export const a = 0;`, + +"/x.ts": +`import * as o from './other'; +export const x = o.foo(); +` + }, +}); From 1d2414822d3d22aa74ecfa2d9dee1efb2785772e Mon Sep 17 00:00:00 2001 From: csigs Date: Thu, 7 May 2020 16:10:38 +0000 Subject: [PATCH 24/28] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- 4 files changed, 144 insertions(+), 12 deletions(-) diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 26722d697ba6b..cce62df571ccf 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3717,6 +3717,12 @@ + + + + + + @@ -4701,6 +4707,15 @@ + + + + + + + + + @@ -5151,6 +5166,15 @@ + + + + + + + + + @@ -8721,6 +8745,15 @@ + + + ']]> + + ']]> + + + + @@ -10287,11 +10320,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - 類型。]]> + 類型。是否要寫入 'Promise<{0}>'?]]> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 4cd9a262bf512..c8e1b56f03611 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3729,6 +3729,12 @@ + + + + + + @@ -4713,6 +4719,15 @@ + + + + + + + + + @@ -5163,6 +5178,15 @@ + + + + + + + + + @@ -8733,6 +8757,15 @@ + + + ']]> + + "]]> + + + + @@ -10299,11 +10332,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - global.]]> + global. ¿Pretendía escribir "Promise<{0}>"?]]> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index f4e76e9b75cff..21232d20adc9e 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3717,6 +3717,12 @@ + + + + + + @@ -4701,6 +4707,15 @@ + + + + + + + + + @@ -5151,6 +5166,15 @@ + + + + + + + + + @@ -8721,6 +8745,15 @@ + + + ']]> + + '(으)로 바꾸기]]> + + + + @@ -10287,11 +10320,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - 형식이어야 합니다.]]> + 형식이어야 합니다. 'Promise<{0}>'을(를) 쓰려고 했습니까?]]> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 6bb8f080d264f..1965a850988b9 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3707,6 +3707,12 @@ + + + + + + @@ -4691,6 +4697,15 @@ + + + + + + + + + @@ -5141,6 +5156,15 @@ + + + + + + + + + @@ -8708,6 +8732,15 @@ + + + ']]> + + ”]]> + + + + @@ -10274,11 +10307,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - .]]> + . Czy chodziło Ci o typ „Promise<{0}>”?]]> From f08863d2fcde8cbbb451be6a23e342cbd74f497e Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Thu, 7 May 2020 13:05:02 -0700 Subject: [PATCH 25/28] Update user baselines (#38128) Co-authored-by: typescript-bot --- .../reference/docker/office-ui-fabric.log | 72 ++---- tests/baselines/reference/docker/vue-next.log | 58 +++-- tests/baselines/reference/docker/xterm.js.log | 19 +- tests/baselines/reference/user/acorn.log | 3 + .../reference/user/adonis-framework.log | 1 + tests/baselines/reference/user/async.log | 8 + tests/baselines/reference/user/axios-src.log | 1 + .../user/chrome-devtools-frontend.log | 26 ++- .../reference/user/enhanced-resolve.log | 9 +- .../baselines/reference/user/graceful-fs.log | 30 +-- tests/baselines/reference/user/lodash.log | 45 ++++ tests/baselines/reference/user/npm.log | 17 ++ tests/baselines/reference/user/prettier.log | 8 + tests/baselines/reference/user/puppeteer.log | 8 - tests/baselines/reference/user/uglify-js.log | 213 +++++++++--------- tests/baselines/reference/user/webpack.log | 13 ++ 16 files changed, 325 insertions(+), 206 deletions(-) create mode 100644 tests/baselines/reference/user/prettier.log delete mode 100644 tests/baselines/reference/user/puppeteer.log diff --git a/tests/baselines/reference/docker/office-ui-fabric.log b/tests/baselines/reference/docker/office-ui-fabric.log index f83c23584273b..a130c29396c6d 100644 --- a/tests/baselines/reference/docker/office-ui-fabric.log +++ b/tests/baselines/reference/docker/office-ui-fabric.log @@ -5,62 +5,28 @@ Standard output: @fluentui/ability-attributes: > @fluentui/ability-attributes@X.X.X schema /office-ui-fabric-react/packages/fluentui/ability-attributes @fluentui/ability-attributes: > allyschema -c "process.env.NODE_ENV !== 'production'" schema.json > ./src/schema.ts @fluentui/ability-attributes: [XX:XX:XX] Requiring external module @uifabric/build/babel/register -@fluentui/ability-attributes: [XX:XX:XX] Using gulpfile /office-ui-fabric-react/packages/fluentui/ability-attributes/gulpfile.ts -@fluentui/ability-attributes: Done in ?s. -@fluentui/digest: yarn run vX.X.X -@fluentui/digest: $ just-scripts build -@fluentui/digest: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/fluentui/digest/tsconfig.json -@fluentui/digest: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --module esnext --outDir lib --project "/office-ui-fabric-react/packages/fluentui/digest/tsconfig.json" -@fluentui/digest: [XX:XX:XX XM] ■ Running Webpack -@fluentui/digest: [XX:XX:XX XM] ■ Webpack Config Path: null -@fluentui/digest: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack -@fluentui/digest: Done in ?s. -@fluentui/docs-components: yarn run vX.X.X -@fluentui/docs-components: $ gulp bundle:package:no-umd -@fluentui/docs-components: [XX:XX:XX] Requiring external module @uifabric/build/babel/register -@fluentui/docs-components: [XX:XX:XX] Using gulpfile /office-ui-fabric-react/packages/fluentui/docs-components/gulpfile.ts -@fluentui/docs-components: Done in ?s. -@uifabric/build: yarn run vX.X.X -@uifabric/build: $ node ./just-scripts.js no-op -@uifabric/build: Done in ?s. -@uifabric/example-data: yarn run vX.X.X -@uifabric/example-data: $ just-scripts build -@uifabric/example-data: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] -@uifabric/example-data: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/example-data/tsconfig.json -@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" -@uifabric/example-data: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/example-data/tsconfig.json -@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" -@uifabric/example-data: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/example-data/lib/index.d.ts' -@uifabric/example-data: Done in ?s. -@fluentui/keyboard-key: yarn run vX.X.X -@fluentui/keyboard-key: $ just-scripts build -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/keyboard-key/tsconfig.json -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/keyboard-key/tsconfig.json" -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/keyboard-key/tsconfig.json -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/keyboard-key/tsconfig.json" -@fluentui/keyboard-key: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/keyboard-key/lib/index.d.ts' -@fluentui/keyboard-key: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. +@fluentui/ability-attributes: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. Standard error: info cli using local version of lerna @fluentui/ability-attributes: npm WARN lifecycle The node binary used for scripts is but npm is using /usr/local/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with. -@uifabric/example-data: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect -@fluentui/keyboard-key: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect -@fluentui/keyboard-key: Warning: You have changed the public API signature for this project. Please copy the file "temp/keyboard-key.api.md" to "etc/keyboard-key.api.md", or perform a local build (which does this automatically). See the Git repo documentation for more info. -@fluentui/keyboard-key: [XX:XX:XX XM] x Error detected while running 'api-extractor:verify' -@fluentui/keyboard-key: [XX:XX:XX XM] x ------------------------------------ -@fluentui/keyboard-key: [XX:XX:XX XM] x Error: The public API file is out of date. Please run the API snapshot and commit the updated API file. -@fluentui/keyboard-key: at apiExtractorVerify (/office-ui-fabric-react/node_modules/just-scripts/src/tasks/apiExtractorTask.ts:73:13) -@fluentui/keyboard-key: at _wrapFunction (/office-ui-fabric-react/node_modules/just-task/lib/wrapTask.js:13:36) -@fluentui/keyboard-key: at api-extractor:verify (/office-ui-fabric-react/node_modules/undertaker/lib/set-task.js:13:15) -@fluentui/keyboard-key: at bound (domain.js:426:14) -@fluentui/keyboard-key: at runBound (domain.js:439:12) -@fluentui/keyboard-key: at asyncRunner (/office-ui-fabric-react/node_modules/async-done/index.js:55:18) -@fluentui/keyboard-key: at processTicksAndRejections (internal/process/task_queues.js:79:11) -@fluentui/keyboard-key: [XX:XX:XX XM] x ------------------------------------ -@fluentui/keyboard-key: [XX:XX:XX XM] x Error previously detected. See above for error messages. -@fluentui/keyboard-key: error Command failed with exit code 1. -lerna ERR! yarn run build exited 1 in '@fluentui/keyboard-key' +@fluentui/ability-attributes: internal/modules/cjs/loader.js:491 +@fluentui/ability-attributes: throw new ERR_PACKAGE_PATH_NOT_EXPORTED(basePath, mappingKey); +@fluentui/ability-attributes: ^ +@fluentui/ability-attributes: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in /office-ui-fabric-react/node_modules/@babel/helper-compilation-targets/package.json +@fluentui/ability-attributes: at applyExports (internal/modules/cjs/loader.js:491:9) +@fluentui/ability-attributes: at resolveExports (internal/modules/cjs/loader.js:507:23) +@fluentui/ability-attributes: at Function.Module._findPath (internal/modules/cjs/loader.js:635:31) +@fluentui/ability-attributes: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1007:27) +@fluentui/ability-attributes: at Function.Module._load (internal/modules/cjs/loader.js:890:27) +@fluentui/ability-attributes: at Module.require (internal/modules/cjs/loader.js:1080:19) +@fluentui/ability-attributes: at require (internal/modules/cjs/helpers.js:72:18) +@fluentui/ability-attributes: at Object. (/office-ui-fabric-react/node_modules/@babel/preset-env/lib/debug.js:8:33) +@fluentui/ability-attributes: at Module._compile (internal/modules/cjs/loader.js:1176:30) +@fluentui/ability-attributes: at Module._compile (/office-ui-fabric-react/node_modules/pirates/lib/index.js:99:24) { +@fluentui/ability-attributes: code: 'ERR_PACKAGE_PATH_NOT_EXPORTED' +@fluentui/ability-attributes: } +@fluentui/ability-attributes: error Command failed with exit code 1. +lerna ERR! yarn run build exited 1 in '@fluentui/ability-attributes' diff --git a/tests/baselines/reference/docker/vue-next.log b/tests/baselines/reference/docker/vue-next.log index e8186149779bb..96c3e8730f471 100644 --- a/tests/baselines/reference/docker/vue-next.log +++ b/tests/baselines/reference/docker/vue-next.log @@ -1,32 +1,37 @@ Exit Code: 0 Standard output: -> @X.X.X-beta.3 build /vue-next +> @X.X.X-beta.10 build /vue-next > node scripts/build.js "--types" Rolling up type definitions for compiler-core... Writing: /vue-next/temp/compiler-core.api.json The API report is up to date: temp/compiler-core.api.md Writing package typings: /vue-next/packages/compiler-core/dist/compiler-core.d.ts +Writing package typings: /vue-next/dist/compiler-core.d.ts API Extractor completed successfully. Rolling up type definitions for compiler-dom... Writing: /vue-next/temp/compiler-dom.api.json The API report is up to date: temp/compiler-dom.api.md Writing package typings: /vue-next/packages/compiler-dom/dist/compiler-dom.d.ts +Writing package typings: /vue-next/dist/compiler-dom.d.ts API Extractor completed successfully. Rolling up type definitions for compiler-sfc... Writing: /vue-next/temp/compiler-sfc.api.json The API report is up to date: temp/compiler-sfc.api.md Writing package typings: /vue-next/packages/compiler-sfc/dist/compiler-sfc.d.ts +Writing package typings: /vue-next/dist/compiler-sfc.d.ts API Extractor completed successfully. Rolling up type definitions for compiler-ssr... Writing: /vue-next/temp/compiler-ssr.api.json The API report is up to date: temp/compiler-ssr.api.md Writing package typings: /vue-next/packages/compiler-ssr/dist/compiler-ssr.d.ts +Writing package typings: /vue-next/dist/compiler-ssr.d.ts API Extractor completed successfully. Rolling up type definitions for reactivity... Writing: /vue-next/temp/reactivity.api.json The API report is up to date: temp/reactivity.api.md Writing package typings: /vue-next/packages/reactivity/dist/reactivity.d.ts +Writing package typings: /vue-next/dist/reactivity.d.ts API Extractor completed successfully. @@ -39,6 +44,27 @@ created packages/compiler-core/dist/compiler-core.esm-bundler.js in ?s created packages/compiler-core/dist/compiler-core.cjs.js in ?s /vue-next/packages/compiler-core/src/index.ts → packages/compiler-core/dist/compiler-core.cjs.prod.js... created packages/compiler-core/dist/compiler-core.cjs.prod.js in ?s +Warning: dist/packages/compiler-core/src/options.d.ts:36:25 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +Warning: dist/packages/compiler-core/src/options.d.ts:36:26 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +Warning: dist/packages/compiler-core/src/options.d.ts:36:19 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +Warning: dist/packages/compiler-core/src/options.d.ts:36:20 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +Warning: dist/packages/compiler-core/src/options.d.ts:36:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:52:39 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +Warning: dist/packages/compiler-core/src/options.d.ts:52:21 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +Warning: dist/packages/compiler-core/src/options.d.ts:59:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:69:42 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +Warning: dist/packages/compiler-core/src/options.d.ts:69:43 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +Warning: dist/packages/compiler-core/src/options.d.ts:69:35 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +Warning: dist/packages/compiler-core/src/options.d.ts:69:36 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +Warning: dist/packages/compiler-core/src/options.d.ts:74:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:79:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:92:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:121:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:126:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:131:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:141:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:146:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration +Warning: dist/packages/compiler-core/src/options.d.ts:152:8 - (tsdoc-undefined-tag) The TSDoc tag "@default" is not defined in this configuration /vue-next/packages/compiler-dom/src/index.ts → packages/compiler-dom/dist/compiler-dom.esm-bundler.js... created packages/compiler-dom/dist/compiler-dom.esm-bundler.js in ?s /vue-next/packages/compiler-dom/src/index.ts → packages/compiler-dom/dist/compiler-dom.esm-browser.js... @@ -54,10 +80,11 @@ created packages/compiler-dom/dist/compiler-dom.cjs.prod.js in ?s /vue-next/packages/compiler-dom/src/index.ts → packages/compiler-dom/dist/compiler-dom.global.prod.js... created packages/compiler-dom/dist/compiler-dom.global.prod.js in ?s /vue-next/packages/compiler-sfc/src/index.ts → packages/compiler-sfc/dist/compiler-sfc.cjs.js... -(!) Unresolved dependencies -https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency -url (imported by packages/compiler-sfc/src/templateUtils.ts) created packages/compiler-sfc/dist/compiler-sfc.cjs.js in ?s +/vue-next/packages/compiler-sfc/src/index.ts → packages/compiler-sfc/dist/compiler-sfc.global.js... +created packages/compiler-sfc/dist/compiler-sfc.global.js in ?s +/vue-next/packages/compiler-sfc/src/index.ts → packages/compiler-sfc/dist/compiler-sfc.esm-browser.js... +created packages/compiler-sfc/dist/compiler-sfc.esm-browser.js in ?s /vue-next/packages/compiler-ssr/src/index.ts → packages/compiler-ssr/dist/compiler-ssr.cjs.js... created packages/compiler-ssr/dist/compiler-ssr.cjs.js in ?s /vue-next/packages/reactivity/src/index.ts → packages/reactivity/dist/reactivity.esm-bundler.js... @@ -75,27 +102,26 @@ created packages/reactivity/dist/reactivity.cjs.prod.js in ?s /vue-next/packages/reactivity/src/index.ts → packages/reactivity/dist/reactivity.global.prod.js... created packages/reactivity/dist/reactivity.global.prod.js in ?s /vue-next/packages/runtime-core/src/index.ts → packages/runtime-core/dist/runtime-core.esm-bundler.js... -[!] (plugin rpt2) Error: /vue-next/packages/runtime-core/src/componentOptions.ts(182,18): semantic error TS2344: Type 'Function & T[key]["get"]' does not satisfy the constraint '(...args: any) => any'. - Type 'Function' provides no match for the signature '(...args: any): any'. -packages/runtime-core/src/componentOptions.ts -Error: /vue-next/packages/runtime-core/src/componentOptions.ts(182,18): semantic error TS2344: Type 'Function & T[key]["get"]' does not satisfy the constraint '(...args: any) => any'. - Type 'Function' provides no match for the signature '(...args: any): any'. - at error (/vue-next/node_modules/rollup/dist/shared/rollup.js:160:30) - at throwPluginError (/vue-next/node_modules/rollup/dist/shared/rollup.js:16838:12) - at Object.error (/vue-next/node_modules/rollup/dist/shared/rollup.js:17857:24) - at Object.error (/vue-next/node_modules/rollup/dist/shared/rollup.js:17011:38) +[!] (plugin rpt2) Error: /vue-next/packages/runtime-core/src/apiInject.ts(40,9): semantic error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. +packages/runtime-core/src/apiInject.ts +Error: /vue-next/packages/runtime-core/src/apiInject.ts(40,9): semantic error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. + at error (/vue-next/node_modules/rollup/dist/shared/rollup.js:161:30) + at throwPluginError (/vue-next/node_modules/rollup/dist/shared/rollup.js:16925:12) + at Object.error (/vue-next/node_modules/rollup/dist/shared/rollup.js:17944:24) + at Object.error (/vue-next/node_modules/rollup/dist/shared/rollup.js:17098:38) at RollupContext.error (/vue-next/node_modules/rollup-plugin-typescript2/src/rollupcontext.ts:37:18) at /vue-next/node_modules/rollup-plugin-typescript2/src/print-diagnostics.ts:41:11 at arrayEach (/vue-next/node_modules/rollup-plugin-typescript2/node_modules/lodash/lodash.js:516:11) at forEach (/vue-next/node_modules/rollup-plugin-typescript2/node_modules/lodash/lodash.js:9342:14) at _.each (/vue-next/node_modules/rollup-plugin-typescript2/src/print-diagnostics.ts:9:2) at Object.transform (/vue-next/node_modules/rollup-plugin-typescript2/src/index.ts:242:5) -(node:18) UnhandledPromiseRejectionWarning: Error: Command failed with exit code 1 (EPERM): rollup -c --environment COMMIT:2acf3e8,NODE_ENV:production,TARGET:runtime-core,TYPES:true +(node:17) UnhandledPromiseRejectionWarning: Error: Command failed with exit code 1 (EPERM): rollup -c --environment COMMIT:b725b63,NODE_ENV:production,TARGET:runtime-core,TYPES:true at makeError (/vue-next/node_modules/execa/lib/error.js:59:11) at handlePromise (/vue-next/node_modules/execa/index.js:112:26) at processTicksAndRejections (internal/process/task_queues.js:97:5) at async build (/vue-next/scripts/build.js:71:3) at async buildAll (/vue-next/scripts/build.js:50:5) at async run (/vue-next/scripts/build.js:40:5) -(node:18) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) -(node:18) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. +(Use `node --trace-warnings ...` to show where the warning was created) +(node:17) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) +(node:17) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. diff --git a/tests/baselines/reference/docker/xterm.js.log b/tests/baselines/reference/docker/xterm.js.log index 6024f04e09d8b..cf85e40c421e0 100644 --- a/tests/baselines/reference/docker/xterm.js.log +++ b/tests/baselines/reference/docker/xterm.js.log @@ -1,9 +1,26 @@ -Exit Code: 0 +Exit Code: 2 Standard output: > xterm@X.X.X build /xtermjs > tsc -b ./tsconfig.all.json +addons/xterm-addon-ligatures/src/font.ts(6,29): error TS2307: Cannot find module 'font-finder' or its corresponding type declarations. +addons/xterm-addon-ligatures/src/font.ts(7,32): error TS2307: Cannot find module 'font-ligatures' or its corresponding type declarations. +addons/xterm-addon-ligatures/src/index.ts(7,22): error TS2307: Cannot find module 'font-ligatures' or its corresponding type declarations. +addons/xterm-addon-ligatures/src/index.ts(75,14): error TS2347: Untyped function calls may not accept type arguments. +addons/xterm-addon-ligatures/src/index.ts(76,9): error TS7006: Parameter 'range' implicitly has an 'any' type. +addons/xterm-addon-ligatures/src/index.test.ts(7,24): error TS2307: Cannot find module 'sinon' or its corresponding type declarations. +addons/xterm-addon-ligatures/src/index.test.ts(9,29): error TS2307: Cannot find module 'font-finder' or its corresponding type declarations. +addons/xterm-addon-ligatures/src/index.test.ts(10,32): error TS2307: Cannot find module 'font-ligatures' or its corresponding type declarations. Standard error: +npm ERR! code ELIFECYCLE +npm ERR! errno 2 +npm ERR! xterm@X.X.X build: `tsc -b ./tsconfig.all.json` +npm ERR! Exit status 2 +npm ERR! +npm ERR! Failed at the xterm@X.X.X build script. +npm ERR! This is probably not a problem with npm. There is likely additional logging output above. +npm ERR! A complete log of this run can be found in: +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log diff --git a/tests/baselines/reference/user/acorn.log b/tests/baselines/reference/user/acorn.log index 7f91a604e8668..aa6f40f779829 100644 --- a/tests/baselines/reference/user/acorn.log +++ b/tests/baselines/reference/user/acorn.log @@ -275,6 +275,9 @@ node_modules/acorn/dist/acorn.js(5299,5): error TS2339: Property 'nextToken' doe node_modules/acorn/dist/acorn.js(5300,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. node_modules/acorn/dist/acorn.js(5307,10): error TS2554: Expected 3 arguments, but got 2. node_modules/acorn/dist/acorn_loose.es.js(45,12): error TS2554: Expected 3 arguments, but got 2. +node_modules/acorn/dist/acorn_loose.es.js(64,7): error TS2532: Object is possibly 'undefined'. +node_modules/acorn/dist/acorn_loose.es.js(64,23): error TS2532: Object is possibly 'undefined'. +node_modules/acorn/dist/acorn_loose.es.js(66,7): error TS2532: Object is possibly 'undefined'. node_modules/acorn/dist/acorn_loose.es.js(73,9): error TS2339: Property 'name' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,9): error TS2339: Property 'value' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,23): error TS2339: Property 'raw' does not exist on type 'Node'. diff --git a/tests/baselines/reference/user/adonis-framework.log b/tests/baselines/reference/user/adonis-framework.log index 3522aa942e68a..328b8e884d588 100644 --- a/tests/baselines/reference/user/adonis-framework.log +++ b/tests/baselines/reference/user/adonis-framework.log @@ -91,6 +91,7 @@ node_modules/adonis-framework/src/Helpers/index.js(256,45): error TS2345: Argume Type 'undefined' is not assignable to type 'string'. node_modules/adonis-framework/src/Helpers/index.js(330,23): error TS2532: Object is possibly 'undefined'. node_modules/adonis-framework/src/Middleware/index.js(13,21): error TS2307: Cannot find module 'adonis-fold' or its corresponding type declarations. +node_modules/adonis-framework/src/Middleware/index.js(87,38): error TS1016: A required parameter cannot follow an optional parameter. node_modules/adonis-framework/src/Middleware/index.js(230,20): error TS8024: JSDoc '@param' tag has name 'Middleware', but there is no parameter with that name. node_modules/adonis-framework/src/Request/index.js(64,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Request/index.js(66,15): error TS2304: Cannot find name 'Mixed'. diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 33f04aa115a09..3c9f1a23f42b6 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -96,6 +96,7 @@ node_modules/async/dist/async.js(754,49): error TS2339: Property 'process' does Property 'process' does not exist on type 'false'. node_modules/async/dist/async.js(810,45): error TS2554: Expected 0 arguments, but got 1. node_modules/async/dist/async.js(923,32): error TS2554: Expected 2 arguments, but got 1. +node_modules/async/dist/async.js(1294,27): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(1299,18): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1303,3): error TS2322: Type 'any[] | undefined' is not assignable to type 'any[]'. Type 'undefined' is not assignable to type 'any[]'. @@ -103,6 +104,7 @@ node_modules/async/dist/async.js(1509,9): error TS2322: Type 'null' is not assig node_modules/async/dist/async.js(1578,20): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/async/dist/async.js(1580,51): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1622,17): error TS2722: Cannot invoke an object which is possibly 'undefined'. +node_modules/async/dist/async.js(1681,26): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(1687,30): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1761,7): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1762,14): error TS2532: Object is possibly 'undefined'. @@ -116,6 +118,7 @@ node_modules/async/dist/async.js(1768,32): error TS2532: Object is possibly 'und node_modules/async/dist/async.js(1768,38): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1769,3): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1773,35): error TS2532: Object is possibly 'undefined'. +node_modules/async/dist/async.js(1964,30): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(1990,16): error TS2554: Expected 3 arguments, but got 1. node_modules/async/dist/async.js(2116,20): error TS2345: Argument of type 'Function | undefined' is not assignable to parameter of type 'number | undefined'. Type 'Function' is not assignable to type 'number'. @@ -154,11 +157,14 @@ node_modules/async/dist/async.js(3848,24): error TS1003: Identifier expected. node_modules/async/dist/async.js(3848,25): error TS1003: Identifier expected. node_modules/async/dist/async.js(4381,5): error TS2322: Type 'any[] | {}' is not assignable to type 'any[]'. Type '{}' is missing the following properties from type 'any[]': length, pop, push, concat, and 28 more. +node_modules/async/dist/async.js(4570,22): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(4617,17): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(4617,17): error TS2684: The 'this' context of type 'Function | undefined' is not assignable to method's 'this' of type 'Function'. Type 'undefined' is not assignable to type 'Function'. +node_modules/async/dist/async.js(4653,33): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(4931,19): error TS2339: Property 'code' does not exist on type 'Error'. node_modules/async/dist/async.js(4933,23): error TS2339: Property 'info' does not exist on type 'Error'. +node_modules/async/dist/async.js(5092,40): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/dist/async.js(5104,9): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/async/dist/async.js(5160,9): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/async/dist/async.js(5179,20): error TS2339: Property 'unmemoized' does not exist on type 'Function'. @@ -590,6 +596,7 @@ node_modules/async/reject.js(44,20): error TS2695: Left side of comma operator i node_modules/async/rejectLimit.js(36,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/rejectSeries.js(34,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/retry.js(48,12): error TS2304: Cannot find name 'AsyncFunction'. +node_modules/async/retry.js(106,22): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/retry.js(112,24): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/retry.js(119,81): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/retry.js(141,18): error TS2695: Left side of comma operator is unused and has no side effects. @@ -641,6 +648,7 @@ node_modules/async/timesLimit.js(40,28): error TS2695: Left side of comma operat node_modules/async/timesSeries.js(27,12): error TS2304: Cannot find name 'AsyncFunction'. node_modules/async/timesSeries.js(31,20): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/transform.js(43,12): error TS2304: Cannot find name 'AsyncFunction'. +node_modules/async/transform.js(72,39): error TS1016: A required parameter cannot follow an optional parameter. node_modules/async/transform.js(76,24): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/transform.js(78,17): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/transform.js(79,22): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/axios-src.log b/tests/baselines/reference/user/axios-src.log index b9e2bb30c0d7d..acfb88abfe19f 100644 --- a/tests/baselines/reference/user/axios-src.log +++ b/tests/baselines/reference/user/axios-src.log @@ -44,6 +44,7 @@ lib/core/enhanceError.js(34,26): error TS2339: Property 'columnNumber' does not lib/core/enhanceError.js(37,20): error TS2339: Property 'config' does not exist on type 'Error'. lib/core/enhanceError.js(38,18): error TS2339: Property 'code' does not exist on type 'Error'. lib/core/settle.js(20,7): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. +lib/helpers/buildURL.js(23,49): error TS1016: A required parameter cannot follow an optional parameter. lib/helpers/cookies.js(16,56): error TS2551: Property 'toGMTString' does not exist on type 'Date'. Did you mean 'toUTCString'? lib/utils.js(258,20): error TS8029: JSDoc '@param' tag has name 'obj1', but there is no parameter with that name. It would match 'arguments' if it had an array type. lib/utils.js(282,20): error TS8029: JSDoc '@param' tag has name 'obj1', but there is no parameter with that name. It would match 'arguments' if it had an array type. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 0985a9094a0e3..13e71352bb460 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -12,7 +12,7 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(270,9): error TS2322: node_modules/chrome-devtools-frontend/front_end/Runtime.js(280,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(283,12): error TS2554: Expected 2-3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/Runtime.js(525,9): error TS2322: Type 'Window' is not assignable to type 'Window & typeof globalThis'. - Type 'Window' is missing the following properties from type 'typeof globalThis': globalThis, eval, parseInt, parseFloat, and 870 more. + Type 'Window' is missing the following properties from type 'typeof globalThis': globalThis, eval, parseInt, parseFloat, and 871 more. node_modules/chrome-devtools-frontend/front_end/Runtime.js(527,49): error TS2352: Conversion of type 'Window & typeof globalThis' to type 'new () => any' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'Window & typeof globalThis' provides no match for the signature 'new (): any'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(539,24): error TS2351: This expression is not constructable. @@ -2969,9 +2969,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65285,7): error TS2339: Property 'description' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65310,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65379,1): error TS2323: Cannot redeclare exported variable '__esModule'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65468,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65533,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'entry' must be of type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }', but here has type '{ multiLine: boolean; slice: any[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: any[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(65576,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'comment' must be of type '{ multiLine: boolean; slice: any[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]', but here has type '{ multiLine: boolean; slice: number[]; range: number[]; loc: { start: { line: number; column: number; }; end: {}; }; }[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66529,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66549,1): error TS2323: Cannot redeclare exported variable '__esModule'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(66811,1): error TS2323: Cannot redeclare exported variable '__esModule'. @@ -3348,7 +3346,7 @@ node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/IsolatedFil node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js(285,12): error TS2339: Property 'onwriteend' does not exist on type 'Writer'. node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js(292,14): error TS2339: Property 'onwriteend' does not exist on type 'Writer'. node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/IsolatedFilesystemTestRunner.js(293,12): error TS2339: Property 'onwriteend' does not exist on type 'Writer'. -node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/OverridesTestRunner.js(7,13): error TS1064: The return type of an async function or method must be the global Promise type. +node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/OverridesTestRunner.js(7,13): error TS1064: The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<{ isolatedFileSystem: IsolatedFileSystem; project: Project; testFileSystem: TestFileSystem; }>'? node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(47,11): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(47,11): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(47,47): error TS2339: Property 'blankLine' does not exist on type 'void'. @@ -3718,6 +3716,9 @@ node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(567,18) node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(570,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(714,24): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(716,24): error TS2339: Property 'value' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(726,29): error TS2339: Property 'value' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(728,31): error TS2339: Property 'value' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(730,27): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(745,16): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(767,22): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/color_picker/Spectrum.js(771,60): error TS2339: Property 'value' does not exist on type 'Element'. @@ -7692,6 +7693,7 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(211,31) node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(213,16): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(213,31): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(215,39): error TS2345: Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string[]'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(229,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(254,19): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(256,35): error TS2339: Property 'metaKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(263,35): error TS2339: Property 'metaKey' does not exist on type 'Event'. @@ -8304,6 +8306,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(219,40): error TS2339: Property 'UID' does not exist on type 'ProfileNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(253,19): error TS2339: Property '_takePropertiesFromProfileDataGridNode' does not exist on type 'ProfileDataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(259,21): error TS2339: Property '_keepOnlyChild' does not exist on type 'ProfileDataGridNode'. +node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(281,21): error TS2339: Property 'remove' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(45,49): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(52,46): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? node_modules/chrome-devtools-frontend/front_end/profiler/CPUProfileFlameChart.js(54,51): error TS2551: Property '_colorGenerator' does not exist on type 'typeof ProfileFlameChartDataProvider'. Did you mean 'colorGenerator'? @@ -8507,6 +8510,7 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(107 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(113,57): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(115,48): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(192,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(206,20): error TS2339: Property 'setDataSource' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(228,60): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(229,63): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(230,64): error TS2555: Expected at least 2 arguments, but got 1. @@ -8516,17 +8520,26 @@ node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(233 node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(243,80): error TS2339: Property 'bytesToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(256,17): error TS2345: Argument of type 'ToolbarText' is not assignable to parameter of type 'ToolbarComboBox | ToolbarInput'. Type 'ToolbarText' is missing the following properties from type 'ToolbarInput': _prompt, _proxyElement, setValue, _internalSetValue, and 4 more. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(335,39): error TS2339: Property 'revealObjectByHeapSnapshotId' does not exist on type 'DataGrid'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(340,103): error TS2339: Property 'nodeFilter' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(344,50): error TS2551: Property 'jumpBackwards' does not exist on type 'SearchConfig'. Did you mean 'jumpBackward'? +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(375,37): error TS2339: Property 'revealObjectByHeapSnapshotId' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(397,25): error TS2339: Property '_loadPromise' does not exist on type 'ProfileHeader'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(405,24): error TS2345: Argument of type 'SearchConfig' is not assignable to parameter of type 'SearchConfig'. Property 'toSearchRegex' is missing in type 'SearchConfig' but required in type 'SearchConfig'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(410,20): error TS2339: Property 'filterSelectIndexChanged' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(418,24): error TS2345: Argument of type 'SearchConfig' is not assignable to parameter of type 'SearchConfig'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(434,22): error TS2339: Property 'populateContextMenu' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(451,65): error TS2339: Property 'allocationNodeId' does not exist on type 'DataGridNode'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(492,76): error TS2339: Property 'value' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(500,31): error TS2339: Property 'snapshot' does not exist on type 'DataGrid'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(507,18): error TS2339: Property 'snapshot' does not exist on type 'DataGrid'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(508,16): error TS2339: Property 'setDataSource' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(514,53): error TS2339: Property '_loadPromise' does not exist on type 'ProfileHeader'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(524,42): error TS2339: Property 'selectedOptions' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(554,24): error TS2345: Argument of type 'SearchConfig' is not assignable to parameter of type 'SearchConfig'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(559,24): error TS2694: Namespace 'Protocol' has no exported member 'HeapProfiler'. +node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(563,37): error TS2339: Property 'revealObjectByHeapSnapshotId' does not exist on type 'DataGrid'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(575,29): error TS2339: Property 'enclosingNodeOrSelfWithNodeName' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(576,28): error TS2339: Property 'enclosingNodeOrSelfWithNodeName' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/profiler/HeapSnapshotView.js(628,44): error TS2555: Expected at least 2 arguments, but got 1. @@ -12530,12 +12543,13 @@ node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(322,39): error node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(325,35): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(350,19): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(365,13): error TS2339: Property 'consume' does not exist on type 'Event'. +node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(386,57): error TS2339: Property 'lowerBound' does not exist on type 'Int32Array'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(478,39): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(500,11): error TS2403: Subsequent variable declarations must have the same type. Variable 'variableOffsets' must be of type 'any', but here has type 'Int32Array'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(523,39): error TS2339: Property 'offsetHeight' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(529,35): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(557,33): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/ui/ListControl.js(592,18): error TS2339: Property 'removeChildren' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/ui/ListModel.js(95,29): error TS2339: Property 'lowerBound' does not exist on type 'T[]'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(16,38): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(17,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/ListWidget.js(127,14): error TS2339: Property 'createChild' does not exist on type 'Element'. diff --git a/tests/baselines/reference/user/enhanced-resolve.log b/tests/baselines/reference/user/enhanced-resolve.log index 99d505ab3e334..5e221a039b24d 100644 --- a/tests/baselines/reference/user/enhanced-resolve.log +++ b/tests/baselines/reference/user/enhanced-resolve.log @@ -1,5 +1,10 @@ Exit Code: 1 Standard output: +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(120,20): error TS2532: Object is possibly 'undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(123,17): error TS2532: Object is possibly 'undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(124,3): error TS2532: Object is possibly 'undefined'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(125,23): error TS2345: Argument of type 'Set | undefined' is not assignable to parameter of type 'Set'. + Type 'undefined' is not assignable to type 'Set'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(127,18): error TS2769: No overload matches this call. Overload 1 of 2, '(intervalId: Timeout): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'. @@ -27,9 +32,7 @@ node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(202,23): error TS2322 node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(207,27): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(212,24): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(217,28): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(221,14): error TS2774: This condition will always return true since the function is always defined. Did you mean to call it instead? node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(235,4): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(239,14): error TS2774: This condition will always return true since the function is always defined. Did you mean to call it instead? node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(246,4): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(252,24): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(257,28): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. @@ -39,8 +42,6 @@ node_modules/enhanced-resolve/lib/Resolver.js(211,13): error TS2339: Property 'm node_modules/enhanced-resolve/lib/Resolver.js(262,20): error TS2339: Property 'recursion' does not exist on type 'Error'. node_modules/enhanced-resolve/lib/concord.js(80,30): error TS2531: Object is possibly 'null'. node_modules/enhanced-resolve/lib/concord.js(81,17): error TS2531: Object is possibly 'null'. -node_modules/enhanced-resolve/lib/createInnerCallback.js(22,20): error TS2339: Property 'stack' does not exist on type '(...args: any[]) => any'. -node_modules/enhanced-resolve/lib/createInnerCallback.js(23,20): error TS2339: Property 'missing' does not exist on type '(...args: any[]) => any'. diff --git a/tests/baselines/reference/user/graceful-fs.log b/tests/baselines/reference/user/graceful-fs.log index 1f60574df06d0..2e5e2bc2377b3 100644 --- a/tests/baselines/reference/user/graceful-fs.log +++ b/tests/baselines/reference/user/graceful-fs.log @@ -4,21 +4,21 @@ node_modules/graceful-fs/clone.js(12,9): error TS2403: Subsequent variable decla node_modules/graceful-fs/clone.js(15,38): error TS2345: Argument of type 'PropertyDescriptor | undefined' is not assignable to parameter of type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor'. -node_modules/graceful-fs/graceful-fs.js(26,3): error TS2322: Type '(msg: string, ...param: any[]) => void' is not assignable to type '() => void'. -node_modules/graceful-fs/graceful-fs.js(29,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. -node_modules/graceful-fs/graceful-fs.js(48,3): error TS2741: Property '__promisify__' is missing in type '(fd: any, cb: any) => void' but required in type 'typeof close'. -node_modules/graceful-fs/graceful-fs.js(70,30): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[number]'. -node_modules/graceful-fs/graceful-fs.js(82,13): error TS2554: Expected 0 arguments, but got 1. -node_modules/graceful-fs/graceful-fs.js(89,54): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. -node_modules/graceful-fs/graceful-fs.js(91,8): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. -node_modules/graceful-fs/graceful-fs.js(199,5): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(200,5): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(220,7): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(230,7): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. -node_modules/graceful-fs/graceful-fs.js(264,68): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. -node_modules/graceful-fs/graceful-fs.js(287,70): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. -node_modules/graceful-fs/graceful-fs.js(336,9): error TS2554: Expected 0 arguments, but got 3. -node_modules/graceful-fs/graceful-fs.js(343,11): error TS2554: Expected 0 arguments, but got 3. +node_modules/graceful-fs/graceful-fs.js(34,3): error TS2322: Type '(msg: string, ...param: any[]) => void' is not assignable to type '() => void'. +node_modules/graceful-fs/graceful-fs.js(37,37): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(52,3): error TS2741: Property '__promisify__' is missing in type '(fd: any, cb: any) => void' but required in type 'typeof close'. +node_modules/graceful-fs/graceful-fs.js(74,30): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[number]'. +node_modules/graceful-fs/graceful-fs.js(86,13): error TS2554: Expected 0 arguments, but got 1. +node_modules/graceful-fs/graceful-fs.js(97,54): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. +node_modules/graceful-fs/graceful-fs.js(99,8): error TS2339: Property '__patched' does not exist on type 'typeof import("fs")'. +node_modules/graceful-fs/graceful-fs.js(207,5): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(208,5): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(228,7): error TS2539: Cannot assign to 'ReadStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(238,7): error TS2539: Cannot assign to 'WriteStream' because it is not a variable. +node_modules/graceful-fs/graceful-fs.js(272,68): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(295,70): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, any?, ...any[]]'. +node_modules/graceful-fs/graceful-fs.js(344,9): error TS2554: Expected 0 arguments, but got 3. +node_modules/graceful-fs/graceful-fs.js(351,11): error TS2554: Expected 0 arguments, but got 3. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index 12bfae18700e0..ccfcf551bfe4a 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -5,28 +5,40 @@ node_modules/lodash/_ListCache.js(20,17): error TS2532: Object is possibly 'unde node_modules/lodash/_MapCache.js(20,17): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_SetCache.js(19,14): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_Stack.js(17,20): error TS2339: Property 'size' does not exist on type 'ListCache'. +node_modules/lodash/_arrayAggregator.js(11,33): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayAggregator.js(16,17): error TS2532: Object is possibly 'undefined'. +node_modules/lodash/_arrayEach.js(10,27): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayEach.js(15,18): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayEach.js(19,3): error TS2322: Type 'any[] | undefined' is not assignable to type 'any[]'. Type 'undefined' is not assignable to type 'any[]'. +node_modules/lodash/_arrayEachRight.js(10,32): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayEachRight.js(14,18): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayEachRight.js(18,3): error TS2322: Type 'any[] | undefined' is not assignable to type 'any[]'. Type 'undefined' is not assignable to type 'any[]'. +node_modules/lodash/_arrayEvery.js(11,28): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayEvery.js(16,20): error TS2532: Object is possibly 'undefined'. +node_modules/lodash/_arrayFilter.js(10,29): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayFilter.js(17,17): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayIncludes.js(9,15): error TS8024: JSDoc '@param' tag has name 'target', but there is no parameter with that name. +node_modules/lodash/_arrayIncludes.js(12,31): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayIncludes.js(14,34): error TS2345: Argument of type 'any[] | undefined' is not assignable to parameter of type 'any[]'. Type 'undefined' is not assignable to type 'any[]'. node_modules/lodash/_arrayIncludesWith.js(6,15): error TS8024: JSDoc '@param' tag has name 'target', but there is no parameter with that name. +node_modules/lodash/_arrayIncludesWith.js(10,35): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayIncludesWith.js(15,27): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayLikeKeys.js(25,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/lodash/_arrayMap.js(10,26): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayMap.js(16,30): error TS2532: Object is possibly 'undefined'. +node_modules/lodash/_arrayReduce.js(13,29): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayReduce.js(18,19): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayReduce.js(21,41): error TS2532: Object is possibly 'undefined'. +node_modules/lodash/_arrayReduceRight.js(13,34): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arrayReduceRight.js(16,19): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_arrayReduceRight.js(19,41): error TS2532: Object is possibly 'undefined'. +node_modules/lodash/_arraySome.js(11,27): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_arraySome.js(16,19): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_asciiWords.js(8,20): error TS8024: JSDoc '@param' tag has name 'The', but there is no parameter with that name. +node_modules/lodash/_baseClamp.js(10,35): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_baseClone.js(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/lodash/_baseClone.js(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/lodash/_baseClone.js(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. @@ -43,9 +55,12 @@ node_modules/lodash/_baseFlatten.js(24,22): error TS2349: This expression is not Type 'Boolean' has no call signatures. node_modules/lodash/_baseFlatten.js(24,22): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_baseFlatten.js(24,22): error TS2722: Cannot invoke an object which is possibly 'undefined'. +node_modules/lodash/_baseHas.js(15,26): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_baseHas.js(16,56): error TS2345: Argument of type 'string | any[]' is not assignable to parameter of type 'string | number | symbol'. Type 'any[]' is not assignable to type 'string | number | symbol'. Type 'any[]' is not assignable to type 'string'. +node_modules/lodash/_baseHasIn.js(9,28): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/_baseHasIn.js(10,28): error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'. node_modules/lodash/_baseIntersection.js(53,40): error TS2345: Argument of type 'Function | undefined' is not assignable to parameter of type 'Function'. Type 'undefined' is not assignable to type 'Function'. node_modules/lodash/_baseIntersection.js(60,54): error TS2345: Argument of type 'Function | undefined' is not assignable to parameter of type 'Function'. @@ -150,6 +165,7 @@ node_modules/lodash/_equalByTag.js(86,7): error TS2454: Variable 'convert' is us node_modules/lodash/_equalObjects.js(70,18): error TS2322: Type 'boolean' is not assignable to type 'number'. node_modules/lodash/_getHolder.js(10,17): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/_getRawTag.js(36,7): error TS2454: Variable 'unmasked' is used before being assigned. +node_modules/lodash/_getValue.js(9,27): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_hasPath.js(35,50): error TS2454: Variable 'key' is used before being assigned. node_modules/lodash/_hashDelete.js(7,20): error TS8024: JSDoc '@param' tag has name 'hash', but there is no parameter with that name. node_modules/lodash/_initCloneArray.js(16,20): error TS2351: This expression is not constructable. @@ -165,6 +181,7 @@ node_modules/lodash/_mergeData.js(67,26): error TS2554: Expected 4 arguments, bu node_modules/lodash/_nodeUtil.js(7,80): error TS2339: Property 'nodeType' does not exist on type '{ "\"../../../tests/cases/user/lodash/node_modules/lodash/_nodeUtil\"": any; }'. node_modules/lodash/_nodeUtil.js(13,47): error TS2339: Property 'process' does not exist on type 'false | Global'. Property 'process' does not exist on type 'false'. +node_modules/lodash/_overRest.js(15,32): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/_overRest.js(20,42): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_overRest.js(24,27): error TS2532: Object is possibly 'undefined'. node_modules/lodash/_overRest.js(27,27): error TS2532: Object is possibly 'undefined'. @@ -175,6 +192,7 @@ node_modules/lodash/_stackSet.js(24,26): error TS2339: Property 'size' does not node_modules/lodash/_unicodeWords.js(62,20): error TS8024: JSDoc '@param' tag has name 'The', but there is no parameter with that name. node_modules/lodash/_updateWrapDetails.js(34,5): error TS1223: 'returns' tag already specified. node_modules/lodash/_wrapperClone.js(14,20): error TS2339: Property 'clone' does not exist on type 'LazyWrapper'. +node_modules/lodash/ary.js(23,23): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/before.js(34,7): error TS2322: Type 'undefined' is not assignable to type 'Function'. node_modules/lodash/bind.js(51,55): error TS2454: Variable 'holders' is used before being assigned. node_modules/lodash/bind.js(55,6): error TS2339: Property 'placeholder' does not exist on type 'Function'. @@ -182,6 +200,8 @@ node_modules/lodash/bindKey.js(62,53): error TS2454: Variable 'holders' is used node_modules/lodash/bindKey.js(66,9): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/castArray.js(10,15): error TS8029: JSDoc '@param' tag has name 'value', but there is no parameter with that name. It would match 'arguments' if it had an array type. node_modules/lodash/chain.js(33,16): error TS2348: Value of type 'typeof lodash' is not callable. Did you mean to include 'new'? +node_modules/lodash/chunk.js(30,29): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/clamp.js(23,31): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/clamp.js(25,5): error TS2322: Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'. node_modules/lodash/clone.js(33,27): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean'. @@ -221,6 +241,7 @@ node_modules/lodash/core.js(1313,20): error TS2322: Type 'boolean' is not assign node_modules/lodash/core.js(1338,60): error TS2554: Expected 1 arguments, but got 2. node_modules/lodash/core.js(1349,5): error TS2322: Type 'boolean | void' is not assignable to type 'boolean'. Type 'void' is not assignable to type 'boolean'. +node_modules/lodash/core.js(1433,34): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/core.js(1434,23): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. node_modules/lodash/core.js(1438,44): error TS2532: Object is possibly 'undefined'. @@ -231,6 +252,8 @@ node_modules/lodash/core.js(1449,17): error TS2538: Type 'undefined' cannot be u node_modules/lodash/core.js(1566,57): error TS2554: Expected 1 arguments, but got 2. node_modules/lodash/core.js(1709,41): error TS2532: Object is possibly 'undefined'. node_modules/lodash/core.js(1745,18): error TS2348: Value of type 'typeof lodash' is not callable. Did you mean to include 'new'? +node_modules/lodash/core.js(1897,41): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/core.js(2167,40): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/core.js(2183,41): error TS8024: JSDoc '@param' tag has name 'iteratees', but there is no parameter with that name. node_modules/lodash/core.js(2473,21): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/lodash/core.js(2473,37): error TS2554: Expected 0 arguments, but got 1. @@ -243,6 +266,7 @@ node_modules/lodash/core.js(3424,41): error TS2769: No overload matches this cal The last overload gave the following error. Argument of type 'Function' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'Function' provides no match for the signature '(substring: string, ...args: any[]): string'. +node_modules/lodash/core.js(3562,26): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/core.js(3573,51): error TS2532: Object is possibly 'undefined'. node_modules/lodash/core.js(3590,63): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. Type 'IArguments' is missing the following properties from type 'any[]': pop, push, concat, join, and 26 more. @@ -252,7 +276,9 @@ node_modules/lodash/core.js(3830,45): error TS2304: Cannot find name 'define'. node_modules/lodash/core.js(3830,71): error TS2304: Cannot find name 'define'. node_modules/lodash/core.js(3839,5): error TS2304: Cannot find name 'define'. node_modules/lodash/core.js(3846,35): error TS2339: Property '_' does not exist on type 'typeof lodash'. +node_modules/lodash/curry.js(47,29): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/curry.js(50,10): error TS2339: Property 'placeholder' does not exist on type 'Function'. +node_modules/lodash/curryRight.js(44,34): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/curryRight.js(47,10): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/debounce.js(83,17): error TS2532: Object is possibly 'undefined'. node_modules/lodash/debounce.js(84,27): error TS2532: Object is possibly 'undefined'. @@ -270,11 +296,14 @@ node_modules/lodash/differenceBy.js(40,52): error TS2345: Argument of type '(val node_modules/lodash/differenceBy.js(40,101): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/differenceWith.js(36,52): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. +node_modules/lodash/drop.js(29,25): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/dropRight.js(29,30): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/dropRightWhile.js(41,48): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/dropWhile.js(41,48): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/escape.js(39,39): error TS2769: No overload matches this call. The last overload gave the following error. Argument of type 'Function' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. +node_modules/lodash/every.js(48,39): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/every.js(53,51): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/filter.js(45,51): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/findIndex.js(52,55): error TS2554: Expected 0-1 arguments, but got 2. @@ -336,6 +365,8 @@ node_modules/lodash/fp/object.js(2,26): error TS2345: Argument of type '{ assign node_modules/lodash/fp/seq.js(2,26): error TS2345: Argument of type '{ at: Function; chain: (value: any) => any; commit: () => any; lodash: typeof lodash; next: typeof wrapperNext; plant: (value: any) => any; reverse: () => any; tap: (value: any, interceptor: Function) => any; ... 5 more ...; wrapperChain: () => any; }' is not assignable to parameter of type 'string'. node_modules/lodash/fp/string.js(2,26): error TS2345: Argument of type '{ camelCase: Function; capitalize: (string?: string | undefined) => string; deburr: (string?: string | undefined) => string; endsWith: (string?: string | undefined, target?: string | undefined, position?: number | undefined) => boolean; ... 26 more ...; words: (string?: string | undefined, pattern?: string | ... 1 m...' is not assignable to parameter of type 'string'. node_modules/lodash/fp/util.js(2,26): error TS2345: Argument of type '{ attempt: Function; bindAll: Function; cond: (pairs: any[]) => Function; conforms: (source: any) => Function; constant: (value: any) => Function; ... 26 more ...; uniqueId: (prefix?: string | undefined) => string; }' is not assignable to parameter of type 'string'. +node_modules/lodash/inRange.js(43,33): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/includes.js(40,49): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/intersectionBy.js(41,55): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/isBuffer.js(5,69): error TS2339: Property 'nodeType' does not exist on type '() => boolean'. node_modules/lodash/isBuffer.js(8,80): error TS2339: Property 'nodeType' does not exist on type '{ "\"../../../tests/cases/user/lodash/node_modules/lodash/isBuffer\"": () => boolean; }'. @@ -356,11 +387,14 @@ node_modules/lodash/matchesProperty.js(34,56): error TS2345: Argument of type 'n node_modules/lodash/maxBy.js(30,50): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/meanBy.js(28,49): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/minBy.js(30,50): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/mixin.js(45,24): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/mixin.js(49,49): error TS2532: Object is possibly 'undefined'. node_modules/lodash/mixin.js(66,61): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. node_modules/lodash/nthArg.js(28,26): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. node_modules/lodash/omit.js(48,32): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean'. +node_modules/lodash/orderBy.js(33,49): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/parseInt.js(34,34): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/partial.js(48,9): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/partialRight.js(47,14): error TS2339: Property 'placeholder' does not exist on type 'Function'. node_modules/lodash/pickBy.js(33,12): error TS2722: Cannot invoke an object which is possibly 'undefined'. @@ -372,16 +406,23 @@ node_modules/lodash/reduce.js(48,50): error TS2554: Expected 0-1 arguments, but node_modules/lodash/reduceRight.js(33,50): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/reject.js(43,58): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/remove.js(41,39): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/repeat.js(28,28): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/replace.js(15,29): error TS8029: JSDoc '@param' tag has name 'replacement', but there is no parameter with that name. It would match 'arguments' if it had an array type. +node_modules/lodash/sampleSize.js(27,36): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/some.js(43,38): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/some.js(48,51): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/sortedIndexBy.js(30,65): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/sortedLastIndexBy.js(30,65): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/sortedUniqBy.js(22,52): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/split.js(31,24): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/split.js(33,5): error TS2322: Type 'undefined' is not assignable to type 'string | RegExp'. node_modules/lodash/spread.js(53,22): error TS2538: Type 'undefined' cannot be used as an index type. node_modules/lodash/sumBy.js(29,45): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/take.js(29,25): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/takeRight.js(29,30): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/takeRightWhile.js(41,48): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/takeWhile.js(41,48): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/template.js(140,36): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/template.js(152,34): error TS2532: Object is possibly 'undefined'. node_modules/lodash/template.js(159,21): error TS2532: Object is possibly 'undefined'. node_modules/lodash/template.js(164,6): error TS2532: Object is possibly 'undefined'. @@ -401,6 +442,9 @@ node_modules/lodash/toUpper.js(11,21): error TS8024: JSDoc '@param' tag has name node_modules/lodash/transform.js(44,37): error TS2554: Expected 0 arguments, but got 1. node_modules/lodash/transform.js(46,37): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/transform.js(60,12): error TS2722: Cannot invoke an object which is possibly 'undefined'. +node_modules/lodash/trim.js(33,30): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/trimEnd.js(29,33): error TS1016: A required parameter cannot follow an optional parameter. +node_modules/lodash/trimStart.js(29,35): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/truncate.js(60,36): error TS2532: Object is possibly 'undefined'. node_modules/lodash/truncate.js(61,26): error TS2532: Object is possibly 'undefined'. node_modules/lodash/truncate.js(62,30): error TS2532: Object is possibly 'undefined'. @@ -418,6 +462,7 @@ node_modules/lodash/unionBy.js(36,91): error TS2554: Expected 0-1 arguments, but node_modules/lodash/unionWith.js(31,42): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/uniqBy.js(28,75): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/lodash/words.js(25,33): error TS1016: A required parameter cannot follow an optional parameter. node_modules/lodash/wrapperAt.js(34,17): error TS2339: Property 'slice' does not exist on type 'LazyWrapper'. node_modules/lodash/wrapperAt.js(40,51): error TS2339: Property 'thru' does not exist on type 'LodashWrapper'. node_modules/lodash/wrapperReverse.js(33,23): error TS2339: Property 'reverse' does not exist on type 'LazyWrapper'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 4da97268ad217..85bbcfa4f142e 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -83,6 +83,7 @@ node_modules/npm/lib/cache.js(16,34): error TS2339: Property 'commands' does not node_modules/npm/lib/cache.js(49,30): error TS2339: Property 'prefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/cache.js(69,35): error TS2339: Property 'cache' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/cache.js(70,12): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/cache.js(82,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/cache.js(114,31): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/cache.js(116,22): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. @@ -143,6 +144,7 @@ node_modules/npm/lib/config/bin-links.js(26,11): error TS2339: Property 'globalD node_modules/npm/lib/config/bin-links.js(27,11): error TS2339: Property 'bin' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/bin-links.js(28,11): error TS2339: Property 'globalBin' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/bin-links.js(30,16): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/config/clear-credentials-by-uri.js(8,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/config/core.js(17,1): error TS2323: Cannot redeclare exported variable 'loaded'. node_modules/npm/lib/config/core.js(18,1): error TS2323: Cannot redeclare exported variable 'rootConf'. node_modules/npm/lib/config/core.js(19,1): error TS2323: Cannot redeclare exported variable 'usingBuiltin'. @@ -193,6 +195,7 @@ node_modules/npm/lib/config/gentle-fs.js(21,11): error TS2339: Property 'bin' do node_modules/npm/lib/config/gentle-fs.js(22,11): error TS2339: Property 'globalBin' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/gentle-fs.js(26,17): error TS2339: Property 'prefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/gentle-fs.js(27,16): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/config/get-credentials-by-uri.js(8,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/config/get-credentials-by-uri.js(26,5): error TS2322: Type 'boolean' is not assignable to type 'undefined'. node_modules/npm/lib/config/get-credentials-by-uri.js(50,5): error TS2322: Type 'string' is not assignable to type 'undefined'. node_modules/npm/lib/config/get-credentials-by-uri.js(68,5): error TS2322: Type 'string' is not assignable to type 'undefined'. @@ -248,6 +251,12 @@ node_modules/npm/lib/config/pacote.js(84,31): error TS2339: Property 'config' do node_modules/npm/lib/config/pacote.js(89,19): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/pacote.js(90,38): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/config/pacote.js(110,60): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/config/set-credentials-by-uri.js(8,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/config/set-credentials-by-uri.js(9,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/config/set-credentials-by-uri.js(20,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/config/set-credentials-by-uri.js(21,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/config/set-credentials-by-uri.js(22,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/config/set-user.js(10,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/config/set-user.js(22,18): error TS2345: Argument of type '(er: any) => any' is not assignable to parameter of type 'string | number | Options | undefined'. Value of type '(er: any) => any' has no properties in common with type 'Options'. Did you mean to call it? node_modules/npm/lib/dedupe.js(35,32): error TS2339: Property 'dir' does not exist on type 'typeof EventEmitter'. @@ -438,6 +447,7 @@ node_modules/npm/lib/install/decompose-actions.js(47,30): error TS2339: Property node_modules/npm/lib/install/deps.js(253,15): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install/deps.js(309,14): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install/deps.js(310,29): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/install/deps.js(382,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/install/deps.js(401,28): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install/deps.js(402,36): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/install/deps.js(402,64): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -932,6 +942,8 @@ node_modules/npm/lib/version.js(296,23): error TS2339: Property 'config' does no node_modules/npm/lib/version.js(297,20): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/version.js(306,20): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/version.js(324,44): error TS2339: Property 'localPrefix' does not exist on type 'typeof EventEmitter'. +node_modules/npm/lib/version.js(331,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/lib/version.js(332,3): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/lib/version.js(336,19): error TS2339: Property 'localPrefix' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/view.js(35,17): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/view.js(36,47): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. @@ -1079,6 +1091,7 @@ node_modules/npm/test/network/registry.js(5,20): error TS2307: Cannot find modul node_modules/npm/test/network/registry.js(29,47): error TS2339: Property '_extend' does not exist on type 'typeof import("util")'. node_modules/npm/test/tap/00-check-mock-dep.js(12,20): error TS2732: Cannot find module 'npm-registry-mock/package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension node_modules/npm/test/tap/00-check-mock-dep.js(13,19): error TS2732: Cannot find module '../../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension +node_modules/npm/test/tap/00-check-mock-dep.js(15,1): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/test/tap/00-verify-bundle-deps.js(1,20): error TS2307: Cannot find module 'tap' or its corresponding type declarations. node_modules/npm/test/tap/00-verify-bundle-deps.js(3,24): error TS2732: Cannot find module '../../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension node_modules/npm/test/tap/00-verify-ls-ok.js(2,20): error TS2307: Cannot find module 'tap' or its corresponding type declarations. @@ -1226,14 +1239,18 @@ node_modules/npm/test/tap/config-save.js(3,20): error TS2307: Cannot find module node_modules/npm/test/tap/correct-mkdir.js(1,20): error TS2307: Cannot find module 'tap' or its corresponding type declarations. node_modules/npm/test/tap/correct-mkdir.js(4,29): error TS2307: Cannot find module 'require-inject' or its corresponding type declarations. node_modules/npm/test/tap/correct-mkdir.js(14,23): error TS2339: Property 'uid' does not exist on type 'Process'. +node_modules/npm/test/tap/correct-mkdir.js(24,7): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +node_modules/npm/test/tap/correct-mkdir.js(70,7): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/test/tap/correct-mkdir.js(96,3): error TS2322: Type '999' is not assignable to type 'string | undefined'. node_modules/npm/test/tap/correct-mkdir.js(97,3): error TS2322: Type '999' is not assignable to type 'string | undefined'. +node_modules/npm/test/tap/correct-mkdir.js(110,7): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/test/tap/correct-mkdir.js(114,16): error TS2532: Object is possibly 'undefined'. node_modules/npm/test/tap/correct-mkdir.js(115,16): error TS2532: Object is possibly 'undefined'. node_modules/npm/test/tap/correct-mkdir.js(131,3): error TS2322: Type '999' is not assignable to type 'string | undefined'. node_modules/npm/test/tap/correct-mkdir.js(132,3): error TS2322: Type '999' is not assignable to type 'string | undefined'. node_modules/npm/test/tap/correct-mkdir.js(133,10): error TS2790: The operand of a 'delete' operator must be optional. node_modules/npm/test/tap/correct-mkdir.js(134,10): error TS2790: The operand of a 'delete' operator must be optional. +node_modules/npm/test/tap/correct-mkdir.js(145,7): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. node_modules/npm/test/tap/cruft-test.js(6,20): error TS2307: Cannot find module 'tap' or its corresponding type declarations. node_modules/npm/test/tap/debug-logs.js(3,20): error TS2307: Cannot find module 'tap' or its corresponding type declarations. node_modules/npm/test/tap/debug-logs.js(4,21): error TS2307: Cannot find module 'tacks' or its corresponding type declarations. diff --git a/tests/baselines/reference/user/prettier.log b/tests/baselines/reference/user/prettier.log new file mode 100644 index 0000000000000..0b0a30fb8b764 --- /dev/null +++ b/tests/baselines/reference/user/prettier.log @@ -0,0 +1,8 @@ +Exit Code: 1 +Standard output: +src/main/comments.js(325,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +src/main/comments.js(326,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. + + + +Standard error: diff --git a/tests/baselines/reference/user/puppeteer.log b/tests/baselines/reference/user/puppeteer.log deleted file mode 100644 index bc838695979c3..0000000000000 --- a/tests/baselines/reference/user/puppeteer.log +++ /dev/null @@ -1,8 +0,0 @@ -Exit Code: 1 -Standard output: -src/Launcher.js(181,17): error TS1003: Identifier expected. -src/Launcher.js(359,17): error TS1003: Identifier expected. - - - -Standard error: diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 87f285a8cd571..29c4a205694d6 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -15,98 +15,107 @@ node_modules/uglify-js/lib/ast.js(985,29): error TS2339: Property 'parent' does node_modules/uglify-js/lib/compress.js(163,24): error TS2554: Expected 2 arguments, but got 0. node_modules/uglify-js/lib/compress.js(188,42): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(248,18): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(536,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(877,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(882,12): error TS2339: Property 'defun_ids' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(883,12): error TS2339: Property 'defun_visited' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(885,12): error TS2339: Property 'in_loop' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(886,12): error TS2339: Property 'loop_ids' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(891,12): error TS2339: Property 'safe_ids' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(1140,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1155,51): error TS2349: This expression is not callable. +node_modules/uglify-js/lib/compress.js(533,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(874,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(879,12): error TS2339: Property 'defun_ids' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(880,12): error TS2339: Property 'defun_visited' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(882,12): error TS2339: Property 'in_loop' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(883,12): error TS2339: Property 'loop_ids' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(888,12): error TS2339: Property 'safe_ids' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(1150,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1165,51): error TS2349: This expression is not callable. Not all constituents of type 'true | ((node: any, tw: any) => any)' are callable. Type 'true' has no call signatures. -node_modules/uglify-js/lib/compress.js(1229,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1250,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1296,112): error TS2454: Variable 'args' is used before being assigned. -node_modules/uglify-js/lib/compress.js(1297,29): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(1315,29): error TS2322: Type 'false' is not assignable to type 'number'. -node_modules/uglify-js/lib/compress.js(1323,29): error TS2322: Type 'false' is not assignable to type 'never'. -node_modules/uglify-js/lib/compress.js(1471,53): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1582,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1606,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1621,46): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1652,39): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1684,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1700,39): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1797,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1828,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1950,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, (number | undefined)?]'. - Property '0' is missing in type 'number[]' but required in type '[number, (number | undefined)?]'. -node_modules/uglify-js/lib/compress.js(2281,59): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(2319,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, (number | undefined)?]'. - Property '0' is missing in type 'any[]' but required in type '[number, (number | undefined)?]'. -node_modules/uglify-js/lib/compress.js(2467,34): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(2912,35): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3256,55): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. -node_modules/uglify-js/lib/compress.js(3257,25): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/compress.js(3257,55): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. -node_modules/uglify-js/lib/compress.js(3257,56): error TS2531: Object is possibly 'null'. -node_modules/uglify-js/lib/compress.js(3298,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3377,33): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(3790,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3816,29): error TS2322: Type '"f"' is not assignable to type 'boolean'. -node_modules/uglify-js/lib/compress.js(3953,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3954,74): error TS2339: Property 'has_directive' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(4006,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4026,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(4143,63): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4273,12): error TS2339: Property 'push' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(4372,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4386,18): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4393,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(4403,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(4488,32): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4605,24): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4666,24): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4727,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. -node_modules/uglify-js/lib/compress.js(4902,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4904,55): error TS2339: Property 'loopcontrol_target' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(4908,56): error TS2339: Property 'push' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(4909,12): error TS2339: Property 'push' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(4994,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(5009,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(5118,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5120,33): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(5268,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(5361,37): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5617,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[string | RegExp, (string | undefined)?]'. +node_modules/uglify-js/lib/compress.js(1239,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1260,53): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1305,112): error TS2454: Variable 'args' is used before being assigned. +node_modules/uglify-js/lib/compress.js(1306,29): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(1331,33): error TS2322: Type 'boolean' is not assignable to type 'number'. +node_modules/uglify-js/lib/compress.js(1333,29): error TS2322: Type 'false' is not assignable to type 'never'. +node_modules/uglify-js/lib/compress.js(1481,53): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1597,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1621,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1636,46): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1667,39): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1699,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1715,39): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1815,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1846,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1970,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. + Type 'number[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 +node_modules/uglify-js/lib/compress.js(2301,59): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2339,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. + Type 'any[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 +node_modules/uglify-js/lib/compress.js(2374,26): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(2530,39): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2552,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2997,35): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3341,55): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. +node_modules/uglify-js/lib/compress.js(3342,25): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/compress.js(3342,55): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +node_modules/uglify-js/lib/compress.js(3342,56): error TS2531: Object is possibly 'null'. +node_modules/uglify-js/lib/compress.js(3383,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3462,33): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(3875,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3901,29): error TS2322: Type '"f"' is not assignable to type 'boolean'. +node_modules/uglify-js/lib/compress.js(4082,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4083,74): error TS2339: Property 'has_directive' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(4135,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4155,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4263,63): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4319,52): error TS2345: Argument of type 'any[]' is not assignable to parameter of type 'never[]'. + Type 'any' is not assignable to type 'never'. +node_modules/uglify-js/lib/compress.js(4419,12): error TS2339: Property 'push' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4524,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4538,18): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4545,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4555,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4640,32): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4757,24): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4818,24): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4879,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. +node_modules/uglify-js/lib/compress.js(4993,23): error TS2454: Variable 'exprs' is used before being assigned. +node_modules/uglify-js/lib/compress.js(4994,20): error TS2454: Variable 'exprs' is used before being assigned. +node_modules/uglify-js/lib/compress.js(5085,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(5087,55): error TS2339: Property 'loopcontrol_target' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(5091,56): error TS2339: Property 'push' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(5092,12): error TS2339: Property 'push' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(5177,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(5192,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(5302,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(5304,33): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(5469,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(5612,37): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(5672,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(5868,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[string | RegExp, (string | undefined)?]'. Property '0' is missing in type 'any[]' but required in type '[string | RegExp, (string | undefined)?]'. -node_modules/uglify-js/lib/compress.js(5775,32): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5781,45): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5788,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: (half: any) => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 23 more ...; parent: (n: any) => any; }'. -node_modules/uglify-js/lib/compress.js(5792,36): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(5797,41): error TS2339: Property 'get' does not exist on type 'string'. -node_modules/uglify-js/lib/compress.js(5834,59): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5946,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5950,21): error TS2322: Type 'null' is not assignable to type 'any[]'. -node_modules/uglify-js/lib/compress.js(5962,25): error TS2322: Type 'null' is not assignable to type 'any[]'. -node_modules/uglify-js/lib/compress.js(5974,32): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(5978,27): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(6405,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. -node_modules/uglify-js/lib/compress.js(7029,29): error TS2367: This condition will always return 'false' since the types 'boolean' and 'string' have no overlap. -node_modules/uglify-js/lib/compress.js(7071,47): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(7152,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(7224,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(7230,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(7233,41): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/compress.js(7795,43): error TS2454: Variable 'property' is used before being assigned. -node_modules/uglify-js/lib/compress.js(7810,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(7813,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. -node_modules/uglify-js/lib/compress.js(7819,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(7852,34): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/minify.js(186,42): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/minify.js(186,75): error TS2339: Property 'compress' does not exist on type 'Compressor'. +node_modules/uglify-js/lib/compress.js(6026,32): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6032,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6039,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: (half: any) => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 23 more ...; parent: (n: any) => any; }'. +node_modules/uglify-js/lib/compress.js(6043,36): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(6048,41): error TS2339: Property 'get' does not exist on type 'string'. +node_modules/uglify-js/lib/compress.js(6085,59): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6197,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6201,21): error TS2322: Type 'null' is not assignable to type 'any[]'. +node_modules/uglify-js/lib/compress.js(6208,25): error TS2322: Type 'null' is not assignable to type 'any[]'. +node_modules/uglify-js/lib/compress.js(6217,25): error TS2322: Type 'null' is not assignable to type 'any[]'. +node_modules/uglify-js/lib/compress.js(6229,32): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(6233,27): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(6452,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6723,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. +node_modules/uglify-js/lib/compress.js(7347,29): error TS2367: This condition will always return 'false' since the types 'boolean' and 'string' have no overlap. +node_modules/uglify-js/lib/compress.js(7389,47): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(7470,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(7542,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(7548,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(7551,41): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/compress.js(8114,43): error TS2454: Variable 'property' is used before being assigned. +node_modules/uglify-js/lib/compress.js(8129,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(8132,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. +node_modules/uglify-js/lib/compress.js(8138,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(8171,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/minify.js(185,42): error TS2554: Expected 2 arguments, but got 1. +node_modules/uglify-js/lib/minify.js(185,75): error TS2339: Property 'compress' does not exist on type 'Compressor'. node_modules/uglify-js/lib/mozilla-ast.js(566,33): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(459,37): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/output.js(460,33): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. @@ -130,7 +139,6 @@ node_modules/uglify-js/lib/parse.js(811,21): error TS2531: Object is possibly 'n node_modules/uglify-js/lib/parse.js(830,21): error TS2531: Object is possibly 'null'. node_modules/uglify-js/lib/parse.js(945,23): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. node_modules/uglify-js/lib/parse.js(1061,9): error TS2322: Type 'any[]' is not assignable to type 'never[]'. - Type 'any' is not assignable to type 'never'. node_modules/uglify-js/lib/parse.js(1118,17): error TS2531: Object is possibly 'null'. node_modules/uglify-js/lib/parse.js(1288,32): error TS2531: Object is possibly 'null'. node_modules/uglify-js/lib/parse.js(1388,20): error TS2531: Object is possibly 'null'. @@ -147,20 +155,19 @@ node_modules/uglify-js/lib/propmangle.js(94,30): error TS2554: Expected 0 argume node_modules/uglify-js/lib/propmangle.js(146,29): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/propmangle.js(163,26): error TS2554: Expected 2 arguments, but got 1. node_modules/uglify-js/lib/propmangle.js(221,31): error TS2554: Expected 2 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(89,21): error TS2339: Property 'defun' does not exist on type 'SymbolDef'. -node_modules/uglify-js/lib/scope.js(89,35): error TS2339: Property 'defun' does not exist on type 'SymbolDef'. -node_modules/uglify-js/lib/scope.js(103,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(158,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(172,33): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/scope.js(198,47): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(248,17): error TS2554: Expected 3 arguments, but got 2. -node_modules/uglify-js/lib/scope.js(428,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(441,49): error TS2339: Property 'has_directive' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/scope.js(496,30): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/scope.js(521,30): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(87,21): error TS2339: Property 'defun' does not exist on type 'SymbolDef'. +node_modules/uglify-js/lib/scope.js(87,35): error TS2339: Property 'defun' does not exist on type 'SymbolDef'. +node_modules/uglify-js/lib/scope.js(101,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(157,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(171,33): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/scope.js(197,47): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(433,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(446,49): error TS2339: Property 'has_directive' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/scope.js(501,30): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/scope.js(526,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/sourcemap.js(82,11): error TS2339: Property 'index' does not exist on type 'any[]'. -node_modules/uglify-js/lib/sourcemap.js(177,31): error TS2339: Property 'index' does not exist on type 'any[]'. -node_modules/uglify-js/lib/sourcemap.js(185,34): error TS2339: Property 'index' does not exist on type 'any[]'. +node_modules/uglify-js/lib/sourcemap.js(178,31): error TS2339: Property 'index' does not exist on type 'any[]'. +node_modules/uglify-js/lib/sourcemap.js(186,34): error TS2339: Property 'index' does not exist on type 'any[]'. node_modules/uglify-js/tools/exit.js(10,37): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[(number | undefined)?]'. Types of property 'length' are incompatible. Type 'number' is not assignable to type '0 | 1'. diff --git a/tests/baselines/reference/user/webpack.log b/tests/baselines/reference/user/webpack.log index 4b4f3e5ad7eb9..5d41ba369c9c8 100644 --- a/tests/baselines/reference/user/webpack.log +++ b/tests/baselines/reference/user/webpack.log @@ -1,9 +1,22 @@ Exit Code: 1 Standard output: +lib/AbstractMethodError.js(26,16): error TS2532: Object is possibly 'undefined'. +lib/ContextModule.js(333,29): error TS2345: Argument of type 'Error' is not assignable to parameter of type 'WebpackError'. + Type 'Error' is missing the following properties from type 'WebpackError': details, module, loc, hideStack, and 4 more. lib/ExternalModule.js(305,28): error TS2554: Expected 1 arguments, but got 0. +lib/MainTemplate.js(40,29): error TS1016: A required parameter cannot follow an optional parameter. +lib/ModuleGraphConnection.js(23,3): error TS1016: A required parameter cannot follow an optional parameter. lib/Stats.js(68,31): error TS2554: Expected 3 arguments, but got 2. +lib/config/normalization.js(27,30): error TS1016: A required parameter cannot follow an optional parameter. +lib/config/normalization.js(37,38): error TS1016: A required parameter cannot follow an optional parameter. +lib/config/normalization.js(47,29): error TS1016: A required parameter cannot follow an optional parameter. +lib/config/normalization.js(56,37): error TS1016: A required parameter cannot follow an optional parameter. lib/library/SystemLibraryPlugin.js(127,35): error TS2554: Expected 1 arguments, but got 0. +lib/library/UmdLibraryPlugin.js(38,31): error TS1016: A required parameter cannot follow an optional parameter. lib/optimize/ConcatenatedModule.js(205,32): error TS2554: Expected 1 arguments, but got 0. +lib/util/fs.js(57,23): error TS1016: A required parameter cannot follow an optional parameter. +lib/util/fs.js(78,19): error TS1016: A required parameter cannot follow an optional parameter. +lib/util/fs.js(98,22): error TS1016: A required parameter cannot follow an optional parameter. lib/wasm-async/AsyncWebAssemblyModulesPlugin.js(36,15): error TS2304: Cannot find name 'Chunk'. lib/wasm-async/AsyncWebAssemblyModulesPlugin.js(37,15): error TS2304: Cannot find name 'DependencyTemplates'. lib/wasm-async/AsyncWebAssemblyModulesPlugin.js(38,15): error TS2304: Cannot find name 'RuntimeTemplate'. From 7798f532dfdabe2976d812d8bfebde60fa719f13 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 7 May 2020 14:05:57 -0700 Subject: [PATCH 26/28] Fix crash caused by assertion with evolving array type (#38398) * Properly finalize evolving array type in getTypeAtFlowCall * Add regression test --- src/compiler/checker.ts | 2 +- .../reference/evolvingArrayTypeInAssert.js | 23 +++++++++++++++ .../evolvingArrayTypeInAssert.symbols | 27 ++++++++++++++++++ .../reference/evolvingArrayTypeInAssert.types | 28 +++++++++++++++++++ .../compiler/evolvingArrayTypeInAssert.ts | 10 +++++++ 5 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/evolvingArrayTypeInAssert.js create mode 100644 tests/baselines/reference/evolvingArrayTypeInAssert.symbols create mode 100644 tests/baselines/reference/evolvingArrayTypeInAssert.types create mode 100644 tests/cases/compiler/evolvingArrayTypeInAssert.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0872ee38e2b35..e60afaeca667f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -20360,7 +20360,7 @@ namespace ts { const predicate = getTypePredicateOfSignature(signature); if (predicate && (predicate.kind === TypePredicateKind.AssertsThis || predicate.kind === TypePredicateKind.AssertsIdentifier)) { const flowType = getTypeAtFlowNode(flow.antecedent); - const type = getTypeFromFlowType(flowType); + const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType)); const narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : predicate.kind === TypePredicateKind.AssertsIdentifier && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; diff --git a/tests/baselines/reference/evolvingArrayTypeInAssert.js b/tests/baselines/reference/evolvingArrayTypeInAssert.js new file mode 100644 index 0000000000000..498bfc283cca6 --- /dev/null +++ b/tests/baselines/reference/evolvingArrayTypeInAssert.js @@ -0,0 +1,23 @@ +//// [evolvingArrayTypeInAssert.ts] +export function unsafeCast(_value: unknown): asserts _value is T { } + +function yadda() { + let out = []; + out.push(100) + unsafeCast(out); + return out; +} + + +//// [evolvingArrayTypeInAssert.js] +"use strict"; +exports.__esModule = true; +exports.unsafeCast = void 0; +function unsafeCast(_value) { } +exports.unsafeCast = unsafeCast; +function yadda() { + var out = []; + out.push(100); + unsafeCast(out); + return out; +} diff --git a/tests/baselines/reference/evolvingArrayTypeInAssert.symbols b/tests/baselines/reference/evolvingArrayTypeInAssert.symbols new file mode 100644 index 0000000000000..19e8c741f0cbd --- /dev/null +++ b/tests/baselines/reference/evolvingArrayTypeInAssert.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/evolvingArrayTypeInAssert.ts === +export function unsafeCast(_value: unknown): asserts _value is T { } +>unsafeCast : Symbol(unsafeCast, Decl(evolvingArrayTypeInAssert.ts, 0, 0)) +>T : Symbol(T, Decl(evolvingArrayTypeInAssert.ts, 0, 27)) +>_value : Symbol(_value, Decl(evolvingArrayTypeInAssert.ts, 0, 30)) +>_value : Symbol(_value, Decl(evolvingArrayTypeInAssert.ts, 0, 30)) +>T : Symbol(T, Decl(evolvingArrayTypeInAssert.ts, 0, 27)) + +function yadda() { +>yadda : Symbol(yadda, Decl(evolvingArrayTypeInAssert.ts, 0, 71)) + + let out = []; +>out : Symbol(out, Decl(evolvingArrayTypeInAssert.ts, 3, 7)) + + out.push(100) +>out.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) +>out : Symbol(out, Decl(evolvingArrayTypeInAssert.ts, 3, 7)) +>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) + + unsafeCast(out); +>unsafeCast : Symbol(unsafeCast, Decl(evolvingArrayTypeInAssert.ts, 0, 0)) +>out : Symbol(out, Decl(evolvingArrayTypeInAssert.ts, 3, 7)) + + return out; +>out : Symbol(out, Decl(evolvingArrayTypeInAssert.ts, 3, 7)) +} + diff --git a/tests/baselines/reference/evolvingArrayTypeInAssert.types b/tests/baselines/reference/evolvingArrayTypeInAssert.types new file mode 100644 index 0000000000000..bcd9e5cfdd0cc --- /dev/null +++ b/tests/baselines/reference/evolvingArrayTypeInAssert.types @@ -0,0 +1,28 @@ +=== tests/cases/compiler/evolvingArrayTypeInAssert.ts === +export function unsafeCast(_value: unknown): asserts _value is T { } +>unsafeCast : (_value: unknown) => asserts _value is T +>_value : unknown + +function yadda() { +>yadda : () => number[] + + let out = []; +>out : any[] +>[] : never[] + + out.push(100) +>out.push(100) : number +>out.push : (...items: any[]) => number +>out : any[] +>push : (...items: any[]) => number +>100 : 100 + + unsafeCast(out); +>unsafeCast(out) : void +>unsafeCast : (_value: unknown) => asserts _value is T +>out : number[] + + return out; +>out : number[] +} + diff --git a/tests/cases/compiler/evolvingArrayTypeInAssert.ts b/tests/cases/compiler/evolvingArrayTypeInAssert.ts new file mode 100644 index 0000000000000..b56ba244808b3 --- /dev/null +++ b/tests/cases/compiler/evolvingArrayTypeInAssert.ts @@ -0,0 +1,10 @@ +// @strict: true + +export function unsafeCast(_value: unknown): asserts _value is T { } + +function yadda() { + let out = []; + out.push(100) + unsafeCast(out); + return out; +} From 0091fd6c64052b5d7c0ec468fd04c105d9681987 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 7 May 2020 15:03:51 -0700 Subject: [PATCH 27/28] Exclude arrays and tuples from full intersection property check (#38395) * Exclude arrays and tuples from full intersection property check * Add regression test --- src/compiler/checker.ts | 2 +- .../intersectionsAndOptionalProperties.errors.txt | 5 +++++ .../reference/intersectionsAndOptionalProperties.js | 8 ++++++++ .../intersectionsAndOptionalProperties.symbols | 9 +++++++++ .../intersectionsAndOptionalProperties.types | 11 +++++++++++ .../compiler/intersectionsAndOptionalProperties.ts | 5 +++++ 6 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e60afaeca667f..1464126e7e4e2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15876,7 +15876,7 @@ namespace ts { // recursive intersections that are structurally similar but not exactly identical. See #37854. if (result && !inPropertyCheck && ( target.flags & TypeFlags.Intersection && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) { + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) { inPropertyCheck = true; result &= recursiveTypeRelatedTo(source, target, reportErrors, IntersectionState.PropertyCheck); inPropertyCheck = false; diff --git a/tests/baselines/reference/intersectionsAndOptionalProperties.errors.txt b/tests/baselines/reference/intersectionsAndOptionalProperties.errors.txt index bcd0a6f841d88..faa8b067b1ac3 100644 --- a/tests/baselines/reference/intersectionsAndOptionalProperties.errors.txt +++ b/tests/baselines/reference/intersectionsAndOptionalProperties.errors.txt @@ -46,4 +46,9 @@ tests/cases/compiler/intersectionsAndOptionalProperties.ts(20,5): error TS2322: ~~~~~~~ !!! error TS2322: Type 'null' is not assignable to type 'number | undefined'. } + + // Repro from #38348 + + const yy: number[] & [number, ...number[]] = [1]; + const xx: [number, ...number[]] = yy; \ No newline at end of file diff --git a/tests/baselines/reference/intersectionsAndOptionalProperties.js b/tests/baselines/reference/intersectionsAndOptionalProperties.js index b2f13a9f67955..5bb0df9d27f3f 100644 --- a/tests/baselines/reference/intersectionsAndOptionalProperties.js +++ b/tests/baselines/reference/intersectionsAndOptionalProperties.js @@ -20,6 +20,11 @@ function foo(v: From) { x = v; // Error x.field = v.field; // Error } + +// Repro from #38348 + +const yy: number[] & [number, ...number[]] = [1]; +const xx: [number, ...number[]] = yy; //// [intersectionsAndOptionalProperties.js] @@ -31,3 +36,6 @@ function foo(v) { x = v; // Error x.field = v.field; // Error } +// Repro from #38348 +var yy = [1]; +var xx = yy; diff --git a/tests/baselines/reference/intersectionsAndOptionalProperties.symbols b/tests/baselines/reference/intersectionsAndOptionalProperties.symbols index c5504794e6ea5..e09f4dce5bbbd 100644 --- a/tests/baselines/reference/intersectionsAndOptionalProperties.symbols +++ b/tests/baselines/reference/intersectionsAndOptionalProperties.symbols @@ -62,3 +62,12 @@ function foo(v: From) { >field : Symbol(field, Decl(intersectionsAndOptionalProperties.ts, 14, 14)) } +// Repro from #38348 + +const yy: number[] & [number, ...number[]] = [1]; +>yy : Symbol(yy, Decl(intersectionsAndOptionalProperties.ts, 24, 5)) + +const xx: [number, ...number[]] = yy; +>xx : Symbol(xx, Decl(intersectionsAndOptionalProperties.ts, 25, 5)) +>yy : Symbol(yy, Decl(intersectionsAndOptionalProperties.ts, 24, 5)) + diff --git a/tests/baselines/reference/intersectionsAndOptionalProperties.types b/tests/baselines/reference/intersectionsAndOptionalProperties.types index 7f5af60c18e6f..98bc85c7e4299 100644 --- a/tests/baselines/reference/intersectionsAndOptionalProperties.types +++ b/tests/baselines/reference/intersectionsAndOptionalProperties.types @@ -63,3 +63,14 @@ function foo(v: From) { >field : null } +// Repro from #38348 + +const yy: number[] & [number, ...number[]] = [1]; +>yy : number[] & [number, ...number[]] +>[1] : [number] +>1 : 1 + +const xx: [number, ...number[]] = yy; +>xx : [number, ...number[]] +>yy : number[] & [number, ...number[]] + diff --git a/tests/cases/compiler/intersectionsAndOptionalProperties.ts b/tests/cases/compiler/intersectionsAndOptionalProperties.ts index a5bc4a1580af4..9878604c1483a 100644 --- a/tests/cases/compiler/intersectionsAndOptionalProperties.ts +++ b/tests/cases/compiler/intersectionsAndOptionalProperties.ts @@ -21,3 +21,8 @@ function foo(v: From) { x = v; // Error x.field = v.field; // Error } + +// Repro from #38348 + +const yy: number[] & [number, ...number[]] = [1]; +const xx: [number, ...number[]] = yy; From 9ba861904b1c0fbe42d9de9baa70d93be74c3874 Mon Sep 17 00:00:00 2001 From: csigs Date: Thu, 7 May 2020 22:11:10 +0000 Subject: [PATCH 28/28] LEGO: check in for master to temporary branch. --- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 36 +++++++++++++++-- .../diagnosticMessages.generated.json.lcl | 39 +++++++++++++++++-- 4 files changed, 141 insertions(+), 12 deletions(-) diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index e5a2a757fdbfc..94715ed4a6c91 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3717,6 +3717,12 @@ + + + + + + @@ -4701,6 +4707,15 @@ + + + + + + + + + @@ -5151,6 +5166,15 @@ + + + + + + + + + @@ -8721,6 +8745,15 @@ + + + ']]> + + "]]> + + + + @@ -10287,11 +10320,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - 类型。]]> + 类型。你是否是指写入 "Promise<{0}>"?]]> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index 2021e5c720177..cefbc586cfe6f 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3714,6 +3714,12 @@ + + + + + + @@ -4698,6 +4704,15 @@ + + + + + + + + + @@ -5148,6 +5163,15 @@ + + + + + + + + + @@ -8715,6 +8739,15 @@ + + + ']]> + + " ersetzen]]> + + + + @@ -10281,11 +10314,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - " sein.]]> + " sein. Wollten Sie eigentlich "Promise<{0}>" verwenden?]]> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 4b60684dca3f4..49bad292a5a5b 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3716,6 +3716,12 @@ + + + + + + @@ -4700,6 +4706,15 @@ + + + + + + + + + @@ -5150,6 +5165,12 @@ + + + + + + @@ -8720,6 +8741,15 @@ + + + ']]> + + "]]> + + + + @@ -10286,11 +10316,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - .]]> + . Вы имели в виду "Promise<{0}>"?]]> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index ade7b5faea4d7..3a93930be9678 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -3710,6 +3710,12 @@ + + + + + + @@ -4694,6 +4700,15 @@ + + + + + + + + + @@ -5144,6 +5159,15 @@ + + + + + + + + + @@ -8714,6 +8738,15 @@ + + + ']]> + + ' ile değiştir]]> + + + + @@ -10280,11 +10313,11 @@ - + - type.]]> + type. Did you mean to write 'Promise<{0}>'?]]> - türü olmalıdır.]]> + türü olmalıdır. 'Promise<{0}>' yazmak mı istediniz?]]>