From 37ac443eb33eaca7eb6e7cc9ceb07d4c5ed029bd Mon Sep 17 00:00:00 2001 From: Daniele Maltese <17677294+ilmalte@users.noreply.github.com> Date: Wed, 23 Feb 2022 17:42:23 +0100 Subject: [PATCH 01/63] docs(@angular-devkit/core): typo in string.ts doc Typo in underscore function code documentation. (cherry picked from commit b20f34ec177e1524de76e2a7a189d0f25cdbb95a) --- packages/angular_devkit/core/src/utils/strings.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/angular_devkit/core/src/utils/strings.ts b/packages/angular_devkit/core/src/utils/strings.ts index 9313f2b2799f..a3dd5195ab83 100644 --- a/packages/angular_devkit/core/src/utils/strings.ts +++ b/packages/angular_devkit/core/src/utils/strings.ts @@ -93,7 +93,7 @@ export function classify(str: string): string { } /** - More general than decamelize. Returns the lower\_case\_and\_underscored + More general than decamelize. Returns the lower_case_and_underscored form of a string. ```javascript From d82d0ebc9448984e8630bfad05fdc5649ceb022d Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Thu, 17 Feb 2022 20:26:45 -0500 Subject: [PATCH 02/63] test: update E2E production application size expectations Improvements to the framework for `13.2.5` resulted in reduced main bundle sizes. (cherry picked from commit ed790c1155cb5d49d9985a9e27e239675f2939ba) --- tests/legacy-cli/e2e/tests/build/prod-build.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/legacy-cli/e2e/tests/build/prod-build.ts b/tests/legacy-cli/e2e/tests/build/prod-build.ts index 38850965eace..d2dc088ae5d2 100644 --- a/tests/legacy-cli/e2e/tests/build/prod-build.ts +++ b/tests/legacy-cli/e2e/tests/build/prod-build.ts @@ -1,7 +1,7 @@ import { statSync } from 'fs'; import { join } from 'path'; import { expectFileToExist, expectFileToMatch, readFile } from '../../utils/fs'; -import { ng } from '../../utils/process'; +import { noSilentNg } from '../../utils/process'; function verifySize(bundle: string, baselineBytes: number) { const size = statSync(`dist/test-project/${bundle}`).size; @@ -29,7 +29,7 @@ export default async function () { // stuck to the first build done const bootstrapRegExp = /bootstrapModule\([a-zA-Z]+[0-9]*\)\./; - await ng('build'); + await noSilentNg('build'); await expectFileToExist(join(process.cwd(), 'dist')); // Check for cache busting hash script src await expectFileToMatch('dist/test-project/index.html', /main\.[0-9a-f]{16}\.js/); @@ -43,5 +43,5 @@ export default async function () { await expectFileToMatch(`dist/test-project/${mainES2017Path}`, bootstrapRegExp); // Size checks in bytes - verifySize(mainES2017Path, 141032); + verifySize(mainES2017Path, 124000); } From 90a5531b1fbe4043ab47f921ad6b858d34e7c7d0 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 4 Mar 2022 15:56:43 +0100 Subject: [PATCH 03/63] fix(@angular-devkit/build-angular): ignore css only chunks during naming Don't name CSS only chunks. Closes #22769 (cherry picked from commit e28c7159725a6d23b218dc6e0f317fc6123173f7) --- .../src/webpack/plugins/named-chunks-plugin.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/named-chunks-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/named-chunks-plugin.ts index 3390682c5bf4..c2d2bd5e0a5f 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/named-chunks-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/named-chunks-plugin.ts @@ -26,6 +26,12 @@ export class NamedChunksPlugin { return; } + if ([...chunk.files.values()].every((f) => f.endsWith('.css'))) { + // If all chunk files are CSS files skip. + // This happens when using `import('./styles.css')` in a lazy loaded module. + return undefined; + } + const name = this.generateName(chunk); if (name) { chunk.name = name; From 49be70eea184ce2dbf826bcd0f78ab0679952330 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 4 Mar 2022 16:26:40 +0100 Subject: [PATCH 04/63] docs(@angular-devkit/build-angular): update link to Angular Package Format documentation The APF spec now lives in AIO. (cherry picked from commit d0407b33673abf44f8333ec718407ec3cdd66448) --- .../angular_devkit/build_angular/README.md | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/angular_devkit/build_angular/README.md b/packages/angular_devkit/build_angular/README.md index c076aa9225d6..68cc3f37106a 100644 --- a/packages/angular_devkit/build_angular/README.md +++ b/packages/angular_devkit/build_angular/README.md @@ -4,16 +4,16 @@ This package contains [Architect builders](/packages/angular_devkit/architect/RE ## Builders -| Name | Description | -| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| app-shell | Build an Angular [App shell](https://angular.io/guide/app-shell). | -| browser | Build an Angular application targeting a browser environment. | -| dev-server | A development server that provides live reloading. | -| extract-i18n | Extract i18n messages from an Angular application. | -| karma | Execute unit tests using [Karma](https://github.com/karma-runner/karma) test runner. | -| ng-packagr | Build and package an Angular library in [Angular Package Format (APF)](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview) format using [ng-packagr](https://github.com/ng-packagr/ng-packagr). | -| server | Build an Angular application targeting a [Node.js](https://nodejs.org) environment. | -| protractor | **Deprecated** - Run end-to-end tests using [Protractor](https://www.protractortest.org/) framework. | +| Name | Description | +| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| app-shell | Build an Angular [App shell](https://angular.io/guide/app-shell). | +| browser | Build an Angular application targeting a browser environment. | +| dev-server | A development server that provides live reloading. | +| extract-i18n | Extract i18n messages from an Angular application. | +| karma | Execute unit tests using [Karma](https://github.com/karma-runner/karma) test runner. | +| ng-packagr | Build and package an Angular library in [Angular Package Format (APF)](https://angular.io/guide/angular-package-format) format using [ng-packagr](https://github.com/ng-packagr/ng-packagr). | +| server | Build an Angular application targeting a [Node.js](https://nodejs.org) environment. | +| protractor | **Deprecated** - Run end-to-end tests using [Protractor](https://www.protractortest.org/) framework. | ## Disclaimer From fc38474548cb9b08606feb62a1bdcb79b62d0fc6 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 4 Mar 2022 16:27:55 +0100 Subject: [PATCH 05/63] docs: remove redundant default empty strings values (cherry picked from commit 3d928c01c8196b1caba7b373eec870540ecda79e) (cherry picked from commit 433b6b49313478418a5a01e73cd55298835ff030) --- .../build_angular/src/builders/browser/schema.json | 3 +-- .../build_angular/src/builders/server/schema.json | 3 +-- packages/schematics/angular/class/schema.json | 3 +-- packages/schematics/angular/interface/schema.json | 1 - .../core/json/schema/serializers/schema_benchmark.json | 6 +----- 5 files changed, 4 insertions(+), 12 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/builders/browser/schema.json b/packages/angular_devkit/build_angular/src/builders/browser/schema.json index 4e15f47faa9f..02cc47ca049e 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/schema.json +++ b/packages/angular_devkit/build_angular/src/builders/browser/schema.json @@ -141,8 +141,7 @@ }, "resourcesOutputPath": { "type": "string", - "description": "The path where style resources will be placed, relative to outputPath.", - "default": "" + "description": "The path where style resources will be placed, relative to outputPath." }, "aot": { "type": "boolean", diff --git a/packages/angular_devkit/build_angular/src/builders/server/schema.json b/packages/angular_devkit/build_angular/src/builders/server/schema.json index d4c68ecf16df..3affefd66222 100644 --- a/packages/angular_devkit/build_angular/src/builders/server/schema.json +++ b/packages/angular_devkit/build_angular/src/builders/server/schema.json @@ -74,8 +74,7 @@ }, "resourcesOutputPath": { "type": "string", - "description": "The path where style resources will be placed, relative to outputPath.", - "default": "" + "description": "The path where style resources will be placed, relative to outputPath." }, "sourceMap": { "description": "Output source maps for scripts and styles. For more information, see https://angular.io/guide/workspace-config#source-map-configuration.", diff --git a/packages/schematics/angular/class/schema.json b/packages/schematics/angular/class/schema.json index e10969584782..1999daaea8f0 100644 --- a/packages/schematics/angular/class/schema.json +++ b/packages/schematics/angular/class/schema.json @@ -36,8 +36,7 @@ }, "type": { "type": "string", - "description": "Adds a developer-defined type to the filename, in the format \"name.type.ts\".", - "default": "" + "description": "Adds a developer-defined type to the filename, in the format \"name.type.ts\"." } }, "required": ["name"] diff --git a/packages/schematics/angular/interface/schema.json b/packages/schematics/angular/interface/schema.json index 0a949d63d904..5ae1aeaa9b80 100644 --- a/packages/schematics/angular/interface/schema.json +++ b/packages/schematics/angular/interface/schema.json @@ -30,7 +30,6 @@ }, "prefix": { "type": "string", - "default": "", "description": "A prefix to apply to generated selectors." }, "type": { diff --git a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json index 3a22c614f601..58a0e1e82e4a 100644 --- a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json +++ b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json @@ -55,17 +55,14 @@ "properties": { "glob": { "type": "string", - "default": "", "description": "The pattern to match." }, "input": { "type": "string", - "default": "", "description": "The dir to search within." }, "output": { "type": "string", - "default": "", "description": "The output path (relative to the outDir)." } }, @@ -395,8 +392,7 @@ "properties": { "prefix": { "description": "Prefix to apply to interface names. (i.e. I)", - "type": "string", - "default": "" + "type": "string" } } }, From 472d46856a5eb6848b1d36e7ec43759fe30252d5 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 4 Mar 2022 16:46:54 +0100 Subject: [PATCH 06/63] refactor(@angular-devkit/build-angular): move dev-server specs into a seperate directory (cherry picked from commit ef753628a648f4b15ce11531e879b9bab73b7385) --- .../src/builders/dev-server/{ => specs}/hmr_spec.ts | 2 +- .../src/builders/dev-server/{ => specs}/index_spec.ts | 2 +- .../src/builders/dev-server/{ => specs}/live-reload_spec.ts | 2 +- .../src/builders/dev-server/{ => specs}/ssl_spec.ts | 2 +- .../src/builders/dev-server/{ => specs}/works_spec.ts | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) rename packages/angular_devkit/build_angular/src/builders/dev-server/{ => specs}/hmr_spec.ts (98%) rename packages/angular_devkit/build_angular/src/builders/dev-server/{ => specs}/index_spec.ts (96%) rename packages/angular_devkit/build_angular/src/builders/dev-server/{ => specs}/live-reload_spec.ts (99%) rename packages/angular_devkit/build_angular/src/builders/dev-server/{ => specs}/ssl_spec.ts (98%) rename packages/angular_devkit/build_angular/src/builders/dev-server/{ => specs}/works_spec.ts (98%) diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/hmr_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts similarity index 98% rename from packages/angular_devkit/build_angular/src/builders/dev-server/hmr_spec.ts rename to packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts index 4b97bb82b2c7..180ea9d4214f 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/hmr_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/hmr_spec.ts @@ -13,7 +13,7 @@ import { Page } from 'puppeteer/lib/cjs/puppeteer/common/Page'; import puppeteer from 'puppeteer/lib/cjs/puppeteer/node'; /* eslint-enable import/no-extraneous-dependencies */ import { debounceTime, switchMap, take } from 'rxjs/operators'; -import { createArchitect, host } from '../../testing/test-utils'; +import { createArchitect, host } from '../../../testing/test-utils'; /* eslint-disable @typescript-eslint/no-explicit-any */ declare const document: any; diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/index_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts similarity index 96% rename from packages/angular_devkit/build_angular/src/builders/dev-server/index_spec.ts rename to packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts index 2787cd93118b..c654826bff01 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/index_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/index_spec.ts @@ -9,7 +9,7 @@ import { DevServerBuilderOutput } from '@angular-devkit/build-angular'; import { workspaces } from '@angular-devkit/core'; import fetch from 'node-fetch'; // eslint-disable-line import/no-extraneous-dependencies -import { createArchitect, host } from '../../testing/test-utils'; +import { createArchitect, host } from '../../../testing/test-utils'; describe('Dev Server Builder index', () => { const targetSpec = { project: 'app', target: 'serve' }; diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/live-reload_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/live-reload_spec.ts similarity index 99% rename from packages/angular_devkit/build_angular/src/builders/dev-server/live-reload_spec.ts rename to packages/angular_devkit/build_angular/src/builders/dev-server/specs/live-reload_spec.ts index f2a90b6a5ffa..166d7bc28e73 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/live-reload_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/live-reload_spec.ts @@ -14,7 +14,7 @@ import { Browser } from 'puppeteer/lib/cjs/puppeteer/common/Browser'; import { Page } from 'puppeteer/lib/cjs/puppeteer/common/Page'; import puppeteer from 'puppeteer/lib/cjs/puppeteer/node'; import { debounceTime, switchMap, take } from 'rxjs/operators'; -import { createArchitect, host } from '../../testing/test-utils'; +import { createArchitect, host } from '../../../testing/test-utils'; // eslint-disable-next-line @typescript-eslint/no-explicit-any declare const document: any; diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/ssl_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts similarity index 98% rename from packages/angular_devkit/build_angular/src/builders/dev-server/ssl_spec.ts rename to packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts index 24910873bae4..ab3583e7dae6 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/ssl_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/ssl_spec.ts @@ -11,7 +11,7 @@ import { DevServerBuilderOutput } from '@angular-devkit/build-angular'; import { tags } from '@angular-devkit/core'; import * as https from 'https'; import fetch from 'node-fetch'; // eslint-disable-line import/no-extraneous-dependencies -import { createArchitect, host } from '../../testing/test-utils'; +import { createArchitect, host } from '../../../testing/test-utils'; describe('Dev Server Builder ssl', () => { const target = { project: 'app', target: 'serve' }; diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/works_spec.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts similarity index 98% rename from packages/angular_devkit/build_angular/src/builders/dev-server/works_spec.ts rename to packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts index 8f9028a010fa..90ef75c2274b 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/works_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/specs/works_spec.ts @@ -10,7 +10,7 @@ import { Architect, BuilderRun } from '@angular-devkit/architect'; import { DevServerBuilderOutput } from '@angular-devkit/build-angular'; import { normalize, virtualFs } from '@angular-devkit/core'; import fetch from 'node-fetch'; // eslint-disable-line import/no-extraneous-dependencies -import { createArchitect, host } from '../../testing/test-utils'; +import { createArchitect, host } from '../../../testing/test-utils'; describe('Dev Server Builder', () => { const target = { project: 'app', target: 'serve' }; From dc0895222032531d69d9418bc4efee7358a6889a Mon Sep 17 00:00:00 2001 From: Joey Perrott Date: Wed, 9 Mar 2022 13:40:54 -0800 Subject: [PATCH 07/63] release: cut the v13.2.6 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 740595826887..534afad68ae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.2.6 (2022-03-09) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------ | +| [90a5531b1](https://github.com/angular/angular-cli/commit/90a5531b1fbe4043ab47f921ad6b858d34e7c7d0) | fix | ignore css only chunks during naming | + +## Special Thanks + +Alan Agius, Charles Lyding and Daniele Maltese + + + # 13.2.5 (2022-02-23) diff --git a/package.json b/package.json index e95cedd32c7a..dedac4a957f0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.2.5", + "version": "13.2.6", "private": true, "description": "Software Development Kit for Angular", "bin": { From 0b55babf239d76a3890af93af28daf00218bc8b4 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 10 Mar 2022 18:53:05 +0100 Subject: [PATCH 08/63] docs: replace `app` with `application` (cherry picked from commit 9ddb220c3da0f45438a429b6a37ac93c9d8a8ca7) --- .../build_angular/src/builders/app-shell/schema.json | 4 ++-- .../build_angular/src/builders/dev-server/schema.json | 2 +- packages/schematics/angular/app-shell/index.ts | 2 +- packages/schematics/angular/app-shell/schema.json | 6 +++--- packages/schematics/angular/application/schema.json | 2 +- packages/schematics/angular/collection.json | 2 +- packages/schematics/angular/e2e/e2e-long.md | 2 +- packages/schematics/angular/e2e/schema.json | 2 +- packages/schematics/angular/service-worker/index.ts | 6 +++--- packages/schematics/angular/service-worker/index_spec.ts | 6 +++--- packages/schematics/angular/universal/schema.json | 2 +- packages/schematics/angular/utility/ng-ast-utils.ts | 2 +- .../schematics/angular/workspace/files/README.md.template | 2 +- .../core/json/schema/serializers/schema_benchmark.json | 2 +- 14 files changed, 21 insertions(+), 21 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/builders/app-shell/schema.json b/packages/angular_devkit/build_angular/src/builders/app-shell/schema.json index 9ea17e4f5120..027cc9f8acf9 100644 --- a/packages/angular_devkit/build_angular/src/builders/app-shell/schema.json +++ b/packages/angular_devkit/build_angular/src/builders/app-shell/schema.json @@ -6,12 +6,12 @@ "properties": { "browserTarget": { "type": "string", - "description": "A browser builder target use for rendering the app shell in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", + "description": "A browser builder target use for rendering the application shell in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", "pattern": "^[^:\\s]+:[^:\\s]+(:[^\\s]+)?$" }, "serverTarget": { "type": "string", - "description": "A server builder target use for rendering the app shell in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", + "description": "A server builder target use for rendering the application shell in the format of `project:target[:configuration]`. You can also pass in more than one configuration name as a comma-separated list. Example: `project:target:production,staging`.", "pattern": "^[^:\\s]+:[^:\\s]+(:[^\\s]+)?$" }, "appModuleBundle": { diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json b/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json index f5316f383b84..58bc9f68948f 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/schema.json @@ -75,7 +75,7 @@ }, "servePath": { "type": "string", - "description": "The pathname where the app will be served." + "description": "The pathname where the application will be served." }, "disableHostCheck": { "type": "boolean", diff --git a/packages/schematics/angular/app-shell/index.ts b/packages/schematics/angular/app-shell/index.ts index 1afe95988e00..f7caa44cabcf 100644 --- a/packages/schematics/angular/app-shell/index.ts +++ b/packages/schematics/angular/app-shell/index.ts @@ -125,7 +125,7 @@ function validateProject(mainPath: string): Rule { const tmpl = getComponentTemplateInfo(host, componentPath); const template = getComponentTemplate(host, componentPath, tmpl); if (!routerOutletCheckRegex.test(template)) { - const errorMsg = `Prerequisite for app shell is to define a router-outlet in your root component.`; + const errorMsg = `Prerequisite for application shell is to define a router-outlet in your root component.`; context.logger.error(errorMsg); throw new SchematicsException(errorMsg); } diff --git a/packages/schematics/angular/app-shell/schema.json b/packages/schematics/angular/app-shell/schema.json index 6b231b8b46d7..44fba253e017 100644 --- a/packages/schematics/angular/app-shell/schema.json +++ b/packages/schematics/angular/app-shell/schema.json @@ -3,7 +3,7 @@ "$id": "SchematicsAngularAppShell", "title": "Angular AppShell Options Schema", "type": "object", - "description": "Generates an app shell for running a server-side version of an app.", + "description": "Generates an application shell for running a server-side version of an app.", "additionalProperties": false, "long-description": "./app-shell-long.md", "properties": { @@ -16,13 +16,13 @@ }, "route": { "type": "string", - "description": "Route path used to produce the app shell.", + "description": "Route path used to produce the application shell.", "default": "shell" }, "appId": { "type": "string", "format": "html-selector", - "description": "The app ID to use in withServerTransition().", + "description": "The application ID to use in withServerTransition().", "default": "serverApp" }, "main": { diff --git a/packages/schematics/angular/application/schema.json b/packages/schematics/angular/application/schema.json index 88a3caa3cd73..f98934c0f70b 100644 --- a/packages/schematics/angular/application/schema.json +++ b/packages/schematics/angular/application/schema.json @@ -3,7 +3,7 @@ "$id": "SchematicsAngularApp", "title": "Angular Application Options Schema", "type": "object", - "description": "Generates a new basic app definition in the \"projects\" subfolder of the workspace.", + "description": "Generates a new basic application definition in the \"projects\" subfolder of the workspace.", "additionalProperties": false, "properties": { "projectRoot": { diff --git a/packages/schematics/angular/collection.json b/packages/schematics/angular/collection.json index aa8acf318481..61aa28cfbfbd 100755 --- a/packages/schematics/angular/collection.json +++ b/packages/schematics/angular/collection.json @@ -104,7 +104,7 @@ "app-shell": { "aliases": ["appShell"], "factory": "./app-shell", - "description": "Create an app shell.", + "description": "Create an application shell.", "schema": "./app-shell/schema.json" }, "library": { diff --git a/packages/schematics/angular/e2e/e2e-long.md b/packages/schematics/angular/e2e/e2e-long.md index 13c83bd3bea8..aa2a9a17582b 100644 --- a/packages/schematics/angular/e2e/e2e-long.md +++ b/packages/schematics/angular/e2e/e2e-long.md @@ -1,2 +1,2 @@ -The e2e tests are created in a separate app in the `projects` folder of the workspace, +The e2e tests are created in a separate application in the `projects` folder of the workspace, next to the project being tested. diff --git a/packages/schematics/angular/e2e/schema.json b/packages/schematics/angular/e2e/schema.json index 185795e63ade..64b5c0e456e5 100644 --- a/packages/schematics/angular/e2e/schema.json +++ b/packages/schematics/angular/e2e/schema.json @@ -13,7 +13,7 @@ "default": "app-root" }, "relatedAppName": { - "description": "The name of the app being tested.", + "description": "The name of the application being tested.", "type": "string" } }, diff --git a/packages/schematics/angular/service-worker/index.ts b/packages/schematics/angular/service-worker/index.ts index 53feb12dfc3c..774493083855 100644 --- a/packages/schematics/angular/service-worker/index.ts +++ b/packages/schematics/angular/service-worker/index.ts @@ -95,11 +95,11 @@ function updateAppModule(mainPath: string): Rule { } } - // register SW in app module + // register SW in application module const importText = tags.stripIndent` ServiceWorkerModule.register('ngsw-worker.js', { enabled: ${importModule}.production, - // Register the ServiceWorker as soon as the app is stable + // Register the ServiceWorker as soon as the application is stable // or after 30 seconds (whichever comes first). registrationStrategy: 'registerWhenStable:30000' }) @@ -146,7 +146,7 @@ export default function (options: ServiceWorkerOptions): Rule { if (!buildTarget) { throw targetBuildNotFoundError(); } - const buildOptions = ((buildTarget.options || {}) as unknown) as BrowserBuilderOptions; + const buildOptions = (buildTarget.options || {}) as unknown as BrowserBuilderOptions; const root = project.root; buildOptions.serviceWorker = true; buildOptions.ngswConfigPath = join(normalize(root), 'ngsw-config.json'); diff --git a/packages/schematics/angular/service-worker/index_spec.ts b/packages/schematics/angular/service-worker/index_spec.ts index ca21f4e744b9..aa16cd4c2246 100644 --- a/packages/schematics/angular/service-worker/index_spec.ts +++ b/packages/schematics/angular/service-worker/index_spec.ts @@ -90,7 +90,7 @@ describe('Service Worker Schematic', () => { new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: environment\\.production,\\n' + - '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + + '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', @@ -128,7 +128,7 @@ describe('Service Worker Schematic', () => { new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: env\\.production,\\n' + - '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + + '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', @@ -166,7 +166,7 @@ describe('Service Worker Schematic', () => { new RegExp( "(\\s+)ServiceWorkerModule\\.register\\('ngsw-worker\\.js', \\{\\n" + '\\1 enabled: environment\\.production,\\n' + - '\\1 // Register the ServiceWorker as soon as the app is stable\\n' + + '\\1 // Register the ServiceWorker as soon as the application is stable\\n' + '\\1 // or after 30 seconds \\(whichever comes first\\)\\.\\n' + "\\1 registrationStrategy: 'registerWhenStable:30000'\\n" + '\\1}\\)', diff --git a/packages/schematics/angular/universal/schema.json b/packages/schematics/angular/universal/schema.json index 577c1864c77a..16ba8cde6a30 100644 --- a/packages/schematics/angular/universal/schema.json +++ b/packages/schematics/angular/universal/schema.json @@ -16,7 +16,7 @@ "appId": { "type": "string", "format": "html-selector", - "description": "The app identifier to use for transition.", + "description": "The application identifier to use for transition.", "default": "serverApp" }, "main": { diff --git a/packages/schematics/angular/utility/ng-ast-utils.ts b/packages/schematics/angular/utility/ng-ast-utils.ts index d344179af4cf..e55effeeea17 100644 --- a/packages/schematics/angular/utility/ng-ast-utils.ts +++ b/packages/schematics/angular/utility/ng-ast-utils.ts @@ -60,7 +60,7 @@ export function findBootstrapModulePath(host: Tree, mainPath: string): string { const mainBuffer = host.read(mainPath); if (!mainBuffer) { - throw new SchematicsException(`Client app main file (${mainPath}) not found`); + throw new SchematicsException(`Client application main file (${mainPath}) not found`); } const mainText = mainBuffer.toString('utf-8'); const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true); diff --git a/packages/schematics/angular/workspace/files/README.md.template b/packages/schematics/angular/workspace/files/README.md.template index 961bc376ff14..c1585a0ff019 100644 --- a/packages/schematics/angular/workspace/files/README.md.template +++ b/packages/schematics/angular/workspace/files/README.md.template @@ -4,7 +4,7 @@ This project was generated with [Angular CLI](https://github.com/angular/angular ## Development server -Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. ## Code scaffolding diff --git a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json index 58a0e1e82e4a..8e39ec498f1b 100644 --- a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json +++ b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json @@ -535,7 +535,7 @@ "default": "@schematics/angular" }, "newApp": { - "description": "The new app schematic.", + "description": "The new application schematic.", "type": "string", "default": "application" } From c995ed5e8a8e1b20cf376f4c48c5141fd5f4548a Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 11 Mar 2022 11:32:02 +0100 Subject: [PATCH 09/63] feat(@angular/cli): support TypeScript 4.6 Adds support for TypeScript 4.6. --- package.json | 26 +- .../angular_devkit/architect/src/architect.ts | 2 +- .../architect/src/schedule-by-name.ts | 2 +- .../angular_devkit/build_angular/package.json | 8 +- .../build_optimizer/package.json | 2 +- .../blank/project-files/package.json | 2 +- .../schematic/files/package.json | 2 +- packages/ngtools/webpack/package.json | 8 +- .../transformers/replace_resources_spec.ts | 2 +- .../Microsoft/TypeScript/BUILD.bazel | 9 +- .../Microsoft/TypeScript/lib/typescript.d.ts | 45 +- .../Microsoft/TypeScript/lib/typescript.js | 7896 ++++++++++------- .../angular/utility/latest-versions.ts | 2 +- .../utility/latest-versions/package.json | 2 +- tests/legacy-cli/e2e/ng-snapshot/package.json | 28 +- yarn.lock | 272 +- 16 files changed, 5128 insertions(+), 3180 deletions(-) diff --git a/package.json b/package.json index dedac4a957f0..320b7b9d083e 100644 --- a/package.json +++ b/package.json @@ -64,21 +64,21 @@ }, "devDependencies": { "@ampproject/remapping": "1.1.1", - "@angular/animations": "13.1.3", + "@angular/animations": "13.3.0-rc.0", "@angular/cdk": "13.1.3", - "@angular/common": "13.1.3", - "@angular/compiler": "13.1.3", - "@angular/compiler-cli": "13.1.3", - "@angular/core": "13.1.3", + "@angular/common": "13.3.0-rc.0", + "@angular/compiler": "13.3.0-rc.0", + "@angular/compiler-cli": "13.3.0-rc.0", + "@angular/core": "13.3.0-rc.0", "@angular/dev-infra-private": "https://github.com/angular/dev-infra-private-builds.git#3a34722a82fb0e8cd3fa00dfc5476767a35e021a", - "@angular/forms": "13.1.3", - "@angular/localize": "13.1.3", + "@angular/forms": "13.3.0-rc.0", + "@angular/localize": "13.3.0-rc.0", "@angular/material": "13.1.3", - "@angular/platform-browser": "13.1.3", - "@angular/platform-browser-dynamic": "13.1.3", - "@angular/platform-server": "13.1.3", - "@angular/router": "13.1.3", - "@angular/service-worker": "13.1.3", + "@angular/platform-browser": "13.3.0-rc.0", + "@angular/platform-browser-dynamic": "13.3.0-rc.0", + "@angular/platform-server": "13.3.0-rc.0", + "@angular/router": "13.3.0-rc.0", + "@angular/service-worker": "13.3.0-rc.0", "@babel/core": "7.16.12", "@babel/generator": "7.16.8", "@babel/helper-annotate-as-pure": "7.16.7", @@ -215,7 +215,7 @@ "tree-kill": "1.2.2", "ts-node": "^10.0.0", "tslib": "2.3.1", - "typescript": "4.5.5", + "typescript": "4.6.2", "verdaccio": "5.5.1", "verdaccio-auth-memory": "^10.0.0", "webpack": "5.67.0", diff --git a/packages/angular_devkit/architect/src/architect.ts b/packages/angular_devkit/architect/src/architect.ts index dff023ea53c5..d852a3113c8b 100644 --- a/packages/angular_devkit/architect/src/architect.ts +++ b/packages/angular_devkit/architect/src/architect.ts @@ -100,7 +100,7 @@ function _createJobHandlerFromBuilderInfo( value: { ...output.value, ...(target ? { target } : 0), - } as json.JsonObject, + } as unknown as json.JsonObject, }; } else { return output; diff --git a/packages/angular_devkit/architect/src/schedule-by-name.ts b/packages/angular_devkit/architect/src/schedule-by-name.ts index d1f8da4b7bc0..f583a7721567 100644 --- a/packages/angular_devkit/architect/src/schedule-by-name.ts +++ b/packages/angular_devkit/architect/src/schedule-by-name.ts @@ -94,7 +94,7 @@ export async function scheduleByName( ...output, ...(options.target ? { target: options.target } : 0), info, - } as BuilderOutput), + } as unknown as BuilderOutput), ), shareReplay(), ); diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 5b569c393143..fb18e8a53a40 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -75,14 +75,14 @@ "esbuild": "0.14.22" }, "peerDependencies": { - "@angular/compiler-cli": "^13.0.0", - "@angular/localize": "^13.0.0", - "@angular/service-worker": "^13.0.0", + "@angular/compiler-cli": "^13.0.0 || ^13.3.0-rc.0", + "@angular/localize": "^13.0.0 || ^13.3.0-rc.0", + "@angular/service-worker": "^13.0.0 || ^13.3.0-rc.0", "karma": "^6.3.0", "ng-packagr": "^13.0.0", "protractor": "^7.0.0", "tailwindcss": "^2.0.0 || ^3.0.0", - "typescript": ">=4.4.3 <4.6" + "typescript": ">=4.4.3 <4.7" }, "peerDependenciesMeta": { "@angular/localize": { diff --git a/packages/angular_devkit/build_optimizer/package.json b/packages/angular_devkit/build_optimizer/package.json index ed1c2eef0341..dcf647c7724b 100644 --- a/packages/angular_devkit/build_optimizer/package.json +++ b/packages/angular_devkit/build_optimizer/package.json @@ -12,7 +12,7 @@ "dependencies": { "source-map": "0.7.3", "tslib": "2.3.1", - "typescript": "4.5.5" + "typescript": "4.6.2" }, "peerDependencies": { "webpack": "^5.30.0" diff --git a/packages/angular_devkit/schematics_cli/blank/project-files/package.json b/packages/angular_devkit/schematics_cli/blank/project-files/package.json index ee5f904eebea..223d8bfe0ae5 100644 --- a/packages/angular_devkit/schematics_cli/blank/project-files/package.json +++ b/packages/angular_devkit/schematics_cli/blank/project-files/package.json @@ -15,7 +15,7 @@ "dependencies": { "@angular-devkit/core": "^<%= coreVersion %>", "@angular-devkit/schematics": "^<%= schematicsVersion %>", - "typescript": "~4.5.2" + "typescript": "~4.6.2" }, "devDependencies": { "@types/node": "^12.11.1", diff --git a/packages/angular_devkit/schematics_cli/schematic/files/package.json b/packages/angular_devkit/schematics_cli/schematic/files/package.json index 095c24b049b8..08532ae4b84e 100644 --- a/packages/angular_devkit/schematics_cli/schematic/files/package.json +++ b/packages/angular_devkit/schematics_cli/schematic/files/package.json @@ -15,7 +15,7 @@ "dependencies": { "@angular-devkit/core": "^<%= coreVersion %>", "@angular-devkit/schematics": "^<%= schematicsVersion %>", - "typescript": "~4.5.2" + "typescript": "~4.6.2" }, "devDependencies": { "@types/node": "^12.11.1", diff --git a/packages/ngtools/webpack/package.json b/packages/ngtools/webpack/package.json index c59708b135d8..a6712bd45e61 100644 --- a/packages/ngtools/webpack/package.json +++ b/packages/ngtools/webpack/package.json @@ -23,14 +23,14 @@ "dependencies": {}, "peerDependencies": { "@angular/compiler-cli": "^13.0.0", - "typescript": ">=4.4.3 <4.6", + "typescript": ">=4.4.3 <4.7", "webpack": "^5.30.0" }, "devDependencies": { "@angular-devkit/core": "0.0.0-PLACEHOLDER", - "@angular/compiler": "13.1.3", - "@angular/compiler-cli": "13.1.3", - "typescript": "4.5.5", + "@angular/compiler": "13.3.0-rc.0", + "@angular/compiler-cli": "13.3.0-rc.0", + "typescript": "4.6.2", "webpack": "5.67.0" } } diff --git a/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts b/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts index 8647f60957a9..e268aba18986 100644 --- a/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts +++ b/packages/ngtools/webpack/src/transformers/replace_resources_spec.ts @@ -93,7 +93,7 @@ describe('@ngtools/webpack transformers', () => { let AppComponent = class AppComponent { constructor() { this.title = 'app'; } }; - AppComponent = (0, tslib_1.__decorate)([ + AppComponent = tslib_1.__decorate([ (0, core_1.Component)({ selector: 'app-root', template: require("./app.component.html?ngResource"), diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel index ba81101c90dd..4a1da3cb0739 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel @@ -1,7 +1,12 @@ load("//tools:defaults.bzl", "ts_library") -# files fetched on 2021-12-10 from -# https://github.com/microsoft/TypeScript/releases/tag/v4.5.2 +# files fetched on 2022-03-11 from +# https://github.com/microsoft/TypeScript/releases/tag/v4.6.2 + +# Commands to download: +# curl https://raw.githubusercontent.com/microsoft/TypeScript/v4.6.2/lib/typescript.d.ts -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts +# curl https://raw.githubusercontent.com/microsoft/TypeScript/v4.6.2/lib/typescript.js -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js + licenses(["notice"]) # Apache 2.0 exports_files([ diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts index 1885ae3396e0..0c1763205539 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "4.5"; + const versionMajorMinor = "4.6"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -572,7 +572,7 @@ declare namespace ts { } export interface JSDocContainer { } - export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ClassStaticBlockDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | EndOfFileToken; + export type HasJSDoc = ParameterDeclaration | CallSignatureDeclaration | ClassStaticBlockDeclaration | ConstructSignatureDeclaration | MethodSignature | PropertySignature | ArrowFunction | ParenthesizedExpression | SpreadAssignment | ShorthandPropertyAssignment | PropertyAssignment | FunctionExpression | EmptyStatement | DebuggerStatement | Block | VariableStatement | ExpressionStatement | IfStatement | DoStatement | WhileStatement | ForStatement | ForInStatement | ForOfStatement | BreakStatement | ContinueStatement | ReturnStatement | WithStatement | SwitchStatement | LabeledStatement | ThrowStatement | TryStatement | FunctionDeclaration | ConstructorDeclaration | MethodDeclaration | VariableDeclaration | PropertyDeclaration | AccessorDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | EnumMember | EnumDeclaration | ModuleDeclaration | ImportEqualsDeclaration | ImportDeclaration | NamespaceExportDeclaration | ExportAssignment | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | ExportDeclaration | NamedTupleMember | ExportSpecifier | EndOfFileToken; export type HasType = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertySignature | PropertyDeclaration | TypePredicateNode | ParenthesizedTypeNode | TypeOperatorNode | MappedTypeNode | AssertionExpression | TypeAliasDeclaration | JSDocTypeExpression | JSDocNonNullableType | JSDocNullableType | JSDocOptionalType | JSDocVariadicType; export type HasTypeArguments = CallExpression | NewExpression | TaggedTemplateExpression | JsxOpeningElement | JsxSelfClosingElement; export type HasInitializer = HasExpressionInitializer | ForStatement | ForInStatement | ForOfStatement | JsxAttribute; @@ -897,7 +897,7 @@ declare namespace ts { export interface TypePredicateNode extends TypeNode { readonly kind: SyntaxKind.TypePredicate; readonly parent: SignatureDeclaration | JSDocTypeExpression; - readonly assertsModifier?: AssertsToken; + readonly assertsModifier?: AssertsKeyword; readonly parameterName: Identifier | ThisTypeNode; readonly type?: TypeNode; } @@ -968,7 +968,7 @@ declare namespace ts { } export interface MappedTypeNode extends TypeNode, Declaration { readonly kind: SyntaxKind.MappedType; - readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken; + readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken; readonly typeParameter: TypeParameterDeclaration; readonly nameType?: TypeNode; readonly questionToken?: QuestionToken | PlusToken | MinusToken; @@ -1465,7 +1465,7 @@ declare namespace ts { } export interface ForOfStatement extends IterationStatement { readonly kind: SyntaxKind.ForOfStatement; - readonly awaitModifier?: AwaitKeywordToken; + readonly awaitModifier?: AwaitKeyword; readonly initializer: ForInitializer; readonly expression: Expression; } @@ -1652,7 +1652,7 @@ declare namespace ts { readonly kind: SyntaxKind.AssertEntry; readonly parent: AssertClause; readonly name: AssertionKey; - readonly value: StringLiteral; + readonly value: Expression; } export interface AssertClause extends Node { readonly kind: SyntaxKind.AssertClause; @@ -1702,7 +1702,7 @@ declare namespace ts { readonly name: Identifier; readonly isTypeOnly: boolean; } - export interface ExportSpecifier extends NamedDeclaration { + export interface ExportSpecifier extends NamedDeclaration, JSDocContainer { readonly kind: SyntaxKind.ExportSpecifier; readonly parent: NamedExports; readonly isTypeOnly: boolean; @@ -1720,19 +1720,23 @@ declare namespace ts { readonly parent: ImportClause & { readonly isTypeOnly: true; }; - } | ImportSpecifier & { + } | ImportSpecifier & ({ + readonly isTypeOnly: true; + } | { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; }; - } | ExportSpecifier & { + }) | ExportSpecifier & ({ + readonly isTypeOnly: true; + } | { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; }; }; - }; + }); /** * This is either an `export =` or an `export default` declaration. * Unless `isExportEquals` is set, this node was parsed as an `export default`. @@ -3078,6 +3082,7 @@ declare namespace ts { ES2019 = 6, ES2020 = 7, ES2021 = 8, + ES2022 = 9, ESNext = 99, JSON = 100, Latest = 99 @@ -3343,7 +3348,7 @@ declare namespace ts { createTrue(): TrueLiteral; createFalse(): FalseLiteral; createModifier(kind: T): ModifierToken; - createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; + createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[] | undefined; createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3575,8 +3580,8 @@ declare namespace ts { updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; - createAssertEntry(name: AssertionKey, value: StringLiteral): AssertEntry; - updateAssertEntry(node: AssertEntry, name: AssertionKey, value: StringLiteral): AssertEntry; + createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; + updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry; createNamespaceImport(name: Identifier): NamespaceImport; updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; createNamespaceExport(name: Identifier): NamespaceExport; @@ -5351,7 +5356,11 @@ declare namespace ts { traceResolution?: boolean; [option: string]: CompilerOptionsValue | undefined; } - type ReportEmitErrorSummary = (errorCount: number) => void; + type ReportEmitErrorSummary = (errorCount: number, filesInError: (ReportFileInError | undefined)[]) => void; + interface ReportFileInError { + fileName: string; + line: number; + } interface SolutionBuilderHostBase extends ProgramHost { createDirectory?(path: string): void; /** @@ -5559,6 +5568,7 @@ declare namespace ts { isTypeParameter(): this is TypeParameter; isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; + isIndexType(): this is IndexType; } interface TypeReference { typeArguments?: readonly Type[]; @@ -5567,6 +5577,7 @@ declare namespace ts { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; + getTypeParameterAtPosition(pos: number): Type; getReturnType(): Type; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; @@ -5753,8 +5764,9 @@ declare namespace ts { * @param position A zero-based index of the character where you want the entries * @param options An object describing how the request was triggered and what kinds * of code actions can be returned with the completions. + * @param formattingSettings settings needed for calling formatting functions. */ - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined, formattingSettings?: FormatCodeSettings): WithMetadata | undefined; /** * Gets the extended details for a completion entry retrieved from `getCompletionsAtPosition`. * @@ -6586,6 +6598,7 @@ declare namespace ts { externalModuleName = "external module name", /** * + * @deprecated */ jsxAttribute = "JSX attribute", /** String literal */ @@ -6855,7 +6868,7 @@ declare namespace ts { /** @deprecated Use `factory.createModifier` or the factory supplied by your transformation context instead. */ const createModifier: (kind: T) => ModifierToken; /** @deprecated Use `factory.createModifiersFromModifierFlags` or the factory supplied by your transformation context instead. */ - const createModifiersFromModifierFlags: (flags: ModifierFlags) => Modifier[]; + const createModifiersFromModifierFlags: (flags: ModifierFlags) => Modifier[] | undefined; /** @deprecated Use `factory.createQualifiedName` or the factory supplied by your transformation context instead. */ const createQualifiedName: (left: EntityName, right: string | Identifier) => QualifiedName; /** @deprecated Use `factory.updateQualifiedName` or the factory supplied by your transformation context instead. */ diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js index 6076298b6efe..89cc0ba3ffb1 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js @@ -290,11 +290,11 @@ 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 = "4.5"; + ts.versionMajorMinor = "4.6"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = "4.5.2"; + ts.version = "4.6.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -305,13 +305,18 @@ var ts; /* @internal */ var NativeCollections; (function (NativeCollections) { + var globals = typeof globalThis !== "undefined" ? globalThis : + typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + undefined; /** * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). */ function tryGetNativeMap() { // Internet Explorer's Map doesn't support iteration, so don't use it. + var gMap = globals === null || globals === void 0 ? void 0 : globals.Map; // eslint-disable-next-line no-in-operator - return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined; + return typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined; } NativeCollections.tryGetNativeMap = tryGetNativeMap; /** @@ -319,8 +324,9 @@ var ts; */ function tryGetNativeSet() { // Internet Explorer's Set doesn't support iteration, so don't use it. + var gSet = globals === null || globals === void 0 ? void 0 : globals.Set; // eslint-disable-next-line no-in-operator - return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; + return typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; })(NativeCollections || (NativeCollections = {})); @@ -335,7 +341,7 @@ var ts; var constructor = (_a = NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](ts.getIterator); if (constructor) return constructor; - throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation."); + throw new Error("TypeScript requires an environment that provides a compatible native ".concat(name, " implementation.")); } })(ts || (ts = {})); /* @internal */ @@ -356,26 +362,6 @@ var ts; ts.emptyArray = []; ts.emptyMap = new ts.Map(); ts.emptySet = new ts.Set(); - function createMap() { - return new ts.Map(); - } - ts.createMap = createMap; - /** - * Create a new map from a template object is provided, the map will copy entries from it. - * @deprecated Use `new Map(getEntries(template))` instead. - */ - function createMapFromTemplate(template) { - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1057,7 +1043,11 @@ var ts; } return deduplicated; } - function insertSorted(array, insert, compare) { + function createSortedArray() { + return []; // TODO: GH#19873 + } + ts.createSortedArray = createSortedArray; + function insertSorted(array, insert, compare, allowDuplicates) { if (array.length === 0) { array.push(insert); return; @@ -1066,6 +1056,9 @@ var ts; if (insertIndex < 0) { array.splice(~insertIndex, 0, insert); } + else if (allowDuplicates) { + array.splice(insertIndex, 0, insert); + } } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { @@ -1475,11 +1468,11 @@ var ts; return result; } ts.getAllKeys = getAllKeys; - function getOwnValues(sparseArray) { + function getOwnValues(collection) { var values = []; - for (var key in sparseArray) { - if (hasOwnProperty.call(sparseArray, key)) { - values.push(sparseArray[key]); + for (var key in collection) { + if (hasOwnProperty.call(collection, key)) { + values.push(collection[key]); } } return values; @@ -1698,7 +1691,7 @@ var ts; function cast(value, test) { if (value !== undefined && test(value)) return value; - return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'."); + return ts.Debug.fail("Invalid cast. The supplied value ".concat(value, " did not pass the test '").concat(ts.Debug.getFunctionName(test), "'.")); } ts.cast = cast; /** Does nothing. */ @@ -1789,7 +1782,7 @@ var ts; function memoizeOne(callback) { var map = new ts.Map(); return function (arg) { - var key = typeof arg + ":" + arg; + var key = "".concat(typeof arg, ":").concat(arg); var value = map.get(key); if (value === undefined && !map.has(key)) { value = callback(arg); @@ -2239,7 +2232,7 @@ var ts; ts.createGetCanonicalFileName = createGetCanonicalFileName; function patternText(_a) { var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; + return "".concat(prefix, "*").concat(suffix); } ts.patternText = patternText; /** @@ -2552,7 +2545,7 @@ var ts; } function fail(message, stackCrawlMark) { debugger; - var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + var e = new Error(message ? "Debug Failure. ".concat(message) : "Debug Failure."); if (Error.captureStackTrace) { Error.captureStackTrace(e, stackCrawlMark || fail); } @@ -2560,12 +2553,12 @@ var ts; } Debug.fail = fail; function failBadSyntaxKind(node, message, stackCrawlMark) { - return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind); + return fail("".concat(message || "Unexpected node.", "\r\nNode ").concat(formatSyntaxKind(node.kind), " was unexpected."), stackCrawlMark || failBadSyntaxKind); } Debug.failBadSyntaxKind = failBadSyntaxKind; function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - message = message ? "False expression: " + message : "False expression."; + message = message ? "False expression: ".concat(message) : "False expression."; if (verboseDebugInfo) { message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); } @@ -2575,26 +2568,26 @@ var ts; Debug.assert = assert; function assertEqual(a, b, msg, msg2, stackCrawlMark) { if (a !== b) { - var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; - fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual); + var message = msg ? msg2 ? "".concat(msg, " ").concat(msg2) : msg : ""; + fail("Expected ".concat(a, " === ").concat(b, ". ").concat(message), stackCrawlMark || assertEqual); } } Debug.assertEqual = assertEqual; function assertLessThan(a, b, msg, stackCrawlMark) { if (a >= b) { - fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan); + fail("Expected ".concat(a, " < ").concat(b, ". ").concat(msg || ""), stackCrawlMark || assertLessThan); } } Debug.assertLessThan = assertLessThan; function assertLessThanOrEqual(a, b, stackCrawlMark) { if (a > b) { - fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual); + fail("Expected ".concat(a, " <= ").concat(b), stackCrawlMark || assertLessThanOrEqual); } } Debug.assertLessThanOrEqual = assertLessThanOrEqual; function assertGreaterThanOrEqual(a, b, stackCrawlMark) { if (a < b) { - fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual); + fail("Expected ".concat(a, " >= ").concat(b), stackCrawlMark || assertGreaterThanOrEqual); } } Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; @@ -2610,11 +2603,6 @@ var ts; return value; } Debug.checkDefined = checkDefined; - /** - * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether - * a value is defined at the statement level. - */ - Debug.assertDefined = checkDefined; function assertEachIsDefined(value, message, stackCrawlMark) { for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { var v = value_1[_i]; @@ -2627,50 +2615,45 @@ var ts; return value; } Debug.checkEachDefined = checkEachDefined; - /** - * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether - * the elements of an array are defined at the statement level. - */ - Debug.assertEachDefined = checkEachDefined; function assertNever(member, message, stackCrawlMark) { if (message === void 0) { message = "Illegal value:"; } var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member); - return fail(message + " " + detail, stackCrawlMark || assertNever); + return fail("".concat(message, " ").concat(detail), stackCrawlMark || assertNever); } Debug.assertNever = assertNever; function assertEachNode(nodes, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) { - assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode); + assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '".concat(getFunctionName(test), "'."); }, stackCrawlMark || assertEachNode); } } Debug.assertEachNode = assertEachNode; function assertNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertNode")) { - assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode); + assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNode); } } Debug.assertNode = assertNode; function assertNotNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) { - assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode); + assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " should not have passed test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertNotNode); } } Debug.assertNotNode = assertNotNode; function assertOptionalNode(node, test, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) { - assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode); + assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " did not pass test '").concat(getFunctionName(test), "'."); }, stackCrawlMark || assertOptionalNode); } } Debug.assertOptionalNode = assertOptionalNode; function assertOptionalToken(node, kind, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) { - assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken); + assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node === null || node === void 0 ? void 0 : node.kind), " was not a '").concat(formatSyntaxKind(kind), "' token."); }, stackCrawlMark || assertOptionalToken); } } Debug.assertOptionalToken = assertOptionalToken; function assertMissingNode(node, message, stackCrawlMark) { if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) { - assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode); + assert(node === undefined, message || "Unexpected node.", function () { return "Node ".concat(formatSyntaxKind(node.kind), " was unexpected'."); }, stackCrawlMark || assertMissingNode); } } Debug.assertMissingNode = assertMissingNode; @@ -2691,7 +2674,7 @@ var ts; } Debug.getFunctionName = getFunctionName; function formatSymbol(symbol) { - return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }"; + return "{ name: ".concat(ts.unescapeLeadingUnderscores(symbol.escapedName), "; flags: ").concat(formatSymbolFlags(symbol.flags), "; declarations: ").concat(ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }), " }"); } Debug.formatSymbol = formatSymbol; /** @@ -2712,7 +2695,7 @@ var ts; break; } if (enumValue !== 0 && enumValue & value) { - result = "" + result + (result ? "|" : "") + enumName; + result = "".concat(result).concat(result ? "|" : "").concat(enumName); remainingFlags &= ~enumValue; } } @@ -2822,7 +2805,7 @@ var ts; this.flags & 1 /* Unreachable */ ? "FlowUnreachable" : "UnknownFlow"; var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1); - return "" + flowHeader + (remainingFlags ? " (" + formatFlowFlags(remainingFlags) + ")" : ""); + return "".concat(flowHeader).concat(remainingFlags ? " (".concat(formatFlowFlags(remainingFlags), ")") : ""); } }, __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, @@ -2861,7 +2844,7 @@ var ts; // We don't care, this is debug code that's only enabled with a debugger attached - // we're just taking note of it for anyone checking regex performance in the future. defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]"); - return "NodeArray " + defaultValue; + return "NodeArray ".concat(defaultValue); } } }); @@ -2916,7 +2899,7 @@ var ts; var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" : "Symbol"; var remainingSymbolFlags = this.flags & ~33554432 /* Transient */; - return symbolHeader + " '" + ts.symbolName(this) + "'" + (remainingSymbolFlags ? " (" + formatSymbolFlags(remainingSymbolFlags) + ")" : ""); + return "".concat(symbolHeader, " '").concat(ts.symbolName(this), "'").concat(remainingSymbolFlags ? " (".concat(formatSymbolFlags(remainingSymbolFlags), ")") : ""); } }, __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } } @@ -2926,11 +2909,11 @@ var ts; __tsDebuggerDisplay: { value: function () { var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" : - this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType " + JSON.stringify(this.value) : - this.flags & 2048 /* BigIntLiteral */ ? "LiteralType " + (this.value.negative ? "-" : "") + this.value.base10Value + "n" : + this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType ".concat(JSON.stringify(this.value)) : + this.flags & 2048 /* BigIntLiteral */ ? "LiteralType ".concat(this.value.negative ? "-" : "").concat(this.value.base10Value, "n") : this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" : this.flags & 32 /* Enum */ ? "EnumType" : - this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType " + this.intrinsicName : + this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType ".concat(this.intrinsicName) : this.flags & 1048576 /* Union */ ? "UnionType" : this.flags & 2097152 /* Intersection */ ? "IntersectionType" : this.flags & 4194304 /* Index */ ? "IndexType" : @@ -2949,7 +2932,7 @@ var ts; "ObjectType" : "Type"; var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~1343 /* ObjectTypeKindMask */ : 0; - return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : ""); + return "".concat(typeHeader).concat(this.symbol ? " '".concat(ts.symbolName(this.symbol), "'") : "").concat(remainingObjectFlags ? " (".concat(formatObjectFlags(remainingObjectFlags), ")") : ""); } }, __debugFlags: { get: function () { return formatTypeFlags(this.flags); } }, @@ -2985,11 +2968,11 @@ var ts; __tsDebuggerDisplay: { value: function () { var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" : - ts.isIdentifier(this) ? "Identifier '" + ts.idText(this) + "'" : - ts.isPrivateIdentifier(this) ? "PrivateIdentifier '" + ts.idText(this) + "'" : - ts.isStringLiteral(this) ? "StringLiteral " + JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...") : - ts.isNumericLiteral(this) ? "NumericLiteral " + this.text : - ts.isBigIntLiteral(this) ? "BigIntLiteral " + this.text + "n" : + ts.isIdentifier(this) ? "Identifier '".concat(ts.idText(this), "'") : + ts.isPrivateIdentifier(this) ? "PrivateIdentifier '".concat(ts.idText(this), "'") : + ts.isStringLiteral(this) ? "StringLiteral ".concat(JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")) : + ts.isNumericLiteral(this) ? "NumericLiteral ".concat(this.text) : + ts.isBigIntLiteral(this) ? "BigIntLiteral ".concat(this.text, "n") : ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" : ts.isParameter(this) ? "ParameterDeclaration" : ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" : @@ -3021,7 +3004,7 @@ var ts; ts.isNamedTupleMember(this) ? "NamedTupleMember" : ts.isImportTypeNode(this) ? "ImportTypeNode" : formatSyntaxKind(this.kind); - return "" + nodeHeader + (this.flags ? " (" + formatNodeFlags(this.flags) + ")" : ""); + return "".concat(nodeHeader).concat(this.flags ? " (".concat(formatNodeFlags(this.flags), ")") : ""); } }, __debugKind: { get: function () { return formatSyntaxKind(this.kind); } }, @@ -3068,10 +3051,10 @@ var ts; Debug.enableDebugInfo = enableDebugInfo; function formatDeprecationMessage(name, error, errorAfter, since, message) { var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: "; - deprecationMessage += "'" + name + "' "; - deprecationMessage += since ? "has been deprecated since v" + since : "is deprecated"; - deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v" + errorAfter + "." : "."; - deprecationMessage += message ? " " + ts.formatStringFromArgs(message, [name], 0) : ""; + deprecationMessage += "'".concat(name, "' "); + deprecationMessage += since ? "has been deprecated since v".concat(since) : "is deprecated"; + deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v".concat(errorAfter, ".") : "."; + deprecationMessage += message ? " ".concat(ts.formatStringFromArgs(message, [name], 0)) : ""; return deprecationMessage; } function createErrorDeprecation(name, errorAfter, since, message) { @@ -3202,11 +3185,11 @@ var ts; } }; Version.prototype.toString = function () { - var result = this.major + "." + this.minor + "." + this.patch; + var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) - result += "-" + this.prerelease.join("."); + result += "-".concat(this.prerelease.join(".")); if (ts.some(this.build)) - result += "+" + this.build.join("."); + result += "+".concat(this.build.join(".")); return result; }; Version.zero = new Version(0, 0, 0); @@ -3473,7 +3456,7 @@ var ts; return ts.map(comparators, formatComparator).join(" "); } function formatComparator(comparator) { - return "" + comparator.operator + comparator.operand; + return "".concat(comparator.operator).concat(comparator.operand); } })(ts || (ts = {})); /*@internal*/ @@ -3771,7 +3754,7 @@ var ts; fs = require("fs"); } catch (e) { - throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")"); + throw new Error("tracing requires having fs\n(original error: ".concat(e.message || e, ")")); } } mode = tracingMode; @@ -3783,11 +3766,11 @@ var ts; if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } - var countPart = mode === "build" ? "." + process.pid + "-" + ++traceCount - : mode === "server" ? "." + process.pid + var countPart = mode === "build" ? ".".concat(process.pid, "-").concat(++traceCount) + : mode === "server" ? ".".concat(process.pid) : ""; - var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json"); - var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json"); + var tracePath = ts.combinePaths(traceDir, "trace".concat(countPart, ".json")); + var typesPath = ts.combinePaths(traceDir, "types".concat(countPart, ".json")); legend.push({ configFilePath: configFilePath, tracePath: tracePath, @@ -3877,7 +3860,7 @@ var ts; } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { - writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time); + writeEvent("X", phase, name, args, "\"dur\":".concat(endTime - time), time); } } function writeEvent(eventType, phase, name, args, extras, time) { @@ -3886,11 +3869,11 @@ var ts; if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; ts.performance.mark("beginTracing"); - fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\""); + fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"".concat(eventType, "\",\"cat\":\"").concat(phase, "\",\"ts\":").concat(time, ",\"name\":\"").concat(name, "\"")); if (extras) - fs.writeSync(traceFd, "," + extras); + fs.writeSync(traceFd, ",".concat(extras)); if (args) - fs.writeSync(traceFd, ",\"args\":" + JSON.stringify(args)); + fs.writeSync(traceFd, ",\"args\":".concat(JSON.stringify(args))); fs.writeSync(traceFd, "}"); ts.performance.mark("endTracing"); ts.performance.measure("Tracing", "beginTracing", "endTracing"); @@ -4994,6 +4977,7 @@ var ts; NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers"; NodeCheckFlags[NodeCheckFlags["ContainsSuperPropertyInStaticInitializer"] = 134217728] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags[NodeCheckFlags["InCheckIdentifier"] = 268435456] = "InCheckIdentifier"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -5050,6 +5034,8 @@ var ts; TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ + TypeFlags[TypeFlags["DefinitelyNonNullable"] = 470302716] = "DefinitelyNonNullable"; + /* @internal */ TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains"; TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; @@ -5416,6 +5402,7 @@ var ts; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; + ScriptTarget[ScriptTarget["ES2022"] = 9] = "ES2022"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5584,15 +5571,16 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; - TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2022"] = 8] = "ContainsES2022"; + TransformFlags[TransformFlags["ContainsES2021"] = 16] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 32] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 64] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 128] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 256] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 512] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 1024] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 2048] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; @@ -5619,15 +5607,16 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; - TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2022"] = 8] = "AssertES2022"; + TransformFlags[TransformFlags["AssertES2021"] = 16] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 32] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 64] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 128] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 256] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 512] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 1024] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 2048] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 4096] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. @@ -5931,704 +5920,6 @@ var ts; }, }; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - ts.altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - //// Path Tests - /** - * Determines whether a charCode corresponds to `/` or `\`. - */ - function isAnyDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } - ts.isAnyDirectorySeparator = isAnyDirectorySeparator; - /** - * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). - */ - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - /** - * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - /** - * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). - * - * ```ts - * // POSIX - * pathIsAbsolute("/path/to/file.ext") === true - * // DOS - * pathIsAbsolute("c:/path/to/file.ext") === true - * // URL - * pathIsAbsolute("file:///path/to/file.ext") === true - * // Non-absolute - * pathIsAbsolute("path/to/file.ext") === false - * pathIsAbsolute("./path/to/file.ext") === false - * ``` - */ - function pathIsAbsolute(path) { - return getEncodedRootLength(path) !== 0; - } - ts.pathIsAbsolute = pathIsAbsolute; - /** - * Determines whether a path starts with a relative path component (i.e. `.` or `..`). - */ - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is neither relative nor absolute, e.g. "path/to/file". - * Also known misleadingly as "non-relative". - */ - function pathIsBareSpecifier(path) { - return !pathIsAbsolute(path) && !pathIsRelative(path); - } - ts.pathIsBareSpecifier = pathIsBareSpecifier; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; - function fileExtensionIs(path, extension) { - return path.length > extension.length && ts.endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - //// Path Parsing - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function getBaseFileName(path, extensions, ignoreCase) { - path = normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") { - return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; - } - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); - if (result) - return result; - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArray([root], rest, true); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - * - * ```ts - * // POSIX - * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] - * getPathComponents("/path/to/") === ["/", "path", "to"] - * getPathComponents("/") === ["/"] - * // DOS - * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] - * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] - * getPathComponents("c:/") === ["c:/"] - * getPathComponents("c:") === ["c:"] - * // URL - * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] - * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] - * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] - * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] - * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] - * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] - * getPathComponents("file://server/") === ["file://server/"] - * getPathComponents("file://server") === ["file://server"] - * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] - * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] - * getPathComponents("file:///") === ["file:///"] - * getPathComponents("file://") === ["file://"] - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = combinePaths(currentDirectory, path); - return pathComponents(path, getRootLength(path)); - } - ts.getPathComponents = getPathComponents; - //// Path Formatting - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - * - * ```ts - * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" - * ``` - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - //// Path Normalization - /** - * Normalize path separators, converting `\` into `/`. - */ - function normalizeSlashes(path) { - var index = path.indexOf("\\"); - if (index === -1) { - return path; - } - backslashRegExp.lastIndex = index; // prime regex with known position - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. - * - * ```ts - * // Non-rooted - * combinePaths("path", "to", "file.ext") === "path/to/file.ext" - * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" - * // POSIX - * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" - * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" - * // DOS - * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" - * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" - * // URL - * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" - * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" - * ``` - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = normalizeSlashes(relativePath); - if (!path || getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. Trailing directory separators are preserved. - * - * ```ts - * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" - * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" - * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" - * ``` - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path)); - } - ts.resolvePath = resolvePath; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - * - * ```ts - * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] - * ``` - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function normalizePath(path) { - path = normalizeSlashes(path); - // Most paths don't require normalization - if (!relativePathSegmentRegExp.test(path)) { - return path; - } - // Some paths only require cleanup of `/./` or leading `./` - var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); - if (simplified !== path) { - path = simplified; - if (!relativePathSegmentRegExp.test(path)) { - return path; - } - } - // Other paths require full normalization - var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); - return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.normalizePath = normalizePath; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = isRootedDiskPath(fileName) - ? normalizePath(fileName) - : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - * - * ```ts - * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" - * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" - * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" - * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" - * ``` - */ - function ensurePathIsNonModuleName(path) { - return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; - //// Path Comparisons - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, getRootLength(a)); - var bRoot = b.substring(0, getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = reducePathComponents(getPathComponents(a)); - var bComponents = reducePathComponents(getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_2 = componentComparer(aComponents[i], bComponents[i]); - if (result_2 !== 0 /* EqualTo */) { - return result_2; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = reducePathComponents(getPathComponents(parent)); - var childComponents = reducePathComponents(getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - /** - * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. - * Comparison is case-sensitive between the canonical paths. - * - * Use `containsPath` if file names are not already reduced and absolute. - */ - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - //// Relative Paths - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = reducePathComponents(getPathComponents(from)); - var toComponents = reducePathComponents(getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArray(__spreadArray([""], relative, true), components, true); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; - function isNodeModulesDirectory(dirPath) { - return ts.endsWith(dirPath, "/node_modules"); - } - ts.isNodeModulesDirectory = isNodeModulesDirectory; -})(ts || (ts = {})); var ts; (function (ts) { /** @@ -6697,7 +5988,7 @@ var ts; pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize; ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds; function getLevel(envVar, level) { - return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase()); + return system.getEnvironmentVariable("".concat(envVar, "_").concat(level.toUpperCase())); } function getCustomLevels(baseVariable) { var customLevels; @@ -7023,11 +6314,15 @@ var ts; ts.getFileWatcherEventKind = getFileWatcherEventKind; /*@internal*/ ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"]; + var curSysLog = ts.noop; // eslint-disable-line prefer-const /*@internal*/ - ts.sysLog = ts.noop; // eslint-disable-line prefer-const + function sysLog(s) { + return curSysLog(s); + } + ts.sysLog = sysLog; /*@internal*/ function setSysLog(logger) { - ts.sysLog = logger; + curSysLog = logger; } ts.setSysLog = setSysLog; /** @@ -7162,7 +6457,7 @@ var ts; } function onTimerToUpdateChildWatches() { timerToUpdateChildWatches = undefined; - ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size); + sysLog("sysLog:: onTimerToUpdateChildWatches:: ".concat(cacheToUpdateChildWatches.size)); var start = ts.timestamp(); var invokeMap = new ts.Map(); while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) { @@ -7175,7 +6470,7 @@ var ts; var hasChanges = updateChildWatches(dirName, dirPath, options); invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames); } - ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size); + sysLog("sysLog:: invokingWatchers:: Elapsed:: ".concat(ts.timestamp() - start, "ms:: ").concat(cacheToUpdateChildWatches.size)); callbackCache.forEach(function (callbacks, rootDirName) { var existing = invokeMap.get(rootDirName); if (existing) { @@ -7191,7 +6486,7 @@ var ts; } }); var elapsed = ts.timestamp() - start; - ts.sysLog("sysLog:: Elapsed:: " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches); + sysLog("sysLog:: Elapsed:: ".concat(elapsed, "ms:: onTimerToUpdateChildWatches:: ").concat(cacheToUpdateChildWatches.size, " ").concat(timerToUpdateChildWatches)); } function removeChildWatches(parentWatcher) { if (!parentWatcher) @@ -7651,7 +6946,7 @@ var ts; var remappedPaths = new ts.Map(); var normalizedDir = ts.normalizeSlashes(__dirname); // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls - var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir; + var fileUrlRoot = "file://".concat(ts.getRootLength(normalizedDir) === 1 ? "" : "/").concat(normalizedDir); for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) { var node = _a[_i]; if (node.callFrame.url) { @@ -7660,7 +6955,7 @@ var ts; node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true); } else if (!nativePattern.test(url)) { - node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url); + node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external".concat(externalFileCounter, ".js"))).get(url); externalFileCounter++; } } @@ -7676,7 +6971,7 @@ var ts; if (!err) { try { if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) { - profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile"); + profilePath = _path.join(profilePath, "".concat((new Date()).toISOString().replace(/:/g, "-"), "+P").concat(process.pid, ".cpuprofile")); } } catch (_c) { @@ -7778,7 +7073,7 @@ var ts; * @param createWatcher */ function invokeCallbackAndUpdateWatcher(createWatcher) { - ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); // Call the callback for current directory callback("rename", ""); // If watcher is not closed, update it @@ -7803,7 +7098,7 @@ var ts; } } if (hitSystemWatcherLimit) { - ts.sysLog("sysLog:: " + fileOrDirectory + ":: Defaulting to fsWatchFile"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); return watchPresentFileSystemEntryWithFsWatchFile(); } try { @@ -7819,7 +7114,7 @@ var ts; // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point // so instead of throwing error, use fs.watchFile hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile"); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); return watchPresentFileSystemEntryWithFsWatchFile(); } } @@ -8057,8 +7352,706 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + ts.altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is neither relative nor absolute, e.g. "path/to/file". + * Also known misleadingly as "non-relative". + */ + function pathIsBareSpecifier(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path); + } + ts.pathIsBareSpecifier = pathIsBareSpecifier; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArray([root], rest, true); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + var index = path.indexOf("\\"); + if (index === -1) { + return path; + } + backslashRegExp.lastIndex = index; // prime regex with known position + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + // Most paths don't require normalization + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + // Some paths only require cleanup of `/./` or leading `./` + var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); + if (simplified !== path) { + path = simplified; + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + } + // Other paths require full normalization + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_2 = componentComparer(aComponents[i], bComponents[i]); + if (result_2 !== 0 /* EqualTo */) { + return result_2; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * Use `containsPath` if file names are not already reduced and absolute. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArray(__spreadArray([""], relative, true), components, true); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + ts.isNodeModulesDirectory = isNodeModulesDirectory; +})(ts || (ts = {})); // -// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +// generated from './diagnosticMessages.json' in 'src/compiler' /* @internal */ var ts; (function (ts) { @@ -8150,7 +8143,7 @@ var ts; Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117", "An object literal cannot have multiple properties with the same name."), An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), @@ -8248,10 +8241,10 @@ var ts; A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), - An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), - An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232", "An import declaration can only be used at the top level of a namespace or module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233", "An export declaration can only be used at the top level of a namespace or module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235", "A namespace declaration is only allowed at the top level of a namespace or module."), The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), @@ -8283,6 +8276,9 @@ var ts; An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."), Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, ts.DiagnosticCategory.Error, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."), An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."), + Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided: diag(1269, ts.DiagnosticCategory.Error, "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided_1269", "Cannot use 'export import' on a type or type-only namespace when the '--isolatedModules' flag is provided."), + Decorator_function_return_type_0_is_not_assignable_to_type_1: diag(1270, ts.DiagnosticCategory.Error, "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270", "Decorator function return type '{0}' is not assignable to type '{1}'."), + Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any: diag(1271, ts.DiagnosticCategory.Error, "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271", "Decorator function return type is '{0}' but is expected to be 'void' or 'any'."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."), @@ -8297,7 +8293,7 @@ var ts; Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node12_or_nodenext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12', or 'nodenext'."), - Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext'."), + Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext' or 'nodenext'."), Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), @@ -8418,6 +8414,9 @@ var ts; Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8437,6 +8436,7 @@ var ts; Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function: diag(2311, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311", "Cannot find name '{0}'. Did you mean to write this in an async function?"), An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), @@ -8500,7 +8500,7 @@ var ts; 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_index_signature_for_type_0: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_index_signature_for_type_0_2374", "Duplicate index signature for type '{0}'."), Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2375, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), - 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."), + A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_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_to_refer_to_super_or_this_when_a_derived_2376", "A 'super' call must be the first statement in the constructor to refer to 'super' or 'this' when a derived class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), @@ -8523,6 +8523,7 @@ var ts; constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."), Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2401, ts.DiagnosticCategory.Error, "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401", "A 'super' call must be a root-level statement within a constructor of a derived class that contains initialized properties, parameter properties, or private identifiers."), Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), @@ -8881,12 +8882,10 @@ var ts; Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), - Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), - Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Class_declaration_cannot_implement_overload_list_for_0: diag(2813, ts.DiagnosticCategory.Error, "Class_declaration_cannot_implement_overload_list_for_0_2813", "Class declaration cannot implement overload list for '{0}'."), @@ -8897,11 +8896,13 @@ var ts; Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers: diag(2818, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818", "Duplicate identifier '{0}'. Compiler reserves name '{1}' when emitting 'super' references in static initializers."), Namespace_name_cannot_be_0: diag(2819, ts.DiagnosticCategory.Error, "Namespace_name_cannot_be_0_2819", "Namespace name cannot be '{0}'."), Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), - Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), + Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext' or 'nodenext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), + Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), + Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), 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}'."), @@ -9100,6 +9101,7 @@ var ts; DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Errors_Files: diag(6041, ts.DiagnosticCategory.Message, "Errors_Files_6041", "Errors Files"), Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), @@ -9293,6 +9295,9 @@ var ts; Output_Formatting: diag(6256, ts.DiagnosticCategory.Message, "Output_Formatting_6256", "Output Formatting"), Completeness: diag(6257, ts.DiagnosticCategory.Message, "Completeness_6257", "Completeness"), _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, ts.DiagnosticCategory.Error, "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"), + Found_1_error_in_1: diag(6259, ts.DiagnosticCategory.Message, "Found_1_error_in_1_6259", "Found 1 error in {1}"), + Found_0_errors_in_the_same_file_starting_at_Colon_1: diag(6260, ts.DiagnosticCategory.Message, "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260", "Found {0} errors in the same file, starting at: {1}"), + Found_0_errors_in_1_files: diag(6261, ts.DiagnosticCategory.Message, "Found_0_errors_in_1_files_6261", "Found {0} errors in {1} files."), Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, ts.DiagnosticCategory.Message, "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."), Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, ts.DiagnosticCategory.Message, "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."), Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, ts.DiagnosticCategory.Message, "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."), @@ -9637,9 +9642,8 @@ var ts; Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), - Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), @@ -9656,8 +9660,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), - Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), - Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), 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}>'"), @@ -9667,6 +9669,10 @@ var ts; Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), + Remove_type_from_import_declaration_from_0: diag(90055, ts.DiagnosticCategory.Message, "Remove_type_from_import_declaration_from_0_90055", "Remove 'type' from import declaration from \"{0}\""), + Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), + Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), + Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{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_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9830,6 +9836,10 @@ var ts; Add_missing_attributes: diag(95167, ts.DiagnosticCategory.Message, "Add_missing_attributes_95167", "Add missing attributes"), Add_all_missing_attributes: diag(95168, ts.DiagnosticCategory.Message, "Add_all_missing_attributes_95168", "Add all missing attributes"), Add_undefined_to_optional_property_type: diag(95169, ts.DiagnosticCategory.Message, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"), + Convert_named_imports_to_default_import: diag(95170, ts.DiagnosticCategory.Message, "Convert_named_imports_to_default_import_95170", "Convert named imports to default import"), + Delete_unused_param_tag_0: diag(95171, ts.DiagnosticCategory.Message, "Delete_unused_param_tag_0_95171", "Delete unused '@param' tag '{0}'"), + Delete_all_unused_param_tags: diag(95172, ts.DiagnosticCategory.Message, "Delete_all_unused_param_tags_95172", "Delete all unused '@param' tags"), + Rename_param_tag_name_0_to_1: diag(95173, ts.DiagnosticCategory.Message, "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"), 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?"), @@ -10121,7 +10131,7 @@ var ts; line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; } else { - ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); + ts.Debug.fail("Bad line number. Line: ".concat(line, ", lineStarts.length: ").concat(lineStarts.length, " , line map is correct? ").concat(debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown")); } } var res = lineStarts[line] + character; @@ -11928,6 +11938,7 @@ var ts; tokenValue = tokenValue.slice(0, -1); pos--; } + return getIdentifierToken(); } return token; } @@ -12173,6 +12184,8 @@ var ts; switch (ts.getEmitScriptTarget(options)) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 9 /* ES2022 */: + return "lib.es2022.full.d.ts"; case 8 /* ES2021 */: return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: @@ -12999,12 +13012,17 @@ var ts; /** Gets the text of a jsdoc comment, flattening links to their text. */ function getTextOfJSDocComment(comment) { return typeof comment === "string" ? comment - : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { - // TODO: Other kinds here - return c.kind === 319 /* JSDocText */ ? c.text : "{@link " + (c.name ? ts.entityNameToString(c.name) + " " : "") + c.text + "}"; - }).join(""); + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { return c.kind === 319 /* JSDocText */ ? c.text : formatJSDocLink(c); }).join(""); } ts.getTextOfJSDocComment = getTextOfJSDocComment; + function formatJSDocLink(link) { + var kind = link.kind === 322 /* JSDocLink */ ? "link" + : link.kind === 323 /* JSDocLinkCode */ ? "linkcode" + : "linkplain"; + var name = link.name ? ts.entityNameToString(link.name) : ""; + var space = link.name && link.text.startsWith("://") ? "" : " "; + return "{@".concat(kind, " ").concat(name).concat(space).concat(link.text, "}"); + } /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -14083,21 +14101,10 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - /** - * Create a new escaped identifier map. - * @deprecated Use `new Map<__String, T>()` instead. - */ - function createUnderscoreEscapedMap() { - return new ts.Map(); + function getDeclarationsOfKind(symbol, kind) { + return ts.filter(symbol.declarations || ts.emptyArray, function (d) { return d.kind === kind; }); } - ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - /** - * @deprecated Use `!!map?.size` instead - */ - function hasEntries(map) { - return !!map && !!map.size; - } - ts.hasEntries = hasEntries; + ts.getDeclarationsOfKind = getDeclarationsOfKind; function createSymbolTable(symbols) { var result = new ts.Map(); if (symbols) { @@ -14269,10 +14276,13 @@ var ts; function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } - function packageIdToString(_a) { - var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; - var fullName = subModuleName ? name + "/" + subModuleName : name; - return fullName + "@" + version; + function packageIdToPackageName(_a) { + var name = _a.name, subModuleName = _a.subModuleName; + return subModuleName ? "".concat(name, "/").concat(subModuleName) : name; + } + ts.packageIdToPackageName = packageIdToPackageName; + function packageIdToString(packageId) { + return "".concat(packageIdToPackageName(packageId), "@").concat(packageId.version); } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { @@ -14330,6 +14340,10 @@ var ts; return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module)); } ts.getSourceFileOfModule = getSourceFileOfModule; + function isPlainJsFile(file, checkJs) { + return !!file && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */) && !file.checkJsDirective && checkJs === undefined; + } + ts.isPlainJsFile = isPlainJsFile; function isStatementWithLocals(node) { switch (node.kind) { case 234 /* Block */: @@ -14351,7 +14365,7 @@ var ts; function nodePosToString(node) { var file = getSourceFileOfNode(node); var loc = ts.getLineAndCharacterOfPosition(file, node.pos); - return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + return "".concat(file.fileName, "(").concat(loc.line + 1, ",").concat(loc.character + 1, ")"); } ts.nodePosToString = nodePosToString; function getEndLinePosition(line, sourceFile) { @@ -14490,7 +14504,7 @@ var ts; ts.isPinnedComment = isPinnedComment; function createCommentDirectivesMap(sourceFile, commentDirectives) { var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([ - "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, + "".concat(ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line), commentDirective, ]); })); var usedLines = new ts.Map(); @@ -14507,10 +14521,10 @@ var ts; }); } function markUsed(line) { - if (!directivesByLine.has("" + line)) { + if (!directivesByLine.has("".concat(line))) { return false; } - usedLines.set("" + line, true); + usedLines.set("".concat(line), true); return true; } } @@ -14639,6 +14653,7 @@ var ts; AsyncIterableIterator: ts.emptyArray, AsyncGenerator: ts.emptyArray, AsyncGeneratorFunction: ts.emptyArray, + NumberFormat: ["formatToParts"] }, es2019: { Array: ["flat", "flatMap"], @@ -14660,8 +14675,22 @@ var ts; PromiseConstructor: ["any"], String: ["replaceAll"] }, - esnext: { - NumberFormat: ["formatToParts"] + es2022: { + Array: ["at"], + String: ["at"], + Int8Array: ["at"], + Uint8Array: ["at"], + Uint8ClampedArray: ["at"], + Int16Array: ["at"], + Uint16Array: ["at"], + Int32Array: ["at"], + Uint32Array: ["at"], + Float32Array: ["at"], + Float64Array: ["at"], + BigInt64Array: ["at"], + BigUint64Array: ["at"], + ObjectConstructor: ["hasOwn"], + Error: ["cause"] } }; } @@ -14725,7 +14754,7 @@ var ts; } return node.text; } - return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '".concat(node.kind, "' not accounted for.")); } ts.getLiteralText = getLiteralText; function canUseOriginalText(node, flags) { @@ -15090,6 +15119,15 @@ var ts; }; } ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain; + function createDiagnosticMessageChainFromDiagnostic(diagnostic) { + return typeof diagnostic.messageText === "string" ? { + code: diagnostic.code, + category: diagnostic.category, + messageText: diagnostic.messageText, + next: diagnostic.next, + } : diagnostic.messageText; + } + ts.createDiagnosticMessageChainFromDiagnostic = createDiagnosticMessageChainFromDiagnostic; function createDiagnosticForRange(sourceFile, range, message) { return { file: sourceFile, @@ -15258,7 +15296,8 @@ var ts; node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */ || node.kind === 211 /* ParenthesizedExpression */ || - node.kind === 253 /* VariableDeclaration */) ? + node.kind === 253 /* VariableDeclaration */ || + node.kind === 274 /* ExportSpecifier */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -15675,6 +15714,34 @@ var ts; } } ts.getThisContainer = getThisContainer; + /** + * @returns Whether the node creates a new 'this' scope for its children. + */ + function isThisContainerOrFunctionBlock(node) { + switch (node.kind) { + // Arrow functions use the same scope, but may do so in a "delayed" manner + // For example, `const getThis = () => this` may be before a super() call in a derived constructor + case 213 /* ArrowFunction */: + case 255 /* FunctionDeclaration */: + case 212 /* FunctionExpression */: + case 166 /* PropertyDeclaration */: + return true; + case 234 /* Block */: + switch (node.parent.kind) { + case 170 /* Constructor */: + case 168 /* MethodDeclaration */: + case 171 /* GetAccessor */: + case 172 /* SetAccessor */: + // Object properties can have computed names; only method-like bodies start a new scope + return true; + default: + return false; + } + default: + return false; + } + } + ts.isThisContainerOrFunctionBlock = isThisContainerOrFunctionBlock; function isInTopLevelContext(node) { // The name of a class or function declaration is a BindingIdentifier in its surrounding scope. if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) { @@ -16033,7 +16100,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { @@ -16091,17 +16158,29 @@ var ts; * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). * This function does not test if the node is in a JavaScript file or not. */ - function isRequireVariableDeclaration(node) { + function isVariableDeclarationInitializedToRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ false); + } + ts.isVariableDeclarationInitializedToRequire = isVariableDeclarationInitializedToRequire; + /** + * Like {@link isVariableDeclarationInitializedToRequire} but allows things like `require("...").foo.bar` or `require("...")["baz"]`. + */ + function isVariableDeclarationInitializedToBareOrAccessedRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ true); + } + ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; + function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { if (node.kind === 202 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); + return ts.isVariableDeclaration(node) && + !!node.initializer && + isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); } - ts.isRequireVariableDeclaration = isRequireVariableDeclaration; function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); + && ts.every(node.declarationList.declarations, function (decl) { return isVariableDeclarationInitializedToRequire(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -17256,11 +17335,11 @@ var ts; } ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForUniqueESSymbol(symbol) { - return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName; + return "__@".concat(ts.getSymbolId(symbol), "@").concat(symbol.escapedName); } ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol; function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { - return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description; + return "__#".concat(ts.getSymbolId(containingClassSymbol), "@").concat(description); } ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier; function isKnownSymbol(symbol) { @@ -19588,7 +19667,7 @@ var ts; getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; function setObjectAllocator(alloc) { - ts.objectAllocator = alloc; + Object.assign(ts.objectAllocator, alloc); } ts.setObjectAllocator = setObjectAllocator; function formatStringFromArgs(text, args, baseIndex) { @@ -19596,13 +19675,22 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; + var localizedDiagnosticMessages; /* @internal */ function setLocalizedDiagnosticMessages(messages) { - ts.localizedDiagnosticMessages = messages; + localizedDiagnosticMessages = messages; } ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages; + /* @internal */ + // If the localized messages json is unset, and if given function use it to set the json + function maybeSetLocalizedDiagnosticMessages(getMessages) { + if (!localizedDiagnosticMessages && getMessages) { + localizedDiagnosticMessages = getMessages(); + } + } + ts.maybeSetLocalizedDiagnosticMessages = maybeSetLocalizedDiagnosticMessages; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createDetachedDiagnostic(fileName, start, length, message) { @@ -19921,7 +20009,7 @@ var ts; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; function getUseDefineForClassFields(compilerOptions) { - return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { @@ -19953,7 +20041,7 @@ var ts; } ts.getJSXImplicitImportBase = getJSXImplicitImportBase; function getJSXRuntimeImport(base, options) { - return base ? base + "/" + (options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined; + return base ? "".concat(base, "/").concat(options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined; } ts.getJSXRuntimeImport = getJSXRuntimeImport; function hasZeroOrOneAsteriskCharacter(str) { @@ -19995,16 +20083,6 @@ var ts; (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } }, - setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { - this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); - var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; - if (commonResolved && commonOriginal) { - this.setSymlinkedDirectory(commonOriginal, { - real: commonResolved, - realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), - }); - } - }, setSymlinksFromResolutions: function (files, typeReferenceDirectives) { var _this = this; var _a; @@ -20070,7 +20148,7 @@ var ts; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; - var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; + var implicitExcludePathRegexPattern = "(?!(".concat(ts.commonPackageFolders.join("|"), ")(/|$))"); var filesMatcher = { /** * Matches any single directory segment unless it is the last segment and a .min.js file @@ -20083,7 +20161,7 @@ var ts; * Regex for the ** wildcard. Matches any number of subdirectories. When used for including * files or directories, does not match subdirectories that start with a . character */ - doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + doubleAsteriskRegexFragment: "(/".concat(implicitExcludePathRegexPattern, "[^/.][^/]*)*?"), replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); } }; var directoriesMatcher = { @@ -20092,7 +20170,7 @@ var ts; * Regex for the ** wildcard. Matches any number of subdirectories. When used for including * files or directories, does not match subdirectories that start with a . character */ - doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?", + doubleAsteriskRegexFragment: "(/".concat(implicitExcludePathRegexPattern, "[^/.][^/]*)*?"), replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); } }; var excludeMatcher = { @@ -20110,10 +20188,10 @@ var ts; if (!patterns || !patterns.length) { return undefined; } - var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + var pattern = patterns.map(function (pattern) { return "(".concat(pattern, ")"); }).join("|"); // If excluding, match "foo/bar/baz...", but if including, only allow "foo". var terminator = usage === "exclude" ? "($|/)" : "$"; - return "^(" + pattern + ")" + terminator; + return "^(".concat(pattern, ")").concat(terminator); } ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; function getRegularExpressionsForWildcards(specs, basePath, usage) { @@ -20135,7 +20213,7 @@ var ts; ts.isImplicitGlob = isImplicitGlob; function getPatternFromSpec(spec, basePath, usage) { var pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); - return pattern && "^(" + pattern + ")" + (usage === "exclude" ? "($|/)" : "$"); + return pattern && "^(".concat(pattern, ")").concat(usage === "exclude" ? "($|/)" : "$"); } ts.getPatternFromSpec = getPatternFromSpec; function getSubPatternFromSpec(spec, basePath, usage, _a) { @@ -20213,7 +20291,7 @@ var ts; currentDirectory = ts.normalizePath(currentDirectory); var absolutePath = ts.combinePaths(currentDirectory, path); return { - includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^".concat(pattern, "$"); }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), @@ -20494,7 +20572,7 @@ var ts; */ function extensionFromPath(path) { var ext = tryGetExtensionFromPath(path); - return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension."); + return ext !== undefined ? ext : ts.Debug.fail("File ".concat(path, " has unknown extension.")); } ts.extensionFromPath = extensionFromPath; function isAnySupportedFileExtension(path) { @@ -20972,9 +21050,97 @@ var ts; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + return text.replace(/\$/gm, function () { return "\\$"; }); } ts.escapeSnippetText = escapeSnippetText; + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + ts.isNumericLiteralName = isNumericLiteralName; + function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed) { + return ts.isIdentifierText(name, target) ? ts.factory.createIdentifier(name) : + !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) : + ts.factory.createStringLiteral(name, !!singleQuote); + } + ts.createPropertyNameNodeForIdentifierOrLiteral = createPropertyNameNodeForIdentifierOrLiteral; + function isThisTypeParameter(type) { + return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); + } + ts.isThisTypeParameter = isThisTypeParameter; + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + ts.getNodeModulePathParts = getNodeModulePathParts; })(ts || (ts = {})); /* @internal */ var ts; @@ -22199,7 +22365,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -22218,7 +22384,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -22346,8 +22512,8 @@ var ts; case 131 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; break; case 123 /* PublicKeyword */: case 121 /* PrivateKeyword */: @@ -22371,10 +22537,10 @@ var ts; transformFlags = 1 /* ContainsTypeScript */; break; case 106 /* SuperKeyword */: - transformFlags = 512 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */; + transformFlags = 1024 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */; break; case 124 /* StaticKeyword */: - transformFlags = 512 /* ContainsES2015 */; + transformFlags = 1024 /* ContainsES2015 */; break; case 108 /* ThisKeyword */: // 'this' indicates a lexical 'this' @@ -22443,7 +22609,7 @@ var ts; result.push(createModifier(144 /* ReadonlyKeyword */)); if (flags & 256 /* Async */) result.push(createModifier(131 /* AsyncKeyword */)); - return result; + return result.length ? result : undefined; } // // Names @@ -22471,7 +22637,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 65536 /* ContainsComputedPropertyName */; return node; } @@ -22519,7 +22685,7 @@ var ts; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; } return node; } @@ -22628,20 +22794,20 @@ var ts; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } return node; } @@ -22682,7 +22848,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -23176,11 +23342,11 @@ var ts; node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 262144 /* ContainsBindingPattern */; if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 32768 /* ContainsObjectRestOrSpread */; } return node; @@ -23197,7 +23363,7 @@ var ts; node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 262144 /* ContainsBindingPattern */; return node; } @@ -23216,7 +23382,7 @@ var ts; node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : @@ -23290,8 +23456,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; } return node; } @@ -23313,7 +23479,7 @@ var ts; node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 16 /* ContainsES2020 */ | + 32 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -23344,8 +23510,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; } return node; } @@ -23370,7 +23536,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; return node; } // @api @@ -23429,7 +23595,7 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -23458,7 +23624,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -23482,12 +23648,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } return node; } @@ -23541,14 +23707,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } return node; } @@ -23572,9 +23738,9 @@ var ts; node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 128 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */; + node.transformFlags |= 256 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */; } return node; } @@ -23634,8 +23800,8 @@ var ts; node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */ | + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */ | 1048576 /* ContainsAwait */; return node; } @@ -23701,35 +23867,35 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 16 /* ContainsES2020 */; + node.transformFlags |= 32 /* ContainsES2020 */; } else if (operatorKind === 63 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 512 /* ContainsES2015 */ | - 64 /* ContainsES2018 */ | - 2048 /* ContainsDestructuringAssignment */ | + 1024 /* ContainsES2015 */ | + 128 /* ContainsES2018 */ | + 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 512 /* ContainsES2015 */ | - 2048 /* ContainsDestructuringAssignment */ | + 1024 /* ContainsES2015 */ | + 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 67 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 256 /* ContainsES2016 */; + node.transformFlags |= 512 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 8 /* ContainsES2021 */; + node.transformFlags |= 16 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) return 32768 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 64 /* ContainsES2018 */) { + if (node.transformFlags & 128 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { @@ -23739,7 +23905,7 @@ var ts; if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 64 /* ContainsES2018 */) { + if (target.transformFlags & 128 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -23791,7 +23957,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -23830,9 +23996,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } return node; } @@ -23861,8 +24027,8 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 512 /* ContainsES2015 */ | - 64 /* ContainsES2018 */ | + 1024 /* ContainsES2015 */ | + 128 /* ContainsES2018 */ | 524288 /* ContainsYield */; return node; } @@ -23879,7 +24045,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 16384 /* ContainsRestOrSpread */; return node; } @@ -23892,7 +24058,7 @@ var ts; // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createBaseClassLikeDeclaration(225 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -23918,7 +24084,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -23989,7 +24155,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 103 /* NewKeyword */: - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; break; case 100 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -24016,7 +24182,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -24029,7 +24195,7 @@ var ts; // @api function createSemicolonClassElement() { var node = createBaseNode(233 /* SemicolonClassElement */); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @@ -24193,9 +24359,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; return node; } // @api @@ -24244,7 +24410,7 @@ var ts; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } @@ -24374,7 +24540,7 @@ var ts; 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 131072 /* ContainsBlockScopedBinding */; } return node; @@ -24398,14 +24564,14 @@ var ts; 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } } return node; @@ -24430,7 +24596,7 @@ var ts; node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -24639,7 +24805,7 @@ var ts; // @api function createAssertClause(elements, multiLine) { var node = createBaseNode(292 /* AssertClause */); - node.elements = elements; + node.elements = createNodeArray(elements); node.multiLine = multiLine; node.transformFlags |= 4 /* ContainsESNext */; return node; @@ -25470,7 +25636,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 94 /* ExtendsKeyword */: - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; break; case 117 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -25501,7 +25667,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 32 /* ContainsES2019 */; + node.transformFlags |= 64 /* ContainsES2019 */; return node; } // @api @@ -25552,7 +25718,7 @@ var ts; node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -25582,7 +25748,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 32768 /* ContainsObjectRestOrSpread */; return node; } @@ -26236,7 +26402,7 @@ var ts; * @param visitor Optional callback used to visit any custom prologue directives. */ function copyPrologue(source, target, ensureUseStrict, visitor) { - var offset = copyStandardPrologue(source, target, ensureUseStrict); + var offset = copyStandardPrologue(source, target, 0, ensureUseStrict); return copyCustomPrologue(source, target, offset, visitor); } function isUseStrictPrologue(node) { @@ -26249,12 +26415,14 @@ var ts; * Copies only the standard (string-expression) prologue-directives into the target statement-array. * @param source origin statements array * @param target result statements array + * @param statementOffset The offset at which to begin the copy. * @param ensureUseStrict boolean determining whether the function need to add prologue-directives + * @returns Count of how many directive statements were copied. */ - function copyStandardPrologue(source, target, ensureUseStrict) { + function copyStandardPrologue(source, target, statementOffset, ensureUseStrict) { + if (statementOffset === void 0) { statementOffset = 0; } ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; - var statementOffset = 0; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; @@ -26400,32 +26568,36 @@ var ts; } function updateModifiers(node, modifiers) { var _a; + var modifierArray; if (typeof modifiers === "number") { - modifiers = createModifiersFromModifierFlags(modifiers); - } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + modifierArray = createModifiersFromModifierFlags(modifiers); + } + else { + modifierArray = modifiers; + } + return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : ts.Debug.assertNever(node); } function asNodeArray(array) { @@ -26483,7 +26655,7 @@ var ts; case 326 /* JSDocAugmentsTag */: return "augments"; case 327 /* JSDocImplementsTag */: return "implements"; default: - return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind)); + return ts.Debug.fail("Unsupported kind: ".concat(ts.Debug.formatSyntaxKind(kind))); } } var rawTextScanner; @@ -26676,7 +26848,7 @@ var ts; sourceMapText = mapTextOrStripInternal; } var node = oldFileOfCurrentEmit ? - parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) : + parseOldFileOfCurrentEmit(ts.Debug.checkDefined(bundleFileInfo)) : parseUnparsedSourceFile(bundleFileInfo, stripInternal, length); node.fileName = fileName; node.sourceMapPath = sourceMapPath; @@ -26811,7 +26983,7 @@ var ts; }; var definedTextGetter_1 = function (path) { var result = textGetter_1(path); - return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n"; + return result !== undefined ? result : "/* Input file ".concat(path, " was missing */\r\n"); }; var buildInfo_1; var getAndCacheBuildInfo_1 = function (getText) { @@ -26823,13 +26995,13 @@ var ts; }; node.javascriptPath = declarationTextOrJavascriptPath; node.javascriptMapPath = javascriptMapPath; - node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath); + node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath); node.declarationMapPath = declarationMapPath; node.buildInfoPath = declarationMapTextOrBuildInfoPath; Object.defineProperties(node, { javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } }, javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } }, - declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } }, + declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } }, declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }, buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } } }); @@ -27673,7 +27845,7 @@ var ts; importName: "__createBinding", scoped: false, priority: 1, - text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));" + text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));" }; ts.setModuleDefaultHelper = { name: "typescript:commonjscreatevalue", @@ -31349,7 +31521,7 @@ var ts; for (var _i = 0, viableKeywordSuggestions_1 = viableKeywordSuggestions; _i < viableKeywordSuggestions_1.length; _i++) { var keyword = viableKeywordSuggestions_1[_i]; if (expressionText.length > keyword.length + 2 && ts.startsWith(expressionText, keyword)) { - return keyword + " " + expressionText.slice(keyword.length); + return "".concat(keyword, " ").concat(expressionText.slice(keyword.length)); } } return undefined; @@ -33732,7 +33904,7 @@ var ts; return true; } } - else if (third === 27 /* CommaToken */) { + else if (third === 27 /* CommaToken */ || third === 63 /* EqualsToken */) { return true; } return false; @@ -33825,9 +33997,14 @@ var ts; // - "(x,y)" is a comma expression parsed as a signature with two parameters. // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type. + // - "a ? (b): (function() {})" as well, but inside of a parenthesized type with an arbitrary amount of nesting. // // So we need just a bit of lookahead to ensure that it can only be a signature. - var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type); + var unwrappedType = type; + while ((unwrappedType === null || unwrappedType === void 0 ? void 0 : unwrappedType.kind) === 190 /* ParenthesizedType */) { + unwrappedType = unwrappedType.type; // Skip parens if need be + } + var hasJSDocFunctionType = unwrappedType && ts.isJSDocFunctionType(unwrappedType); if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; @@ -35175,7 +35352,7 @@ var ts; // one out no matter what. var finallyBlock; if (!catchClause || token() === 96 /* FinallyKeyword */) { - parseExpected(96 /* FinallyKeyword */); + parseExpected(96 /* FinallyKeyword */, ts.Diagnostics.catch_or_finally_expected); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); @@ -36219,7 +36396,7 @@ var ts; var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* StringLiteral */); parseExpected(58 /* ColonToken */); - var value = parseLiteralLikeNode(10 /* StringLiteral */); + var value = parseAssignmentExpressionOrHigher(); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause() { @@ -36324,7 +36501,8 @@ var ts; return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(274 /* ExportSpecifier */); + var hasJSDoc = hasPrecedingJSDocComment(); + return withJSDoc(parseImportOrExportSpecifier(274 /* ExportSpecifier */), hasJSDoc); } function parseImportSpecifier() { return parseImportOrExportSpecifier(269 /* ImportSpecifier */); @@ -38113,7 +38291,7 @@ var ts; if (namedArgRegExCache.has(name)) { return namedArgRegExCache.get(name); } - var result = new RegExp("(\\s" + name + "\\s*=\\s*)(?:(?:'([^']*)')|(?:\"([^\"]*)\"))", "im"); + var result = new RegExp("(\\s".concat(name, "\\s*=\\s*)(?:(?:'([^']*)')|(?:\"([^\"]*)\"))"), "im"); namedArgRegExCache.set(name, result); return result; } @@ -38226,7 +38404,11 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; + ts.compileOnSaveCommandLineOption = { + name: "compileOnSave", + type: "boolean", + defaultValueDescription: false, + }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38255,6 +38437,7 @@ var ts; ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], ["es2021", "lib.es2021.d.ts"], + ["es2022", "lib.es2022.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -38298,12 +38481,16 @@ var ts; ["es2021.string", "lib.es2021.string.d.ts"], ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["es2021.intl", "lib.es2021.intl.d.ts"], - ["esnext.array", "lib.es2019.array.d.ts"], + ["es2022.array", "lib.es2022.array.d.ts"], + ["es2022.error", "lib.es2022.error.d.ts"], + ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.string", "lib.es2022.string.d.ts"], + ["esnext.array", "lib.es2022.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.es2021.string.d.ts"], + ["esnext.string", "lib.es2022.string.d.ts"], ["esnext.promise", "lib.es2021.promise.d.ts"], ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; @@ -38335,6 +38522,7 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_how_the_TypeScript_watch_mode_works, + defaultValueDescription: ts.WatchFileKind.UseFsEvents, }, { name: "watchDirectory", @@ -38346,6 +38534,7 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, + defaultValueDescription: ts.WatchDirectoryKind.UseFsEvents, }, { name: "fallbackPolling", @@ -38357,13 +38546,14 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, + defaultValueDescription: ts.PollingWatchKind.PriorityInterval, }, { name: "synchronousWatchDirectory", type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "excludeDirectories", @@ -38399,13 +38589,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "help", shortName: "?", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "watch", @@ -38415,7 +38605,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "preserveWatchOutput", @@ -38423,28 +38613,28 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_all_of_the_files_read_during_the_compilation, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listEmittedFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "pretty", @@ -38452,28 +38642,28 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, - defaultValueDescription: "true" + defaultValueDescription: true, }, { name: "traceResolution", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Log_paths_used_during_the_moduleResolution_process, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "diagnostics", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Output_compiler_performance_information_after_building, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "extendedDiagnostics", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Output_more_detailed_compiler_performance_information_after_building, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "generateCpuProfile", @@ -38509,7 +38699,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "locale", @@ -38535,6 +38725,7 @@ var ts; es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, es2021: 8 /* ES2021 */, + es2022: 9 /* ES2022 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -38544,7 +38735,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, - defaultValueDescription: "ES3" + defaultValueDescription: 0 /* ES3 */, }; var commandOptionsWithoutBuild = [ // CommandLine only options @@ -38554,7 +38745,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "version", @@ -38563,7 +38754,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "init", @@ -38571,7 +38762,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "project", @@ -38590,7 +38781,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "showConfig", @@ -38599,7 +38790,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listFilesOnly", @@ -38609,7 +38800,7 @@ var ts; affectsEmit: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, - defaultValueDescription: "false", + defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, @@ -38636,13 +38827,15 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, }, { name: "lib", type: "list", element: { name: "lib", - type: ts.libMap + type: ts.libMap, + defaultValueDescription: undefined, }, affectsProgramStructure: true, showInSimplifiedHelpView: true, @@ -38657,7 +38850,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "checkJs", @@ -38665,7 +38858,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "jsx", @@ -38677,7 +38870,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_what_JSX_code_is_generated, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "declaration", @@ -38697,7 +38890,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Create_sourcemaps_for_d_ts_files }, { @@ -38708,7 +38901,7 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "sourceMap", @@ -38716,7 +38909,7 @@ var ts; affectsEmit: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Create_source_map_files_for_emitted_JavaScript_files, }, { @@ -38757,7 +38950,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references, }, { @@ -38777,7 +38970,7 @@ var ts; affectsEmit: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Disable_emitting_comments, }, { @@ -38787,7 +38980,7 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_files_from_a_compilation, transpileOptionValue: undefined, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "importHelpers", @@ -38795,7 +38988,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "importsNotUsedAsValues", @@ -38807,7 +39000,8 @@ var ts; affectsEmit: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Emit, - description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types + description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, + defaultValueDescription: 0 /* Remove */, }, { name: "downlevelIteration", @@ -38815,7 +39009,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "isolatedModules", @@ -38823,7 +39017,7 @@ var ts; category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Strict Type Checks { @@ -38834,7 +39028,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noImplicitAny", @@ -38895,7 +39089,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "alwaysStrict", @@ -38913,7 +39107,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_a_local_variables_aren_t_read, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noUnusedParameters", @@ -38921,7 +39115,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "exactOptionalPropertyTypes", @@ -38929,7 +39123,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitReturns", @@ -38937,7 +39131,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noFallthroughCasesInSwitch", @@ -38946,7 +39140,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noUncheckedIndexedAccess", @@ -38954,7 +39148,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Include_undefined_in_index_signature_results, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitOverride", @@ -38962,7 +39156,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noPropertyAccessFromIndexSignature", @@ -38970,7 +39164,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Module Resolution { @@ -39064,14 +39258,14 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "preserveSymlinks", type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "allowUmdGlobalAccess", @@ -39079,7 +39273,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Source Maps { @@ -39104,7 +39298,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "inlineSources", @@ -39112,7 +39306,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Experimental { @@ -39121,7 +39315,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "emitDecoratorMetadata", @@ -39130,7 +39324,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, - defaultValueDescription: "false", + defaultValueDescription: false, }, // Advanced { @@ -39162,7 +39356,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Enable_importing_json_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "out", @@ -39188,7 +39382,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "charset", @@ -39203,7 +39397,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "newLine", @@ -39223,7 +39417,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noLib", @@ -39234,7 +39428,7 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noResolve", @@ -39245,7 +39439,7 @@ var ts; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "stripInternal", @@ -39253,7 +39447,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableSizeLimit", @@ -39261,7 +39455,7 @@ var ts; affectsProgramStructure: true, category: ts.Diagnostics.Editor_Support, description: ts.Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "disableSourceOfProjectReferenceRedirect", @@ -39269,7 +39463,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableSolutionSearching", @@ -39277,7 +39471,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableReferencedProjectLoad", @@ -39285,7 +39479,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitUseStrict", @@ -39293,7 +39487,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noEmitHelpers", @@ -39301,7 +39495,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noEmitOnError", @@ -39310,7 +39504,7 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "preserveConstEnums", @@ -39318,7 +39512,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "declarationDir", @@ -39335,7 +39529,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "allowUnusedLabels", @@ -39344,7 +39538,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "allowUnreachableCode", @@ -39353,7 +39547,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "suppressExcessPropertyErrors", @@ -39361,7 +39555,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "suppressImplicitAnyIndexErrors", @@ -39369,7 +39563,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "forceConsistentCasingInFileNames", @@ -39377,7 +39571,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Ensure_that_casing_is_correct_in_imports, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "maxNodeModuleJsDepth", @@ -39385,7 +39579,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, - defaultValueDescription: "0" + defaultValueDescription: 0, }, { name: "noStrictGenericChecks", @@ -39393,7 +39587,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "useDefineForClassFields", @@ -39410,14 +39604,14 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "keyofStringsOnly", type: "boolean", category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, - defaultValueDescription: "false" + defaultValueDescription: false, }, { // A list of plugins to load in the language service @@ -39459,7 +39653,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "dry", @@ -39467,7 +39661,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "force", @@ -39475,14 +39669,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, } ]; /* @internal */ @@ -39495,12 +39689,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "enable", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "include", @@ -39521,7 +39715,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, ]; /*@internal*/ @@ -39575,8 +39769,8 @@ var ts; } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'".concat(key, "'"); }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--".concat(opt.name), namesOfType); } /* @internal */ function parseCustomTypeOption(opt, value, errors) { @@ -40370,10 +40564,10 @@ var ts; var newValue = compilerOptionsMap.get(cmd.name); var defaultValue = getDefaultValueForOption(cmd); if (newValue !== defaultValue) { - result.push("" + tab + cmd.name + ": " + newValue); + result.push("".concat(tab).concat(cmd.name, ": ").concat(newValue)); } else if (ts.hasProperty(ts.defaultInitCompilerOptions, cmd.name)) { - result.push("" + tab + cmd.name + ": " + defaultValue); + result.push("".concat(tab).concat(cmd.name, ": ").concat(defaultValue)); } }); return result.join(newLine) + newLine; @@ -40424,19 +40618,19 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* " + category + " */" }); + entries.push({ value: "/* ".concat(category, " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; if (compilerOptionsMap.has(option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + optionName = "\"".concat(option.name, "\": ").concat(JSON.stringify(compilerOptionsMap.get(option.name))).concat((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { - optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + optionName = "// \"".concat(option.name, "\": ").concat(JSON.stringify(getDefaultValueForOption(option)), ","); } entries.push({ value: optionName, - description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + description: "/* ".concat(option.description && ts.getLocaleSpecificMessage(option.description) || option.name, " */") }); marginLength = Math.max(optionName.length, marginLength); } @@ -40445,25 +40639,25 @@ var ts; var tab = makePadding(2); 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("".concat(tab, "\"compilerOptions\": {")); + result.push("".concat(tab).concat(tab, "/* ").concat(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 _a = 0, entries_2 = entries; _a < entries_2.length; _a++) { var entry = entries_2[_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))); + result.push(value && "".concat(tab).concat(tab).concat(value).concat(description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { - result.push(tab + "},"); - result.push(tab + "\"files\": ["); + result.push("".concat(tab, "},")); + result.push("".concat(tab, "\"files\": [")); for (var i = 0; i < fileNames.length; i++) { - result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + result.push("".concat(tab).concat(tab).concat(JSON.stringify(fileNames[i])).concat(i === fileNames.length - 1 ? "" : ",")); } - result.push(tab + "]"); + result.push("".concat(tab, "]")); } else { - result.push(tab + "}"); + result.push("".concat(tab, "}")); } result.push("}"); return result.join(newLine) + newLine; @@ -40861,7 +41055,7 @@ var ts; if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) { var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; + extendedConfigPath = "".concat(extendedConfigPath, ".json"); if (!host.fileExists(extendedConfigPath)) { errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig)); return undefined; @@ -41106,7 +41300,7 @@ var ts; // Valid only if *.json specified if (!jsonOnlyIncludeRegexes) { var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); }); - var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; }); + var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^".concat(pattern, "$"); }); jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray; } var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); }); @@ -41287,7 +41481,7 @@ var ts; ? 1 /* Recursive */ : 0 /* None */ }; } - if (ts.isImplicitGlob(spec)) { + if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), flags: 1 /* Recursive */ @@ -41542,7 +41736,7 @@ var ts; var bestVersionKey = result.version, bestVersionPaths = result.paths; if (typeof bestVersionPaths !== "object") { if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths); + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['".concat(bestVersionKey, "']"), "object", typeof bestVersionPaths); } return; } @@ -41653,7 +41847,8 @@ var ts; } } var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.AllFeatures, conditions: ["node", "require", "types"] }; + var features = getDefaultNodeResolutionFeatures(options); + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: features, conditions: ["node", "require", "types"] }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -41737,6 +41932,34 @@ var ts; } } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getDefaultNodeResolutionFeatures(options) { + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 ? NodeResolutionFeatures.Node12Default : + ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext ? NodeResolutionFeatures.NodeNextDefault : + NodeResolutionFeatures.None; + } + /** + * @internal + * Does not try `@types/${packageName}` - use a second pass if needed. + */ + function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: isTraceEnabled(options, host), + failedLookupLocations: [], + packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), + conditions: ts.emptyArray, + features: NodeResolutionFeatures.None, + }; + return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); + var candidate = ts.combinePaths(nodeModulesFolder, packageName); + return getPackageJsonInfo(candidate, /*onlyRecordFailures*/ false, moduleResolutionState); + } + }); + } + ts.resolvePackageNameToPackageJson = resolvePackageNameToPackageJson; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -41920,7 +42143,7 @@ var ts; }; return cache; function getUnderlyingCacheKey(specifier, mode) { - var result = mode === undefined ? specifier : mode + "|" + specifier; + var result = mode === undefined ? specifier : "".concat(mode, "|").concat(specifier); memoizedReverseKeys.set(result, [specifier, mode]); return result; } @@ -41951,7 +42174,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName, mode, redirectedReference) { ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName)); - return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, mode === undefined ? nonRelativeModuleName : mode + "|" + nonRelativeModuleName, createPerModuleNameCache); + return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, mode === undefined ? nonRelativeModuleName : "".concat(mode, "|").concat(nonRelativeModuleName), createPerModuleNameCache); } function createPerModuleNameCache() { var directoryPathMap = new ts.Map(); @@ -42098,10 +42321,10 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference); break; default: - return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: ".concat(moduleResolution)); } if (result && result.resolvedModule) - ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\""); + ts.perfLogger.logInfoEvent("Module \"".concat(moduleName, "\" resolved to \"").concat(result.resolvedModule.resolvedFileName, "\"")); ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null"); if (perFolderCache) { perFolderCache.set(moduleName, resolutionMode, result); @@ -42304,17 +42527,12 @@ var ts; function resolveJSModule(moduleName, initialDir, host) { var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (!resolvedModule) { - throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", ")); + throw new Error("Could not resolve JS module '".concat(moduleName, "' starting at '").concat(initialDir, "'. Looked in: ").concat(failedLookupLocations.join(", "))); } return resolvedModule.resolvedFileName; } ts.resolveJSModule = resolveJSModule; /* @internal */ - function tryResolveJSModule(moduleName, initialDir, host) { - return tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; - } - ts.tryResolveJSModule = tryResolveJSModule; - /* @internal */ var NodeResolutionFeatures; (function (NodeResolutionFeatures) { NodeResolutionFeatures[NodeResolutionFeatures["None"] = 0] = "None"; @@ -42328,13 +42546,15 @@ var ts; // not currently backported to node 12 - https://github.com/nodejs/Release/issues/690 NodeResolutionFeatures[NodeResolutionFeatures["ExportsPatternTrailers"] = 16] = "ExportsPatternTrailers"; NodeResolutionFeatures[NodeResolutionFeatures["AllFeatures"] = 30] = "AllFeatures"; + NodeResolutionFeatures[NodeResolutionFeatures["Node12Default"] = 14] = "Node12Default"; + NodeResolutionFeatures[NodeResolutionFeatures["NodeNextDefault"] = 30] = "NodeNextDefault"; NodeResolutionFeatures[NodeResolutionFeatures["EsmMode"] = 32] = "EsmMode"; })(NodeResolutionFeatures || (NodeResolutionFeatures = {})); function node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Imports | NodeResolutionFeatures.SelfName | NodeResolutionFeatures.Exports, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Node12Default, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.AllFeatures, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); @@ -42417,7 +42637,7 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); } - ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); + ts.Debug.assert(host.fileExists(real), "".concat(path, " linked to nonexistent file ").concat(real)); return real; } function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) { @@ -42620,6 +42840,97 @@ var ts; var versionPaths = packageInfo && packageInfo.versionPaths; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } + /* @internal */ + function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) { + if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) { + // Cached value excludes resolutions to JS files - those could be + // cached separately, but they're used rarely. + return packageJsonInfo.resolvedEntrypoints; + } + var entrypoints; + var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; + var features = getDefaultNodeResolutionFeatures(options); + var requireState = { + compilerOptions: options, + host: host, + traceEnabled: isTraceEnabled(options, host), + failedLookupLocations: [], + packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), + conditions: ["node", "require", "types"], + features: features, + }; + var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, + /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); + entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); + if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) { + for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) { + var conditions = _a[_i]; + var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions }); + var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions); + if (exportResolutions) { + for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) { + var resolution = exportResolutions_1[_b]; + entrypoints = ts.appendIfUnique(entrypoints, resolution.path); + } + } + } + } + return packageJsonInfo.resolvedEntrypoints = entrypoints || false; + } + ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo; + function loadEntrypointsFromExportMap(scope, exports, state, extensions) { + var entrypoints; + if (ts.isArray(exports)) { + for (var _i = 0, exports_1 = exports; _i < exports_1.length; _i++) { + var target = exports_1[_i]; + loadEntrypointsFromTargetExports(target); + } + } + // eslint-disable-next-line no-null/no-null + else if (typeof exports === "object" && exports !== null && allKeysStartWithDot(exports)) { + for (var key in exports) { + loadEntrypointsFromTargetExports(exports[key]); + } + } + else { + loadEntrypointsFromTargetExports(exports); + } + return entrypoints; + function loadEntrypointsFromTargetExports(target) { + var _a, _b; + if (typeof target === "string" && ts.startsWith(target, "./") && target.indexOf("*") === -1) { + var partsAfterFirst = ts.getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + return false; + } + var resolvedTarget = ts.combinePaths(scope.packageDirectory, target); + var finalPath = ts.getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); + var result = loadJSOrExactTSFileName(extensions, finalPath, /*recordOnlyFailures*/ false, state); + if (result) { + entrypoints = ts.appendIfUnique(entrypoints, result, function (a, b) { return a.path === b.path; }); + return true; + } + } + else if (Array.isArray(target)) { + for (var _i = 0, target_1 = target; _i < target_1.length; _i++) { + var t = target_1[_i]; + var success = loadEntrypointsFromTargetExports(t); + if (success) { + return true; + } + } + } + // eslint-disable-next-line no-null/no-null + else if (typeof target === "object" && target !== null) { + return ts.forEach(ts.getOwnKeys(target), function (key) { + if (key === "default" || ts.contains(state.conditions, key) || isApplicableVersionedTypesKey(state.conditions, key)) { + loadEntrypointsFromTargetExports(target[key]); + return true; + } + }); + } + } + } /** * A function for locating the package.json scope for a given path */ @@ -42676,7 +42987,7 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); return result; } @@ -42803,7 +43114,7 @@ var ts; return undefined; } var trailingParts = parts.slice(nameParts.length); - return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : "." + ts.directorySeparator + trailingParts.join(ts.directorySeparator), state, cache, redirectedReference); + return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference); } function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) { if (!scope.packageJsonContent.exports) { @@ -42973,8 +43284,8 @@ var ts; } return toSearchResult(/*value*/ undefined); } - for (var _d = 0, target_1 = target; _d < target_1.length; _d++) { - var elem = target_1[_d]; + for (var _d = 0, target_2 = target; _d < target_2.length; _d++) { + var elem = target_2[_d]; var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); if (result) { return result; @@ -43131,7 +43442,7 @@ var ts; } /* @internal */ function getTypesPackageName(packageName) { - return "@types/" + mangleScopedPackageName(packageName); + return "@types/".concat(mangleScopedPackageName(packageName)); } ts.getTypesPackageName = getTypesPackageName; /* @internal */ @@ -43396,14 +43707,12 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -43463,7 +43772,9 @@ var ts; ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); bind(file); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; delayedBindJSDocTypedefTag(); @@ -43532,7 +43843,7 @@ var ts; if (name) { if (ts.isAmbientModule(node)) { var moduleName = ts.getTextOfIdentifierOrLiteral(name); - return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"".concat(moduleName, "\"")); } if (name.kind === 161 /* ComputedPropertyName */) { var nameExpression = name.expression; @@ -43589,7 +43900,7 @@ var ts; case 163 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 315 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 315 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: ".concat(ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind, ", expected JSDocFunctionType"); }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -43701,7 +44012,7 @@ var ts; var relatedInformation_1 = []; if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) { // export type T; - may have meant export type { T }? - relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }")); + relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { ".concat(ts.unescapeLeadingUnderscores(node.name.escapedText), " }"))); } var declarationName_1 = ts.getNameOfDeclaration(node) || node; ts.forEach(symbol.declarations, function (declaration, index) { @@ -44503,7 +44814,7 @@ var ts; maybeBindExpressionFlowIfCall(node.expression); } function maybeBindExpressionFlowIfCall(node) { - // A top level or LHS of comma expression call expression with a dotted function name and at least one argument + // A top level or comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. if (node.kind === 207 /* CallExpression */) { var call = node; @@ -44671,22 +44982,27 @@ var ts; } return state; } - function onLeft(left, state, _node) { + function onLeft(left, state, node) { if (!state.skip) { - return maybeBind(left); + var maybeBound = maybeBind(left); + if (node.operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(left); + } + return maybeBound; } } - function onOperator(operatorToken, state, node) { + function onOperator(operatorToken, state, _node) { if (!state.skip) { - if (operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } bind(operatorToken); } } - function onRight(right, state, _node) { + function onRight(right, state, node) { if (!state.skip) { - return maybeBind(right); + var maybeBound = maybeBind(right); + if (node.operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(right); + } + return maybeBound; } } function onExit(node, state) { @@ -45137,10 +45453,6 @@ var ts; seen.set(identifier.escapedText, currentKind); continue; } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } } } return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); @@ -45374,7 +45686,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + if (languageVersion < 1 /* ES5 */ && inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -45433,6 +45745,8 @@ var ts; return; } ts.setParent(node, parent); + if (ts.tracing) + node.tracingPath = file.path; var saveInStrictMode = inStrictMode; // Even though in the AST the jsdoc @typedef node belongs to the current node, // its symbol might be in the same scope with the current node's symbol. Consider: @@ -45774,7 +46088,7 @@ var ts; } } function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"".concat(ts.removeFileExtension(file.fileName), "\"")); } function bindExportAssignment(node) { if (!container.symbol || !container.symbol.exports) { @@ -46253,7 +46567,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -46764,6 +47078,9 @@ var ts; TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + // Masks + TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; + TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = new ts.Map(ts.getEntries({ string: 1 /* TypeofEQString */, @@ -46804,6 +47121,9 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive"; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; + CheckMode[CheckMode["RestBindingElement"] = 32] = "RestBindingElement"; + // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, + // we need to preserve generic types instead of substituting them for constraints })(CheckMode || (CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { @@ -46819,8 +47139,7 @@ var ts; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -47017,6 +47336,7 @@ var ts; var location = ts.getParseTreeNode(locationIn); return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; }, + getTypeOfSymbol: getTypeOfSymbol, getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); if (parameter === undefined) @@ -47040,6 +47360,7 @@ var ts; getIndexInfosOfType: getIndexInfosOfType, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: function (type, kind) { return getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType); }, + getIndexType: function (type) { return getIndexType(type); }, getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, @@ -47722,6 +48043,9 @@ var ts; suggestionDiagnostics.add(diagnostic); return diagnostic; } + function isDeprecatedSymbol(symbol) { + return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 134217728 /* Deprecated */); + } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); return addDeprecatedSuggestionWorker(declarations, diagnostic); @@ -47851,30 +48175,34 @@ var ts; else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); - var message = isEitherEnum - ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped_1 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var isSourcePlainJs = ts.isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs); + var isTargetPlainJs = ts.isPlainJsFile(targetSymbolFile, compilerOptions.checkJs); var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; - var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () { + var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, "".concat(firstFile_1.path, "|").concat(secondFile_1.path), function () { return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() }); }); var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); - addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + if (!isSourcePlainJs) + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + if (!isTargetPlainJs) + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); } else { - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + if (!isSourcePlainJs) + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + if (!isTargetPlainJs) + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } } return target; @@ -48297,11 +48625,12 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); + if (getSpellingSuggstions === void 0) { getSpellingSuggstions = true; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48330,6 +48659,8 @@ var ts; // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || lastLocation.kind === 163 /* Parameter */ || + lastLocation.kind === 338 /* JSDocParameterTag */ || + lastLocation.kind === 339 /* JSDocReturnTag */ || lastLocation.kind === 162 /* TypeParameter */ // local types not visible outside the function body : false; @@ -48589,9 +48920,9 @@ var ts; lastSelfReferenceLocation = location; } lastLocation = location; - location = ts.isJSDocTemplateTag(location) ? - ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent : - location.parent; + location = ts.isJSDocTemplateTag(location) ? ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent : + ts.isJSDocParameterTag(location) || ts.isJSDocReturnTag(location) ? ts.getHostSignatureFromJSDoc(location) || location.parent : + location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. @@ -48618,7 +48949,7 @@ var ts; } } if (!result) { - if (nameNotFoundMessage) { + if (nameNotFoundMessage && produceDiagnostics) { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && @@ -48628,7 +48959,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (suggestionCount < maximumSuggestionCount) { + if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48664,7 +48995,7 @@ var ts; return undefined; } // Perform extra checks only if error reporting was requested - if (nameNotFoundMessage) { + if (nameNotFoundMessage && produceDiagnostics) { if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed @@ -48712,24 +49043,19 @@ var ts; 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 */) { - checkSymbolUsageInExpressionContext(result, name, errorLocation); + if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + if (typeOnlyDeclaration) { + var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ + ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type + : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; + var unescapedName = ts.unescapeLeadingUnderscores(name); + addTypeOnlyDeclarationRelatedInfo(error(errorLocation, message, unescapedName), typeOnlyDeclaration, unescapedName); + } } } return result; } - function checkSymbolUsageInExpressionContext(symbol, name, useSite) { - if (!ts.isValidTypeOnlyAliasUseSite(useSite)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol); - if (typeOnlyDeclaration) { - var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ - ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type - : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; - var unescapedName = ts.unescapeLeadingUnderscores(name); - addTypeOnlyDeclarationRelatedInfo(error(useSite, message, unescapedName), typeOnlyDeclaration, unescapedName); - } - } - } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { if (!typeOnlyDeclaration) return diagnostic; @@ -48977,10 +49303,12 @@ var ts; } /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. * If at any point current node is equal to 'parent' node - return true. + * If current node is an IIFE, continue walking up. * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === parent + || (n === stopAt || ts.isFunctionLike(n) && !ts.getImmediatelyInvokedFunctionExpression(n) ? "quit" : false); }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -49031,7 +49359,7 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 295 /* ShorthandPropertyAssignment */ || node.kind === 294 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node); + || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -49728,16 +50056,20 @@ var ts; return; } var host = ts.getJSDocHost(node); - if (host && - ts.isExpressionStatement(host) && - ts.isBinaryExpression(host.expression) && - ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { - // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + if (host && ts.isExpressionStatement(host) && ts.isPrototypePropertyAssignment(host.expression)) { + // /** @param {K} p */ X.prototype.m = function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); if (symbol) { return getDeclarationOfJSPrototypeContainer(symbol); } } + if (host && ts.isFunctionExpression(host) && ts.isPrototypePropertyAssignment(host.parent) && ts.isExpressionStatement(host.parent.parent)) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } if (host && (ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && ts.isBinaryExpression(host.parent.parent) && ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { @@ -49819,8 +50151,14 @@ var ts; var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + var sourceFile = resolvedModule + && (!resolutionDiagnostic || resolutionDiagnostic === ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) + && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { + // If there's a resolutionDiagnostic we need to report it even if a sourceFile is found. + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); @@ -50002,7 +50340,7 @@ var ts; if (!sigs || !sigs.length) { sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); } - if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */, /*skipObjectFunctionPropertyAugment*/ true)) { var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } @@ -50502,7 +50840,7 @@ var ts; var cache = (links.accessibleChainCache || (links.accessibleChainCache = new ts.Map())); // Go from enclosingDeclaration to the first scope we check, so the cache is keyed off the scope and thus shared more var firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, function (_, __, ___, node) { return node; }); - var key = (useOnlyExternalAliasing ? 0 : 1) + "|" + (firstRelevantLocation && getNodeId(firstRelevantLocation)) + "|" + meaning; + var key = "".concat(useOnlyExternalAliasing ? 0 : 1, "|").concat(firstRelevantLocation && getNodeId(firstRelevantLocation), "|").concat(meaning); if (cache.has(key)) { return cache.get(key); } @@ -50962,6 +51300,7 @@ var ts; getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), + getPackageJsonInfoCache: function () { var _a; return (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host); }, useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), redirectTargetsMap: host.redirectTargetsMap, getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); }, @@ -51140,7 +51479,7 @@ var ts; context.approximateLength += 6; return ts.factory.createKeywordTypeNode(147 /* ObjectKeyword */); } - if (isThisTypeParameter(type)) { + if (ts.isThisTypeParameter(type)) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -51350,7 +51689,7 @@ var ts; context.symbolDepth = new ts.Map(); } var links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration); - var key = getTypeId(type) + "|" + context.flags; + var key = "".concat(getTypeId(type), "|").concat(context.flags); if (links) { links.serializedTypes || (links.serializedTypes = new ts.Map()); } @@ -51619,7 +51958,7 @@ var ts; } } if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { - typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined)); + typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... ".concat(properties.length - i, " more ..."), /*questionToken*/ undefined, /*type*/ undefined)); addPropertyToElementList(properties[properties.length - 1], context, typeElements); break; } @@ -51734,7 +52073,7 @@ var ts; else if (types.length > 2) { return [ typeToTypeNodeHelper(types[0], context), - ts.factory.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + ts.factory.createTypeReferenceNode("... ".concat(types.length - 2, " more ..."), /*typeArguments*/ undefined), typeToTypeNodeHelper(types[types.length - 1], context) ]; } @@ -51748,7 +52087,7 @@ var ts; var type = types_2[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result_5.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_5.push(ts.factory.createTypeReferenceNode("... ".concat(types.length - i, " more ..."), /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { result_5.push(typeNode_1); @@ -51832,8 +52171,8 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 170 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - if (signature.thisParameter) { - var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + var thisParameter = tryGetThisParameterDeclaration(signature, context); + if (thisParameter) { parameters.unshift(thisParameter); } var returnTypeNode; @@ -51882,6 +52221,21 @@ var ts; } return node; } + function tryGetThisParameterDeclaration(signature, context) { + if (signature.thisParameter) { + return symbolToParameterDeclaration(signature.thisParameter, context); + } + if (signature.declaration) { + var thisTag = ts.getJSDocThisTag(signature.declaration); + if (thisTag && thisTag.typeExpression) { + return ts.factory.createParameterDeclaration( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "this", + /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); + } + } + } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic @@ -52191,8 +52545,8 @@ var ts; } else { if (parent && getExportsOfSymbol(parent)) { - var exports_1 = getExportsOfSymbol(parent); - ts.forEachEntry(exports_1, function (ex, name) { + var exports_2 = getExportsOfSymbol(parent); + ts.forEachEntry(exports_2, function (ex, name) { if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) { symbolName = ts.unescapeLeadingUnderscores(name); return true; @@ -52256,7 +52610,7 @@ var ts; var text = rawtext; while (((_b = context.typeParameterNamesByText) === null || _b === void 0 ? void 0 : _b.has(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; - text = rawtext + "_" + i; + text = "".concat(rawtext, "_").concat(i); } if (text !== rawtext) { result = ts.factory.createIdentifier(text, result.typeArguments); @@ -52323,10 +52677,8 @@ var ts; firstChar = symbolName.charCodeAt(0); } var expression = void 0; - if (ts.isSingleOrDoubleQuote(firstChar)) { - expression = ts.factory.createStringLiteral(symbolName - .substring(1, symbolName.length - 1) - .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */); + if (ts.isSingleOrDoubleQuote(firstChar) && !(symbol.flags & 8 /* EnumMember */)) { + expression = ts.factory.createStringLiteral(ts.stripQuotes(symbolName).replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */); } else if (("" + +symbolName) === symbolName) { expression = ts.factory.createNumericLiteral(+symbolName); @@ -52355,7 +52707,7 @@ var ts; } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); - return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); + return ts.createPropertyNameNodeForIdentifierOrLiteral(rawName, ts.getEmitScriptTarget(compilerOptions), singleQuote, stringNamed); } // See getNameForSymbolFromNameType for a stringy equivalent function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { @@ -52363,24 +52715,19 @@ var ts; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; - if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) { + if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !ts.isNumericLiteralName(name)) { return ts.factory.createStringLiteral(name, !!singleQuote); } - if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { + if (ts.isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name)); } - return createPropertyNameNodeForIdentifierOrLiteral(name); + return ts.createPropertyNameNodeForIdentifierOrLiteral(name, ts.getEmitScriptTarget(compilerOptions)); } if (nameType.flags & 8192 /* UniqueESSymbol */) { return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */)); } } } - function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) { - return ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) ? ts.factory.createIdentifier(name) : - !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) : - ts.factory.createStringLiteral(name, !!singleQuote); - } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); // Make type parameters created within this context not consume the name outside this context @@ -52474,7 +52821,8 @@ var ts; includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); } if (ts.isIdentifier(node)) { - var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node); + var type = getDeclaredTypeOfSymbol(sym); + var name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : ts.factory.cloneNode(node); name.symbol = sym; // for quickinfo, which uses identifier symbol information return { introducesError: introducesError, node: ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } @@ -52582,7 +52930,7 @@ var ts; function getNameForJSDocFunctionParameter(p, index) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? "args" - : "arg" + index; + : "arg".concat(index); } function rewriteModuleSpecifier(parent, lit) { if (bundled) { @@ -53667,7 +54015,7 @@ var ts; return results_1; } // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static - return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags)); + return ts.Debug.fail("Unhandled class member kind! ".concat(p.__debugFlags || p.flags)); }; } function serializePropertySymbolForInterface(p, baseType) { @@ -53742,7 +54090,7 @@ var ts; if (ref) { return ref; } - var tempName = getUnusedName(rootName + "_base"); + var tempName = getUnusedName("".concat(rootName, "_base")); var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([ ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context)) ], 2 /* Const */)); @@ -53789,7 +54137,7 @@ var ts; var original = input; while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) { i++; - input = original + "_" + i; + input = "".concat(original, "_").concat(i); } (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input); if (id) { @@ -53896,16 +54244,16 @@ var ts; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; - if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) { - return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !ts.isNumericLiteralName(name)) { + return "\"".concat(ts.escapeString(name, 34 /* doubleQuote */), "\""); } - if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { - return "[" + name + "]"; + if (ts.isNumericLiteralName(name) && ts.startsWith(name, "-")) { + return "[".concat(name, "]"); } return name; } if (nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + return "[".concat(getNameOfSymbolAsWritten(nameType.symbol, context), "]"); } } } @@ -54208,9 +54556,12 @@ var ts; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. - function getTypeForBindingElementParent(node) { + function getTypeForBindingElementParent(node, checkMode) { + if (checkMode !== 0 /* Normal */) { + return getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false, checkMode); + } var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false, checkMode); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); @@ -54221,7 +54572,27 @@ var ts; return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + var spreadableProperties = []; + var unspreadableToRestKeys = []; + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */); + if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + spreadableProperties.push(prop); + } + else { + unspreadableToRestKeys.push(literalTypeFromProperty); + } + } if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (unspreadableToRestKeys.length) { + // If the type we're spreading from has properties that cannot + // be spread into the rest type (e.g. getters, methods), ensure + // they are explicitly omitted, as they would in the non-generic case. + omitKeyType = getUnionType(__spreadArray([omitKeyType], unspreadableToRestKeys, true)); + } if (omitKeyType.flags & 131072 /* Never */) { return source; } @@ -54232,13 +54603,9 @@ var ts; return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]); } var members = ts.createSymbolTable(); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) - && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) - && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false)); - } + for (var _b = 0, spreadableProperties_1 = spreadableProperties; _b < spreadableProperties_1.length; _b++) { + var prop = spreadableProperties_1[_b]; + members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false)); } var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfosOfType(source)); result.objectFlags |= 8388608 /* ObjectRestType */; @@ -54312,12 +54679,16 @@ var ts; } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - // If no type or an any type was inferred for parent, infer that for the binding element - if (!parentType || isTypeAny(parentType)) { + var checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + var parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode); + return parentType && getBindingElementTypeFromParentType(declaration, parentType); + } + function getBindingElementTypeFromParentType(declaration, parentType) { + // If an any type was inferred for parent, infer that for the binding element + if (isTypeAny(parentType)) { return parentType; } + var pattern = declaration.parent; // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); @@ -54381,9 +54752,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* Normal */)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -54406,11 +54777,11 @@ var ts; return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type; } // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 242 /* ForInStatement */) { - var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression, /*checkMode*/ checkMode))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 243 /* ForOfStatement */) { @@ -54465,12 +54836,9 @@ var ts; } } if (ts.isInJSFile(declaration)) { - var typeTag = ts.getJSDocType(func); - if (typeTag && ts.isFunctionTypeNode(typeTag)) { - var signature = getSignatureFromDeclaration(typeTag); - var pos = func.parameters.indexOf(declaration); - return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); - } + var type_1 = getParameterTypeOfTypeTag(func, declaration); + if (type_1) + return type_1; } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); @@ -54487,7 +54855,7 @@ var ts; return containerObjectType; } } - var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); + var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode)); return addOptionality(type, isProperty, isOptional); } if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { @@ -54859,7 +55227,7 @@ var ts; // contextual type or, if the element itself is a binding pattern, with the type implied by that binding // pattern. var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType; - return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType))); + return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); } if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -54948,7 +55316,7 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true, 0 /* Normal */), declaration, reportErrors); } function isGlobalSymbolConstructor(node) { var symbol = getSymbolOfNode(node); @@ -55037,9 +55405,9 @@ var ts; if (typeNode === undefined) { return useUnknownInCatchVariables ? unknownType : anyType; } - var type_1 = getTypeOfNode(typeNode); + var type_2 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error - return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; + return isTypeAny(type_2) || type_2 === unknownType ? type_2 : errorType; } // Handle export default expressions if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { @@ -55177,10 +55545,12 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 171 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 172 /* SetAccessor */); - var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing && setterType) { - return instantiateTypeIfNeeded(setterType, symbol); + if (writing) { + var setterType_1 = getAnnotatedAccessorType(setter); + if (setterType_1) { + return instantiateTypeIfNeeded(setterType_1, symbol); + } } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { @@ -55195,6 +55565,7 @@ var ts; return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; } @@ -55265,11 +55636,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_3 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_3; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -55343,6 +55714,39 @@ var ts; } return links.type; } + function getWriteTypeOfSymbolWithDeferredType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.writeType && links.deferralWriteConstituents) { + ts.Debug.assertIsDefined(links.deferralParent); + ts.Debug.assertIsDefined(links.deferralConstituents); + links.writeType = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents); + } + return links.writeType; + } + /** + * Distinct write types come only from set accessors, but union and intersection + * properties deriving from set accessors will either pre-compute or defer the + * union or intersection of the writeTypes of their constituents. To account for + * this, we will assume that any deferred type or transient symbol may have a + * `writeType` (or a deferred write type ready to be computed) that should be + * used before looking for set accessor declarations. + */ + function getWriteTypeOfSymbol(symbol) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { + var writeType = getWriteTypeOfSymbolWithDeferredType(symbol); + if (writeType) { + return writeType; + } + } + if (symbol.flags & 33554432 /* Transient */) { + var writeType = symbol.writeType; + if (writeType) { + return writeType; + } + } + return getSetAccessorTypeOfSymbol(symbol); + } function getSetAccessorTypeOfSymbol(symbol) { if (symbol.flags & 98304 /* Accessor */) { var type = getTypeOfSetAccessor(symbol); @@ -55540,7 +55944,8 @@ var ts; return false; } function getBaseTypeNodeOfClass(type) { - return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + var decl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + return decl && ts.getEffectiveBaseTypeNode(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -55562,8 +55967,8 @@ var ts; */ function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { - var decl = type.symbol.valueDeclaration; - var extended = ts.getEffectiveBaseTypeNode(decl); + var decl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + var extended = decl && ts.getEffectiveBaseTypeNode(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -56679,7 +57084,7 @@ var ts; !leftName ? rightName : !rightName ? leftName : undefined; - var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg".concat(i)); paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } @@ -57290,6 +57695,11 @@ var ts; return simplified !== type ? simplified : getConstraintOfType(type); } function getConstraintFromIndexedAccess(type) { + if (isMappedTypeGenericIndexedAccess(type)) { + // For indexed access types of the form { [P in K]: E }[X], where K is non-generic and X is generic, + // we substitute an instantiation of E where P is replaced with X. + return substituteIndexedMappedType(type.objectType, type.indexType); + } var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType); if (indexConstraint && indexConstraint !== type.indexType) { var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags); @@ -57462,10 +57872,10 @@ var ts; var baseTypes = []; var different = false; for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type_3 = types_7[_i]; - var baseType = getBaseConstraint(type_3); + var type_4 = types_7[_i]; + var baseType = getBaseConstraint(type_4); if (baseType) { - if (baseType !== type_3) { + if (baseType !== type_4) { different = true; } baseTypes.push(baseType); @@ -57494,6 +57904,11 @@ var ts; return constraint ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* IndexedAccess */) { + if (isMappedTypeGenericIndexedAccess(t)) { + // For indexed access types of the form { [P in K]: E }[X], where K is non-generic and X is generic, + // we substitute an instantiation of E where P is replaced with X. + return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType)); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags); @@ -57568,13 +57983,17 @@ var ts; } return type; } + function isMappedTypeGenericIndexedAccess(type) { + return type.flags & 8388608 /* IndexedAccess */ && ts.getObjectFlags(type.objectType) & 32 /* Mapped */ && + !isGenericMappedType(type.objectType) && isGenericIndexType(type.indexType); + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. */ function getApparentType(type) { - var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; + var t = !(type.flags & 465829888 /* Instantiable */) ? type : getBaseConstraintOfType(type) || unknownType; return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 402653316 /* StringLike */ ? globalStringType : @@ -57698,6 +58117,7 @@ var ts; var firstType; var nameType; var propTypes = []; + var writeTypes; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { @@ -57714,6 +58134,10 @@ var ts; firstType = type; nameType = getSymbolLinks(prop).nameType; } + var writeType = getWriteTypeOfSymbol(prop); + if (writeTypes || writeType !== type) { + writeTypes = ts.append(!writeTypes ? propTypes.slice() : writeTypes, writeType); + } else if (type !== firstType) { checkFlags |= 64 /* HasNonUniformType */; } @@ -57742,9 +58166,13 @@ var ts; result.checkFlags |= 65536 /* DeferredType */; result.deferralParent = containingType; result.deferralConstituents = propTypes; + result.deferralWriteConstituents = writeTypes; } else { result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + if (writeTypes) { + result.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes); + } } return result; } @@ -57912,7 +58340,7 @@ var ts; // signature applies to types assignable to 'number' and numeric string literal types. return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || - target === numberType && !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value); + target === numberType && !!(source.flags & 128 /* StringLiteral */) && ts.isNumericLiteralName(source.value); } function getIndexInfosOfStructuredType(type) { if (type.flags & 3670016 /* StructuredType */) { @@ -58160,6 +58588,13 @@ var ts; var typeTag = ts.getJSDocTypeTag(node); return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } + function getParameterTypeOfTypeTag(func, parameter) { + var signature = getSignatureOfTypeTag(func); + if (!signature) + return undefined; + var pos = func.parameters.indexOf(parameter); + return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); + } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); return signature && getReturnTypeOfSignature(signature); @@ -58190,6 +58625,8 @@ var ts; case 205 /* PropertyAccessExpression */: case 206 /* ElementAccessExpression */: return traverse(node.expression); + case 294 /* PropertyAssignment */: + return traverse(node.initializer); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } @@ -58598,7 +59035,7 @@ var ts; return result; } function getAliasId(aliasSymbol, aliasTypeArguments) { - return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : ""; + return aliasSymbol ? "@".concat(getSymbolId(aliasSymbol)) + (aliasTypeArguments ? ":".concat(getTypeListId(aliasTypeArguments)) : "") : ""; } // This function is used to propagate certain flags when creating new object type references and union types. // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type @@ -58784,7 +59221,7 @@ var ts; return undefined; } function getSymbolPath(symbol) { - return symbol.parent ? getSymbolPath(symbol.parent) + "." + symbol.escapedName : symbol.escapedName; + return symbol.parent ? "".concat(getSymbolPath(symbol.parent), ".").concat(symbol.escapedName) : symbol.escapedName; } function getUnresolvedSymbolForEntityName(name) { var identifier = name.kind === 160 /* QualifiedName */ ? name.right : @@ -58795,7 +59232,7 @@ var ts; var parentSymbol = name.kind === 160 /* QualifiedName */ ? getUnresolvedSymbolForEntityName(name.left) : name.kind === 205 /* PropertyAccessExpression */ ? getUnresolvedSymbolForEntityName(name.expression) : undefined; - var path = parentSymbol ? getSymbolPath(parentSymbol) + "." + text : text; + var path = parentSymbol ? "".concat(getSymbolPath(parentSymbol), ".").concat(text) : text; var result = unresolvedSymbols.get(path); if (!result) { unresolvedSymbols.set(path, result = createSymbol(524288 /* TypeAlias */, text, 1048576 /* Unresolved */)); @@ -58868,7 +59305,7 @@ var ts; if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) { return baseType; } - var id = getTypeId(baseType) + ">" + getTypeId(substitute); + var id = "".concat(getTypeId(baseType), ">").concat(getTypeId(substitute)); var cached = substitutionTypes.get(id); if (cached) { return cached; @@ -58884,7 +59321,7 @@ var ts; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : - getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : undefined; } function getConditionalFlowTypeOfType(type, node) { @@ -59069,7 +59506,7 @@ var ts; } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary - return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -59792,9 +60229,9 @@ var ts; return types[0]; } var typeKey = !origin ? getTypeListId(types) : - origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) : - origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) : - "#" + origin.type.id + "|" + getTypeListId(types); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving + origin.flags & 1048576 /* Union */ ? "|".concat(getTypeListId(origin.types)) : + origin.flags & 2097152 /* Intersection */ ? "&".concat(getTypeListId(origin.types)) : + "#".concat(origin.type.id, "|").concat(getTypeListId(types)); // origin type id alone is insufficient, as `keyof x` may resolve to multiple WIP values while `x` is still resolving var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments); var type = unionTypes.get(id); if (!type) { @@ -60316,7 +60753,7 @@ var ts; if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* String */); })) { return stringType; } - var id = getTypeListId(newTypes) + "|" + ts.map(newTexts, function (t) { return t.length; }).join(",") + "|" + newTexts.join(""); + var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); if (!type) { templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes)); @@ -60376,7 +60813,7 @@ var ts; return str; } function getStringMappingTypeForGenericType(symbol, type) { - var id = getSymbolId(symbol) + "," + getTypeId(type); + var id = "".concat(getSymbolId(symbol), ",").concat(getTypeId(type)); var result = stringMappingTypes.get(id); if (!result) { stringMappingTypes.set(id, result = createStringMappingType(symbol, type)); @@ -60454,7 +60891,7 @@ var ts; } var prop = getPropertyOfType(objectType, propName); if (prop) { - if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } @@ -60476,7 +60913,7 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { @@ -60648,9 +61085,6 @@ var ts; return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 8388608 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 16777216 /* IsGenericIndexType */ : 0); } - function isThisTypeParameter(type) { - return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); - } function getSimplifiedType(type, writing) { return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : @@ -60764,7 +61198,7 @@ var ts; return everyType(indexType, function (t) { if (t.flags & 384 /* StringOrNumberLiteral */) { var propName = getPropertyNameFromType(t); - if (isNumericLiteralName(propName)) { + if (ts.isNumericLiteralName(propName)) { var index = +propName; return index >= 0 && index < limit; } @@ -61294,7 +61728,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), removeMissingOrUndefinedType(rightType)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), removeMissingOrUndefinedType(rightType)], 2 /* Subtype */); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -61396,7 +61830,7 @@ var ts; function createUniqueESSymbolType(symbol) { var type = createType(8192 /* UniqueESSymbol */); type.symbol = symbol; - type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); + type.escapedName = "__@".concat(type.symbol.escapedName, "@").concat(getSymbolId(type.symbol)); return type; } function getESSymbolLikeTypeForNode(node) { @@ -62939,7 +63373,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, 0 /* None */, relation)); + var related = relation.get(getRelationKey(source, target, 0 /* None */, relation, /*ignoreConstraints*/ false)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -62991,11 +63425,11 @@ var ts; var overflow = false; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; - var incompatibleStack = []; + var incompatibleStack; var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, 3 /* Both */, /*reportErrors*/ !!errorNode, headMessage); - if (incompatibleStack.length) { + if (incompatibleStack) { reportIncompatibleStack(); } if (overflow) { @@ -63052,19 +63486,19 @@ var ts; return { errorInfo: errorInfo, lastSkippedInfo: lastSkippedInfo, - incompatibleStack: incompatibleStack.slice(), + incompatibleStack: incompatibleStack === null || incompatibleStack === void 0 ? void 0 : incompatibleStack.slice(), overrideNextErrorInfo: overrideNextErrorInfo, - relatedInfo: !relatedInfo ? undefined : relatedInfo.slice() + relatedInfo: relatedInfo === null || relatedInfo === void 0 ? void 0 : relatedInfo.slice(), }; } function reportIncompatibleError(message, arg0, arg1, arg2, arg3) { overrideNextErrorInfo++; // Suppress the next relation error lastSkippedInfo = undefined; // Reset skipped info cache - incompatibleStack.push([message, arg0, arg1, arg2, arg3]); + (incompatibleStack || (incompatibleStack = [])).push([message, arg0, arg1, arg2, arg3]); } function reportIncompatibleStack() { - var stack = incompatibleStack; - incompatibleStack = []; + var stack = incompatibleStack || []; + incompatibleStack = undefined; var info = lastSkippedInfo; lastSkippedInfo = undefined; if (stack.length === 1) { @@ -63085,24 +63519,24 @@ var ts; case ts.Diagnostics.Types_of_property_0_are_incompatible.code: { // Parenthesize a `new` if there is one if (path.indexOf("new ") === 0) { - path = "(" + path + ")"; + path = "(".concat(path, ")"); } var str = "" + args[0]; // If leading, just print back the arg (irrespective of if it's a valid identifier) if (path.length === 0) { - path = "" + str; + path = "".concat(str); } // Otherwise write a dotted name if possible else if (ts.isIdentifierText(str, ts.getEmitScriptTarget(compilerOptions))) { - path = path + "." + str; + path = "".concat(path, ".").concat(str); } // Failing that, check if the name is already a computed name else if (str[0] === "[" && str[str.length - 1] === "]") { - path = "" + path + str; + path = "".concat(path).concat(str); } // And finally write out a computed name as a last resort else { - path = path + "[" + str + "]"; + path = "".concat(path, "[").concat(str, "]"); } break; } @@ -63131,7 +63565,7 @@ var ts; msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) ? "" : "..."; - path = "" + prefix + path + "(" + params + ")"; + path = "".concat(prefix).concat(path, "(").concat(params, ")"); } break; } @@ -63144,7 +63578,7 @@ var ts; break; } default: - return ts.Debug.fail("Unhandled Diagnostic: " + msg.code); + return ts.Debug.fail("Unhandled Diagnostic: ".concat(msg.code)); } } if (path) { @@ -63170,7 +63604,7 @@ var ts; } function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - if (incompatibleStack.length) + if (incompatibleStack) reportIncompatibleStack(); if (message.elidedInCompatabilityPyramid) return; @@ -63186,7 +63620,7 @@ var ts; } } function reportRelationError(message, source, target) { - if (incompatibleStack.length) + if (incompatibleStack) reportIncompatibleStack(); var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1]; var generalizedSource = source; @@ -63298,7 +63732,9 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); + if (reportErrors) { + reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage); + } return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -63310,7 +63746,12 @@ var ts; if (source === target) return -1 /* True */; if (relation === identityRelation) { - return isIdenticalTo(source, target, recursionFlags); + if (source.flags !== target.flags) + return 0 /* False */; + if (source.flags & 67358815 /* Singleton */) + return -1 /* True */; + traceUnionsOrIntersectionsTooLarge(source, target); + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags); } // 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, @@ -63320,163 +63761,130 @@ var ts; 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. - // Then see if the target is stripped down to a single non-union type. - // Note - // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), - // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" - // when dealing with generics. - // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); - if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - target = getNormalizedType(nullStrippedTarget, /*writing*/ true); - } - if (source === nullStrippedTarget) - return -1 /* True */; + // See if we're relating a definitely non-nullable type to a union that includes null and/or undefined + // plus a single non-nullable type. If so, remove null and/or undefined from the target type. + if (source.flags & 470302716 /* DefinitelyNonNullable */ && target.flags & 1048576 /* Union */) { + var types = target.types; + var candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] : + types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] : + undefined; + if (candidate && !(candidate.flags & 98304 /* Nullable */)) { + target = getNormalizedType(candidate, /*writing*/ true); + if (source === target) + return -1 /* True */; + } } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); - if (isPerformingExcessPropertyChecks) { - if (hasExcessProperties(source, target, reportErrors)) { + if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) { + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); + if (isPerformingExcessPropertyChecks) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target); + } + return 0 /* False */; + } + } + var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { - reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target); + var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source); + var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target); + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); + } } return 0 /* False */; } - } - var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) && - source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && - target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && - (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)); - if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) { - if (reportErrors) { - var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source); - var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target); - var calls = getSignaturesOfType(source, 0 /* Call */); - var constructs = getSignaturesOfType(source, 1 /* Construct */); - if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) || - constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) { - reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); - } - else { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); - } + traceUnionsOrIntersectionsTooLarge(source, target); + var skipCaching = source.flags & 1048576 /* Union */ && source.types.length < 4 && !(target.flags & 1048576 /* Union */) || + target.flags & 1048576 /* Union */ && target.types.length < 4 && !(source.flags & 469499904 /* StructuredOrInstantiable */); + var result_7 = skipCaching ? + unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : + recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); + // 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_7 && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags); + inPropertyCheck = false; + } + if (result_7) { + return result_7; } - return 0 /* False */; - } - traceUnionsOrIntersectionsTooLarge(source, target); - var result = 0 /* False */; - var saveErrorInfo = captureErrorCalculationState(); - if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { - // We skip caching when source or target is a union with no more than three constituents. - result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); } - else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); + if (reportErrors) { + reportErrorResults(originalSource, originalTarget, source, target, headMessage); } - if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { - resetErrorInfo(saveErrorInfo); + return 0 /* False */; + } + function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? 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*/ true); + 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 (ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return; } } - if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) { - // The combined constraint of an intersection type is the intersection of the constraints of - // the constituents. When an intersection type contains instantiable types with union type - // constraints, there are situations where we need to examine the combined constraint. One is - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // needs to have its constraint hoisted into an intersection with said type parameter, this way - // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) - // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */)); - if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) { - if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - } - } - } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); } - // 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) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { - inPropertyCheck = true; - result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } - reportErrorResults(source, target, result, isComparingJsxAttributes); - return result; - function reportErrorResults(source, target, result, isComparingJsxAttributes) { - if (!result && reportErrors) { - var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); - var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); - source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; - target = (originalTarget.aliasSymbol || targetHasBase) ? 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 (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && - (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; } + reportRelationError(headMessage, source, target); } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -63503,21 +63911,6 @@ var ts; } } } - function isIdenticalTo(source, target, recursionFlags) { - if (source.flags !== target.flags) - return 0 /* False */; - if (source.flags & 67358815 /* Singleton */) - return -1 /* True */; - traceUnionsOrIntersectionsTooLarge(source, target); - if (source.flags & 3145728 /* UnionOrIntersection */) { - var result_7 = eachTypeRelatedToSomeType(source, target); - if (result_7) { - result_7 &= eachTypeRelatedToSomeType(target, source); - } - return result_7; - } - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags); - } function getTypeOfPropertyInTypes(types, name) { var appendPropType = function (propTypes, type) { var _a; @@ -63616,6 +64009,41 @@ var ts; function shouldCheckAsExcessProperty(prop, container) { return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } + function unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) { + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + return relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); + } + if (target.flags & 1048576 /* Union */) { + return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + if (target.flags & 2097152 /* Intersection */) { + return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); + } + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, getBaseConstraintOrType); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. + // Don't report errors though. Elaborating on whether a source constituent is related to the target is + // not actually useful and leads to some confusing error messages. Instead, we rely on the caller + // checking whether the full intersection viewed as an object is related to the target. + return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -63651,8 +64079,11 @@ var ts; } } if (reportErrors) { + // Elaborate only if we can find a best matching type in the target union var bestMatchingType = getBestMatchingType(source, target, isRelatedTo); - isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], 2 /* Target */, /*reportErrors*/ true); + if (bestMatchingType) { + isRelatedTo(source, bestMatchingType, 2 /* Target */, /*reportErrors*/ true); + } } return 0 /* False */; } @@ -63788,7 +64219,8 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0), relation); + var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0); + var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -63815,16 +64247,13 @@ var ts; targetStack = []; } else { - // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids - // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus - // prevent finding matches- but it should hit up the common cases - var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { - var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); - return "=" + index; - }); }).join(","); + // A key that starts with "*" is an indication that we have type references that reference constrained + // type parameters. For such keys we also check against the key we would have gotten if all type parameters + // were unconstrained. + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -63858,6 +64287,7 @@ var ts; return originalHandler(onlyUnreliable); }; } + var result; if (expandingFlags === 3 /* Both */) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, @@ -63867,8 +64297,13 @@ var ts; depth: sourceDepth, targetDepth: targetDepth }); + result = 3 /* Maybe */; + } + else { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } @@ -63900,98 +64335,97 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); - var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - return result; - } - function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { if (intersectionState & 4 /* PropertyCheck */) { return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); } - if (intersectionState & 8 /* UnionIntersectionCheck */) { - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 1048576 /* Union */) { - return relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */); - } - if (target.flags & 1048576 /* Union */) { - return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); - } - if (target.flags & 2097152 /* Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - } - // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the - // constraints of all non-primitive types in the source into a new intersection. We do this because the - // intersection may further constrain the constraints of the non-primitive types. For example, given a type - // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't - // appear to be comparable to '2'. - if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { - var constraints = ts.sameMap(source.types, getBaseConstraintOrType); - if (constraints !== source.types) { - source = getIntersectionType(constraints); - if (!(source.flags & 2097152 /* Intersection */)) { - return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false); - } + var result; + var originalErrorInfo; + var varianceCheckFailed = false; + var saveErrorInfo = captureErrorCalculationState(); + var sourceFlags = source.flags; + var targetFlags = target.flags; + if (relation === identityRelation) { + // We've already checked that source.flags and target.flags are identical + if (sourceFlags & 3145728 /* UnionOrIntersection */) { + var result_8 = eachTypeRelatedToSomeType(source, target); + if (result_8) { + result_8 &= eachTypeRelatedToSomeType(target, source); } + return result_8; } - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } - var flags = source.flags & target.flags; - if (relation === identityRelation && !(flags & 524288 /* Object */)) { - if (flags & 4194304 /* Index */) { + if (sourceFlags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, 3 /* Both */, /*reportErrors*/ false); } - var result_8 = 0 /* False */; - if (flags & 8388608 /* IndexedAccess */) { - if (result_8 = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) { - return result_8; + if (sourceFlags & 8388608 /* IndexedAccess */) { + if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) { + return result; } } } - if (flags & 16777216 /* Conditional */) { + if (sourceFlags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_8 = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { - return result_8; + if (result = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { + return result; } } } } } } - if (flags & 33554432 /* Substitution */) { + if (sourceFlags & 33554432 /* Substitution */) { return isRelatedTo(source.substitute, target.substitute, 3 /* Both */, /*reportErrors*/ false); } - return 0 /* False */; + if (!(sourceFlags & 524288 /* Object */)) { + return 0 /* False */; + } + } + else if (sourceFlags & 3145728 /* UnionOrIntersection */ || targetFlags & 3145728 /* UnionOrIntersection */) { + if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { + return result; + } + if (source.flags & 2097152 /* Intersection */ || source.flags & 262144 /* TypeParameter */ && target.flags & 1048576 /* Union */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // needs to have its constraint hoisted into an intersection with said type parameter, this way + // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) + // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } + // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: + // Source is instantiable (e.g. source has union or intersection constraint). + // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). + // Source is an intersection, target is an object (e.g. { a } & { b } <=> { a, b }). + // Source is an intersection, target is a union (e.g. { a } & { b: boolean } <=> { a, b: true } | { a, b: false }). + // Source is an intersection, target instantiable (e.g. string & { tag } <=> T["a"] constrained to string & { tag }). + if (!(sourceFlags & 465829888 /* Instantiable */ || + sourceFlags & 524288 /* Object */ && targetFlags & 1048576 /* Union */ || + sourceFlags & 2097152 /* Intersection */ && targetFlags & (524288 /* Object */ | 1048576 /* Union */ | 465829888 /* Instantiable */))) { + return 0 /* False */; + } } - var result; - var originalErrorInfo; - var varianceCheckFailed = false; - var saveErrorInfo = captureErrorCalculationState(); // We limit alias variance probing to only object and conditional types since their alias behavior // is more predictable than other, interned types, which may or may not have an alias depending on // the order in which things were checked. - if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); @@ -64009,7 +64443,7 @@ var ts; isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], 2 /* Target */))) { return result; } - if (target.flags & 262144 /* TypeParameter */) { + if (targetFlags & 262144 /* TypeParameter */) { // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source), 3 /* Both */)) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { @@ -64021,10 +64455,10 @@ var ts; } } } - else if (target.flags & 4194304 /* Index */) { + else if (targetFlags & 4194304 /* Index */) { var targetType_1 = target.type; // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 4194304 /* Index */) { + if (sourceFlags & 4194304 /* Index */) { if (result = isRelatedTo(targetType_1, source.type, 3 /* Both */, /*reportErrors*/ false)) { return result; } @@ -64075,8 +64509,8 @@ var ts; } } } - else if (target.flags & 8388608 /* IndexedAccess */) { - if (source.flags & 8388608 /* IndexedAccess */) { + else if (targetFlags & 8388608 /* IndexedAccess */) { + if (sourceFlags & 8388608 /* IndexedAccess */) { // Relate components directly before falling back to constraint relationships // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, reportErrors)) { @@ -64182,7 +64616,7 @@ var ts; } } } - else if (target.flags & 16777216 /* Conditional */) { + else if (targetFlags & 16777216 /* Conditional */) { // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { @@ -64207,8 +64641,8 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.flags & 134217728 /* TemplateLiteral */) { + else if (targetFlags & 134217728 /* TemplateLiteral */) { + if (sourceFlags & 134217728 /* TemplateLiteral */) { if (relation === comparableRelation) { return templateLiteralTypesDefinitelyUnrelated(source, target) ? 0 /* False */ : -1 /* True */; } @@ -64220,11 +64654,11 @@ var ts; return -1 /* True */; } } - if (source.flags & 8650752 /* TypeVariable */) { - // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch - if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { + if (sourceFlags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch + if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { + if (!constraint || (sourceFlags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */), 3 /* Both */)) { resetErrorInfo(saveErrorInfo); @@ -64237,20 +64671,31 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } + if (isMappedTypeGenericIndexedAccess(source)) { + // For an indexed access type { [P in K]: E}[X], above we have already explored an instantiation of E with X + // substituted for P. We also want to explore type { [P in K]: E }[C], where C is the constraint of X. + var indexConstraint = getConstraintOfType(source.indexType); + if (indexConstraint) { + if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } } } - else if (source.flags & 4194304 /* Index */) { + else if (sourceFlags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* Source */, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } } - else if (source.flags & 134217728 /* TemplateLiteral */ && !(target.flags & 524288 /* Object */)) { - if (!(target.flags & 134217728 /* TemplateLiteral */)) { + else if (sourceFlags & 134217728 /* TemplateLiteral */ && !(targetFlags & 524288 /* Object */)) { + if (!(targetFlags & 134217728 /* TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* Source */, reportErrors))) { resetErrorInfo(saveErrorInfo); @@ -64258,8 +64703,8 @@ var ts; } } } - else if (source.flags & 268435456 /* StringMapping */) { - if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { + else if (sourceFlags & 268435456 /* StringMapping */) { + if (targetFlags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, 3 /* Both */, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; @@ -64273,14 +64718,14 @@ var ts; } } } - else if (source.flags & 16777216 /* Conditional */) { + else if (sourceFlags & 16777216 /* Conditional */) { // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { resetErrorInfo(saveErrorInfo); return 3 /* Maybe */; } - if (target.flags & 16777216 /* Conditional */) { + if (targetFlags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -64308,7 +64753,7 @@ var ts; else { // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way // more assignments than are desirable (since it maps the source check type to its constraint, it loses information) - var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* Source */, reportErrors)) { resetErrorInfo(saveErrorInfo); @@ -64340,9 +64785,10 @@ var ts; } return 0 /* False */; } - var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + var sourceIsPrimitive = !!(sourceFlags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); + sourceFlags = source.flags; } else if (isGenericMappedType(source)) { return 0 /* False */; @@ -64384,7 +64830,7 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive; result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState); @@ -64408,7 +64854,7 @@ var ts; // there exists a constituent of T for every combination of the discriminants of S // with respect to T. We do not report errors here, as we will use the existing // error result from checking each constituent of the union. - if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); @@ -64854,7 +65300,7 @@ var ts; for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) { var targetProp = _c[_b]; var name = targetProp.escapedName; - if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { + if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || ts.isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { var related = propertyRelatedTo(source, target, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); @@ -64923,11 +65369,11 @@ var ts; } } var result = -1 /* True */; - var saveErrorInfo = captureErrorCalculationState(); var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn; var sourceObjectFlags = ts.getObjectFlags(source); var targetObjectFlags = ts.getObjectFlags(target); - if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) { + if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol || + sourceObjectFlags & 4 /* Reference */ && targetObjectFlags & 4 /* Reference */ && source.target === target.target) { // We have instantiations of the same anonymous type (which typically will be the type of a // method). Simply do a pairwise comparison of the signatures in the two signature lists instead // of the much more expensive N * M comparison matrix we explore below. We erase type parameters @@ -64963,6 +65409,7 @@ var ts; else { outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; + var saveErrorInfo = captureErrorCalculationState(); // Only elaborate errors from the first failure var shouldElaborateErrors = reportErrors; for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) { @@ -65331,48 +65778,56 @@ var ts; function isTypeReferenceWithGenericArguments(type) { return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } - /** - * getTypeReferenceId(A) returns "111=0-12=1" - * where A.id=111 and number.id=12 - */ - function getTypeReferenceId(type, typeParameters, depth) { - if (depth === void 0) { depth = 0; } - var result = "" + type.target.id; - for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) { - var t = _a[_i]; - if (isUnconstrainedTypeParameter(t)) { - var index = typeParameters.indexOf(t); - if (index < 0) { - index = typeParameters.length; - typeParameters.push(t); + function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) { + var typeParameters = []; + var constraintMarker = ""; + var sourceId = getTypeReferenceId(source, 0); + var targetId = getTypeReferenceId(target, 0); + return "".concat(constraintMarker).concat(sourceId, ",").concat(targetId).concat(postFix); + // getTypeReferenceId(A) returns "111=0-12=1" + // where A.id=111 and number.id=12 + function getTypeReferenceId(type, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 262144 /* TypeParameter */) { + if (ignoreConstraints || isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + continue; + } + // We mark type references that reference constrained type parameters such that we know to obtain + // and look for a "broadest equivalent key" in the cache. + constraintMarker = "*"; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, depth + 1) + ">"; + continue; } - result += "=" + index; - } - else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { - result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; - } - else { result += "-" + t.id; } + return result; } - return result; } /** * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, intersectionState, relation) { + function getRelationKey(source, target, intersectionState, relation, ignoreConstraints) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } var postFix = intersectionState ? ":" + intersectionState : ""; - if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { - var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix; - } - return source.id + "," + target.id + postFix; + return isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target) ? + getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) : + "".concat(source.id, ",").concat(target.id).concat(postFix); } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -65420,28 +65875,35 @@ var ts; !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons - // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // for maxDepth or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely - // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least maxDepth // levels, but unequal at some level beyond that. - // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially - // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives - // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). - // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of + // In addition, this will also detect when an indexed access has been chained off of maxDepth more times (which is + // essentially the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding + // false positives for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). + // It also detects when a recursive type reference has expanded maxDepth or more times, e.g. if the true branch of // `type A = null extends T ? [A>] : [T]` - // has expanded into `[A>>>>>]` - // in such cases we need to terminate the expansion, and we do so here. + // has expanded into `[A>>>>>]`. In such cases we need + // to terminate the expansion, and we do so here. function isDeeplyNestedType(type, stack, depth, maxDepth) { - if (maxDepth === void 0) { maxDepth = 5; } + if (maxDepth === void 0) { maxDepth = 3; } if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; + var lastTypeId = 0; for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= maxDepth) { - return true; + var t = stack[i]; + if (getRecursionIdentity(t) === identity_1) { + // We only count occurrences with a higher type id than the previous occurrence, since higher + // type ids are an indicator of newer instantiations caused by recursion. + if (t.id >= lastTypeId) { + count++; + if (count >= maxDepth) { + return true; + } } + lastTypeId = t.id; } } } @@ -65736,7 +66198,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -65947,9 +66409,12 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { - return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : - !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + return type.flags & 2097152 /* Intersection */ + ? ts.every(type.types, isObjectTypeWithInferableIndex) + : !!(type.symbol + && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 + && !(type.symbol.flags & 32 /* Class */) + && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -66749,12 +67214,14 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */) { + return; + } if (!inference.isFixed) { if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; @@ -66785,21 +67252,19 @@ var ts; inferencePriority = Math.min(inferencePriority, priority); return; } - else { - // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine - var simplified = getSimplifiedType(target, /*writing*/ false); - if (simplified !== target) { - invokeOnce(source, simplified, inferFromTypes); - } - else if (target.flags & 8388608 /* IndexedAccess */) { - var indexType = getSimplifiedType(target.indexType, /*writing*/ false); - // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider - // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. - if (indexType.flags & 465829888 /* Instantiable */) { - var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false); - if (simplified_1 && simplified_1 !== target) { - invokeOnce(source, simplified_1, inferFromTypes); - } + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target, /*writing*/ false); + if (simplified !== target) { + inferFromTypes(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType, /*writing*/ false); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 465829888 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false); + if (simplified_1 && simplified_1 !== target) { + inferFromTypes(source, simplified_1); } } } @@ -67451,6 +67916,11 @@ var ts; case "BigInt64Array": case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; + case "await": + if (ts.isCallExpression(node.parent)) { + return ts.Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; + } + // falls through default: if (node.parent.kind === 295 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; @@ -67484,11 +67954,11 @@ var ts; case 79 /* Identifier */: if (!ts.isThisInTypeQuery(node)) { var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + getSymbolId(symbol) : undefined; + return symbol !== unknownSymbol ? "".concat(flowContainer ? getNodeId(flowContainer) : "-1", "|").concat(getTypeId(declaredType), "|").concat(getTypeId(initialType), "|").concat(getSymbolId(symbol)) : undefined; } // falls through case 108 /* ThisKeyword */: - return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType); + return "0|".concat(flowContainer ? getNodeId(flowContainer) : "-1", "|").concat(getTypeId(declaredType), "|").concat(getTypeId(initialType)); case 229 /* NonNullExpression */: case 211 /* ParenthesizedExpression */: return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); @@ -67547,35 +68017,13 @@ var ts; } return false; } - function getPropertyAccess(expr) { - if (ts.isAccessExpression(expr)) { - return expr; - } - if (ts.isIdentifier(expr)) { - var symbol = getResolvedSymbol(expr); - if (isConstVariable(symbol)) { - var declaration = symbol.valueDeclaration; - // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' - if (ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && ts.isAccessExpression(declaration.initializer)) { - return declaration.initializer; - } - // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' - if (ts.isBindingElement(declaration) && !declaration.initializer) { - var parent = declaration.parent.parent; - if (ts.isVariableDeclaration(parent) && !parent.type && parent.initializer && (ts.isIdentifier(parent.initializer) || ts.isAccessExpression(parent.initializer))) { - return declaration; - } - } - } - } - return undefined; - } function getAccessedPropertyName(access) { var propertyName; return access.kind === 205 /* PropertyAccessExpression */ ? access.name.escapedText : access.kind === 206 /* ElementAccessExpression */ && ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : access.kind === 202 /* BindingElement */ && (propertyName = getDestructuringPropertyName(access)) ? ts.escapeLeadingUnderscores(propertyName) : - undefined; + access.kind === 163 /* Parameter */ ? ("" + access.parent.parameters.indexOf(access)) : + undefined; } function containsMatchingReference(source, target) { while (ts.isAccessExpression(source)) { @@ -67808,7 +68256,10 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */ && !ignoreObjects) { + if (flags & 524288 /* Object */) { + if (ignoreObjects) { + return 16768959 /* AndFactsMask */; // This is the identity element for computing type facts of intersection. + } return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -67841,10 +68292,23 @@ var ts; // When an intersection contains a primitive type we ignore object type constituents as they are // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); + return getIntersectionTypeFacts(type, ignoreObjects); } return 16777215 /* All */; } + function getIntersectionTypeFacts(type, ignoreObjects) { + // When computing the type facts of an intersection type, certain type facts are computed as `and` + // and others are computed as `or`. + var oredFacts = 0 /* None */; + var andedFacts = 16777215 /* All */; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + var f = getTypeFacts(t, ignoreObjects); + oredFacts |= f; + andedFacts &= f; + } + return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 16768959 /* AndFactsMask */; + } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } @@ -68116,9 +68580,6 @@ var ts; getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : mapType(type, mapper); } - function getConstituentCount(type) { - return type.flags & 1048576 /* Union */ ? type.types.length : 1; - } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); } @@ -68468,20 +68929,21 @@ var ts; } return false; } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, flowNode) { if (initialType === void 0) { initialType = declaredType; } + if (flowNode === void 0) { flowNode = reference.flowNode; } var key; var isKeySet = false; var flowDepth = 0; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode) { + if (!flowNode) { return declaredType; } flowInvocationCount++; var sharedFlowStart = sharedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode)); sharedFlowCount = sharedFlowStart; // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations @@ -68913,13 +69375,58 @@ var ts; } return result; } + function getCandidateDiscriminantPropertyAccess(expr) { + if (ts.isBindingPattern(reference) || ts.isFunctionExpressionOrArrowFunction(reference)) { + // When the reference is a binding pattern or function or arrow expression, we are narrowing a pesudo-reference in + // getNarrowedTypeOfSymbol. An identifier for a destructuring variable declared in the same binding pattern or + // parameter declared in the same parameter list is a candidate. + if (ts.isIdentifier(expr)) { + var symbol = getResolvedSymbol(expr); + var declaration = symbol.valueDeclaration; + if (declaration && (ts.isBindingElement(declaration) || ts.isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) { + return declaration; + } + } + } + else if (ts.isAccessExpression(expr)) { + // An access expression is a candidate if the reference matches the left hand expression. + if (isMatchingReference(reference, expr.expression)) { + return expr; + } + } + else if (ts.isIdentifier(expr)) { + var symbol = getResolvedSymbol(expr); + if (isConstVariable(symbol)) { + var declaration = symbol.valueDeclaration; + // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' + if (ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && ts.isAccessExpression(declaration.initializer) && + isMatchingReference(reference, declaration.initializer.expression)) { + return declaration.initializer; + } + // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' + if (ts.isBindingElement(declaration) && !declaration.initializer) { + var parent = declaration.parent.parent; + if (ts.isVariableDeclaration(parent) && !parent.type && parent.initializer && (ts.isIdentifier(parent.initializer) || ts.isAccessExpression(parent.initializer)) && + isMatchingReference(reference, parent.initializer)) { + return declaration; + } + } + } + } + return undefined; + } function getDiscriminantPropertyAccess(expr, computedType) { - var access, name; var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; - return type.flags & 1048576 /* Union */ && (access = getPropertyAccess(expr)) && (name = getAccessedPropertyName(access)) && - isMatchingReference(reference, ts.isAccessExpression(access) ? access.expression : access.parent.parent.initializer) && - isDiscriminantProperty(type, name) ? - access : undefined; + if (type.flags & 1048576 /* Union */) { + var access = getCandidateDiscriminantPropertyAccess(expr); + if (access) { + var name = getAccessedPropertyName(access); + if (name && isDiscriminantProperty(type, name)) { + return access; + } + } + } + return undefined; } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -68986,7 +69493,7 @@ var ts; function narrowByInKeyword(type, name, assumeTrue) { if (type.flags & 1048576 /* Union */ || type.flags & 524288 /* Object */ && declaredType !== type - || isThisTypeParameter(type) + || ts.isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { return filterType(type, function (t) { return isTypePresencePossible(t, name, assumeTrue); }); } @@ -69623,12 +70130,16 @@ var ts; function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */)); } - function hasNonBindingPatternContextualTypeWithNoGenericTypes(node) { + function hasContextualTypeWithNoGenericTypes(node, checkMode) { // Computing the contextual type for a child of a JSX element involves resolving the type of the // element's tag name, so we exclude that here to avoid circularities. + // If check mode has `CheckMode.RestBindingElement`, we skip binding pattern contextual types, + // as we want the type of a rest element to be generic when possible. var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && - getContextualType(node, 8 /* SkipBindingPatterns */); + (checkMode && checkMode & 32 /* RestBindingElement */ ? + getContextualType(node, 8 /* SkipBindingPatterns */) + : getContextualType(node)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -69641,7 +70152,7 @@ var ts; // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && - (isConstraintPosition(type, reference) || hasNonBindingPatternContextualTypeWithNoGenericTypes(reference)); + (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { @@ -69677,7 +70188,92 @@ var ts; } } } + function getNarrowedTypeOfSymbol(symbol, location) { + var declaration = symbol.valueDeclaration; + if (declaration) { + // If we have a non-rest binding element with no initializer declared as a const variable or a const-like + // parameter (a parameter for which there are no assignments in the function body), and if the parent type + // for the destructuring is a union type, one or more of the binding elements may represent discriminant + // properties, and we want the effects of conditional checks on such discriminants to affect the types of + // other binding elements from the same destructuring. Consider: + // + // type Action = + // | { kind: 'A', payload: number } + // | { kind: 'B', payload: string }; + // + // function f({ kind, payload }: Action) { + // if (kind === 'A') { + // payload.toFixed(); + // } + // if (kind === 'B') { + // payload.toUpperCase(); + // } + // } + // + // Above, we want the conditional checks on 'kind' to affect the type of 'payload'. To facilitate this, we use + // the binding pattern AST instance for '{ kind, payload }' as a pseudo-reference and narrow this reference + // as if it occurred in the specified location. We then recompute the narrowed binding element type by + // destructuring from the narrowed parent type. + if (ts.isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { + var parent = declaration.parent.parent; + if (parent.kind === 253 /* VariableDeclaration */ && ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || parent.kind === 163 /* Parameter */) { + var links = getNodeLinks(location); + if (!(links.flags & 268435456 /* InCheckIdentifier */)) { + links.flags |= 268435456 /* InCheckIdentifier */; + var parentType = getTypeForBindingElementParent(parent, 0 /* Normal */); + links.flags &= ~268435456 /* InCheckIdentifier */; + if (parentType && parentType.flags & 1048576 /* Union */ && !(parent.kind === 163 /* Parameter */ && isSymbolAssigned(symbol))) { + var pattern = declaration.parent; + var narrowedType = getFlowTypeOfReference(pattern, parentType, parentType, /*flowContainer*/ undefined, location.flowNode); + if (narrowedType.flags & 131072 /* Never */) { + return neverType; + } + return getBindingElementTypeFromParentType(declaration, narrowedType); + } + } + } + } + // If we have a const-like parameter with no type annotation or initializer, and if the parameter is contextually + // typed by a signature with a single rest parameter of a union of tuple types, one or more of the parameters may + // represent discriminant tuple elements, and we want the effects of conditional checks on such discriminants to + // affect the types of other parameters in the same parameter list. Consider: + // + // type Action = [kind: 'A', payload: number] | [kind: 'B', payload: string]; + // + // const f: (...args: Action) => void = (kind, payload) => { + // if (kind === 'A') { + // payload.toFixed(); + // } + // if (kind === 'B') { + // payload.toUpperCase(); + // } + // } + // + // Above, we want the conditional checks on 'kind' to affect the type of 'payload'. To facilitate this, we use + // the arrow function AST node for '(kind, payload) => ...' as a pseudo-reference and narrow this reference as + // if it occurred in the specified location. We then recompute the narrowed parameter type by indexing into the + // narrowed tuple type. + if (ts.isParameter(declaration) && !declaration.type && !declaration.initializer && !declaration.dotDotDotToken) { + var func = declaration.parent; + if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) { + var restType = getTypeOfSymbol(contextualSignature.parameters[0]); + if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !isSymbolAssigned(symbol)) { + var narrowedType = getFlowTypeOfReference(func, restType, restType, /*flowContainer*/ undefined, location.flowNode); + var index = func.parameters.indexOf(declaration) - (ts.getThisParameter(func) ? 1 : 0); + return getIndexedAccessType(narrowedType, getNumberLiteralType(index)); + } + } + } + } + } + return getTypeOfSymbol(symbol); + } function checkIdentifier(node, checkMode) { + if (ts.isThisInTypeQuery(node)) { + return checkThisExpression(node); + } var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -69711,9 +70307,9 @@ var ts; markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); + var targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { @@ -69750,7 +70346,7 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getNarrowedTypeOfSymbol(localOrExportSymbol, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && @@ -70480,7 +71076,7 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 202 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 202 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; if (parent.name.kind === 201 /* ArrayBindingPattern */) { @@ -70793,13 +71389,13 @@ var ts; function isCircularMappedProperty(symbol) { return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0); } - function getTypeOfPropertyOfContextualType(type, name) { + function getTypeOfPropertyOfContextualType(type, name, nameType) { return mapType(type, function (t) { var _a; if (isGenericMappedType(t)) { var constraint = getConstraintTypeFromMappedType(t); var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; - var propertyNameType = getStringLiteralType(ts.unescapeLeadingUnderscores(name)); + var propertyNameType = nameType || getStringLiteralType(ts.unescapeLeadingUnderscores(name)); if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { return substituteIndexedMappedType(t, propertyNameType); } @@ -70811,11 +71407,11 @@ var ts; } if (isTupleType(t)) { var restType = getRestTypeOfTupleType(t); - if (restType && isNumericLiteralName(name) && +name >= 0) { + if (restType && ts.isNumericLiteralName(name) && +name >= 0) { return restType; } } - return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), getStringLiteralType(ts.unescapeLeadingUnderscores(name)))) === null || _a === void 0 ? void 0 : _a.type; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(ts.unescapeLeadingUnderscores(name)))) === null || _a === void 0 ? void 0 : _a.type; } return undefined; }, /*noReductions*/ true); @@ -70843,7 +71439,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - return getTypeOfPropertyOfContextualType(type, getSymbolOfNode(element).escapedName); + var symbol = getSymbolOfNode(element); + return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType); } if (element.name) { var nameType_2 = getLiteralTypeFromPropertyName(element.name); @@ -71250,7 +71847,7 @@ var ts; !leftName ? rightName : !rightName ? leftName : undefined; - var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg".concat(i)); paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } @@ -71451,10 +72048,10 @@ var ts; case 161 /* ComputedPropertyName */: return isNumericComputedName(name); case 79 /* Identifier */: - return isNumericLiteralName(name.escapedText); + return ts.isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: case 10 /* StringLiteral */: - return isNumericLiteralName(name.text); + return ts.isNumericLiteralName(name.text); default: return false; } @@ -71464,35 +72061,12 @@ var ts; // but this behavior is consistent with checkIndexedAccess return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } - function isNumericLiteralName(name) { - // The intent of numeric names is that - // - they are names with text in a numeric form, and that - // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', - // acquired by applying the abstract 'ToNumber' operation on the name's text. - // - // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. - // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. - // - // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' - // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. - // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names - // because their 'ToString' representation is not equal to their original text. - // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. - // - // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. - // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. - // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. - // - // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. - // This is desired behavior, because when indexing with them as numeric entities, you are indexing - // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. - return (+name).toString() === name; - } function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) - && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */ + && node.parent.kind !== 171 /* GetAccessor */ && node.parent.kind !== 172 /* SetAccessor */) { return links.resolvedType = errorType; } links.resolvedType = checkExpression(node.expression); @@ -71523,7 +72097,7 @@ var ts; function isSymbolWithNumericName(symbol) { var _a; var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; - return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name)); + return ts.isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name)); } function isSymbolWithSymbolName(symbol) { var _a; @@ -71762,15 +72336,9 @@ var ts; } } function isValidSpreadType(type) { - if (type.flags & 465829888 /* Instantiable */) { - var constraint = getBaseConstraintOfType(type); - if (constraint !== undefined) { - return isValidSpreadType(constraint); - } - } - return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || - getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + var t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType)); + return !!(t.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + t.flags & 3145728 /* UnionOrIntersection */ && ts.every(t.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { checkJsxOpeningLikeElementOrOpeningFragment(node); @@ -72575,11 +73143,14 @@ var ts; if (!ts.getContainingClass(privId)) { return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } - if (!ts.isExpressionNode(privId)) { - return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression); - } - if (!getSymbolForPrivateIdentifierExpression(privId)) { - return grammarErrorOnNode(privId, ts.Diagnostics.Cannot_find_name_0, ts.idText(privId)); + if (!ts.isForInStatement(privId.parent)) { + if (!ts.isExpressionNode(privId)) { + return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression); + } + var isInOperation = ts.isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 101 /* InKeyword */; + if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) { + return grammarErrorOnNode(privId, ts.Diagnostics.Cannot_find_name_0, ts.idText(privId)); + } } return false; } @@ -72664,23 +73235,6 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } - if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && !useDefineForClassFields)) { - var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); - var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { - if (n === lexicalClass_1) - return "quit"; - if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { - return true; - } - return false; - }); - if (parentStaticFieldInitializer) { - var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); - ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); - var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); - ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); - } - } if (isAnyLike) { if (lexicallyScopedSymbol) { return isErrorType(apparentType) ? errorType : apparentType; @@ -72721,7 +73275,7 @@ var ts; } var propType; if (!prop) { - var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? + var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || ts.isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : undefined; if (!(indexInfo && indexInfo.type)) { var isUncheckedJS = isUncheckedJSSuggestion(node, leftType.symbol, /*excludeClasses*/ true); @@ -72738,7 +73292,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); + reportNonexistentProperty(right, ts.isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); } return errorType; } @@ -72751,7 +73305,7 @@ var ts; } } else { - if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); @@ -72763,7 +73317,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); } return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } @@ -73031,7 +73585,7 @@ var ts; } function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ true, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -73277,7 +73831,7 @@ var ts; } var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType; var accessFlags = ts.isAssignmentTarget(node) ? - 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0) : + 4 /* Writing */ | (isGenericObjectType(objectType) && !ts.isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0) : 32 /* ExpressionPosition */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType; return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); @@ -74210,7 +74764,7 @@ var ts; } 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 chain = ts.chainDiagnosticMessages(ts.map(diags_3, ts.createDiagnosticMessageChainFromDiagnostic), ts.Diagnostics.No_overload_matches_this_call); // The below is a spread to guarantee we get a new (mutable) array - our `flatMap` helper tries to do "smart" optimizations where it reuses input // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic var related = __spreadArray([], ts.flatMap(diags_3, function (d) { return d.relatedInformation; }), true); @@ -74427,7 +74981,7 @@ var ts; typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + typeArguments.push(getDefaultFromTypeParameter(typeParameters[typeArguments.length]) || getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } return typeArguments; } @@ -75083,8 +75637,7 @@ var ts; */ function checkCallExpression(node, checkMode) { var _a; - if (!checkGrammarTypeArguments(node, node.typeArguments)) - checkGrammarArguments(node.arguments); + checkGrammarTypeArguments(node, node.typeArguments); var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that @@ -75189,8 +75742,7 @@ var ts; } function checkImportCallExpression(node) { // Check grammar of dynamic import - if (!checkGrammarArguments(node.arguments)) - checkGrammarImportCallExpression(node); + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -75235,8 +75787,8 @@ var ts; if (hasDefaultOnly && type && !isErrorType(type)) { var synthType = type; if (!synthType.defaultOnlyType) { - var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); - synthType.defaultOnlyType = type_4; + var type_5 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_5; } return synthType.defaultOnlyType; } @@ -75445,6 +75997,10 @@ var ts; return restParameter.escapedName; } function getParameterIdentifierNameAtPosition(signature, pos) { + var _a; + if (((_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 315 /* JSDocFunctionType */) { + return undefined; + } var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { var param = signature.parameters[pos]; @@ -75686,27 +76242,28 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { var declaration = parameter.valueDeclaration; - links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); if (declaration.name.kind !== 79 /* Identifier */) { // if inference didn't come up with anything but unknown, fall back to the binding pattern if present. if (links.type === unknownType) { links.type = getTypeFromBindingPattern(declaration.name); } - assignBindingElementTypes(declaration.name); + assignBindingElementTypes(declaration.name, links.type); } } } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push // the destructured type into the contained binding elements. - function assignBindingElementTypes(pattern) { + function assignBindingElementTypes(pattern, parentType) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { + var type = getBindingElementTypeFromParentType(element, parentType); if (element.name.kind === 79 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + getSymbolLinks(getSymbolOfNode(element)).type = type; } else { - assignBindingElementTypes(element.name); + assignBindingElementTypes(element.name, type); } } } @@ -75959,12 +76516,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_5 = getBaseConstraintOfType(operandType) || operandType; + var type_6 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_5.flags & 3 /* AnyOrUnknown */) { + if (type_6.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -77417,11 +77974,11 @@ var ts; } } function checkExpressionCached(node, checkMode) { + if (checkMode && checkMode !== 0 /* Normal */) { + return checkExpression(node, checkMode); + } var links = getNodeLinks(node); if (!links.resolvedType) { - if (checkMode && checkMode !== 0 /* Normal */) { - return checkExpression(node, checkMode); - } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -77441,10 +77998,12 @@ var ts; node.kind === 228 /* AsExpression */ || ts.isJSDocTypeAssertion(node); } - function checkDeclarationInitializer(declaration, contextualType) { + function checkDeclarationInitializer(declaration, checkMode, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || - (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); + (contextualType ? + checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, checkMode || 0 /* Normal */) + : checkExpressionCached(initializer, checkMode)); return ts.isParameter(declaration) && declaration.name.kind === 201 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; @@ -77759,7 +78318,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -78084,6 +78643,7 @@ var ts; } } checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkUnmatchedJSDocParameters(node); ts.forEach(node.parameters, checkParameter); // TODO(rbuckton): Should we start checking JSDoc types? if (node.type) { @@ -78314,9 +78874,6 @@ var ts; checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); - if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { - error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); - } // property signatures already report "initializer not allowed in ambient context" elsewhere if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* PropertyDeclaration */ && node.initializer) { error(node, ts.Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); @@ -78405,32 +78962,38 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - // The first statement in the body of a constructor (excluding prologue directives) must be a super call - // if both of the following are true: + // A super call must be root-level in a constructor if both of the following are true: // - 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.getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && + var superCallShouldBeRootLevel = (ts.getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); - // Skip past any prologue directives to find the first statement - // to ensure that it was a super call. - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { - var statement = statements_4[_i]; - if (statement.kind === 237 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; + if (superCallShouldBeRootLevel) { + // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional + // See GH #8277 + if (!superCallIsRootLevelInConstructor(superCall, node.body)) { + error(superCall, ts.Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); + } + // Skip past any prologue directives to check statements for referring to 'super' or 'this' before a super call + else { + var superCallStatement = void 0; + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isExpressionStatement(statement) && ts.isSuperCall(ts.skipOuterExpressions(statement.expression))) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement) && nodeImmediatelyReferencesSuperOrThis(statement)) { + break; + } } - if (!ts.isPrologueDirective(statement)) { - break; + // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional + // See GH #8277 + if (superCallStatement === undefined) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers); } } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers); - } } } else if (!classExtendsNull) { @@ -78438,6 +79001,19 @@ var ts; } } } + function superCallIsRootLevelInConstructor(superCall, body) { + var superCallParent = ts.walkUpParenthesizedExpressions(superCall.parent); + return ts.isExpressionStatement(superCallParent) && superCallParent.parent === body; + } + function nodeImmediatelyReferencesSuperOrThis(node) { + if (node.kind === 106 /* SuperKeyword */ || node.kind === 108 /* ThisKeyword */) { + return true; + } + if (ts.isThisContainerOrFunctionBlock(node)) { + return false; + } + return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); + } function checkAccessorDeclaration(node) { if (produceDiagnostics) { // Grammar checking accessors @@ -79428,28 +80004,24 @@ var ts; if (returnType.flags & 1 /* Any */) { return; } + var headMessage; var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; switch (node.parent.kind) { case 256 /* ClassDeclaration */: + headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 163 /* Parameter */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; case 166 /* PropertyDeclaration */: + case 163 /* Parameter */: + headMessage = ts.Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -79457,7 +80029,7 @@ var ts; default: return ts.Debug.fail(); } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -79639,31 +80211,6 @@ var ts; } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); - if (!ts.getParameterSymbolFromJSDoc(node)) { - var decl = ts.getHostSignatureFromJSDoc(node); - // don't issue an error for invalid hosts -- just functions -- - // and give a better error message when the host function mentions `arguments` - // but the tag doesn't have an array type - if (decl) { - var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); - if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { - return; - } - if (!containsArgumentsReference(decl)) { - if (ts.isQualifiedName(node.name)) { - error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); - } - else { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); - } - } - else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && - node.typeExpression && node.typeExpression.type && - !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 160 /* QualifiedName */ ? node.name.right : node.name)); - } - } - } } function checkJSDocPropertyTag(node) { checkSourceElement(node.typeExpression); @@ -80365,7 +80912,8 @@ var ts; } // check private/protected variable access var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); + var parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + var parentType = getTypeForBindingElementParent(parent, parentCheckMode); var name = node.propertyName || node.name; if (parentType && !ts.isBindingPattern(name)) { var exprType = getLiteralTypeFromPropertyName(name); @@ -80421,7 +80969,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { checkAliasSymbol(node); return; } @@ -80499,7 +81047,7 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); @@ -81163,7 +81711,7 @@ var ts; function getPropertyNameForKnownSymbolName(symbolName) { var ctorType = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false); var uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), ts.escapeLeadingUnderscores(symbolName)); - return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@" + symbolName; + return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : "__@".concat(symbolName); } /** * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like @@ -81604,7 +82152,7 @@ var ts; var declaration = catchClause.variableDeclaration; var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); if (typeNode) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false, 0 /* Normal */); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } @@ -81735,6 +82283,47 @@ var ts; error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 } } + function checkUnmatchedJSDocParameters(node) { + var jsdocParameters = ts.filter(ts.getJSDocTags(node), ts.isJSDocParameterTag); + if (!ts.length(jsdocParameters)) + return; + var isJs = ts.isInJSFile(node); + var parameters = new ts.Set(); + var excludedParameters = new ts.Set(); + ts.forEach(node.parameters, function (_a, index) { + var name = _a.name; + if (ts.isIdentifier(name)) { + parameters.add(name.escapedText); + } + if (ts.isBindingPattern(name)) { + excludedParameters.add(index); + } + }); + var containsArguments = containsArgumentsReference(node); + if (containsArguments) { + var lastJSDocParam = ts.lastOrUndefined(jsdocParameters); + if (isJs && lastJSDocParam && ts.isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && + lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) { + error(lastJSDocParam.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(lastJSDocParam.name)); + } + } + else { + ts.forEach(jsdocParameters, function (_a, index) { + var name = _a.name; + if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { + return; + } + if (ts.isQualifiedName(name)) { + if (isJs) { + error(name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(name), ts.entityNameToString(name.left)); + } + } + else { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } + }); + } + } /** * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ @@ -82298,7 +82887,7 @@ var ts; 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)) { + if (existing && prop.parent === existing.parent) { seen.delete(prop.escapedName); } } @@ -82466,7 +83055,7 @@ var ts; } else { var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !ts.isInfinityOrNaNString(text)) { + if (ts.isNumericLiteralName(text) && !ts.isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -82572,16 +83161,15 @@ var ts; return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 206 /* ElementAccessExpression */: case 205 /* PropertyAccessExpression */: - var ex = expr; - if (isConstantMemberAccess(ex)) { - var type = getTypeOfExpression(ex.expression); + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 205 /* PropertyAccessExpression */) { - name = ex.name.escapedText; + if (expr.kind === 205 /* PropertyAccessExpression */) { + name = expr.name.escapedText; } else { - name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text); + name = ts.escapeLeadingUnderscores(ts.cast(expr.argumentExpression, ts.isLiteralExpression).text); } return evaluateEnumMember(expr, type.symbol, name); } @@ -82595,7 +83183,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member) && ts.isEnumDeclaration(declaration.parent)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -82609,6 +83197,10 @@ var ts; } } function isConstantMemberAccess(node) { + var type = getTypeOfExpression(node); + if (type === errorType) { + return false; + } return node.kind === 79 /* Identifier */ || node.kind === 205 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || node.kind === 206 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && @@ -82707,7 +83299,7 @@ var ts; var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. return; @@ -82889,10 +83481,20 @@ var ts; return false; } } + if (!ts.isImportEqualsDeclaration(node) && node.assertClause) { + var hasError = false; + for (var _i = 0, _a = node.assertClause.elements; _i < _a.length; _i++) { + var clause = _a[_i]; + if (!ts.isStringLiteral(clause.value)) { + hasError = true; + error(clause.value, ts.Diagnostics.Import_assertion_values_must_be_string_literal_expressions); + } + } + return !hasError; + } return true; } function checkAliasSymbol(node) { - var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -82930,6 +83532,9 @@ var ts; var name = ts.idText(node.kind === 269 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name); } + if (isType && node.kind === 264 /* ImportEqualsDeclaration */ && ts.hasEffectiveModifier(node, 1 /* Export */)) { + error(node, ts.Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided); + } break; } case 274 /* ExportSpecifier */: { @@ -82948,11 +83553,46 @@ var ts; } } } - if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { - addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); + if (ts.isImportSpecifier(node)) { + var targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); + if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); + } } } } + function isDeprecatedAliasedSymbol(symbol) { + return !!symbol.declarations && ts.every(symbol.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }); + } + function checkDeprecatedAliasedSymbol(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */)) + return symbol; + var targetSymbol = resolveAlias(symbol); + if (targetSymbol === unknownSymbol) + return targetSymbol; + while (symbol.flags & 2097152 /* Alias */) { + var target = getImmediateAliasedSymbol(symbol); + if (target) { + if (target === targetSymbol) + break; + if (target.declarations && ts.length(target.declarations)) { + if (isDeprecatedAliasedSymbol(target)) { + addDeprecatedSuggestion(location, target.declarations, target.escapedName); + break; + } + else { + if (symbol === targetSymbol) + break; + symbol = target; + } + } + } + else { + break; + } + } + return targetSymbol; + } function checkImportBinding(node) { checkCollisionsForDeclarationName(node, node.name); checkAliasSymbol(node); @@ -82966,8 +83606,11 @@ var ts; function checkAssertClause(declaration) { var _a; if (declaration.assertClause) { - if (moduleKind !== ts.ModuleKind.ESNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext); + var mode = (moduleKind === ts.ModuleKind.NodeNext) && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); + if (mode !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.ESNext) { + return grammarErrorOnNode(declaration.assertClause, moduleKind === ts.ModuleKind.NodeNext + ? ts.Diagnostics.Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls + : ts.Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext); } if (ts.isImportDeclaration(declaration) ? (_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.isTypeOnly : declaration.isTypeOnly) { return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); @@ -82975,7 +83618,7 @@ var ts; } } function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } @@ -83008,7 +83651,7 @@ var ts; checkAssertClause(node); } function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } @@ -83045,7 +83688,7 @@ var ts; } } function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } @@ -83257,9 +83900,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_3 = getExportsOfModule(moduleSymbol); + if (exports_3) { + exports_3.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -83568,9 +84211,8 @@ var ts; var enclosingFile = ts.getSourceFileOfNode(node); var links = getNodeLinks(enclosingFile); if (!(links.flags & 1 /* TypeChecked */)) { - links.deferredNodes = links.deferredNodes || new ts.Map(); - var id = getNodeId(node); - links.deferredNodes.set(id, node); + links.deferredNodes || (links.deferredNodes = new ts.Set()); + links.deferredNodes.add(node); } } function checkDeferredNodes(context) { @@ -83580,7 +84222,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -84140,7 +84782,10 @@ var ts; case 80 /* PrivateIdentifier */: case 205 /* PropertyAccessExpression */: case 160 /* QualifiedName */: - return getSymbolOfNameOrPropertyAccessExpression(node); + if (!ts.isThisInTypeQuery(node)) { + return getSymbolOfNameOrPropertyAccessExpression(node); + } + // falls through case 108 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { @@ -84277,7 +84922,7 @@ var ts; return errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true, 0 /* Normal */) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -84616,7 +85261,7 @@ var ts; if (!symbol) { return false; } - var target = resolveAlias(symbol); + var target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) { return true; } @@ -85385,7 +86030,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; + var lastStatic, lastDeclare, lastAsync, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -85489,7 +86134,6 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; - lastReadonly = modifier; break; case 93 /* ExportKeyword */: if (flags & 1 /* Export */) { @@ -85602,18 +86246,12 @@ var ts; if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 - } if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } - else if (flags & 256 /* Async */) { + if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } return false; } else if ((node.kind === 265 /* ImportDeclaration */ || node.kind === 264 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { @@ -85849,20 +86487,6 @@ var ts; } return false; } - function checkGrammarForOmittedArgument(args) { - if (args) { - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 226 /* OmittedExpression */) { - return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - return false; - } - function checkGrammarArguments(args) { - return checkGrammarForOmittedArgument(args); - } function checkGrammarHeritageClause(node) { var types = node.types; if (checkGrammarForDisallowedTrailingComma(types)) { @@ -85980,15 +86604,14 @@ var ts; if (prop.kind === 295 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); + grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 80 /* PrivateIdentifier */) { grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; if (mod.kind !== 131 /* AsyncKeyword */ || prop.kind !== 168 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); @@ -86038,9 +86661,12 @@ var ts; seen.set(effectiveName, currentKind); } else { - if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) { + if ((currentKind & 8 /* Method */) && (existingKind & 8 /* Method */)) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } + else if ((currentKind & 4 /* PropertyAssignment */) && (existingKind & 4 /* PropertyAssignment */)) { + grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name, ts.getTextOfNode(name)); + } else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) { if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); @@ -86738,18 +87364,22 @@ var ts; return false; } function checkNumericLiteralValueSize(node) { + // We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "." + // e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`. + var isFractional = ts.getTextOfNode(node).indexOf(".") !== -1; + var isScientific = node.numericLiteralFlags & 16 /* Scientific */; // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint - // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1 // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway - if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) { + if (isFractional || isScientific) { return; } - // We can't rely on the runtime to accurately store and compare extremely large numeric values - // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298 - // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER, - // it's likely addition operations on it will fail too - var apparentValue = +ts.getTextOfNode(node); - if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) { + // Here `node` is guaranteed to be a numeric literal representing an integer. + // We need to judge whether the integer `node` represents is <= 2 ** 53 - 1, which can be accomplished by comparing to `value` defined below because: + // 1) when `node` represents an integer <= 2 ** 53 - 1, `node.text` is its exact string representation and thus `value` precisely represents the integer. + // 2) otherwise, although `node.text` may be imprecise string representation, its mathematical value and consequently `value` cannot be less than 2 ** 53, + // thus the result of the predicate won't be affected. + var value = +node.text; + if (value <= Math.pow(2, 53) - 1) { return; } addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers)); @@ -86814,12 +87444,12 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); } var nodeArguments = node.arguments; - if (moduleKind !== ts.ModuleKind.ESNext) { + if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) { // We are allowed trailing comma after proposal-import-assertions. checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { var assertionArgument = nodeArguments[1]; - return grammarErrorOnNode(assertionArgument, ts.Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext); + return grammarErrorOnNode(assertionArgument, ts.Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext); } } if (nodeArguments.length === 0 || nodeArguments.length > 2) { @@ -86865,28 +87495,27 @@ var ts; } function findMostOverlappyType(source, unionTarget) { var bestMatch; - var matchingCount = 0; - for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { - var target = _a[_i]; - var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); - if (overlap.flags & 4194304 /* Index */) { - // perfect overlap of keys - bestMatch = target; - matchingCount = Infinity; - } - else if (overlap.flags & 1048576 /* Union */) { - // We only want to account for literal types otherwise. - // If we have a union of index types, it seems likely that we - // needed to elaborate between two generic mapped types anyway. - var len = ts.length(ts.filter(overlap.types, isUnitType)); - if (len >= matchingCount) { - bestMatch = target; - matchingCount = len; - } - } - else if (isUnitType(overlap) && 1 >= matchingCount) { - bestMatch = target; - matchingCount = 1; + if (!(source.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target = _a[_i]; + if (!(target.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + return target; + } + else if (isUnitType(overlap) || overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = overlap.flags & 1048576 /* Union */ ? ts.countWhere(overlap.types, isUnitType) : 1; + if (len >= matchingCount) { + bestMatch = target; + matchingCount = len; + } + } + } } } return bestMatch; @@ -87522,7 +88151,7 @@ var ts; return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); case 293 /* AssertEntry */: ts.Debug.type(node); - return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isStringLiteral)); + return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isExpressionNode)); case 266 /* ImportClause */: ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); @@ -88135,7 +88764,7 @@ var ts; value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 : value === 62 ? 43 /* plus */ : value === 63 ? 47 /* slash */ : - ts.Debug.fail(value + ": not a base64 value"); + ts.Debug.fail("".concat(value, ": not a base64 value")); } function base64FormatDecode(ch) { return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ : @@ -88210,7 +88839,7 @@ var ts; var mappings = ts.arrayFrom(decoder, processMapping); if (decoder.error !== undefined) { if (host.log) { - host.log("Encountered error while decoding sourcemap: " + decoder.error); + host.log("Encountered error while decoding sourcemap: ".concat(decoder.error)); } decodedMappings = ts.emptyArray; } @@ -88566,34 +89195,31 @@ var ts; } ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment; /** - * Adds super call and preceding prologue directives into the list of statements. - * - * @param ctor The constructor node. - * @param result The list of statements. - * @param visitor The visitor to apply to each node added to the result array. - * @returns index of the statement that follows super call + * @returns Contained super() call from descending into the statement ignoring parentheses, if that call exists. + */ + function getSuperCallFromStatement(statement) { + if (!ts.isExpressionStatement(statement)) { + return undefined; + } + var expression = ts.skipParentheses(statement.expression); + return ts.isSuperCall(expression) + ? expression + : undefined; + } + ts.getSuperCallFromStatement = getSuperCallFromStatement; + /** + * @returns The index (after prologue statements) of a super call, or -1 if not found. */ - function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) { - if (ctor.body) { - var statements = ctor.body.statements; - // add prologue directives to the list (if any) - var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor); - if (index === statements.length) { - // list contains nothing but prologue directives (or empty) - exit - return index; - } - var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index); - if (superIndex > -1) { - for (var i = index; i <= superIndex; i++) { - result.push(ts.visitNode(statements[i], visitor, ts.isStatement)); - } - return superIndex + 1; + function findSuperStatementIndex(statements, indexAfterLastPrologueStatement) { + for (var i = indexAfterLastPrologueStatement; i < statements.length; i += 1) { + var statement = statements[i]; + if (getSuperCallFromStatement(statement)) { + return i; } - return index; } - return 0; + return -1; } - ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall; + ts.findSuperStatementIndex = findSuperStatementIndex; function getProperties(node, requireInitializer, isStatic) { return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); }); } @@ -90211,7 +90837,7 @@ var ts; // ], C.prototype, "prop"); // var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* Ambient */)); var descriptor = languageVersion > 0 /* ES3 */ ? member.kind === 166 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it @@ -90492,6 +91118,7 @@ var ts; case 176 /* TypePredicate */: case 133 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); + case 197 /* TemplateLiteralType */: case 149 /* StringKeyword */: return factory.createIdentifier("String"); case 147 /* ObjectKeyword */: @@ -90830,10 +91457,14 @@ var ts; return ts.visitFunctionBody(body, visitor, context); } var statements = []; - var indexOfFirstStatement = 0; resumeLexicalEnvironment(); - indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor); - // Add parameters with property assignments. Transforms this: + var indexAfterLastPrologueStatement = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); + var superStatementIndex = ts.findSuperStatementIndex(body.statements, indexAfterLastPrologueStatement); + // If there was a super call, visit existing statements up to and including it + if (superStatementIndex >= 0) { + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexAfterLastPrologueStatement, superStatementIndex + 1 - indexAfterLastPrologueStatement)); + } + // Transform parameters into property assignments. Transforms this: // // constructor (public x, public y) { // } @@ -90845,9 +91476,17 @@ var ts; // this.y = y; // } // - ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment)); - // Add the existing statements, skipping the initial super call. - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + var parameterPropertyAssignments = ts.mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); + // If there is a super() call, the parameter properties go immediately after it + if (superStatementIndex >= 0) { + ts.addRange(statements, parameterPropertyAssignments); + } + // Since there was no super() call, parameter properties are the first statements in the constructor + else { + statements = ts.addRange(parameterPropertyAssignments, statements); + } + // Add remaining statements from the body, skipping the super() call if it was found + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -91025,11 +91664,10 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. - // HOWEVER - if there are leading comments on the expression itself, to handle ASI - // correctly for return and throw, we must keep the parenthesis - if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { - return factory.updateParenthesizedExpression(node, expression); - } + // + // If there are leading comments on the expression itself, the emitter will handle ASI + // for return, throw, and yield by re-introducing parenthesis during emit on an as-need + // basis. return factory.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -91876,7 +92514,7 @@ var ts; var propertyName = ts.isPropertyAccessExpression(originalNode) ? ts.declarationNameToString(originalNode.name) : ts.getTextOfNode(originalNode.argumentExpression); - ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " "); + ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " ".concat(propertyName, " ")); } return substitute; } @@ -91939,11 +92577,13 @@ var ts; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); - var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 99 /* ESNext */; + var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* ES2022 */; + // We need to transform `this` in a static initializer into a reference to the class + // when targeting < ES2022 since the assignment will be moved outside of the class body. + var shouldTransformThisInStaticInitializers = languageVersion < 9 /* ES2022 */; // We don't need to transform `super` property access when targeting ES5, ES3 because // the es2015 transformation handles those. - var shouldTransformSuperInStaticInitializers = (languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields) && languageVersion >= 2 /* ES2015 */; - var shouldTransformThisInStaticInitializers = languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields; + var shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= 2 /* ES2015 */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -91969,7 +92609,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || useDefineForClassFields && ts.getEmitScriptTarget(options) === 99 /* ESNext */) { + || useDefineForClassFields && ts.getEmitScriptTarget(options) >= 9 /* ES2022 */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92172,6 +92812,10 @@ var ts; ts.Debug.assert(!ts.some(node.decorators)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { + if (ts.isStatic(node)) { + // static fields are left as is + return ts.visitEachChild(node, visitor, context); + } // Initializer is elided as the field is initialized in transformConstructor. return factory.updatePropertyDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, @@ -92193,6 +92837,22 @@ var ts; if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } + if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { + var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); + if (initializerStatement) { + var staticBlock = factory.createClassStaticBlockDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + ts.setOriginalNode(staticBlock, node); + ts.setCommentRange(staticBlock, node); + // Set the comment range for the statement to an empty synthetic range + // and drop synthetic comments from the statement to avoid printing them twice. + ts.setCommentRange(initializerStatement, { pos: -1, end: -1 }); + ts.setSyntheticLeadingComments(initializerStatement, undefined); + ts.setSyntheticTrailingComments(initializerStatement, undefined); + return staticBlock; + } + } return undefined; } function createPrivateIdentifierAccess(info, receiver) { @@ -92580,7 +93240,6 @@ var ts; if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) { enableSubstitutionForClassStaticThisOrSuperReference(); } - var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); // If a class has private static fields, or a static field has a `this` or `super` reference, // then we need to allocate a temp variable to hold on to that reference. var pendingClassReferenceAssignment; @@ -92608,6 +93267,7 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); if (ts.some(staticProperties)) { addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -92646,7 +93306,7 @@ var ts; } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - var hasTransformableStatics = ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifier(p.name)); }); + var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); @@ -92693,6 +93353,7 @@ var ts; return undefined; } function transformClassMembers(node, isDerivedClass) { + var members = []; if (shouldTransformPrivateElementsOrClassStaticBlocks) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -92705,12 +93366,20 @@ var ts; createBrandCheckWeakSetForPrivateMethods(); } } - var members = []; var constructor = transformConstructor(node, isDerivedClass); + var visitedMembers = ts.visitNodes(node.members, classElementVisitor, ts.isClassElement); if (constructor) { members.push(constructor); } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { + members.push(factory.createClassStaticBlockDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, factory.createBlock([ + factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) + ]))); + pendingExpressions = undefined; + } + ts.addRange(members, visitedMembers); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } function createBrandCheckWeakSetForPrivateMethods() { @@ -92726,7 +93395,7 @@ var ts; if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. - return languageVersion < 99 /* ESNext */; + return languageVersion < 9 /* ES2022 */; } return ts.isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierClassElementDeclaration(member); } @@ -92746,6 +93415,7 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { + var _a; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -92757,9 +93427,21 @@ var ts; return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); - var indexOfFirstStatement = 0; + var needsSyntheticConstructor = !constructor && isDerivedClass; + var indexOfFirstStatementAfterSuper = 0; + var prologueStatementCount = 0; + var superStatementIndex = -1; var statements = []; - if (!constructor && isDerivedClass) { + if ((_a = constructor === null || constructor === void 0 ? void 0 : constructor.body) === null || _a === void 0 ? void 0 : _a.statements) { + prologueStatementCount = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); + superStatementIndex = ts.findSuperStatementIndex(constructor.body.statements, prologueStatementCount); + // If there was a super call, visit existing statements up to and including it + if (superStatementIndex >= 0) { + indexOfFirstStatementAfterSuper = superStatementIndex + 1; + statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, prologueStatementCount, indexOfFirstStatementAfterSuper - prologueStatementCount), true), statements.slice(prologueStatementCount), true); + } + } + if (needsSyntheticConstructor) { // Add a synthetic `super` call: // // super(...arguments); @@ -92767,9 +93449,6 @@ var ts; statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))]))); } - if (constructor) { - indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor); - } // Add the property initializers. Transforms this: // // public x = 1; @@ -92780,31 +93459,59 @@ var ts; // this.x = 1; // } // + // If we do useDefineForClassFields, they'll be converted elsewhere. + // We instead *remove* them from the transformed output at this stage. + var parameterPropertyDeclarationCount = 0; if (constructor === null || constructor === void 0 ? void 0 : constructor.body) { - var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement); - if (afterParameterProperties === -1) { - afterParameterProperties = constructor.body.statements.length; + if (useDefineForClassFields) { + statements = statements.filter(function (statement) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor); }); } - if (afterParameterProperties > indexOfFirstStatement) { - if (!useDefineForClassFields) { - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement)); + else { + for (var _i = 0, _b = constructor.body.statements; _i < _b.length; _i++) { + var statement = _b[_i]; + if (ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { + parameterPropertyDeclarationCount++; + } + } + if (parameterPropertyDeclarationCount > 0) { + var parameterProperties = ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatementAfterSuper, parameterPropertyDeclarationCount); + // If there was a super() call found, add parameter properties immediately after it + if (superStatementIndex >= 0) { + ts.addRange(statements, parameterProperties); + } + // If a synthetic super() call was added, add them just after it + else if (needsSyntheticConstructor) { + statements = __spreadArray(__spreadArray([ + statements[0] + ], parameterProperties, true), statements.slice(1), true); + } + // Since there wasn't a super() call, add them to the top of the constructor + else { + statements = __spreadArray(__spreadArray([], parameterProperties, true), statements, true); + } + indexOfFirstStatementAfterSuper += parameterPropertyDeclarationCount; } - indexOfFirstStatement = afterParameterProperties; } } var receiver = factory.createThis(); // private methods can be called in property initializers, they should execute first. addMethodStatements(statements, privateMethodsAndAccessors, receiver); addPropertyOrClassStaticBlockStatements(statements, properties, receiver); - // Add existing statements, skipping the initial super call. + // Add existing statements after the initial prologues and super call if (constructor) { - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitBodyStatement, ts.isStatement, indexOfFirstStatementAfterSuper + prologueStatementCount)); } statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ constructor ? constructor.body.statements : node.members), /*multiLine*/ true), /*location*/ constructor ? constructor.body : undefined); + function visitBodyStatement(statement) { + if (useDefineForClassFields && ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { + return undefined; + } + return visitor(statement); + } } /** * Generates assignment statements for property initializers. @@ -92815,19 +93522,34 @@ var ts; function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; - var expression = ts.isClassStaticBlockDeclaration(property) ? - transformClassStaticBlockDeclaration(property) : - transformProperty(property, receiver); - if (!expression) { + if (ts.isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { + continue; + } + var statement = transformPropertyOrClassStaticBlock(property, receiver); + if (!statement) { continue; } - var statement = factory.createExpressionStatement(expression); - ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - ts.setCommentRange(statement, property); - ts.setOriginalNode(statement, property); statements.push(statement); } } + function transformPropertyOrClassStaticBlock(property, receiver) { + var expression = ts.isClassStaticBlockDeclaration(property) ? + transformClassStaticBlockDeclaration(property) : + transformProperty(property, receiver); + if (!expression) { + return undefined; + } + var statement = factory.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + // `setOriginalNode` *copies* the `emitNode` from `property`, so now both + // `statement` and `expression` have a copy of the synthesized comments. + // Drop the comments from expression to avoid printing them twice. + ts.setSyntheticLeadingComments(expression, undefined); + ts.setSyntheticTrailingComments(expression, undefined); + return statement; + } /** * Generates assignment expressions for property initializers. * @@ -93268,8 +93990,8 @@ var ts; } function createHoistedVariableForClass(name, node) { var className = getPrivateIdentifierEnvironment().className; - var prefix = className ? "_" + className : ""; - var identifier = factory.createUniqueName(prefix + "_" + name, 16 /* Optimistic */); + var prefix = className ? "_".concat(className) : ""; + var identifier = factory.createUniqueName("".concat(prefix, "_").concat(name), 16 /* Optimistic */); if (resolver.getNodeCheckFlags(node) & 524288 /* BlockScopedBindingInLoop */) { addBlockScopedVariable(identifier); } @@ -93519,7 +94241,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -94077,6 +94799,7 @@ var ts; var exportedVariableStatement = false; var enabledSubstitutions; var enclosingFunctionFlags; + var parametersWithPrecedingObjectRestOrSpread; var enclosingSuperContainerFlags = 0; var hierarchyFacts = 0; var currentSourceFile; @@ -94152,7 +94875,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -94235,7 +94958,7 @@ var ts; function visitYieldExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { if (node.asteriskToken) { - var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression); + var expression = ts.visitNode(ts.Debug.checkDefined(node.expression), visitor, ts.isExpression); return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node); } @@ -94533,6 +95256,7 @@ var ts; /*incrementor*/ undefined, /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([ @@ -94550,7 +95274,19 @@ var ts; ]), 1 /* SingleLine */)) ])); } + function parameterVisitor(node) { + ts.Debug.assertNode(node, ts.isParameter); + return visitParameter(node); + } function visitParameter(node) { + if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { + return factory.updateParameterDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. @@ -94562,85 +95298,119 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function collectParametersWithPrecedingObjectRestOrSpread(node) { + var parameters; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameters) { + parameters.add(parameter); + } + else if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + parameters = new ts.Set(); + } + } + return parameters; + } function visitConstructorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitGetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitSetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitMethodDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateMethodDeclaration(node, /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitFunctionDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateFunctionDeclaration(node, /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateArrowFunction(node, node.modifiers, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitFunctionExpression(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function transformAsyncGeneratorFunctionBody(node) { @@ -94701,16 +95471,71 @@ var ts; return body; } function appendObjectRestAssignmentsIfNeeded(statements, node) { + var containsPrecedingObjectRestOrSpread = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { - var temp = factory.getGeneratedNameForNode(parameter); - var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + if (containsPrecedingObjectRestOrSpread) { + if (ts.isBindingPattern(parameter.name)) { + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + // + // NOTE: see `insertDefaultValueAssignmentForBindingPattern` in es2015.ts + if (parameter.name.elements.length > 0) { + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)); + if (ts.some(declarations)) { + var declarationList = factory.createVariableDeclarationList(declarations); + var statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + else if (parameter.initializer) { + var name = factory.getGeneratedNameForNode(parameter); + var initializer = ts.visitNode(parameter.initializer, visitor, ts.isExpression); + var assignment = factory.createAssignment(name, initializer); + var statement = factory.createExpressionStatement(assignment); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + else if (parameter.initializer) { + // Converts a parameter initializer into a function body statement, i.e.: + // + // function f(x = 1) { } + // + // becomes + // + // function f(x) { + // if (typeof x === "undefined") { x = 1; } + // } + var name = factory.cloneNode(parameter.name); + ts.setTextRange(name, parameter.name); + ts.setEmitFlags(name, 48 /* NoSourceMap */); + var initializer = ts.visitNode(parameter.initializer, visitor, ts.isExpression); + ts.addEmitFlags(initializer, 48 /* NoSourceMap */ | 1536 /* NoComments */); + var assignment = factory.createAssignment(name, initializer); + ts.setTextRange(assignment, parameter); + ts.setEmitFlags(assignment, 1536 /* NoComments */); + var block = factory.createBlock([factory.createExpressionStatement(assignment)]); + ts.setTextRange(block, parameter); + ts.setEmitFlags(block, 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + var typeCheck = factory.createTypeCheck(factory.cloneNode(parameter.name), "undefined"); + var statement = factory.createIfStatement(typeCheck, block); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements = ts.append(statements, statement); + } + } + else if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + containsPrecedingObjectRestOrSpread = true; + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, /*skipInitializer*/ true); if (ts.some(declarations)) { - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations)); + var declarationList = factory.createVariableDeclarationList(declarations); + var statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); statements = ts.append(statements, statement); } @@ -94849,7 +95674,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -94881,7 +95706,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { @@ -94977,11 +95802,11 @@ var ts; } function visitOptionalExpression(node, captureThisArg, isDelete) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; - var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false); + var left = visitNonOptionalExpression(ts.skipPartiallyEmittedExpressions(expression), ts.isCallChain(chain[0]), /*isDelete*/ false); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; - var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var capturedLeft = leftExpression; - if (!ts.isSimpleCopiableExpression(leftExpression)) { + var capturedLeft = ts.isSyntheticReference(left) ? left.expression : left; + var leftExpression = factory.restoreOuterExpressions(expression, capturedLeft, 8 /* PartiallyEmittedExpressions */); + if (!ts.isSimpleCopiableExpression(capturedLeft)) { capturedLeft = factory.createTempVariable(hoistVariableDeclaration); leftExpression = factory.createAssignment(capturedLeft, leftExpression); } @@ -95007,6 +95832,10 @@ var ts; break; case 207 /* CallExpression */: if (i === 0 && leftThisArg) { + if (!ts.isGeneratedIdentifier(leftThisArg)) { + leftThisArg = factory.cloneNode(leftThisArg); + ts.addEmitFlags(leftThisArg, 1536 /* NoComments */); + } rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 106 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { @@ -95058,7 +95887,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { @@ -95160,14 +95989,14 @@ var ts; return existing.name; } if (!currentFileState.utilizedImplicitRuntimeImports) { - currentFileState.utilizedImplicitRuntimeImports = ts.createMap(); + currentFileState.utilizedImplicitRuntimeImports = new ts.Map(); } var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); if (!specifierSourceImports) { - specifierSourceImports = ts.createMap(); + specifierSourceImports = new ts.Map(); currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports); } - var generatedName = factory.createUniqueName("_" + name, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */); + var generatedName = factory.createUniqueName("_".concat(name), 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */); var specifier = factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier(name), generatedName); generatedName.generatedImportReference = specifier; specifierSourceImports.set(name, specifier); @@ -95316,10 +96145,19 @@ var ts; var _a; var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); - var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; + var args = [tagName, objectProperties]; + // function jsx(type, config, maybeKey) {} + // "maybeKey" is optional. It is acceptable to use "_jsx" without a third argument + if (keyAttr) { + args.push(transformJsxAttributeInitializer(keyAttr.initializer)); + } if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { + // "maybeKey" has to be replaced with "void 0" to not break the jsxDEV signature + if (keyAttr === undefined) { + args.push(factory.createVoidZero()); + } // isStaticChildren development flag args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag @@ -95822,7 +96660,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 512 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -96070,7 +96908,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -96306,11 +97144,11 @@ var ts; } else { if (node.kind === 245 /* BreakStatement */) { - labelMarker = "break-" + label.escapedText; + labelMarker = "break-".concat(label.escapedText); setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + label.escapedText; + labelMarker = "continue-".concat(label.escapedText); setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } @@ -96587,37 +97425,39 @@ var ts; var prologue = []; var statements = []; resumeLexicalEnvironment(); + // In derived classes, there may be code before the necessary super() call + // We'll remove pre-super statements to be tacked on after the rest of the body + var existingPrologue = ts.takeWhile(constructor.body.statements, ts.isPrologueDirective); + var _a = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue), superCall = _a.superCall, superStatementIndex = _a.superStatementIndex; + var postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1; // If a super call has already been synthesized, // we're going to assume that we should just transform everything after that. // The assumption is that no prior step in the pipeline has added any prologue directives. - var statementOffset = 0; + var statementOffset = postSuperStatementsStart; if (!hasSynthesizedSuper) - statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false); - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false); if (!hasSynthesizedSuper) - statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor); - // If the first statement is a call to `super()`, visit the statement directly + statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ undefined); + // If there already exists a call to `super()`, visit the statement directly var superCallExpression; if (hasSynthesizedSuper) { superCallExpression = createDefaultSuperCallOrThis(); } - else if (isDerivedClass && statementOffset < constructor.body.statements.length) { - var firstStatement = constructor.body.statements[statementOffset]; - if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } + else if (superCall) { + superCallExpression = visitSuperCallInBody(superCall); } if (superCallExpression) { hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */; - statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } + // Add parameter defaults at the beginning of the output, with prologue statements + addDefaultValueAssignmentsIfNeeded(prologue, constructor); + addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); // visit the remaining statements ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); - if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { + if (isDerivedClass || superCallExpression) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -96637,10 +97477,10 @@ var ts; // return C; // })(Base); // ``` - var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var superCall_1 = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); var returnStatement = factory.createReturnStatement(superCallExpression); - ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); - ts.setEmitFlags(superCall, 1536 /* NoComments */); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall_1)); + ts.setEmitFlags(superCall_1, 1536 /* NoComments */); statements.push(returnStatement); } else { @@ -96665,9 +97505,19 @@ var ts; // return C; // })(Base); // ``` - // Since the `super()` call was the first statement, we insert the `this` capturing call to - // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). - insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + // If the super() call is the first statement, we can directly create and assign its result to `_this` + if (superStatementIndex <= existingPrologue.length) { + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + } + // Since the `super()` call isn't the first statement, it's split across 1-2 statements: + // * A prologue `var _this = this;`, in case the constructor accesses this before super() + // * If it exists, a reassignment to that `_this` of the super() call + else { + insertCaptureThisForNode(prologue, constructor, createActualThis()); + if (superCallExpression) { + insertSuperThisCaptureThisForNode(statements, superCallExpression); + } + } if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */))); } @@ -96690,11 +97540,27 @@ var ts; // ``` insertCaptureThisForNodeIfNeeded(prologue, constructor); } - var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), + var body = factory.createBlock(ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], existingPrologue, true), prologue, true), (superStatementIndex <= existingPrologue.length ? ts.emptyArray : ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, existingPrologue.length, superStatementIndex)), true), statements, true)), /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor.body); - return block; + ts.setTextRange(body, constructor.body); + return body; + } + function findSuperCallAndStatementIndex(originalBodyStatements, existingPrologue) { + for (var i = existingPrologue.length; i < originalBodyStatements.length; i += 1) { + var superCall = ts.getSuperCallFromStatement(originalBodyStatements[i]); + if (superCall) { + // With a super() call, split the statements into pre-super() and 'body' (post-super()) + return { + superCall: superCall, + superStatementIndex: i, + }; + } + } + // Since there was no super() call found, consider all statements to be in the main 'body' (post-super()) + return { + superStatementIndex: -1, + }; } /** * We want to try to avoid emitting a return statement in certain cases if a user already returned something. @@ -96923,6 +97789,18 @@ var ts; } return false; } + /** + * Assigns the `this` in a constructor to the result of its `super()` call. + * + * @param statements Statements in the constructor body. + * @param superExpression Existing `super()` call for the constructor. + */ + function insertSuperThisCaptureThisForNode(statements, superExpression) { + enableSubstitutionsForCapturedThis(); + var assignSuperExpression = factory.createExpressionStatement(factory.createBinaryExpression(factory.createThis(), 63 /* EqualsToken */, superExpression)); + ts.insertStatementAfterCustomPrologue(statements, assignSuperExpression); + ts.setCommentRange(assignSuperExpression, ts.getOriginalNode(superExpression).parent); + } function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = factory.createVariableStatement( @@ -97232,7 +98110,7 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false); + statementOffset = factory.copyStandardPrologue(body.statements, prologue, 0, /*ensureUseStrict*/ false); statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction); statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement); } @@ -97908,10 +98786,12 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { - var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + var hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) || + shouldConvertConditionOfForStatement(node) || + shouldConvertIncrementorOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } } var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; @@ -98265,27 +99145,33 @@ var ts; caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } } } else { loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); var flags = 0; if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } - if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { - flags |= 2 /* Initializer */; + if (ts.isForStatement(container)) { + if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || + container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) { + flags |= 1 /* Body */; + } } loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } @@ -98603,7 +99489,7 @@ var ts; /*type*/ undefined, factory.updateBlock(func.body, statements))), /*typeArguments*/ undefined, call.arguments)))); } - function visitImmediateSuperCallInBody(node) { + function visitSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { @@ -99383,7 +100269,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 2048 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -99406,7 +100292,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 1024 /* ContainsGenerator */) { + else if (transformFlags & 2048 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -99462,7 +100348,7 @@ var ts; if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -102111,7 +102997,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* ContainsDynamicImport */ | 2048 /* ContainsDestructuringAssignment */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4194304 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -103101,7 +103987,7 @@ var ts; if (ts.isIdentifier(node.expression)) { var expression = substituteExpressionIdentifier(node.expression); noSubstitution[ts.getNodeId(expression)] = true; - if (!ts.isIdentifier(expression)) { + if (!ts.isIdentifier(expression) && !(ts.getEmitFlags(node.expression) & 4096 /* HelperName */)) { return ts.addEmitFlags(factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, node.arguments), 536870912 /* IndirectCall */); } @@ -103112,7 +103998,7 @@ var ts; if (ts.isIdentifier(node.tag)) { var tag = substituteExpressionIdentifier(node.tag); noSubstitution[ts.getNodeId(tag)] = true; - if (!ts.isIdentifier(tag)) { + if (!ts.isIdentifier(tag) && !(ts.getEmitFlags(node.tag) & 4096 /* HelperName */)) { return ts.addEmitFlags(factory.updateTaggedTemplateExpression(node, tag, /*typeArguments*/ undefined, node.template), 536870912 /* IndirectCall */); } @@ -104327,7 +105213,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (2048 /* ContainsDestructuringAssignment */ | 4194304 /* ContainsDynamicImport */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* ContainsDestructuringAssignment */ | 4194304 /* ContainsDynamicImport */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -105119,7 +106005,7 @@ var ts; return getTypeAliasDeclarationVisibilityError; } else { - return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: ".concat(ts.SyntaxKind[node.kind])); } function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { if (node.kind === 253 /* VariableDeclaration */ || node.kind === 202 /* BindingElement */) { @@ -105330,7 +106216,7 @@ var ts; ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1; default: - return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + return ts.Debug.fail("Unknown parent for parameter: ".concat(ts.SyntaxKind[node.parent.kind])); } } function getTypeParameterConstraintVisibilityError() { @@ -106088,7 +106974,7 @@ var ts; while (ts.length(lateMarkedStatements)) { var i = lateMarkedStatements.shift(); if (!ts.isLateVisibilityPaintedStatement(i)) { - return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: ".concat(ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } var priorNeedsDeclare = needsDeclare; needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); @@ -106277,7 +107163,7 @@ var ts; return cleanup(input); return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); } - default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: ".concat(ts.SyntaxKind[input.kind])); } } if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) { @@ -106568,7 +107454,7 @@ var ts; if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 104 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; - var newId_1 = factory.createUniqueName(oldId + "_base", 16 /* Optimistic */); + var newId_1 = factory.createUniqueName("".concat(oldId, "_base"), 16 /* Optimistic */); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -106609,7 +107495,7 @@ var ts; } } // Anything left unhandled is an error, so this should be unreachable - return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: ".concat(ts.SyntaxKind[input.kind])); function cleanup(node) { if (isEnclosingDeclaration(input)) { enclosingDeclaration = previousEnclosingDeclaration; @@ -107501,13 +108387,13 @@ var ts; if (ts.fileExtensionIs(inputFileName, ".json" /* Json */)) return; if (js && configFile.options.sourceMap) { - addOutput(js + ".map"); + addOutput("".concat(js, ".map")); } if (ts.getEmitDeclarations(configFile.options)) { var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory); addOutput(dts); if (configFile.options.declarationMap) { - addOutput(dts + ".map"); + addOutput("".concat(dts, ".map")); } } } @@ -107576,7 +108462,7 @@ var ts; function getFirstProjectOutput(configFile, ignoreCase) { if (ts.outFile(configFile.options)) { var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath; - return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output"); + return ts.Debug.checkDefined(jsFilePath, "project ".concat(configFile.options.configFilePath, " expected to have at least one output")); } var getCommonSourceDirectory = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); }); for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) { @@ -107595,7 +108481,7 @@ var ts; var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options); if (buildInfoPath) return buildInfoPath; - return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output"); + return ts.Debug.fail("project ".concat(configFile.options.configFilePath, " expected to have at least one output")); } ts.getFirstProjectOutput = getFirstProjectOutput; /*@internal*/ @@ -107821,7 +108707,7 @@ var ts; if (sourceMappingURL) { if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); - writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment + writer.writeComment("//# ".concat("sourceMappingURL", "=").concat(sourceMappingURL)); // Tools can sometimes see this line as a source mapping url comment } // Write the source map if (sourceMapFilePath) { @@ -107870,7 +108756,7 @@ var ts; // Encode the sourceMap into the sourceMap url var sourceMapText = sourceMapGenerator.toString(); var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); - return "data:application/json;base64," + base64SourceMapText; + return "data:application/json;base64,".concat(base64SourceMapText); } var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath))); if (mapOptions.mapRoot) { @@ -108050,7 +108936,7 @@ var ts; return; break; default: - ts.Debug.fail("Unexpected path: " + name); + ts.Debug.fail("Unexpected path: ".concat(name)); } outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, @@ -108759,6 +109645,7 @@ var ts; return emitJSDocSignature(node); case 325 /* JSDocTag */: case 330 /* JSDocClassTag */: + case 335 /* JSDocOverrideTag */: return emitJSDocSimpleTag(node); case 326 /* JSDocAugmentsTag */: case 327 /* JSDocImplementsTag */: @@ -108771,7 +109658,6 @@ var ts; case 332 /* JSDocPrivateTag */: case 333 /* JSDocProtectedTag */: case 334 /* JSDocReadonlyTag */: - case 335 /* JSDocOverrideTag */: return; case 336 /* JSDocCallbackTag */: return emitJSDocCallbackTag(node); @@ -108910,7 +109796,7 @@ var ts; return writeTokenNode(node, writeKeyword); if (ts.isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); - ts.Debug.fail("Unhandled SyntaxKind: " + ts.Debug.formatSyntaxKind(node.kind) + "."); + ts.Debug.fail("Unhandled SyntaxKind: ".concat(ts.Debug.formatSyntaxKind(node.kind), ".")); } function emitMappedTypeParameter(node) { emit(node.name); @@ -109075,18 +109961,21 @@ var ts; emitPlaceholder(hint, node, snippet); break; case 0 /* TabStop */: - emitTabStop(snippet); + emitTabStop(hint, node, snippet); break; } } function emitPlaceholder(hint, node, snippet) { - nonEscapingWrite("${" + snippet.order + ":"); // `${2:` + nonEscapingWrite("${".concat(snippet.order, ":")); // `${2:` pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...` nonEscapingWrite("}"); // `}` // `${2:...}` } - function emitTabStop(snippet) { - nonEscapingWrite("$" + snippet.order); + function emitTabStop(hint, node, snippet) { + // A tab stop should only be attached to an empty node, i.e. a node that doesn't emit any text. + ts.Debug.assert(node.kind === 235 /* EmptyStatement */, "A tab stop cannot be attached to a node of kind ".concat(ts.Debug.formatSyntaxKind(node.kind), ".")); + ts.Debug.assert(hint !== 5 /* EmbeddedStatement */, "A tab stop cannot be attached to an embedded statement."); + nonEscapingWrite("$".concat(snippet.order)); } // // Identifiers @@ -109789,7 +110678,7 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(125 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma); } function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); @@ -109986,9 +110875,49 @@ var ts; } return pos; } + function commentWillEmitNewLine(node) { + return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; + } + function willEmitLeadingNewLine(node) { + if (!currentSourceFile) + return false; + if (ts.some(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine)) + return true; + if (ts.some(ts.getSyntheticLeadingComments(node), commentWillEmitNewLine)) + return true; + if (ts.isPartiallyEmittedExpression(node)) { + if (node.pos !== node.expression.pos) { + if (ts.some(ts.getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) + return true; + } + return willEmitLeadingNewLine(node.expression); + } + return false; + } + /** + * Wraps an expression in parens if we would emit a leading comment that would introduce a line separator + * between the node and its parent. + */ + function parenthesizeExpressionForNoAsi(node) { + if (!commentsDisabled && ts.isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode && ts.isParenthesizedExpression(parseNode)) { + // If the original node was a parenthesized expression, restore it to preserve comment and source map emit + var parens = ts.factory.createParenthesizedExpression(node.expression); + ts.setOriginalNode(parens, node); + ts.setTextRange(parens, parseNode); + return parens; + } + return ts.factory.createParenthesizedExpression(node); + } + return node; + } + function parenthesizeExpressionForNoAsiAndDisallowedComma(node) { + return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); + } function emitReturnStatement(node) { emitTokenWithComment(105 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitWithStatement(node) { @@ -110016,7 +110945,7 @@ var ts; } function emitThrowStatement(node) { emitTokenWithComment(109 /* ThrowKeyword */, node.pos, writeKeyword, node); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitTryStatement(node) { @@ -110808,17 +111737,17 @@ var ts; writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { - writeComment("/// "); + writeComment("/// ")); writeLine(); } if (currentSourceFile && currentSourceFile.amdDependencies) { for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { var dep = _b[_a]; if (dep.name) { - writeComment("/// "); + writeComment("/// ")); } else { - writeComment("/// "); + writeComment("/// ")); } writeLine(); } @@ -110826,7 +111755,7 @@ var ts; for (var _c = 0, files_2 = files; _c < files_2.length; _c++) { var directive = files_2[_c]; var pos = writer.getTextPos(); - writeComment("/// "); + writeComment("/// ")); if (bundleFileInfo) bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); @@ -110834,7 +111763,7 @@ var ts; for (var _d = 0, types_24 = types; _d < types_24.length; _d++) { var directive = types_24[_d]; var pos = writer.getTextPos(); - writeComment("/// "); + writeComment("/// ")); if (bundleFileInfo) bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName }); writeLine(); @@ -110842,7 +111771,7 @@ var ts; for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { var directive = libs_1[_e]; var pos = writer.getTextPos(); - writeComment("/// "); + writeComment("/// ")); if (bundleFileInfo) bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName }); writeLine(); @@ -110860,7 +111789,14 @@ var ts; } // Transformation nodes function emitPartiallyEmittedExpression(node) { + var emitFlags = ts.getEmitFlags(node); + if (!(emitFlags & 512 /* NoLeadingComments */) && node.pos !== node.expression.pos) { + emitTrailingCommentsOfPosition(node.expression.pos); + } emitExpression(node.expression); + if (!(emitFlags & 1024 /* NoTrailingComments */) && node.end !== node.expression.end) { + emitLeadingCommentsOfPosition(node.expression.end); + } } function emitCommaList(node) { emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); @@ -111224,10 +112160,8 @@ var ts; // Emit this child. previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); if (shouldEmitInterveningComments) { - if (emitTrailingCommentsOfPosition) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } else { shouldEmitInterveningComments = mayEmitInterveningComments; @@ -111548,7 +112482,7 @@ var ts; function writeLineSeparatorsAndIndentBefore(node, parent) { var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } @@ -111617,9 +112551,9 @@ var ts; var textSourceNode = node.textSourceNode; if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) { var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode); - return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(text) + "\"" : - neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(text) + "\"" : - "\"" + ts.escapeNonAsciiString(text) + "\""; + return jsxAttributeEscape ? "\"".concat(ts.escapeJsxAttributeString(text), "\"") : + neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"".concat(ts.escapeString(text), "\"") : + "\"".concat(ts.escapeNonAsciiString(text), "\""); } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); @@ -112096,8 +113030,8 @@ var ts; } function formatSynthesizedComment(comment) { return comment.kind === 3 /* MultiLineCommentTrivia */ - ? "/*" + comment.text + "*/" - : "//" + comment.text; + ? "/*".concat(comment.text, "*/") + : "//".concat(comment.text); } function emitBodyWithDetachedComments(node, detachedRange, emitCallback) { enterComment(); @@ -112818,7 +113752,7 @@ var ts; var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog, toPath = _a.toPath; var newPath = ts.removeIgnoredPath(fileOrDirectoryPath); if (!newPath) { - writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory); + writeLog("Project: ".concat(configFileName, " Detected ignored path: ").concat(fileOrDirectory)); return true; } fileOrDirectoryPath = newPath; @@ -112827,11 +113761,11 @@ var ts; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) { - writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + writeLog("Project: ".concat(configFileName, " Detected file add/remove of non supported extension: ").concat(fileOrDirectory)); return true; } if (ts.isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) { - writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory); + writeLog("Project: ".concat(configFileName, " Detected excluded file: ").concat(fileOrDirectory)); return true; } if (!program) @@ -112855,7 +113789,7 @@ var ts; var builderProgram = !realProgram && !ts.isArray(program) ? program : undefined; if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) || hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) { - writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory); + writeLog("Project: ".concat(configFileName, " Detected output file: ").concat(fileOrDirectory)); return true; } return false; @@ -112923,36 +113857,36 @@ var ts; host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log("ExcludeWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); + log("ExcludeWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo))); return { - close: function () { return log("ExcludeWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); } + close: function () { return log("ExcludeWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo))); } }; } function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log("FileWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); + log("FileWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo))); var watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: function () { - log("FileWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); + log("FileWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo))); watcher.close(); } }; } function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - var watchInfo = "DirectoryWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo); + var watchInfo = "DirectoryWatcher:: Added:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); log(watchInfo); var start = ts.timestamp(); var watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); var elapsed = ts.timestamp() - start; - log("Elapsed:: " + elapsed + "ms " + watchInfo); + log("Elapsed:: ".concat(elapsed, "ms ").concat(watchInfo)); return { close: function () { - var watchInfo = "DirectoryWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo); + var watchInfo = "DirectoryWatcher:: Close:: ".concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); log(watchInfo); var start = ts.timestamp(); watcher.close(); var elapsed = ts.timestamp() - start; - log("Elapsed:: " + elapsed + "ms " + watchInfo); + log("Elapsed:: ".concat(elapsed, "ms ").concat(watchInfo)); } }; } @@ -112962,16 +113896,16 @@ var ts; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } - var triggerredInfo = (key === "watchFile" ? "FileWatcher" : "DirectoryWatcher") + ":: Triggered with " + args[0] + " " + (args[1] !== undefined ? args[1] : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = "".concat(key === "watchFile" ? "FileWatcher" : "DirectoryWatcher", ":: Triggered with ").concat(args[0], " ").concat(args[1] !== undefined ? args[1] : "", ":: ").concat(getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); log(triggerredInfo); var start = ts.timestamp(); cb.call.apply(cb, __spreadArray([/*thisArg*/ undefined], args, false)); var elapsed = ts.timestamp() - start; - log("Elapsed:: " + elapsed + "ms " + triggerredInfo); + log("Elapsed:: ".concat(elapsed, "ms ").concat(triggerredInfo)); }, flags, options, detailInfo1, detailInfo2); }; } function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); + return "WatchInfo: ".concat(file, " ").concat(flags, " ").concat(JSON.stringify(options), " ").concat(getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : "".concat(detailInfo1, " ").concat(detailInfo2)); } } ts.getWatchFactory = getWatchFactory; @@ -113278,12 +114212,12 @@ var ts; } ts.formatDiagnostics = formatDiagnostics; function formatDiagnostic(diagnostic, host) { - var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + var errorMessage = "".concat(ts.diagnosticCategoryName(diagnostic), " TS").concat(diagnostic.code, ": ").concat(flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())).concat(host.getNewLine()); if (diagnostic.file) { var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 var fileName = diagnostic.file.fileName; var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + return "".concat(relativeFileName, "(").concat(line + 1, ",").concat(character + 1, "): ") + errorMessage; } return errorMessage; } @@ -113371,9 +114305,9 @@ var ts; var output = ""; output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); output += ":"; - output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += color("".concat(firstLine + 1), ForegroundColorEscapeSequences.Yellow); output += ":"; - output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + output += color("".concat(firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); return output; } ts.formatLocation = formatLocation; @@ -113387,7 +114321,7 @@ var ts; output += " - "; } output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); - output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += formatColorAndReset(" TS".concat(diagnostic.code, ": "), ForegroundColorEscapeSequences.Grey); output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); if (diagnostic.file) { output += host.getNewLine(); @@ -113496,7 +114430,7 @@ var ts; var result = void 0; var mode = getModeForResolutionAtIndex(containingFile, i); i++; - var cacheKey = mode !== undefined ? mode + "|" + name : name; + var cacheKey = mode !== undefined ? "".concat(mode, "|").concat(name) : name; if (cache.has(cacheKey)) { result = cache.get(cacheKey); } @@ -113691,6 +114625,100 @@ var ts; } } ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /** @internal */ + ts.plainJSErrors = new ts.Set([ + // binder errors + ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, + ts.Diagnostics.A_module_cannot_have_multiple_default_exports.code, + ts.Diagnostics.Another_export_default_is_here.code, + ts.Diagnostics.The_first_export_default_is_here.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code, + ts.Diagnostics.constructor_is_a_reserved_word.code, + ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code, + ts.Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code, + ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code, + ts.Diagnostics.Invalid_use_of_0_in_strict_mode.code, + ts.Diagnostics.A_label_is_not_allowed_here.code, + ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode.code, + ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode.code, + // grammar errors + ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code, + ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code, + ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code, + ts.Diagnostics.A_class_member_cannot_have_the_0_keyword.code, + ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code, + ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code, + ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code, + ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code, + ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer.code, + ts.Diagnostics.A_get_accessor_cannot_have_parameters.code, + ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code, + ts.Diagnostics.A_rest_element_cannot_have_a_property_name.code, + ts.Diagnostics.A_rest_element_cannot_have_an_initializer.code, + ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code, + ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer.code, + ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code, + ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code, + ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body.code, + ts.Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code, + ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter.code, + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code, + ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + ts.Diagnostics.An_export_declaration_cannot_have_modifiers.code, + ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + ts.Diagnostics.An_import_declaration_cannot_have_modifiers.code, + ts.Diagnostics.An_object_member_cannot_be_declared_optional.code, + ts.Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code, + ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code, + ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code, + ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code, + ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code, + ts.Diagnostics.Classes_can_only_extend_a_single_class.code, + ts.Diagnostics.Classes_may_not_have_a_field_named_constructor.code, + ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, + ts.Diagnostics.Duplicate_label_0.code, + ts.Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code, + ts.Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code, + ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, + ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, + ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, + ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code, + ts.Diagnostics.Jump_target_cannot_cross_function_boundary.code, + ts.Diagnostics.Line_terminator_not_permitted_before_arrow.code, + ts.Diagnostics.Modifiers_cannot_appear_here.code, + ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code, + ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code, + ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code, + ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, + ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code, + ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code, + ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code, + ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code, + ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code, + ts.Diagnostics.Trailing_comma_not_allowed.code, + ts.Diagnostics.Variable_declaration_list_cannot_be_empty.code, + ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code, + ts.Diagnostics._0_expected.code, + ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code, + ts.Diagnostics._0_list_cannot_be_empty.code, + ts.Diagnostics._0_modifier_already_seen.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter.code, + ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, + ts.Diagnostics._0_modifier_cannot_be_used_here.code, + ts.Diagnostics._0_modifier_must_precede_1_modifier.code, + ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code, + ts.Diagnostics.const_declarations_must_be_initialized.code, + ts.Diagnostics.extends_clause_already_seen.code, + ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, + ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ]); /** * Determine if source file needs to be re-created even if its text hasn't changed */ @@ -114351,6 +115379,7 @@ var ts; newSourceFile.originalFileName = oldSourceFile.originalFileName; newSourceFile.resolvedPath = oldSourceFile.resolvedPath; newSourceFile.fileName = oldSourceFile.fileName; + newSourceFile.impliedNodeFormat = oldSourceFile.impliedNodeFormat; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -114707,14 +115736,24 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + var isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + var isCheckJs = isJs && ts.isCheckJsEnabledForFile(sourceFile, options); + var isPlainJs = ts.isPlainJsFile(sourceFile, options.checkJs); var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false; - // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + // By default, only type-check .ts, .tsx, Deferred, plain JS, checked JS and External + // - plain JS: .js files with no // ts-check and checkJs: undefined + // - check JS: .js files with either // ts-check or checkJs: true + // - external: files that are added by plugins var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ - || sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); + || sourceFile.scriptKind === 5 /* External */ || isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; - return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); + if (isPlainJs) { + bindDiagnostics = ts.filter(bindDiagnostics, function (d) { return ts.plainJSErrors.has(d.code); }); + checkDiagnostics = ts.filter(checkDiagnostics, function (d) { return ts.plainJSErrors.has(d.code); }); + } + // skip ts-expect-error errors in plain JS files, and skip JSDoc errors except in checked JS + return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); }); } function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) { @@ -115358,14 +116397,14 @@ var ts; redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); - sourceFileToPackageName.set(path, packageId.name); + sourceFileToPackageName.set(path, ts.packageIdToPackageName(packageId)); processingOtherFiles.push(dupFile); return dupFile; } else if (file) { // This is the first source file to have this packageId. packageIdToSourceFile.set(packageIdKey, file); - sourceFileToPackageName.set(path, packageId.name); + sourceFileToPackageName.set(path, ts.packageIdToPackageName(packageId)); } } addFileToFilesByName(file, path, redirectedPath); @@ -115580,7 +116619,7 @@ var ts; path += (i === 2 ? "/" : "-") + components[i]; i++; } - var resolveFrom = ts.combinePaths(currentDirectory, "__lib_node_modules_lookup_" + libFileName + "__.ts"); + var resolveFrom = ts.combinePaths(currentDirectory, "__lib_node_modules_lookup_".concat(libFileName, "__.ts")); var localOverrideModuleResult = ts.resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, moduleResolutionCache); if (localOverrideModuleResult === null || localOverrideModuleResult === void 0 ? void 0 : localOverrideModuleResult.resolvedModule) { return localOverrideModuleResult.resolvedModule.resolvedFileName; @@ -115728,7 +116767,7 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { - var isNightly = ts.stringContains(ts.version, "-dev"); + var isNightly = ts.stringContains(ts.version, "-dev") || ts.stringContains(ts.version, "-insiders"); if (!isNightly) { if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); @@ -116401,12 +117440,12 @@ var ts; } function directoryExistsIfProjectReferenceDeclDir(dir) { var dirPath = host.toPath(dir); - var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; + var dirPathWithTrailingDirectorySeparator = "".concat(dirPath).concat(ts.directorySeparator); return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || // Any parent directory of declaration dir ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || // Any directory inside declaration dir - ts.startsWith(dirPath, declDirPath + "/"); }); + ts.startsWith(dirPath, "".concat(declDirPath, "/")); }); } function handleDirectoryCouldBeSymlink(directory) { var _a; @@ -116459,7 +117498,7 @@ var ts; if (isFile && result) { // Store the real path for the file' var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); - symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), "")); + symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "".concat(symlinkedDirectory.real).concat(absolutePath.replace(new RegExp(directoryPath, "i"), ""))); } return result; }) || false; @@ -116917,7 +117956,7 @@ var ts; /*forceDtsEmit*/ true); var firstDts_1 = ts.firstOrUndefined(emitOutput_1.outputFiles); if (firstDts_1) { - ts.Debug.assert(ts.fileExtensionIsOneOf(firstDts_1.name, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); }); + ts.Debug.assert(ts.fileExtensionIsOneOf(firstDts_1.name, [".d.ts" /* Dts */, ".d.mts" /* Dmts */, ".d.cts" /* Dcts */]), "File extension for signature expected to be dts", function () { return "Found: ".concat(ts.getAnyExtensionFromPath(firstDts_1.name), " for ").concat(firstDts_1.name, ":: All output files: ").concat(JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; }))); }); latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text); if (exportedModulesMapCache && latestSignature !== prevSignature) { updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache); @@ -117425,7 +118464,7 @@ var ts; return; } else { - ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: " + affectedFile.fileName); + ts.Debug.assert(state.hasCalledUpdateShapeSignature.has(affectedFile.resolvedPath) || ((_a = state.currentAffectedFilesSignatures) === null || _a === void 0 ? void 0 : _a.has(affectedFile.resolvedPath)), "Signature not updated for affected file: ".concat(affectedFile.fileName)); } if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) { forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); }); @@ -118570,7 +119609,7 @@ var ts; failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator); var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator); - ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath); + ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: ".concat(failedLookupLocation, " failedLookupLocationPath: ").concat(failedLookupLocationPath)); if (failedLookupPathSplit.length > rootSplitLength + 1) { // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution return { @@ -118623,7 +119662,7 @@ var ts; function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { if (resolution.refCount) { resolution.refCount++; - ts.Debug.assertDefined(resolution.files); + ts.Debug.assertIsDefined(resolution.files); } else { resolution.refCount = 1; @@ -118691,7 +119730,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { - ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath); + ts.unorderedRemoveItem(ts.Debug.checkDefined(resolution.files), filePath); resolution.refCount--; if (resolution.refCount) { return; @@ -118783,7 +119822,7 @@ var ts; if (resolution.isInvalidated || !canInvalidate(resolution)) continue; resolution.isInvalidated = invalidated = true; - for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) { + for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution @@ -118991,11 +120030,12 @@ var ts; }; } function isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) { + var _a; if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node12 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { return false; } - return ts.getImpliedNodeFormatForFile(importingSourceFileName, /*packageJsonInfoCache*/ undefined, getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS; + return ts.getImpliedNodeFormatForFile(importingSourceFileName, (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host), getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS; } function getModuleResolutionHost(host) { var _a; @@ -119008,28 +120048,37 @@ var ts; useCaseSensitiveFileNames: (_a = host.useCaseSensitiveFileNames) === null || _a === void 0 ? void 0 : _a.call(host), }; } - function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) { - var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {}); + // `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`? + // Because when this is called by the file renamer, `importingSourceFile` is the file being renamed, + // while `importingSourceFileName` its *new* name. We need a source file just to get its + // `impliedNodeFormat` and to detect certain preferences from existing import module specifiers. + function updateModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {}); if (res === oldImportSpecifier) return undefined; return res; } moduleSpecifiers_1.updateModuleSpecifier = updateModuleSpecifier; - // Note: importingSourceFile is just for usesJsExtensionOnImports + // `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`? + // Because when this is called by the declaration emitter, `importingSourceFile` is the implementation + // file, but `importingSourceFileName` and `toFileName` refer to declaration files (the former to the + // one currently being produced; the latter to the one being imported). We need an implementation file + // just to get its `impliedNodeFormat` and to detect certain preferences from existing import module + // specifiers. function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host) { - return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}); + return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}); } moduleSpecifiers_1.getModuleSpecifier = getModuleSpecifier; - function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host, preferences) { - var info = getInfo(importingSourceFileName, host); - var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host, preferences); - return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); }); + function getNodeModulesPackageName(compilerOptions, importingSourceFile, nodeModulesFileName, host, preferences) { + var info = getInfo(importingSourceFile.path, host); + var modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences); + return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, /*packageNameOnly*/ true); }); } moduleSpecifiers_1.getNodeModulesPackageName = getNodeModulesPackageName; - function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences, userPreferences) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences, userPreferences) { var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences); - return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) || + return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions); }) || getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences) { @@ -119096,7 +120145,7 @@ var ts; var relativeSpecifiers; for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) { var modulePath = modulePaths_1[_i]; - var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); + var specifier = tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions); nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier); if (specifier && modulePath.isRedirect) { // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar", @@ -119488,13 +120537,13 @@ var ts; ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) : ts.removeFileExtension(relativePath); } - function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) { + function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, packageNameOnly) { var path = _a.path, isRedirect = _a.isRedirect; var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory; if (!host.fileExists || !host.readFile) { return undefined; } - var parts = getNodeModulePathParts(path); + var parts = ts.getNodeModulePathParts(path); if (!parts) { return undefined; } @@ -119546,16 +120595,26 @@ var ts; // For classic resolution, only allow importing from node_modules/@types, not other node_modules return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Classic && packageName === nodeModulesDirectoryName ? undefined : packageName; function tryDirectoryWithPackageJson(packageRootIndex) { + var _a, _b; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - // TODO: Inject `require` or `import` condition based on the intended import mode + var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { + var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate + // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is + // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` + // with, so for now we just stick with the mode of the file. + var conditions = ["node", importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" + ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) + : undefined; if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) + ? fromExports + : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); } if (packageJsonContent.exports) { @@ -119607,62 +120666,10 @@ var ts; } } } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 - return isPathRelativeToParent(relativePath) ? undefined : relativePath; + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } function removeExtensionAndIndexPostFix(fileName, ending, options) { @@ -119684,7 +120691,7 @@ var ts; } function getJSExtensionForFile(fileName, options) { var _a; - return (_a = tryGetJSExtensionForFile(fileName, options)) !== null && _a !== void 0 ? _a : ts.Debug.fail("Extension " + ts.extensionFromPath(fileName) + " is unsupported:: FileName:: " + fileName); + return (_a = tryGetJSExtensionForFile(fileName, options)) !== null && _a !== void 0 ? _a : ts.Debug.fail("Extension ".concat(ts.extensionFromPath(fileName), " is unsupported:: FileName:: ").concat(fileName)); } function tryGetJSExtensionForFile(fileName, options) { var ext = ts.tryGetExtensionFromPath(fileName); @@ -119729,7 +120736,7 @@ var ts; getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) } : undefined; /** - * Create a function that reports error by writing to the system and handles the formating of the diagnostic + * Create a function that reports error by writing to the system and handles the formatting of the diagnostic */ function createDiagnosticReporter(system, pretty) { var host = system === ts.sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : { @@ -119781,14 +120788,14 @@ var ts; } ts.getLocaleTimeString = getLocaleTimeString; /** - * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + * Create a function that reports watch status by writing to the system and handles the formatting of the diagnostic */ function createWatchStatusReporter(system, pretty) { return pretty ? function (diagnostic, newLine, options) { clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); - var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); + var output = "[".concat(ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey), "] "); + output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(newLine + newLine); system.write(output); } : function (diagnostic, newLine, options) { @@ -119796,8 +120803,8 @@ var ts; if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { output += newLine; } - output += getLocaleTimeString(system) + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); + output += "".concat(getLocaleTimeString(system), " - "); + output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(getPlainDiagnosticFollowingNewLines(diagnostic, newLine)); system.write(output); }; } @@ -119815,19 +120822,84 @@ var ts; return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); } ts.getErrorCountForSummary = getErrorCountForSummary; + function getFilesInErrorForSummary(diagnostics) { + var filesInError = ts.filter(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }) + .map(function (errorDiagnostic) { + if (errorDiagnostic.file === undefined) + return; + return "".concat(errorDiagnostic.file.fileName); + }); + return filesInError.map(function (fileName) { + var diagnosticForFileName = ts.find(diagnostics, function (diagnostic) { + return diagnostic.file !== undefined && diagnostic.file.fileName === fileName; + }); + if (diagnosticForFileName !== undefined) { + var line = ts.getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start).line; + return { + fileName: fileName, + line: line + 1, + }; + } + }); + } + ts.getFilesInErrorForSummary = getFilesInErrorForSummary; function getWatchErrorSummaryDiagnosticMessage(errorCount) { return errorCount === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes; } ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; - function getErrorSummaryText(errorCount, newLine) { + function prettyPathForFileError(error, cwd) { + var line = ts.formatColorAndReset(":" + error.line, ts.ForegroundColorEscapeSequences.Grey); + if (ts.pathIsAbsolute(error.fileName) && ts.pathIsAbsolute(cwd)) { + return ts.getRelativePathFromDirectory(cwd, error.fileName, /* ignoreCase */ false) + line; + } + return error.fileName + line; + } + function getErrorSummaryText(errorCount, filesInError, newLine, host) { if (errorCount === 0) return ""; - var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); - return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine; + var nonNilFiles = filesInError.filter(function (fileInError) { return fileInError !== undefined; }); + var distinctFileNamesWithLines = nonNilFiles.map(function (fileInError) { return "".concat(fileInError.fileName, ":").concat(fileInError.line); }) + .filter(function (value, index, self) { return self.indexOf(value) === index; }); + var firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); + var d = errorCount === 1 ? + ts.createCompilerDiagnostic(filesInError[0] !== undefined ? + ts.Diagnostics.Found_1_error_in_1 : + ts.Diagnostics.Found_1_error, errorCount, firstFileReference) : + ts.createCompilerDiagnostic(distinctFileNamesWithLines.length === 0 ? + ts.Diagnostics.Found_0_errors : + distinctFileNamesWithLines.length === 1 ? + ts.Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1 : + ts.Diagnostics.Found_0_errors_in_1_files, errorCount, distinctFileNamesWithLines.length === 1 ? firstFileReference : distinctFileNamesWithLines.length); + var suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : ""; + return "".concat(newLine).concat(ts.flattenDiagnosticMessageText(d.messageText, newLine)).concat(newLine).concat(newLine).concat(suffix); } ts.getErrorSummaryText = getErrorSummaryText; + function createTabularErrorsDisplay(filesInError, host) { + var distinctFiles = filesInError.filter(function (value, index, self) { return index === self.findIndex(function (file) { return (file === null || file === void 0 ? void 0 : file.fileName) === (value === null || value === void 0 ? void 0 : value.fileName); }); }); + if (distinctFiles.length === 0) + return ""; + var numberLength = function (num) { return Math.log(num) * Math.LOG10E + 1; }; + var fileToErrorCount = distinctFiles.map(function (file) { return [file, ts.countWhere(filesInError, function (fileInError) { return fileInError.fileName === file.fileName; })]; }); + var maxErrors = fileToErrorCount.reduce(function (acc, value) { return Math.max(acc, value[1] || 0); }, 0); + var headerRow = ts.Diagnostics.Errors_Files.message; + var leftColumnHeadingLength = headerRow.split(" ")[0].length; + var leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors)); + var headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0); + var tabularData = ""; + tabularData += " ".repeat(headerPadding) + headerRow + "\n"; + fileToErrorCount.forEach(function (row) { + var file = row[0], errorCount = row[1]; + var errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0; + var leftPadding = errorCountDigitsLength < leftPaddingGoal ? + " ".repeat(leftPaddingGoal - errorCountDigitsLength) + : ""; + var fileRef = prettyPathForFileError(file, host.getCurrentDirectory()); + tabularData += "".concat(leftPadding).concat(errorCount, " ").concat(fileRef, "\n"); + }); + return tabularData; + } function isBuilderProgram(program) { return !!program.getState; } @@ -119851,9 +120923,9 @@ var ts; var relativeFileName = function (fileName) { return ts.convertToRelativePath(fileName, program.getCurrentDirectory(), getCanonicalFileName); }; for (var _i = 0, _c = program.getSourceFiles(); _i < _c.length; _i++) { var file = _c[_i]; - write("" + toFileName(file, relativeFileName)); - (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" " + fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText); }); - (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" " + d.messageText); }); + write("".concat(toFileName(file, relativeFileName))); + (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write(" ".concat(fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText)); }); + (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write(" ".concat(d.messageText)); }); } } ts.explainFiles = explainFiles; @@ -119893,7 +120965,7 @@ var ts; if (isJsonFile && !ts.endsWith(includeSpec, ".json" /* Json */)) return false; var pattern = ts.getPatternFromSpec(includeSpec, basePath, "files"); - return !!pattern && ts.getRegexFromPattern("(" + pattern + ")$", useCaseSensitiveFileNames).test(fileName); + return !!pattern && ts.getRegexFromPattern("(".concat(pattern, ")$"), useCaseSensitiveFileNames).test(fileName); }); } ts.getMatchedIncludeSpec = getMatchedIncludeSpec; @@ -119902,7 +120974,7 @@ var ts; var options = program.getCompilerOptions(); if (ts.isReferencedFile(reason)) { var referenceLocation = ts.getReferencedFileLocation(function (path) { return program.getSourceFileByPath(path); }, reason); - var referenceText = ts.isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : "\"" + referenceLocation.text + "\""; + var referenceText = ts.isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : "\"".concat(referenceLocation.text, "\""); var message = void 0; ts.Debug.assert(ts.isReferenceFileLocation(referenceLocation) || reason.kind === ts.FileIncludeKind.Import, "Only synthetic references are imports"); switch (reason.kind) { @@ -120026,12 +121098,12 @@ var ts; var currentDir_1 = program.getCurrentDirectory(); ts.forEach(emittedFiles, function (file) { var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); - write("TSFILE: " + filepath); + write("TSFILE: ".concat(filepath)); }); listFiles(program, write); } if (reportSummary) { - reportSummary(getErrorCountForSummary(diagnostics)); + reportSummary(getErrorCountForSummary(diagnostics), getFilesInErrorForSummary(diagnostics)); } return { emitResult: emitResult, @@ -120242,7 +121314,7 @@ var ts; var system = input.system || ts.sys; var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system)); var builderProgram = ts.createIncrementalProgram(input); - var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount, filesInError) { return system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)); } : undefined); if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); return exitStatus; @@ -120325,6 +121397,7 @@ var ts; var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution + var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -120354,7 +121427,7 @@ var ts; } var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + writeLog("Current directory: ".concat(currentDirectory, " CaseSensitiveFileNames: ").concat(useCaseSensitiveFileNames)); var configFileWatcher; if (configFileName) { configFileWatcher = watchFile(configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile); @@ -120487,14 +121560,21 @@ var ts; var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } else { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } createNewProgram(hasInvalidatedResolution); } changesAffectResolution = false; // reset for next sync + reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); } @@ -120503,10 +121583,10 @@ var ts; function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); + writeLog(" roots: ".concat(JSON.stringify(rootFileNames))); + writeLog(" options: ".concat(JSON.stringify(compilerOptions))); if (projectReferences) - writeLog(" projectReferences: " + JSON.stringify(projectReferences)); + writeLog(" projectReferences: ".concat(JSON.stringify(projectReferences))); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -120667,7 +121747,7 @@ var ts; return resolutionCache.invalidateResolutionsOfFailedLookupLocations(); } var pending = clearInvalidateResolutionsOfFailedLookupLocations(); - writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled earlier one" : "")); + writeLog("Scheduling invalidateFailedLookup".concat(pending ? ", Cancelled earlier one" : "")); timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250); } function invalidateResolutionsOfFailedLookup() { @@ -120696,7 +121776,7 @@ var ts; } function updateProgramWithWatchStatus() { timerToUpdateProgram = undefined; - reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + reportFileChangeDetectedOnCreateProgram = true; updateProgram(); } function updateProgram() { @@ -120727,7 +121807,7 @@ var ts; synchronizeProgram(); } function reloadConfigFile() { - writeLog("Reloading config file: " + configFileName); + writeLog("Reloading config file: ".concat(configFileName)); reloadLevel = ts.ConfigFileProgramReloadLevel.None; if (cachedDirectoryStructureHost) { cachedDirectoryStructureHost.clearCache(); @@ -120768,7 +121848,7 @@ var ts; return config.parsedCommandLine; } } - writeLog("Loading config file: " + configFileName); + writeLog("Loading config file: ".concat(configFileName)); var parsedCommandLine = host.getParsedCommandLine ? host.getParsedCommandLine(configFileName) : getParsedCommandLineFromConfigFileHost(configFileName); @@ -121072,8 +122152,8 @@ var ts; */ function createBuilderStatusReporter(system, pretty) { return function (diagnostic) { - var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine); + var output = pretty ? "[".concat(ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey), "] ") : "".concat(ts.getLocaleTimeString(system), " - "); + output += "".concat(ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine)).concat(system.newLine + system.newLine); system.write(output); }; } @@ -121848,7 +122928,7 @@ var ts; function listEmittedFile(_a, proj, file) { var write = _a.write; if (write && proj.options.listEmittedFiles) { - write("TSFILE: " + file); + write("TSFILE: ".concat(file)); } } function getOldProgram(_a, proj, parsed) { @@ -121877,7 +122957,7 @@ var ts; function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions()); reportAndStoreErrors(state, resolvedPath, diagnostics); - state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: "".concat(errorType, " errors") }); if (canEmitBuildInfo) return { buildResult: buildResult, step: BuildStep.EmitBuildInfo }; afterProgramDone(state, program, config); @@ -121905,7 +122985,7 @@ var ts; if (!host.fileExists(inputFile)) { return { type: ts.UpToDateStatusType.Unbuildable, - reason: inputFile + " does not exist" + reason: "".concat(inputFile, " does not exist") }; } if (!force) { @@ -122264,7 +123344,7 @@ var ts; } } if (filesToDelete) { - reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * ".concat(f); }).join("")); } return ts.ExitStatus.Success; } @@ -122461,11 +123541,14 @@ var ts; var canReportSummary = state.watch || !!state.host.reportErrorSummary; var diagnostics = state.diagnostics; var totalErrors = 0; + var filesInError = []; if (isCircularBuildOrder(buildOrder)) { reportBuildQueue(state, buildOrder.buildOrder); reportErrors(state, buildOrder.circularDiagnostics); if (canReportSummary) totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics); + if (canReportSummary) + filesInError = __spreadArray(__spreadArray([], filesInError, true), ts.getFilesInErrorForSummary(buildOrder.circularDiagnostics), true); } else { // Report errors from the other projects @@ -122477,12 +123560,14 @@ var ts; }); if (canReportSummary) diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); }); + if (canReportSummary) + diagnostics.forEach(function (singleProjectErrors) { return __spreadArray(__spreadArray([], filesInError, true), ts.getFilesInErrorForSummary(singleProjectErrors), true); }); } if (state.watch) { reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); } else if (state.host.reportErrorSummary) { - state.host.reportErrorSummary(totalErrors); + state.host.reportErrorSummary(totalErrors, filesInError); } } /** @@ -122597,7 +123682,7 @@ var ts; function nowString() { // E.g. "12:34:56.789" var d = new Date(); - return ts.padLeft(d.getHours().toString(), 2, "0") + ":" + ts.padLeft(d.getMinutes().toString(), 2, "0") + ":" + ts.padLeft(d.getSeconds().toString(), 2, "0") + "." + ts.padLeft(d.getMilliseconds().toString(), 3, "0"); + return "".concat(ts.padLeft(d.getHours().toString(), 2, "0"), ":").concat(ts.padLeft(d.getMinutes().toString(), 2, "0"), ":").concat(ts.padLeft(d.getSeconds().toString(), 2, "0"), ".").concat(ts.padLeft(d.getMilliseconds().toString(), 3, "0")); } server.nowString = nowString; })(server = ts.server || (ts.server = {})); @@ -122608,7 +123693,7 @@ var ts; var JsTyping; (function (JsTyping) { function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts".concat(ts.versionMajorMinor)) || ts.getProperty(availableTypingVersions, "latest")); return availableVersion.compareTo(cachedTyping.version) <= 0; } JsTyping.isTypingUpToDate = isTypingUpToDate; @@ -122661,7 +123746,7 @@ var ts; "worker_threads", "zlib" ]; - JsTyping.prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map(function (name) { return "node:" + name; }); + JsTyping.prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map(function (name) { return "node:".concat(name); }); JsTyping.nodeCoreModuleList = __spreadArray(__spreadArray([], unprefixedNodeCoreModuleList, true), JsTyping.prefixedNodeCoreModuleList, true); JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList); function nonRelativeModuleNameForTypingCache(moduleName) { @@ -122711,14 +123796,8 @@ var ts; var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); possibleSearchDirs.add(projectRootPath); possibleSearchDirs.forEach(function (searchDir) { - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); }); if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); @@ -122740,7 +123819,7 @@ var ts; var excludeTypingName = exclude_1[_i]; var didDelete = inferredTypings.delete(excludeTypingName); if (didDelete && log) - log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + log("Typing for ".concat(excludeTypingName, " is in exclude list, will be ignored.")); } var newTypingNames = []; var cachedTypingPaths = []; @@ -122754,7 +123833,7 @@ var ts; }); var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; if (log) - log("Result: " + JSON.stringify(result)); + log("Result: ".concat(JSON.stringify(result))); return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { @@ -122763,20 +123842,104 @@ var ts; } function addInferredTypings(typingNames, message) { if (log) - log(message + ": " + JSON.stringify(typingNames)); + log("".concat(message, ": ").concat(JSON.stringify(typingNames))); ts.forEach(typingNames, addInferredTyping); } /** - * Get the typing info from common package manager json files like package.json or bower.json + * Adds inferred typings from manifest/module pairs (think package.json + node_modules) + * + * @param projectRootPath is the path to the directory where to look for package.json, bower.json and other typing information + * @param manifestName is the name of the manifest (package.json or bower.json) + * @param modulesDirName is the directory name for modules (node_modules or bower_components). Should be lowercase! + * @param filesToWatch are the files to watch for changes. We will push things into this array. */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (!host.fileExists(jsonPath)) { + function getTypingNames(projectRootPath, manifestName, modulesDirName, filesToWatch) { + // First, we check the manifests themselves. They're not + // _required_, but they allow us to do some filtering when dealing + // with big flat dep directories. + var manifestPath = ts.combinePaths(projectRootPath, manifestName); + var manifest; + var manifestTypingNames; + if (host.fileExists(manifestPath)) { + filesToWatch.push(manifestPath); + manifest = ts.readConfigFile(manifestPath, function (path) { return host.readFile(path); }).config; + manifestTypingNames = ts.flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], ts.getOwnKeys); + addInferredTypings(manifestTypingNames, "Typing names in '".concat(manifestPath, "' dependencies")); + } + // Now we scan the directories for typing information in + // already-installed dependencies (if present). Note that this + // step happens regardless of whether a manifest was present, + // which is certainly a valid configuration, if an unusual one. + var packagesFolderPath = ts.combinePaths(projectRootPath, modulesDirName); + filesToWatch.push(packagesFolderPath); + if (!host.directoryExists(packagesFolderPath)) { return; } - filesToWatch.push(jsonPath); - var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; - var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); - addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + // There's two cases we have to take into account here: + // 1. If manifest is undefined, then we're not using a manifest. + // That means that we should scan _all_ dependencies at the top + // level of the modulesDir. + // 2. If manifest is defined, then we can do some special + // filtering to reduce the amount of scanning we need to do. + // + // Previous versions of this algorithm checked for a `_requiredBy` + // field in the package.json, but that field is only present in + // `npm@>=3 <7`. + // Package names that do **not** provide their own typings, so + // we'll look them up. + var packageNames = []; + var dependencyManifestNames = manifestTypingNames + // This is #1 described above. + ? manifestTypingNames.map(function (typingName) { return ts.combinePaths(packagesFolderPath, typingName, manifestName); }) + // And #2. Depth = 3 because scoped packages look like `node_modules/@foo/bar/package.json` + : host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 3) + .filter(function (manifestPath) { + if (ts.getBaseFileName(manifestPath) !== manifestName) { + return false; + } + // It's ok to treat + // `node_modules/@foo/bar/package.json` as a manifest, + // but not `node_modules/jquery/nested/package.json`. + // We only assume depth 3 is ok for formally scoped + // packages. So that needs this dance here. + var pathComponents = ts.getPathComponents(ts.normalizePath(manifestPath)); + var isScoped = pathComponents[pathComponents.length - 3][0] === "@"; + return isScoped && pathComponents[pathComponents.length - 4].toLowerCase() === modulesDirName || // `node_modules/@foo/bar` + !isScoped && pathComponents[pathComponents.length - 3].toLowerCase() === modulesDirName; // `node_modules/foo` + }); + if (log) + log("Searching for typing names in ".concat(packagesFolderPath, "; all files: ").concat(JSON.stringify(dependencyManifestNames))); + // Once we have the names of things to look up, we iterate over + // and either collect their included typings, or add them to the + // list of typings we need to look up separately. + for (var _i = 0, dependencyManifestNames_1 = dependencyManifestNames; _i < dependencyManifestNames_1.length; _i++) { + var manifestPath_1 = dependencyManifestNames_1[_i]; + var normalizedFileName = ts.normalizePath(manifestPath_1); + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var manifest_1 = result_1.config; + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!manifest_1.name) { + continue; + } + var ownTypes = manifest_1.types || manifest_1.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (host.fileExists(absolutePath)) { + if (log) + log(" Package '".concat(manifest_1.name, "' provides its own types.")); + inferredTypings.set(manifest_1.name, absolutePath); + } + else { + if (log) + log(" Package '".concat(manifest_1.name, "' provides its own types but they are missing.")); + } + } + else { + packageNames.push(manifest_1.name); + } + } + addInferredTypings(packageNames, " Found package names"); } /** * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" @@ -122802,55 +123965,6 @@ var ts; addInferredTyping("react"); } } - /** - * Infer typing names from packages folder (ex: node_module, bower_components) - * @param packagesFolderPath is the path to the packages folder - */ - function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { - filesToWatch.push(packagesFolderPath); - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(packagesFolderPath)) { - return; - } - // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - if (log) - log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); - var packageNames = []; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; - var normalizedFileName = ts.normalizePath(fileName); - var baseFileName = ts.getBaseFileName(normalizedFileName); - if (baseFileName !== "package.json" && baseFileName !== "bower.json") { - continue; - } - var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_1.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (baseFileName === "package.json" && packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - var ownTypes = packageJson.types || packageJson.typings; - if (ownTypes) { - var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); - if (log) - log(" Package '" + packageJson.name + "' provides its own types."); - inferredTypings.set(packageJson.name, absolutePath); - } - else { - packageNames.push(packageJson.name); - } - } - addInferredTypings(packageNames, " Found package names"); - } } JsTyping.discoverTypings = discoverTypings; var NameValidationResult; @@ -122914,15 +124028,15 @@ var ts; var kind = isScopeName ? "Scope" : "Package"; switch (result) { case 1 /* EmptyName */: - return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty"; + return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot be empty"); case 2 /* NameTooLong */: - return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters"; + return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' should be less than ").concat(maxPackageNameLength, " characters"); case 3 /* NameStartsWithDot */: - return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'"; + return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot start with '.'"); case 4 /* NameStartsWithUnderscore */: - return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'"; + return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' cannot start with '_'"); case 5 /* NameContainsNonURISafeCharacters */: - return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters"; + return "'".concat(typing, "':: ").concat(kind, " name '").concat(name, "' contains non URI safe characters"); case 0 /* Ok */: return ts.Debug.fail(); // Shouldn't have called this. default: @@ -123186,6 +124300,7 @@ var ts; ScriptElementKind["externalModuleName"] = "external module name"; /** * + * @deprecated */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ @@ -123361,13 +124476,6 @@ var ts; || ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isImportEqualsDeclaration(parent) && node === parent.name) { - var decl = parent; - while (decl) { - if (ts.isImportEqualsDeclaration(decl) || ts.isImportClause(decl) || ts.isExportDeclaration(decl)) { - return decl.isTypeOnly ? 2 /* Type */ : 7 /* All */; - } - decl = decl.parent; - } return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -124518,7 +125626,7 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile, n.kind); return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { @@ -124532,7 +125640,7 @@ var ts; // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -124548,17 +125656,19 @@ var ts; if (children.length === 0) { return n; } - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile, parentKind) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { - ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + if (i === 0 && (parentKind === 11 /* JsxText */ || parentKind === 278 /* JsxSelfClosingElement */)) { + ts.Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } } else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; @@ -125084,6 +126194,7 @@ var ts; useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), + getPackageJsonInfoCache: function () { var _a; return (_a = program.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache(); }, getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), redirectTargetsMap: program.redirectTargetsMap, getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); }, @@ -125480,7 +126591,7 @@ var ts; var prefix = ts.isJSDocLink(link) ? "link" : ts.isJSDocLinkCode(link) ? "linkcode" : "linkplain"; - var parts = [linkPart("{@" + prefix + " ")]; + var parts = [linkPart("{@".concat(prefix, " "))]; if (!link.name) { if (link.text) parts.push(linkTextPart(link.text)); @@ -125497,7 +126608,7 @@ var ts; parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); + parts.push(linkTextPart(name + (suffix || text.indexOf("://") === 0 ? "" : " ") + text)); } } parts.push(linkPart("}")); @@ -125728,7 +126839,7 @@ var ts; function getUniqueName(baseName, sourceFile) { var nameText = baseName; for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { - nameText = baseName + "_" + i; + nameText = "".concat(baseName, "_").concat(i); } return nameText; } @@ -125838,7 +126949,7 @@ var ts; // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = getQuotePreference(sourceFile, preferences); var quoted = JSON.stringify(text); - return quotePreference === 0 /* Single */ ? "'" + ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"') + "'" : quoted; + return quotePreference === 0 /* Single */ ? "'".concat(ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"'), "'") : quoted; } ts.quote = quote; function isEqualityOperatorKind(kind) { @@ -125898,7 +127009,6 @@ var ts; || kind === 165 /* PropertySignature */ || kind === 167 /* MethodSignature */; } - ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { return kind === 255 /* FunctionDeclaration */ || kind === 170 /* Constructor */ @@ -125906,11 +127016,9 @@ var ts; || kind === 171 /* GetAccessor */ || kind === 172 /* SetAccessor */; } - ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { return kind === 260 /* ModuleDeclaration */; } - ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { return kind === 236 /* VariableStatement */ || kind === 237 /* ExpressionStatement */ @@ -125985,19 +127093,34 @@ var ts; ts.forEachChild(sourceFile, function visit(node) { if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) { var lastToken = node.getLastToken(sourceFile); - if (lastToken && lastToken.kind === 26 /* SemicolonToken */) { + if ((lastToken === null || lastToken === void 0 ? void 0 : lastToken.kind) === 26 /* SemicolonToken */) { withSemicolon++; } else { withoutSemicolon++; } } + else if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) { + var lastToken = node.getLastToken(sourceFile); + if ((lastToken === null || lastToken === void 0 ? void 0 : lastToken.kind) === 26 /* SemicolonToken */) { + withSemicolon++; + } + else if (lastToken && lastToken.kind !== 27 /* CommaToken */) { + var lastTokenLine = ts.getLineAndCharacterOfPosition(sourceFile, lastToken.getStart(sourceFile)).line; + var nextTokenLine = ts.getLineAndCharacterOfPosition(sourceFile, ts.getSpanOfTokenAtPosition(sourceFile, lastToken.end).start).line; + // Avoid counting missing semicolon in single-line objects: + // `function f(p: { x: string /*no semicolon here is insignificant*/ }) {` + if (lastTokenLine !== nextTokenLine) { + withoutSemicolon++; + } + } + } if (withSemicolon + withoutSemicolon >= nStatementsToObserve) { return true; } return ts.forEachChild(node, visit); }); - // One statement missing a semicolon isn’t sufficient evidence to say the user + // One statement missing a semicolon isn't sufficient evidence to say the user // doesn’t want semicolons, because they may not even be done writing that statement. if (withSemicolon === 0 && withoutSemicolon <= 1) { return true; @@ -126196,7 +127319,7 @@ var ts; if (!ts.stringContains(importedFileName, "node_modules")) { return undefined; } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost, preferences); + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile, importedFileName, moduleSpecifierResolutionHost, preferences); if (!specifier) { return undefined; } @@ -126210,7 +127333,7 @@ var ts; var components = ts.getPathComponents(ts.getPackageNameFromTypesPackageName(fullSpecifier)).slice(1); // Scoped packages if (ts.startsWith(components[0], "@")) { - return components[0] + "/" + components[1]; + return "".concat(components[0], "/").concat(components[1]); } return components[0]; } @@ -126306,24 +127429,44 @@ var ts; return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray; } ts.firstOrOnly = firstOrOnly; - function getNameForExportedSymbol(symbol, scriptTarget) { - if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { + function getNamesForExportedSymbol(symbol, scriptTarget) { + if (needsNameFromDeclaration(symbol)) { + var fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); + if (fromDeclaration) + return fromDeclaration; + var fileNameCase = ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ false); + var capitalized = ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ true); + if (fileNameCase === capitalized) + return fileNameCase; + return [fileNameCase, capitalized]; + } + return symbol.name; + } + ts.getNamesForExportedSymbol = getNamesForExportedSymbol; + function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) { + if (needsNameFromDeclaration(symbol)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) - || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); + return getDefaultLikeExportNameFromDeclaration(symbol) + || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized); } return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + function needsNameFromDeclaration(symbol) { + return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); + } + function getDefaultLikeExportNameFromDeclaration(symbol) { + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }); + } function getSymbolParentOrFail(symbol) { var _a; - return ts.Debug.checkDefined(symbol.parent, "Symbol parent was undefined. Flags: " + ts.Debug.formatSymbolFlags(symbol.flags) + ". " + - ("Declarations: " + ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.map(function (d) { + return ts.Debug.checkDefined(symbol.parent, "Symbol parent was undefined. Flags: ".concat(ts.Debug.formatSymbolFlags(symbol.flags), ". ") + + "Declarations: ".concat((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.map(function (d) { var kind = ts.Debug.formatSyntaxKind(d.kind); var inJS = ts.isInJSFile(d); var expression = d.expression; - return (inJS ? "[JS]" : "") + kind + (expression ? " (expression: " + ts.Debug.formatSyntaxKind(expression.kind) + ")" : ""); - }).join(", ")) + ".")); + return (inJS ? "[JS]" : "") + kind + (expression ? " (expression: ".concat(ts.Debug.formatSyntaxKind(expression.kind), ")") : ""); + }).join(", "), ".")); } /** * Useful to check whether a string contains another string at a specific index @@ -126396,6 +127539,16 @@ var ts; : ts.getLocaleSpecificMessage(diag); } ts.diagnosticToString = diagnosticToString; + /** + * Get format code settings for a code writing context (e.g. when formatting text changes or completions code). + */ + function getFormatCodeSettingsForWriting(_a, sourceFile) { + var options = _a.options; + var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore; + var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile); + return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore }); + } + ts.getFormatCodeSettingsForWriting = getFormatCodeSettingsForWriting; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -126419,6 +127572,17 @@ var ts; var exportInfoId = 1; var exportInfo = ts.createMultiMap(); var symbols = new ts.Map(); + /** + * Key: node_modules package name (no @types). + * Value: path to deepest node_modules folder seen that is + * both visible to `usableByFileName` and contains the package. + * + * Later, we can see if a given SymbolExportInfo is shadowed by + * a another installation of the same package in a deeper + * node_modules folder by seeing if its path starts with the + * value stored here. + */ + var packages = new ts.Map(); var usableByFileName; var cache = { isUsableByFile: function (importingFile) { return importingFile === usableByFileName; }, @@ -126428,11 +127592,32 @@ var ts; symbols.clear(); usableByFileName = undefined; }, - add: function (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, scriptTarget, checker) { + add: function (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, checker) { if (importingFile !== usableByFileName) { cache.clear(); usableByFileName = importingFile; } + var packageName; + if (moduleFile) { + var nodeModulesPathParts = ts.getNodeModulePathParts(moduleFile.fileName); + if (nodeModulesPathParts) { + var topLevelNodeModulesIndex = nodeModulesPathParts.topLevelNodeModulesIndex, topLevelPackageNameIndex = nodeModulesPathParts.topLevelPackageNameIndex, packageRootIndex = nodeModulesPathParts.packageRootIndex; + packageName = ts.unmangleScopedPackageName(ts.getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex))); + if (ts.startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) { + var prevDeepestNodeModulesPath = packages.get(packageName); + var nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex); + if (prevDeepestNodeModulesPath) { + var prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(ts.nodeModulesPathPart); + if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) { + packages.set(packageName, nodeModulesPath); + } + } + else { + packages.set(packageName, nodeModulesPath); + } + } + } + } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. @@ -126442,9 +127627,11 @@ var ts; // 3. Otherwise, we have a default/namespace import that can be imported by any name, and // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to // get a better name. - var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) + var names = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) - : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); + : ts.getNamesForExportedSymbol(namedSymbol, /*scriptTarget*/ undefined); + var symbolName = typeof names === "string" ? names : names[0]; + var capitalizedSymbolName = typeof names === "string" ? undefined : names[1]; var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; var target = ts.skipAlias(symbol, checker); @@ -126452,13 +127639,15 @@ var ts; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { + exportInfo.add(key(symbolName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, - symbolName: importedName, + symbolName: symbolName, + capitalizedSymbolName: capitalizedSymbolName, moduleName: moduleName, moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + packageName: packageName, exportKind: exportKind, targetFlags: target.flags, isFromPackageJson: isFromPackageJson, @@ -126472,12 +127661,19 @@ var ts; var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, - forEach: function (importingFile, action) { + search: function (importingFile, preferCapitalized, matches, action) { if (importingFile !== usableByFileName) return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); + var name = preferCapitalized && info[0].capitalizedSymbolName || symbolName; + if (matches(name, info[0].targetFlags)) { + var rehydrated = info.map(rehydrateCachedInfo); + var filtered = rehydrated.filter(function (r, i) { return isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName); }); + if (filtered.length) { + action(filtered, name, !!ambientModuleName, key); + } + } }); }, releaseSymbols: function () { @@ -126531,7 +127727,7 @@ var ts; : checker.tryFindAmbientModule(info.moduleName)); var symbol = info.symbol || cachedSymbol || ts.Debug.checkDefined(exportKind === 2 /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) - : checker.tryGetMemberInModuleExportsAndProperties(ts.unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), "Could not find symbol '" + info.symbolName + "' by key '" + info.symbolTableKey + "' in module " + moduleSymbol.name); + : checker.tryGetMemberInModuleExportsAndProperties(ts.unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), "Could not find symbol '".concat(info.symbolName, "' by key '").concat(info.symbolTableKey, "' in module ").concat(moduleSymbol.name)); symbols.set(id, [symbol, moduleSymbol]); return { symbol: symbol, @@ -126544,7 +127740,7 @@ var ts; } function key(importedName, symbol, ambientModuleName, checker) { var moduleKey = ambientModuleName || ""; - return importedName + "|" + ts.getSymbolId(ts.skipAlias(symbol, checker)) + "|" + moduleKey; + return "".concat(importedName, "|").concat(ts.getSymbolId(ts.skipAlias(symbol, checker)), "|").concat(moduleKey); } function parseKey(key) { var symbolName = key.substring(0, key.indexOf("|")); @@ -126577,6 +127773,12 @@ var ts; } return true; } + function isNotShadowedByDeeperNodeModulesPackage(info, packageName) { + if (!packageName || !info.moduleFileName) + return true; + var packageDeepestNodeModulesPath = packages.get(packageName); + return !packageDeepestNodeModulesPath || ts.startsWith(info.moduleFileName, packageDeepestNodeModulesPath); + } } ts.createCacheableExportInfoMap = createCacheableExportInfoMap; function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { @@ -126624,7 +127826,7 @@ var ts; if (autoImportProvider) { var start = ts.timestamp(); forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), function (module, file) { return cb(module, file, autoImportProvider, /*isFromPackageJson*/ true); }); - (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: " + (ts.timestamp() - start)); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "forEachExternalModuleToImportFrom autoImportProvider: ".concat(ts.timestamp() - start)); } } ts.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; @@ -126659,7 +127861,6 @@ var ts; } (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getExportInfoMap: cache miss or empty; calculating new results"); var compilerOptions = program.getCompilerOptions(); - var scriptTarget = ts.getEmitScriptTarget(compilerOptions); var moduleCount = 0; forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) @@ -126670,15 +127871,15 @@ var ts; // Note: I think we shouldn't actually see resolved module symbols here, but weird merges // can cause it to happen: see 'completionsImport_mergedReExport.ts' if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { - cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); + cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { - cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); + cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, checker); } }); }); - (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getExportInfoMap: done in " + (ts.timestamp() - start) + " ms"); + (_e = host.log) === null || _e === void 0 ? void 0 : _e.call(host, "getExportInfoMap: done in ".concat(ts.timestamp() - start, " ms")); return cache; } ts.getExportInfoMap = getExportInfoMap; @@ -127211,7 +128412,7 @@ var ts; return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { var length = end - start; - ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); + ts.Debug.assert(length > 0, "Classification had non-positive length of ".concat(length)); spans.push(start); spans.push(length); spans.push(type); @@ -127715,6 +128916,9 @@ var ts; } return; } + if (ts.isConstTypeReference(token.parent)) { + return 3 /* keyword */; + } } return 2 /* identifier */; } @@ -128015,8 +129219,9 @@ var ts; case 0 /* Paths */: return convertPathCompletions(completion.paths); case 1 /* Properties */: { - var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + var entries = ts.createSortedArray(); + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options, + /*formatContext*/ undefined); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -128079,7 +129284,7 @@ var ts; case ".d.cts" /* Dcts */: return ".d.cts" /* dctsModifier */; case ".cjs" /* Cjs */: return ".cjs" /* cjsModifier */; case ".cts" /* Cts */: return ".cts" /* ctsModifier */; - case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported."); + case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension ".concat(".tsbuildinfo" /* TsBuildInfo */, " is unsupported.")); case undefined: return "" /* none */; default: return ts.Debug.assertNever(extension); @@ -128213,7 +129418,7 @@ var ts; var types = ts.flatMap(candidates, function (candidate) { if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + var type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); return getStringLiteralTypes(type, uniques); }); @@ -128744,6 +129949,8 @@ var ts; CompletionSource["ThisProperty"] = "ThisProperty/"; /** Auto-import that comes attached to a class member snippet */ CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; + /** A type-only import that needs to be promoted in order to be used at the completion location */ + CompletionSource["TypeOnlyAlias"] = "TypeOnlyAlias/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -128753,6 +129960,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["TypeOnlyAlias"] = 64] = "TypeOnlyAlias"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -128780,6 +129988,9 @@ var ts; function originIsNullableMember(origin) { return !!(origin.kind & 16 /* Nullable */); } + function originIsTypeOnlyAlias(origin) { + return !!(origin && origin.kind & 64 /* TypeOnlyAlias */); + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -128802,16 +130013,17 @@ var ts; function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, preferences, isForImportStatementCompletion, cb) { var _a, _b, _c; var start = ts.timestamp(); + var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); var resolutionLimitExceeded = false; var ambientCount = 0; var resolvedCount = 0; var resolvedFromCacheCount = 0; var cacheAttemptCount = 0; var result = cb({ tryResolve: tryResolve, resolutionLimitExceeded: function () { return resolutionLimitExceeded; } }); - var hitRateMessage = cacheAttemptCount ? " (" + (resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1) + "% hit rate)" : ""; - (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, logPrefix + ": resolved " + resolvedCount + " module specifiers, plus " + ambientCount + " ambient and " + resolvedFromCacheCount + " from cache" + hitRateMessage); - (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, logPrefix + ": response is " + (resolutionLimitExceeded ? "incomplete" : "complete")); - (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, logPrefix + ": " + (ts.timestamp() - start)); + var hitRateMessage = cacheAttemptCount ? " (".concat((resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1), "% hit rate)") : ""; + (_a = host.log) === null || _a === void 0 ? void 0 : _a.call(host, "".concat(logPrefix, ": resolved ").concat(resolvedCount, " module specifiers, plus ").concat(ambientCount, " ambient and ").concat(resolvedFromCacheCount, " from cache").concat(hitRateMessage)); + (_b = host.log) === null || _b === void 0 ? void 0 : _b.call(host, "".concat(logPrefix, ": response is ").concat(resolutionLimitExceeded ? "incomplete" : "complete")); + (_c = host.log) === null || _c === void 0 ? void 0 : _c.call(host, "".concat(logPrefix, ": ").concat(ts.timestamp() - start)); return result; function tryResolve(exportInfo, isFromAmbientModule) { if (isFromAmbientModule) { @@ -128824,7 +130036,7 @@ var ts; var shouldResolveModuleSpecifier = isForImportStatementCompletion || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, sourceFile, program, host, preferences, shouldGetModuleSpecifierFromCache) + ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { resolutionLimitExceeded = true; @@ -128837,7 +130049,7 @@ var ts; return result; } } - function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken) { + function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext) { var _a; var previousToken = getRelevantTokens(position, sourceFile).previousToken; if (triggerCharacter && !ts.isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) { @@ -128877,7 +130089,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -128897,6 +130109,29 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + // Editors will use the `sortText` and then fall back to `name` for sorting, but leave ties in response order. + // So, it's important that we sort those ties in the order we want them displayed if it matters. We don't + // strictly need to sort by name or SortText here since clients are going to do it anyway, but we have to + // do the work of comparing them so we can sort those ties appropriately; plus, it makes the order returned + // by the language service consistent with what TS Server does and what editors typically do. This also makes + // completions tests make more sense. We used to sort only alphabetically and only in the server layer, but + // this made tests really weird, since most fourslash tests don't use the server. + function compareCompletionEntries(entryInArray, entryToInsert) { + var _a, _b; + var result = ts.compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText); + if (result === 0 /* EqualTo */) { + result = ts.compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name); + } + if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) === null || _a === void 0 ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) === null || _b === void 0 ? void 0 : _b.moduleSpecifier)) { + // Sort same-named auto-imports by module specifier + result = ts.compareNumberOfDirectorySeparators(entryInArray.data.moduleSpecifier, entryToInsert.data.moduleSpecifier); + } + if (result === 0 /* EqualTo */) { + // Fall back to symbol order - if we return `EqualTo`, `insertSorted` will put later symbols first. + return -1 /* LessThan */; + } + return result; + } function completionEntryDataIsResolved(data) { return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); } @@ -128974,8 +130209,8 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position) { + var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, isRightOfOpenTag = completionData.isRightOfOpenTag, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { var completionInfo = getJsxClosingTagCompletion(location, sourceFile); @@ -128983,31 +130218,38 @@ var ts; return completionInfo; } } - var entries = []; + var entries = ts.createSortedArray(); if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag); } if (keywordFilters !== 0 /* None */) { - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); + var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (!entryNames.has(keywordEntry.name)) { - entries.push(keywordEntry); + if (!entryNames_1.has(keywordEntry.name)) { + ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { - var literal = literals_1[_b]; - entries.push(createCompletionEntryForLiteral(sourceFile, preferences, literal)); + var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); + for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { + var keywordEntry = _c[_b]; + if (!entryNames.has(keywordEntry.name)) { + ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + } + for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { + var literal = literals_1[_d]; + ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); } return { isGlobalCompletion: isInSnippetScope, @@ -129083,13 +130325,13 @@ var ts; var realName = ts.unescapeLeadingUnderscores(name); if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { uniqueNames.add(realName); - entries.push({ + ts.insertSorted(entries, { name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: SortText.JavascriptIdentifiers, isFromUncheckedFile: true - }); + }, compareCompletionEntries); } }); } @@ -129100,7 +130342,7 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag) { var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); @@ -129114,15 +130356,15 @@ var ts; var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { insertText = needsConvertPropertyAccess - ? "this" + (insertQuestionDot ? "?." : "") + "[" + quotePropertyName(sourceFile, preferences, name) + "]" - : "this" + (insertQuestionDot ? "?." : ".") + name; + ? "this".concat(insertQuestionDot ? "?." : "", "[").concat(quotePropertyName(sourceFile, preferences, name), "]") + : "this".concat(insertQuestionDot ? "?." : ".").concat(name); } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) { - insertText = useBraces ? needsConvertPropertyAccess ? "[" + quotePropertyName(sourceFile, preferences, name) + "]" : "[" + name + "]" : name; + insertText = useBraces ? needsConvertPropertyAccess ? "[".concat(quotePropertyName(sourceFile, preferences, name), "]") : "[".concat(name, "]") : name; if (insertQuestionDot || propertyAccessToConvert.questionDotToken) { - insertText = "?." + insertText; + insertText = "?.".concat(insertText); } var dot = ts.findChildOfKind(propertyAccessToConvert, 24 /* DotToken */, sourceFile) || ts.findChildOfKind(propertyAccessToConvert, 28 /* QuestionDotToken */, sourceFile); @@ -129136,7 +130378,7 @@ var ts; if (isJsxInitializer) { if (insertText === undefined) insertText = name; - insertText = "{" + insertText + "}"; + insertText = "{".concat(insertText, "}"); if (typeof isJsxInitializer !== "boolean") { replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); } @@ -129149,8 +130391,8 @@ var ts; if (precedingToken && ts.positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) { awaitText = ";"; } - awaitText += "(await " + propertyAccessToConvert.expression.getText() + ")"; - insertText = needsConvertPropertyAccess ? "" + awaitText + insertText : "" + awaitText + (insertQuestionDot ? "?." : ".") + insertText; + awaitText += "(await ".concat(propertyAccessToConvert.expression.getText(), ")"); + insertText = needsConvertPropertyAccess ? "".concat(awaitText).concat(insertText) : "".concat(awaitText).concat(insertQuestionDot ? "?." : ".").concat(insertText); replacementSpan = ts.createTextSpanFromBounds(propertyAccessToConvert.getStart(sourceFile), propertyAccessToConvert.end); } if (originIsResolvedExport(origin)) { @@ -129160,19 +130402,21 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) { + hasAction = true; + } if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location)) { var importAdder = void 0; - (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { hasAction = true; source = CompletionSource.ClassMemberSnippet; } } - var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); - if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { + if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { var useBraces_1 = preferences.jsxAttributeCompletionStyle === "braces"; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); // If is boolean like or undefined, don't return a snippet we want just to return the completion. @@ -129181,7 +130425,7 @@ var ts; && !(type.flags & 1048576 /* Union */ && ts.find(type.types, function (type) { return !!(type.flags & 528 /* BooleanLike */); }))) { if (type.flags & 402653316 /* StringLike */ || (type.flags & 1048576 /* Union */ && ts.every(type.types, function (type) { return !!(type.flags & (402653316 /* StringLike */ | 32768 /* Undefined */)); }))) { // If is string like or undefined use quotes - insertText = ts.escapeSnippetText(name) + "=" + ts.quote(sourceFile, preferences, "$1"); + insertText = "".concat(ts.escapeSnippetText(name), "=").concat(ts.quote(sourceFile, preferences, "$1")); isSnippet = true; } else { @@ -129190,7 +130434,7 @@ var ts; } } if (useBraces_1) { - insertText = ts.escapeSnippetText(name) + "={$1}"; + insertText = "".concat(ts.escapeSnippetText(name), "={$1}"); isSnippet = true; } } @@ -129210,7 +130454,7 @@ var ts; // entries (like JavaScript identifier entries). return { name: name, - kind: kind, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, source: source, @@ -129264,7 +130508,7 @@ var ts; ts.isSyntaxList(location) && ts.isClassLike(location.parent))); } - function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext) { var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); if (!classLikeDeclaration) { return { insertText: name }; @@ -129281,15 +130525,16 @@ var ts; newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), }); var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + // Create empty body for possible method implementation. var body; if (preferences.includeCompletionsWithSnippetText) { isSnippet = true; // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, // if it has one, so that the cursor ends up in the body once the completion is inserted. // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. - var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); - ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); - body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + var emptyStmt = ts.factory.createEmptyStatement(); + body = ts.factory.createBlock([emptyStmt], /* multiline */ true); + ts.setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 }); } else { body = ts.factory.createBlock([], /* multiline */ true); @@ -129335,7 +130580,27 @@ var ts; completionNodes.push(node); }, body, 2 /* Property */, isAbstract); if (completionNodes.length) { - insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + // If we have access to formatting settings, we print the nodes using the emitter, + // and then format the printed text. + if (formatContext) { + var syntheticFile_1 = { + text: printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile), + getLineAndCharacterOfPosition: function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }, + }; + var formatOptions_1 = ts.getFormatCodeSettingsForWriting(formatContext, sourceFile); + var changes = ts.flatMap(completionNodes, function (node) { + var nodeWithPos = ts.textChanges.assignPositionsToNode(node); + return ts.formatting.formatNodeGivenIndentation(nodeWithPos, syntheticFile_1, sourceFile.languageVariant, + /* indentation */ 0, + /* delta */ 0, __assign(__assign({}, formatContext), { options: formatOptions_1 })); + }); + insertText = ts.textChanges.applyChanges(syntheticFile_1.text, changes); + } + else { // Otherwise, just use emitter to print the new nodes. + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } } return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; } @@ -129379,8 +130644,8 @@ var ts; return undefined; } function createSnippetPrinter(printerOptions) { - var printer = ts.createPrinter(printerOptions); - var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var baseWriter = ts.textChanges.createWriter(ts.getNewLineCharacter(printerOptions)); + var printer = ts.createPrinter(printerOptions, baseWriter); var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { printSnippetList: printSnippetList, @@ -129454,14 +130719,14 @@ var ts; var importKind = ts.codefix.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ true); var isTopLevelTypeOnly = ((_b = (_a = ts.tryCast(importCompletionNode, ts.isImportDeclaration)) === null || _a === void 0 ? void 0 : _a.importClause) === null || _b === void 0 ? void 0 : _b.isTypeOnly) || ((_c = ts.tryCast(importCompletionNode, ts.isImportEqualsDeclaration)) === null || _c === void 0 ? void 0 : _c.isTypeOnly); var isImportSpecifierTypeOnly = couldBeTypeOnlyImportSpecifier(importCompletionNode, contextToken); - var topLevelTypeOnlyText = isTopLevelTypeOnly ? " " + ts.tokenToString(151 /* TypeKeyword */) + " " : " "; - var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? ts.tokenToString(151 /* TypeKeyword */) + " " : ""; + var topLevelTypeOnlyText = isTopLevelTypeOnly ? " ".concat(ts.tokenToString(151 /* TypeKeyword */), " ") : " "; + var importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? "".concat(ts.tokenToString(151 /* TypeKeyword */), " ") : ""; var suffix = useSemicolons ? ";" : ""; switch (importKind) { - case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " = require(" + quotedModuleSpecifier + ")" + suffix }; - case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " from " + quotedModuleSpecifier + suffix }; - case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "* as " + ts.escapeSnippetText(name) + " from " + quotedModuleSpecifier + suffix }; - case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import" + topLevelTypeOnlyText + "{ " + importSpecifierTypeOnlyText + ts.escapeSnippetText(name) + tabStop + " } from " + quotedModuleSpecifier + suffix }; + case 3 /* CommonJS */: return { replacementSpan: replacementSpan, insertText: "import".concat(topLevelTypeOnlyText).concat(ts.escapeSnippetText(name)).concat(tabStop, " = require(").concat(quotedModuleSpecifier, ")").concat(suffix) }; + case 1 /* Default */: return { replacementSpan: replacementSpan, insertText: "import".concat(topLevelTypeOnlyText).concat(ts.escapeSnippetText(name)).concat(tabStop, " from ").concat(quotedModuleSpecifier).concat(suffix) }; + case 2 /* Namespace */: return { replacementSpan: replacementSpan, insertText: "import".concat(topLevelTypeOnlyText, "* as ").concat(ts.escapeSnippetText(name), " from ").concat(quotedModuleSpecifier).concat(suffix) }; + case 0 /* Named */: return { replacementSpan: replacementSpan, insertText: "import".concat(topLevelTypeOnlyText, "{ ").concat(importSpecifierTypeOnlyText).concat(ts.escapeSnippetText(name)).concat(tabStop, " } from ").concat(quotedModuleSpecifier).concat(suffix) }; } } function quotePropertyName(sourceFile, preferences, name) { @@ -129484,8 +130749,11 @@ var ts; if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) { + return CompletionSource.TypeOnlyAlias; + } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); @@ -129506,14 +130774,14 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag); if (!entry) { continue; } /** 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(); })); + var shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); uniques.set(name, shouldShadowLaterSymbols); - entries.push(entry); + ts.insertSorted(entries, entry, compareCompletionEntries, /*allowDuplicates*/ true); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); // Prevent consumers of this map from having to worry about @@ -129524,6 +130792,7 @@ var ts; add: function (name) { return uniques.set(name, true); }, }; function shouldIncludeSymbol(symbol, symbolToSortTextIdMap) { + var allFlags = symbol.flags; if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -129549,11 +130818,10 @@ var ts; || symbolToSortTextIdMap[ts.getSymbolId(symbolOrigin)] === 11 /* LocationPriority */)) { return false; } - // Continue with origin symbol - symbol = symbolOrigin; + allFlags |= ts.getCombinedLocalAndExportSymbolFlags(symbolOrigin); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); + return !!(allFlags & 1920 /* Namespace */); } if (isTypeOnlyLocation) { // It's a type, but you can reach it by namespace.type as well @@ -129561,7 +130829,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + return !!(allFlags & 111551 /* Value */); } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; @@ -129695,14 +130963,13 @@ var ts; Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; - if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } if (source === CompletionSource.ClassMemberSnippet) { - var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken, formatContext).importAdder; if (importAdder) { var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); return { @@ -129714,13 +130981,19 @@ var ts; }; } } + if (originIsTypeOnlyAlias(origin)) { + var codeAction_1 = ts.codefix.getPromoteTypeOnlyCompletionAction(sourceFile, origin.declaration.name, program, host, formatContext, preferences); + ts.Debug.assertIsDefined(codeAction_1, "Expected to have a code action for promoting type-only alias"); + return { codeActions: [codeAction_1], sourceDisplay: undefined }; + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var isJsxOpeningTagName = (contextToken === null || contextToken === void 0 ? void 0 : contextToken.kind) === 29 /* LessThanToken */ && ts.isJsxOpeningLikeElement(contextToken.parent); + var _a = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), isJsxOpeningTagName), isJsxOpeningTagName, host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129775,7 +131048,8 @@ var ts; case 103 /* NewKeyword */: return checker.getContextualType(parent); case 82 /* CaseKeyword */: - return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + var caseClause = ts.tryCast(parent, ts.isCaseClause); + return caseClause ? ts.getSwitchedType(caseClause, checker) : undefined; case 18 /* OpenBraceToken */: return ts.isJsxExpression(parent) && !ts.isJsxElement(parent.parent) && !ts.isJsxFragment(parent.parent) ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: @@ -130100,6 +131374,7 @@ var ts; symbolToSortTextIdMap: symbolToSortTextIdMap, isTypeOnlyLocation: isTypeOnlyLocation, isJsxIdentifierExpected: isJsxIdentifierExpected, + isRightOfOpenTag: isRightOfOpenTag, importCompletionNode: importCompletionNode, hasUnresolvedAutoImports: hasUnresolvedAutoImports, }; @@ -130178,9 +131453,7 @@ var ts; // GH#39946. Pulling on the type of a node inside of a function with a contextual `this` parameter can result in a circularity // if the `node` is part of the exprssion of a `yield` or `return`. This circularity doesn't exist at compile time because // we will check (and cache) the type of `this` *before* checking the type of the node. - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - if (!ts.isSourceFile(container) && container.parent) - typeChecker.getTypeAtLocation(container); + typeChecker.tryGetThisTypeAt(node, /*includeGlobalThis*/ false); var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -130391,21 +131664,29 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); var symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var typeOnlyAliasNeedsPromotion = previousToken && !ts.isValidTypeOnlyAliasUseSite(previousToken); symbols = ts.concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextIdMap[ts.getSymbolId(symbol)] = 15 /* GlobalsOrKeywords */; } + if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */)) { + var typeOnlyAliasDeclaration = symbol.declarations && ts.find(symbol.declarations, ts.isTypeOnlyImportOrExportDeclaration); + if (typeOnlyAliasDeclaration) { + var origin = { kind: 64 /* TypeOnlyAlias */, declaration: typeOnlyAliasDeclaration }; + symbolToOriginInfoMap[i] = origin; + } + } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 303 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { - for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { - var symbol = _b[_a]; + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextIdMap[ts.getSymbolId(symbol)] = 14 /* SuggestedClassMembers */; @@ -130508,39 +131789,47 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { + exportInfo.search(sourceFile.path, + /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) - return; + return false; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) + return false; + if (!isTypeOnlyLocation && !importCompletionNode && !(targetFlags & 111551 /* Value */)) + return false; + if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */))) + return false; + // Do not try to auto-import something with a lowercase first letter for a JSX tag + var firstChar = symbolName.charCodeAt(0); + if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */)) + return false; + if (detailsEntryId) + return true; + return charactersFuzzyMatchInString(symbolName, lowerCaseTokenText); + }, function (info, symbolName, isFromAmbientModule, exportMapKey) { + if (detailsEntryId && !ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); })) { return; - // `targetFlags` should be the same for each `info` - if (!isTypeOnlyLocation && !importCompletionNode && !(info[0].targetFlags & 111551 /* Value */)) - return; - if (isTypeOnlyLocation && !(info[0].targetFlags & (1536 /* Module */ | 788968 /* Type */))) + } + var defaultExportInfo = ts.find(info, isImportableExportInfo); + if (!defaultExportInfo) { return; - var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); - if (isCompletionDetailsMatch || !detailsEntryId && charactersFuzzyMatchInString(symbolName, lowerCaseTokenText)) { - var defaultExportInfo = ts.find(info, isImportableExportInfo); - if (!defaultExportInfo) { - return; - } - // If we don't need to resolve module specifiers, we can use any re-export that is importable at all - // (We need to ensure that at least one is importable to show a completion.) - var _a = context.tryResolve(info, isFromAmbientModule) || {}, _b = _a.exportInfo, exportInfo_1 = _b === void 0 ? defaultExportInfo : _b, moduleSpecifier = _a.moduleSpecifier; - var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; - var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; - pushAutoImportSymbol(symbol, { - kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSpecifier: moduleSpecifier, - symbolName: symbolName, - exportMapKey: exportMapKey, - exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, - fileName: exportInfo_1.moduleFileName, - isDefaultExport: isDefaultExport, - moduleSymbol: exportInfo_1.moduleSymbol, - isFromPackageJson: exportInfo_1.isFromPackageJson, - }); } + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = context.tryResolve(info, isFromAmbientModule) || {}, _b = _a.exportInfo, exportInfo = _b === void 0 ? defaultExportInfo : _b, moduleSpecifier = _a.moduleSpecifier; + var isDefaultExport = exportInfo.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo.symbol) || exportInfo.symbol; + pushAutoImportSymbol(symbol, { + kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportMapKey: exportMapKey, + exportName: exportInfo.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo.symbol.name, + fileName: exportInfo.moduleFileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo.moduleSymbol, + isFromPackageJson: exportInfo.isFromPackageJson, + }); }); hasUnresolvedAutoImports = context.resolutionLimitExceeded(); }); @@ -130594,16 +131883,19 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { + // /**/ /> + // /**/ > + // - contextToken: GreaterThanToken (before cursor) + // - location: JsxSelfClosingElement or JsxOpeningElement + // - contextToken.parent === location + if (location === contextToken.parent && (location.kind === 279 /* JsxOpeningElement */ || location.kind === 278 /* JsxSelfClosingElement */)) { + return false; + } if (contextToken.parent.kind === 279 /* JsxOpeningElement */) { - // Two possibilities: - // 1.
/**/ - // - contextToken: GreaterThanToken (before cursor) - // - location: JSXElement - // - different parents (JSXOpeningElement, JSXElement) - // 2. /**/> - // - contextToken: GreaterThanToken (before cursor) - // - location: GreaterThanToken (after cursor) - // - same parent (JSXOpeningElement) + //
/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) return location.parent.kind !== 279 /* JsxOpeningElement */; } if (contextToken.parent.kind === 280 /* JsxClosingElement */ || contextToken.parent.kind === 278 /* JsxSelfClosingElement */) { @@ -131510,10 +132802,40 @@ var ts; function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } + function getContextualKeywords(contextToken, position) { + var entries = []; + /** + * An `AssertClause` can come after an import declaration: + * import * from "foo" | + * import "foo" | + * or after a re-export declaration that has a module specifier: + * export { foo } from "foo" | + * Source: https://tc39.es/proposal-import-assertions/ + */ + if (contextToken) { + var file = contextToken.getSourceFile(); + var parent = contextToken.parent; + var tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line; + var currentLine = file.getLineAndCharacterOfPosition(position).line; + if ((ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent) && parent.moduleSpecifier) + && contextToken === parent.moduleSpecifier + && tokenLine === currentLine) { + entries.push({ + name: ts.tokenToString(129 /* AssertKeyword */), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); + } + } + return entries; + } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { - var jsdoc = ts.findAncestor(node, ts.isJSDoc); - return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + return ts.findAncestor(node, function (n) { + return ts.isJSDocTag(n) && ts.rangeContainsPosition(n, position) ? true : + ts.isJSDoc(n) ? "quit" : false; + }); } function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { var hasCompletionsType = completionsType && completionsType !== contextualType; @@ -131529,6 +132851,8 @@ var ts; // function f(x: T) {} // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself function hasDeclarationOtherThanSelf(member) { + if (!ts.length(member.declarations)) + return true; return ts.some(member.declarations, function (decl) { return decl.parent !== obj; }); } } @@ -131800,10 +133124,14 @@ var ts; /** True if symbol is a type or a module containing at least one type. */ function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); - return !!(sym.flags & 788968 /* Type */) || checker.isUnknownSymbol(sym) || - !!(sym.flags & 1536 /* Module */) && ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + // Since an alias can be merged with a local declaration, we need to test both the alias and its target. + // This code used to just test the result of `skipAlias`, but that would ignore any locally introduced meanings. + return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + function nonAliasCanBeReferencedAtTypeLocation(symbol) { + return !!(symbol.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol) || + !!(symbol.flags & 1536 /* Module */) && ts.addToSeen(seenModules, ts.getSymbolId(symbol)) && + checker.getExportsOfModule(symbol).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } } function isDeprecated(symbol, checker) { var declarations = ts.skipAlias(symbol, checker).declarations; @@ -132360,13 +133688,30 @@ var ts; } function getDocumentRegistryEntry(bucketEntry, scriptKind) { var entry = isDocumentRegistryEntry(bucketEntry) ? bucketEntry : bucketEntry.get(ts.Debug.checkDefined(scriptKind, "If there are more than one scriptKind's for same document the scriptKind should be provided")); - ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:" + scriptKind + " and sourceFile.scriptKind: " + (entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind) + ", !entry: " + !entry); + ts.Debug.assert(scriptKind === undefined || !entry || entry.sourceFile.scriptKind === scriptKind, "Script kind should match provided ScriptKind:".concat(scriptKind, " and sourceFile.scriptKind: ").concat(entry === null || entry === void 0 ? void 0 : entry.sourceFile.scriptKind, ", !entry: ").concat(!entry)); return entry; } function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : ts.getEmitScriptTarget(compilationSettings); + var oldBucketCount = buckets.size; var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + if (ts.tracing) { + if (buckets.size > oldBucketCount) { + // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - + // perhaps they are for two projects that don't have any overlap. + // Bonus: these events can help us interpret the more interesting event below. + ts.tracing.instant("session" /* Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + } + // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. + // If this occurs unexpectedly, the fix is likely to synchronize the project settings. + // Skip .d.ts files to reduce noise (should also cover most of node_modules). + var otherBucketKey = !ts.fileExtensionIs(path, ".d.ts" /* Dts */) && + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + if (otherBucketKey) { + ts.tracing.instant("session" /* Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + } + } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { @@ -133031,7 +134376,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 202 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); default: return false; } @@ -133372,7 +134717,7 @@ var ts; sourceFile: def.file, name: def.reference.fileName, kind: "string" /* string */, - displayParts: [ts.displayPart("\"" + def.reference.fileName + "\"", ts.SymbolDisplayPartKind.stringLiteral)] + displayParts: [ts.displayPart("\"".concat(def.reference.fileName, "\""), ts.SymbolDisplayPartKind.stringLiteral)] }; } default: @@ -133512,7 +134857,7 @@ var ts; function getTextSpan(node, sourceFile, endNode) { var start = node.getStart(sourceFile); var end = (endNode || node).getEnd(); - if (ts.isStringLiteralLike(node)) { + if (ts.isStringLiteralLike(node) && (end - start) > 2) { ts.Debug.assert(endNode === undefined); start += 1; end -= 1; @@ -133952,7 +135297,7 @@ var ts; if (symbol.flags & 33554432 /* Transient */) return undefined; // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.fail("Unexpected symbol at " + ts.Debug.formatSyntaxKind(node.kind) + ": " + ts.Debug.formatSymbol(symbol)); + ts.Debug.fail("Unexpected symbol at ".concat(ts.Debug.formatSyntaxKind(node.kind), ": ").concat(ts.Debug.formatSymbol(symbol))); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) @@ -134057,8 +135402,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var sym = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var sym = symbols_1[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -134245,7 +135590,7 @@ var ts; var token = _a[_i]; if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; - var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + var referenceSymbol = checker.getSymbolAtLocation(token); if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { @@ -134431,7 +135776,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 202 /* BindingElement */ - && ts.isRequireVariableDeclaration(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -134875,7 +136220,8 @@ var ts; } } else { - return nodeEntry(ref, 2 /* StringLiteral */); + return ts.isNoSubstitutionTemplateLiteral(ref) && !ts.rangeIsOnSingleLine(ref, sourceFile) ? undefined : + nodeEntry(ref, 2 /* StringLiteral */); } } }); @@ -135236,8 +136582,8 @@ var ts; var end = pos + 6; /* "static".length */ var typeChecker = program.getTypeChecker(); var symbol = typeChecker.getSymbolAtLocation(node.parent); - var prefix = symbol ? typeChecker.symbolToString(symbol, node.parent) + " " : ""; - return { text: prefix + "static {}", pos: pos, end: end }; + var prefix = symbol ? "".concat(typeChecker.symbolToString(symbol, node.parent), " ") : ""; + return { text: "".concat(prefix, "static {}"), pos: pos, end: end }; } var declName = isConstNamedExpression(node) ? node.parent.name : ts.Debug.checkDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); @@ -135779,7 +137125,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), getCanonicalFileName(newImportFromPath), toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath), toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text) : undefined; }); }; @@ -136031,7 +137377,7 @@ var ts; return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size()) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTouchingToken(sourceFile, position); if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, ts.getModeForUsageLocation(sourceFile, node))) { var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text, ts.getModeForUsageLocation(sourceFile, node))) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); @@ -136056,14 +137402,17 @@ var ts; if (node === sourceFile) { return undefined; } - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbol(node, typeChecker); if (!symbol) return undefined; var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); // If a function returns 'void' or some other type with no definition, just return the function definition. - return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + var typeDefinitions = fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + return typeDefinitions.length ? typeDefinitions + : !(symbol.flags & 111551 /* Value */) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, ts.skipAlias(symbol, typeChecker), node) + : undefined; } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function definitionFromType(type, checker, node) { @@ -136138,7 +137487,7 @@ var ts; return declaration.parent.kind === 268 /* NamedImports */; case 202 /* BindingElement */: case 253 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); + return ts.isInJSFile(declaration) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(declaration); default: return false; } @@ -136436,7 +137785,27 @@ var ts; case 326 /* JSDocAugmentsTag */: return withNode(tag.class); case 342 /* JSDocTemplateTag */: - return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + var templateTag = tag; + var displayParts_3 = []; + if (templateTag.constraint) { + displayParts_3.push(ts.textPart(templateTag.constraint.getText())); + } + if (ts.length(templateTag.typeParameters)) { + if (ts.length(displayParts_3)) { + displayParts_3.push(ts.spacePart()); + } + var lastTypeParameter_1 = templateTag.typeParameters[templateTag.typeParameters.length - 1]; + ts.forEach(templateTag.typeParameters, function (tp) { + displayParts_3.push(namePart(tp.getText())); + if (lastTypeParameter_1 !== tp) { + displayParts_3.push.apply(displayParts_3, [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]); + } + }); + } + if (comment) { + displayParts_3.push.apply(displayParts_3, __spreadArray([ts.spacePart()], getDisplayPartsFromComment(comment, checker), true)); + } + return displayParts_3; case 341 /* JSDocTypeTag */: return withNode(tag.typeExpression); case 343 /* JSDocTypedefTag */: @@ -136498,7 +137867,7 @@ var ts; function getJSDocTagCompletions() { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { - name: "@" + tagName, + name: "@".concat(tagName), kind: "keyword" /* keyword */, kindModifiers: "", sortText: ts.Completions.SortText.LocationPriority @@ -136630,11 +137999,11 @@ var ts; var name = _a.name, dotDotDotToken = _a.dotDotDotToken; var paramName = name.kind === 79 /* Identifier */ ? name.text : "param" + i; var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; - return indentationStr + " * @param " + type + paramName + newLine; + return "".concat(indentationStr, " * @param ").concat(type).concat(paramName).concat(newLine); }).join(""); } function returnsDocComment(indentationStr, newLine) { - return indentationStr + " * @returns" + newLine; + return "".concat(indentationStr, " * @returns").concat(newLine); } function getCommentOwnerInfo(tokenAtPos, options) { return ts.forEachAncestor(tokenAtPos, function (n) { return getCommentOwnerInfoWorker(n, options); }); @@ -136828,7 +138197,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, // TODO: GH#18217 Just use `container ? ...` + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -137421,6 +138790,9 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { + if (!a.body || !b.body) { + return a.body === b.body; + } return a.body.kind === b.body.kind && (a.body.kind !== 260 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ @@ -137474,7 +138846,7 @@ var ts; } if (name) { var text = ts.isIdentifier(name) ? name.text - : ts.isElementAccessExpression(name) ? "[" + nodeText(name.argumentExpression) + "]" + : ts.isElementAccessExpression(name) ? "[".concat(nodeText(name.argumentExpression), "]") : nodeText(name); if (text.length > 0) { return cleanText(text); @@ -137484,7 +138856,7 @@ var ts; case 303 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + ? "\"".concat(ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))), "\"") : ""; case 270 /* ExportAssignment */: return ts.isExportAssignment(node) && node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; @@ -137680,10 +139052,10 @@ var ts; if (name !== undefined) { name = cleanText(name); if (name.length > maxLength) { - return name + " callback"; + return "".concat(name, " callback"); } var args = cleanText(ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", ")); - return name + "(" + args + ") callback"; + return "".concat(name, "(").concat(args, ") callback"); } } return ""; @@ -137696,7 +139068,7 @@ var ts; else if (ts.isPropertyAccessExpression(expr)) { var left = getCalledExpressionName(expr.expression); var right = expr.name.text; - return left === undefined ? right : left + "." + right; + return left === undefined ? right : "".concat(left, ".").concat(right); } else { return undefined; @@ -137921,7 +139293,7 @@ var ts; newImportSpecifiers.push(ts.factory.createImportSpecifier(/*isTypeOnly*/ false, ts.factory.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + newImportSpecifiers.push.apply(newImportSpecifiers, getNewImportSpecifiers(namedImports)); var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] @@ -138131,6 +139503,21 @@ var ts; return 6; } } + function getNewImportSpecifiers(namedImports) { + return ts.flatMap(namedImports, function (namedImport) { + return ts.map(tryGetNamedBindingElements(namedImport), function (importSpecifier) { + return importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText + ? ts.factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ undefined, importSpecifier.name) + : importSpecifier; + }); + }); + } + function tryGetNamedBindingElements(namedImport) { + var _a; + return ((_a = namedImport.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings) && ts.isNamedImports(namedImport.importClause.namedBindings) + ? namedImport.importClause.namedBindings.elements + : undefined; + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -138173,7 +139560,7 @@ var ts; if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); - if (ts.isDeclaration(n) || ts.isVariableStatement(n) || ts.isReturnStatement(n) || n.kind === 1 /* EndOfFileToken */) { + if (ts.isDeclaration(n) || ts.isVariableStatement(n) || ts.isReturnStatement(n) || ts.isCallOrNewExpression(n) || n.kind === 1 /* EndOfFileToken */) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } if (ts.isFunctionLike(n) && ts.isBinaryExpression(n.parent) && ts.isPropertyAccessExpression(n.parent.left)) { @@ -139844,12 +141231,12 @@ var ts; : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; - function getArgumentOrParameterListInfo(node, sourceFile) { + function getArgumentOrParameterListInfo(node, position, sourceFile) { var info = getArgumentOrParameterListAndIndex(node, sourceFile); if (!info) return undefined; var list = info.list, argumentIndex = info.argumentIndex; - var argumentCount = getArgumentCount(list); + var argumentCount = getArgumentCount(list, /*ignoreTrailingComma*/ ts.isInString(sourceFile, position, node)); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } @@ -139895,7 +141282,7 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - var info = getArgumentOrParameterListInfo(node, sourceFile); + var info = getArgumentOrParameterListInfo(node, position, sourceFile); if (!info) return undefined; var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -139964,8 +141351,8 @@ var ts; function countBinaryExpressionParameters(b) { return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; } - function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { - var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + function tryGetParameterInfo(startingToken, position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker); if (!info) return undefined; var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -139977,7 +141364,7 @@ var ts; var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(nonNullableContextualType.symbol) }; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + function getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker) { if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; @@ -139986,7 +141373,7 @@ var ts; case 168 /* MethodDeclaration */: case 212 /* FunctionExpression */: case 213 /* ArrowFunction */: - var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + var info = getArgumentOrParameterListInfo(startingToken, position, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -140033,7 +141420,7 @@ var ts; } return argumentIndex; } - function getArgumentCount(argumentsList) { + function getArgumentCount(argumentsList, ignoreTrailingComma) { // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there @@ -140047,7 +141434,7 @@ var ts; // arg count of 3. var listChildren = argumentsList.getChildren(); var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + if (!ignoreTrailingComma && listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -140128,7 +141515,7 @@ var ts; var _loop_9 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.formatSyntaxKind(n.kind) + ", parent: " + ts.Debug.formatSyntaxKind(n.parent.kind); }); + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: ".concat(ts.Debug.formatSyntaxKind(n.kind), ", parent: ").concat(ts.Debug.formatSyntaxKind(n.parent.kind)); }); var argumentInfo = getImmediatelyContainingArgumentOrContextualParameterInfo(n, position, sourceFile, checker); if (argumentInfo) { return { value: argumentInfo }; @@ -140300,7 +141687,7 @@ var ts; (function (InlayHints) { var maxHintsLength = 30; var leadingParameterNameCommentRegexFactory = function (name) { - return new RegExp("^\\s?/\\*\\*?\\s?" + name + "\\s?\\*\\/\\s?$"); + return new RegExp("^\\s?/\\*\\*?\\s?".concat(name, "\\s?\\*\\/\\s?$")); }; function shouldShowParameterNameHints(preferences) { return preferences.includeInlayParameterNameHints === "literals" || preferences.includeInlayParameterNameHints === "all"; @@ -140364,7 +141751,7 @@ var ts; } function addParameterHints(text, position, isFirstVariadicArgument) { result.push({ - text: "" + (isFirstVariadicArgument ? "..." : "") + truncation(text, maxHintsLength) + ":", + text: "".concat(isFirstVariadicArgument ? "..." : "").concat(truncation(text, maxHintsLength), ":"), position: position, kind: "Parameter" /* Parameter */, whitespaceAfter: true, @@ -140372,7 +141759,7 @@ var ts; } function addTypeHints(text, position) { result.push({ - text: ": " + truncation(text, maxHintsLength), + text: ": ".concat(truncation(text, maxHintsLength)), position: position, kind: "Type" /* Type */, whitespaceBefore: true, @@ -140380,7 +141767,7 @@ var ts; } function addEnumMemberValueHints(text, position) { result.push({ - text: "= " + truncation(text, maxHintsLength), + text: "= ".concat(truncation(text, maxHintsLength)), position: position, kind: "Enum" /* Enum */, whitespaceBefore: true, @@ -140915,7 +142302,7 @@ var ts; } } function getKeyFromNode(exp) { - return exp.pos.toString() + ":" + exp.end.toString(); + return "".concat(exp.pos.toString(), ":").concat(exp.end.toString()); } function canBeConvertedToClass(node, checker) { var _a, _b, _c, _d; @@ -140993,7 +142380,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 108 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 108 /* ThisKeyword */ && ts.isExpression(location) || ts.isThisInTypeQuery(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -141011,6 +142398,8 @@ var ts; } if (flags & 16 /* Function */) return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + // FIXME: getter and setter use the same symbol. And it is rare to use only setter without getter, so in most cases the symbol always has getter flag. + // So, even when the location is just on the declaration of setter, this function returns getter. if (flags & 32768 /* GetAccessor */) return "getter" /* memberGetAccessorElement */; if (flags & 65536 /* SetAccessor */) @@ -141039,18 +142428,7 @@ var ts; } return unionPropertyKind; } - // If we requested completions after `x.` at the top-level, we may be at a source file location. - switch (location.parent && location.parent.kind) { - // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 279 /* JsxOpeningElement */: - case 277 /* JsxElement */: - case 278 /* JsxSelfClosingElement */: - return location.kind === 79 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 284 /* JsxAttribute */: - return "JSX attribute" /* jsxAttribute */; - default: - return "property" /* memberVariableElement */; - } + return "property" /* memberVariableElement */; } return "" /* unknown */; } @@ -141097,7 +142475,7 @@ var ts; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 108 /* ThisKeyword */ && ts.isInExpressionContext(location); + var isThisExpression = location.kind === 108 /* ThisKeyword */ && ts.isInExpressionContext(location) || ts.isThisInTypeQuery(location); var type; var printer; var documentationFromAlias; @@ -141108,9 +142486,24 @@ var ts; } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { - // If it is accessor they are allowed only if location is at name of the accessor + // If symbol is accessor, they are allowed only if location is at declaration identifier of the accessor if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { - symbolKind = "property" /* memberVariableElement */; + var declaration = ts.find(symbol.declarations, function (declaration) { return declaration.name === location; }); + if (declaration) { + switch (declaration.kind) { + case 171 /* GetAccessor */: + symbolKind = "getter" /* memberGetAccessorElement */; + break; + case 172 /* SetAccessor */: + symbolKind = "setter" /* memberSetAccessorElement */; + break; + default: + ts.Debug.assertNever(declaration); + } + } + else { + symbolKind = "property" /* memberVariableElement */; + } } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); @@ -141263,7 +142656,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(63 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, ts.isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -141424,6 +142817,8 @@ var ts; } // For properties, variables and local vars: show the type if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "getter" /* memberGetAccessorElement */ || + symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || @@ -141493,8 +142888,20 @@ var ts; } } } + if (documentation.length === 0 && ts.isIdentifier(location) && symbol.valueDeclaration && ts.isBindingElement(symbol.valueDeclaration)) { + var declaration = symbol.valueDeclaration; + var parent = declaration.parent; + if (ts.isIdentifier(declaration.name) && ts.isObjectBindingPattern(parent)) { + var name_4 = ts.getTextOfIdentifierOrLiteral(declaration.name); + var objectType = typeChecker.getTypeAtLocation(parent); + documentation = ts.firstDefined(objectType.isUnion() ? objectType.types : [objectType], function (t) { + var prop = t.getProperty(name_4); + return prop ? prop.getDocumentationComment(typeChecker) : undefined; + }) || ts.emptyArray; + } + } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(typeChecker); + tags = symbol.getContextualJsDocTags(enclosingDeclaration, typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -141857,6 +143264,7 @@ var ts; lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, skipToStartOf: skipToStartOf, + getStartPos: function () { var _a; return (_a = lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.pos) !== null && _a !== void 0 ? _a : scanner.getTokenPos(); }, }); lastTokenInfo = undefined; scanner.setText(undefined); @@ -142030,8 +143438,7 @@ var ts; } function isOnToken() { var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); - var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); - return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + return current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); } function isOnEOF() { var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); @@ -143219,7 +144626,7 @@ var ts; return 0; } function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { - var range = { pos: 0, end: sourceFileLike.text.length }; + var range = { pos: node.pos, end: node.end }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); }); } @@ -143270,6 +144677,15 @@ var ts; } } } + if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + var token = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : + formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : + undefined; + if (token) { + processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, enclosingNode, previousRange, previousRangeStartLine, previousParent, enclosingNode, + /*dynamicIndentation*/ undefined); + } + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -143452,19 +144868,13 @@ var ts; processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); // proceed any tokens in the node that are located after child nodes - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(node); - if (tokenInfo.token.end > node.end) { + if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) { break; } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } - if (!node.parent && formattingScanner.isOnEOF()) { - var token = formattingScanner.readEOFTokenRange(); - if (token.end <= node.end && previousRange) { - processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, node, previousRange, previousRangeStartLine, previousParent, contextNode, nodeDynamicIndentation); - } - } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; @@ -143490,9 +144900,12 @@ var ts; if (child.getFullWidth() === 0) { return inheritedIndentation; } - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > originalRange.end) { + return inheritedIndentation; + } if (tokenInfo.token.end > childStartPos) { if (tokenInfo.token.pos > childStartPos) { formattingScanner.skipToStartOf(child); @@ -143502,7 +144915,7 @@ var ts; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); } - if (!formattingScanner.isOnToken()) { + if (!formattingScanner.isOnToken() || formattingScanner.getStartPos() >= originalRange.end) { return inheritedIndentation; } if (ts.isToken(child)) { @@ -143531,7 +144944,7 @@ var ts; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { // introduce a new indentation scope for lists (including list start and end tokens) - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list @@ -143567,7 +144980,7 @@ var ts; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } var listEndToken = getCloseTokenForOpenToken(listStartToken); - if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; @@ -143698,24 +145111,26 @@ var ts; // win in a conflict with lower priority rules. ts.forEachRight(rules, function (rule) { lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - switch (lineAction) { - case 2 /* LineRemoved */: - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode); - } - break; - case 1 /* LineAdded */: - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode); - } - break; - default: - ts.Debug.assert(lineAction === 0 /* None */); + if (dynamicIndentation) { + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -144432,6 +145847,8 @@ var ts; case 179 /* ConstructorType */: case 174 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); + case 171 /* GetAccessor */: + return getList(node.parameters); case 256 /* ClassDeclaration */: case 225 /* ClassExpression */: case 257 /* InterfaceDeclaration */: @@ -144906,6 +146323,7 @@ var ts; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; + /** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); @@ -145033,7 +146451,7 @@ var ts; var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); var indent = sourceFile.text.slice(lineStartPosition, startPosition); - var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + var text = "".concat(insertAtLineStart ? "" : this.newLineCharacter, "//").concat(commentText).concat(this.newLineCharacter).concat(indent); this.insertText(sourceFile, token.getStart(sourceFile), text); }; ChangeTracker.prototype.insertJsdocCommentBefore = function (sourceFile, node, tag) { @@ -145051,6 +146469,30 @@ var ts; var indent = sourceFile.text.slice(startPosition, fnStart); this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); }; + ChangeTracker.prototype.createJSDocText = function (sourceFile, node) { + var comments = ts.flatMap(node.jsDoc, function (jsDoc) { + return ts.isString(jsDoc.comment) ? ts.factory.createJSDocText(jsDoc.comment) : jsDoc.comment; + }); + var jsDoc = ts.singleOrUndefined(node.jsDoc); + return jsDoc && ts.positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && ts.length(comments) === 0 ? undefined : + ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))); + }; + ChangeTracker.prototype.replaceJSDocComment = function (sourceFile, node, tags) { + this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), ts.factory.createJSDocComment(this.createJSDocText(sourceFile, node), ts.factory.createNodeArray(tags))); + }; + ChangeTracker.prototype.addJSDocTags = function (sourceFile, parent, newTags) { + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + this.replaceJSDocComment(sourceFile, parent, __spreadArray(__spreadArray([], oldTags, true), unmergedNewTags, true)); + }; + ChangeTracker.prototype.filterJSDocTags = function (sourceFile, parent, predicate) { + this.replaceJSDocComment(sourceFile, parent, ts.filter(ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }), predicate)); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; @@ -145233,7 +146675,7 @@ var ts; }; ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { var options = this.getInsertNodeAfterOptionsWorker(after); - return __assign(__assign({}, options), { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + return __assign(__assign({}, options), { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n".concat(options.prefix) : "\n") : options.prefix }); }; ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { switch (node.kind) { @@ -145267,7 +146709,7 @@ var ts; } else { // `x => {}` -> `function f(x) {}` - this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function ".concat(name, "(")); // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` this.replaceRange(sourceFile, arrow, ts.factory.createToken(21 /* CloseParenToken */)); } @@ -145285,6 +146727,15 @@ var ts; ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { this.insertText(sourceFile, node.getStart(sourceFile), "export "); }; + ChangeTracker.prototype.insertImportSpecifierAtIndex = function (sourceFile, importSpecifier, namedImports, index) { + var prevSpecifier = namedImports.elements[index - 1]; + if (prevSpecifier) { + this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier); + } + else { + this.insertNodeBefore(sourceFile, namedImports.elements[0], importSpecifier, !ts.positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)); + } + }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. @@ -145324,7 +146775,7 @@ var ts; var nextNode = containingList[index + 1]; var startPos = skipWhitespacesAndLineBreaks(sourceFile.text, nextNode.getFullStart()); // write separator and leading trivia of the next element as suffix - var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, startPos); + var suffix = "".concat(ts.tokenToString(nextToken.kind)).concat(sourceFile.text.substring(nextToken.end, startPos)); this.insertNodesAt(sourceFile, startPos, [newNode], { suffix: suffix }); } } @@ -145369,7 +146820,7 @@ var ts; this.replaceRange(sourceFile, ts.createRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); + this.replaceRange(sourceFile, ts.createRange(end), newNode, { prefix: "".concat(ts.tokenToString(separator), " ") }); } } }; @@ -145445,6 +146896,35 @@ var ts; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + function updateJSDocHost(parent) { + if (parent.kind !== 213 /* ArrowFunction */) { + return parent; + } + var jsDocNode = parent.parent.kind === 166 /* PropertyDeclaration */ ? + parent.parent : + parent.parent.parent; + jsDocNode.jsDoc = parent.jsDoc; + jsDocNode.jsDocCache = parent.jsDocCache; + return jsDocNode; + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 338 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) + : undefined; + } + case 339 /* JSDocReturnTag */: + return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + case 341 /* JSDocTypeTag */: + return ts.factory.createJSDocTypeTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + } + } // find first non-whitespace position in the leading trivia of the node function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -145471,7 +146951,7 @@ var ts; var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); var _loop_12 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { - return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); + return "".concat(JSON.stringify(normalized[i].range), " and ").concat(JSON.stringify(normalized[i + 1].range)); }); }; // verify that change intervals do not overlap, except possibly at end points. @@ -145523,19 +147003,13 @@ var ts; + ((!options.suffix || ts.endsWith(noIndent, options.suffix)) ? "" : options.suffix); } - function getFormatCodeSettingsForWriting(_a, sourceFile) { - var options = _a.options; - var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore; - var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !ts.probablyUsesSemicolons(sourceFile); - return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore }); - } /** Note: this may mutate `nodeIn`. */ function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; if (validate) validate(node, text); - var formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); + var formatOptions = ts.getFormatCodeSettingsForWriting(formatContext, sourceFile); var initialIndentation = indentation !== undefined ? indentation : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); @@ -145568,7 +147042,7 @@ var ts; function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { var _a = changes[i], span = _a.span, newText = _a.newText; - text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); + text = "".concat(text.substring(0, span.start)).concat(newText).concat(text.substring(ts.textSpanEnd(span))); } return text; } @@ -145583,6 +147057,7 @@ var ts; ts.setTextRangePosEnd(newNode, getPos(node), getEnd(node)); return newNode; } + textChanges_3.assignPositionsToNode = assignPositionsToNode; function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); if (!visited) { @@ -145753,6 +147228,7 @@ var ts; clear: clear }; } + textChanges_3.createWriter = createWriter; function getInsertionPositionAtSourceFileTop(sourceFile) { var lastPrologue; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -146146,21 +147622,32 @@ var ts; var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { + var assertion = getAssertion(context.sourceFile, context.span.start); + if (assertion === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, assertion); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var assertion = getAssertion(diag.file, diag.start); + if (assertion) { + makeChange(changes, diag.file, assertion); + } + }); }, }); - function makeChange(changeTracker, sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos); - var assertion = ts.Debug.checkDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertionExpression(n); }), "Expected to find an assertion expression"); + function makeChange(changeTracker, sourceFile, assertion) { var replacement = ts.isAsExpression(assertion) ? ts.factory.createAsExpression(assertion.expression, ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */)) : ts.factory.createTypeAssertion(ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */), assertion.expression); changeTracker.replaceNode(sourceFile, assertion.expression, replacement); } + function getAssertion(sourceFile, pos) { + if (ts.isInJSFile(sourceFile)) + return undefined; + return ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), function (n) { return ts.isAsExpression(n) || ts.isTypeAssertionExpression(n); }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -146173,7 +147660,7 @@ var ts; ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( @@ -146202,7 +147689,7 @@ var ts; codefix.registerCodeFix({ fixIds: [fixId], errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingAsync(context) { var sourceFile = context.sourceFile, errorCode = context.errorCode, cancellationToken = context.cancellationToken, program = context.program, span = context.span; var diagnostic = ts.find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); var directSpan = diagnostic && diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; }); @@ -146299,7 +147786,7 @@ var ts; codefix.registerCodeFix({ fixIds: [fixId], errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingAwait(context) { var sourceFile = context.sourceFile, errorCode = context.errorCode, span = context.span, cancellationToken = context.cancellationToken, program = context.program; var expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program); if (!expression) { @@ -146531,7 +148018,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingConst(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start, context.program); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_const_to_unresolved_variable, fixId, ts.Diagnostics.Add_const_to_all_unresolved_variables)]; @@ -146631,7 +148118,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Prefix_with_declare, fixId, ts.Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)]; @@ -146665,7 +148152,7 @@ var ts; var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, @@ -146690,7 +148177,7 @@ var ts; var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; }, @@ -148040,7 +149527,7 @@ var ts; if (!res.has(text) && (originalKeywordKind !== undefined && ts.isNonContextualKeyword(originalKeywordKind) || checker.resolveName(text, node, 111551 /* Value */, /*excludeGlobals*/ true))) { // Unconditionally add an underscore in case `text` is a keyword. - res.set(text, makeUniqueName("_" + text, identifiers)); + res.set(text, makeUniqueName("_".concat(text), identifiers)); } }); return res; @@ -148140,7 +149627,7 @@ var ts; // `const a = require("b").c` --> `import { c as a } from "./b"; return convertedImports([makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]); default: - return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid syntax form ".concat(name.kind)); } } function convertAssignment(sourceFile, checker, assignment, changes, exports, useSitesToUnqualify) { @@ -148191,7 +149678,7 @@ var ts; case 168 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.factory.createToken(93 /* ExportKeyword */)], prop, useSitesToUnqualify); default: - ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind " + prop.kind); + ts.Debug.assertNever(prop, "Convert to ES6 got invalid prop kind ".concat(prop.kind)); } }); return statements && [statements, false]; @@ -148302,8 +149789,6 @@ var ts; var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined - // (TODO: GH#18217) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { @@ -148325,7 +149810,7 @@ var ts; case 79 /* Identifier */: return convertSingleIdentifierImport(name, moduleSpecifier, checker, identifiers, quotePreference); default: - return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind " + name.kind); + return ts.Debug.assertNever(name, "Convert to ES module got invalid name kind ".concat(name.kind)); } } /** @@ -148382,7 +149867,7 @@ var ts; // Identifiers helpers function makeUniqueName(name, identifiers) { while (identifiers.original.has(name) || identifiers.additional.has(name)) { - name = "_" + name; + name = "_".concat(name); } identifiers.additional.add(name); return name; @@ -148462,7 +149947,7 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + var newText = "".concat(qualifiedName.left.text, "[\"").concat(qualifiedName.right.text, "\"]"); return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], @@ -148494,14 +149979,14 @@ var ts; var fixId = "convertToTypeOnlyExport"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context); }); if (changes.length) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_export, fixId, ts.Diagnostics.Convert_all_re_exported_types_to_type_only_exports)]; } }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { var fixedExportDeclarations = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile); @@ -148562,7 +150047,7 @@ var ts; var fixId = "convertToTypeOnlyImport"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { var importDeclaration = getImportDeclarationForDiagnosticSpan(context.span, context.sourceFile); fixSingleImportDeclaration(t, importDeclaration, context); @@ -148572,7 +150057,7 @@ var ts; } }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var importDeclaration = getImportDeclarationForDiagnosticSpan(diag, context.sourceFile); fixSingleImportDeclaration(changes, importDeclaration, context); @@ -148611,7 +150096,7 @@ var ts; var errorCodes = [ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { var sourceFile = context.sourceFile, span = context.span; var info = getInfo(sourceFile, span.start); if (!info) { @@ -148753,7 +150238,8 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, - ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code + ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, + ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -148762,9 +150248,10 @@ var ts; var info = getFixesInfo(context, errorCode, span.start, /*useAutoImportProvider*/ true); if (!info) return undefined; - var fixes = info.fixes, symbolName = info.symbolName; + var fixes = info.fixes, symbolName = info.symbolName, errorIdentifierText = info.errorIdentifierText; var quotePreference = ts.getQuotePreference(sourceFile, preferences); - return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference, program.getCompilerOptions()); }); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, + /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, quotePreference, program.getCompilerOptions()); }); }, fixIds: [importFixId], getAllCodeActions: function (context) { @@ -148799,11 +150286,11 @@ var ts; var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions)); var checker = program.getTypeChecker(); var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); - var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, host, program, preferences, useAutoImportProvider); + var exportInfo = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, /*isJsxTagName*/ false, host, program, preferences, useAutoImportProvider); var useRequire = shouldUseRequire(sourceFile, program); - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); + var fix = getImportFixForSymbol(sourceFile, exportInfo, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); if (fix) { - addImport({ fixes: [fix], symbolName: symbolName }); + addImport({ fixes: [fix], symbolName: symbolName, errorIdentifierText: undefined }); } } function addImport(info) { @@ -148858,8 +150345,11 @@ var ts; } break; } + case 4 /* PromoteTypeOnly */: + // Excluding from fix-all + break; default: - ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind); + ts.Debug.assertNever(fix, "fix wasn't never - got kind ".concat(fix.kind)); } function reduceAddAsTypeOnlyValues(prevValue, newValue) { // `NotAllowed` overrides `Required` because one addition of a new import might be required to be type-only @@ -148903,7 +150393,7 @@ var ts; return newEntry; } function newImportsKey(moduleSpecifier, topLevelTypeOnly) { - return (topLevelTypeOnly ? 1 : 0) + "|" + moduleSpecifier; + return "".concat(topLevelTypeOnly ? 1 : 0, "|").concat(moduleSpecifier); } } function writeFixes(changeTracker) { @@ -148949,6 +150439,7 @@ var ts; ImportFixKind[ImportFixKind["JsdocTypeImport"] = 1] = "JsdocTypeImport"; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + ImportFixKind[ImportFixKind["PromoteTypeOnly"] = 4] = "PromoteTypeOnly"; })(ImportFixKind || (ImportFixKind = {})); // These should not be combined as bitflags, but are given powers of 2 values to // easily detect conflicts between `NotAllowed` and `Required` by giving them a unique sum. @@ -148960,23 +150451,33 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, isJsxTagName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, isJsxTagName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); return { moduleSpecifier: fix.moduleSpecifier, - codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences), compilerOptions)) + codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, + /*includeSymbolNameInDescription*/ false, ts.getQuotePreference(sourceFile, preferences), compilerOptions)) }; } codefix.getImportCompletionAction = getImportCompletionAction; + function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions); + var fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program); + var includeSymbolNameInDescription = symbolName !== symbolToken.text; + return fix && codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, includeSymbolNameInDescription, 1 /* Double */, compilerOptions)); + } + codefix.getPromoteTypeOnlyCompletionAction = getPromoteTypeOnlyCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol || info.symbol.parent === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, host, preferences); + var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); + return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, packageJsonImportFilter, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -149002,7 +150503,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, isJsxTagName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -149015,7 +150516,7 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -149031,12 +150532,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences, fromCacheOnly) { + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { var _a = getNewImportFixes(program, importingFile, /*position*/ undefined, /*isValidTypeOnlyUseSite*/ false, /*useRequire*/ false, exportInfo, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, host, preferences); + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); } codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; @@ -149170,7 +150671,7 @@ var ts; var importKind = getImportKind(importingFile, exportKind, compilerOptions); return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent)) { + if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; } if (i.kind === 265 /* ImportDeclaration */ || i.kind === 264 /* ImportEqualsDeclaration */) { @@ -149206,7 +150707,7 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, moduleSymbols, host, preferences, fromCacheOnly) { + function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); @@ -149215,7 +150716,7 @@ var ts; ? function (moduleSymbol) { return ({ moduleSpecifiers: ts.moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }); } : function (moduleSymbol, checker) { return ts.moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); }; var computedWithoutCacheCount = 0; - var fixes = ts.flatMap(moduleSymbols, function (exportInfo) { + var fixes = ts.flatMap(exportInfo, function (exportInfo, i) { var checker = getChecker(exportInfo.isFromPackageJson); var _a = getModuleSpecifiers(exportInfo.moduleSymbol, checker), computedWithoutCache = _a.computedWithoutCache, moduleSpecifiers = _a.moduleSpecifiers; var importedSymbolHasValueMeaning = !!(exportInfo.targetFlags & 111551 /* Value */); @@ -149224,7 +150725,7 @@ var ts; return moduleSpecifiers === null || moduleSpecifiers === void 0 ? void 0 : moduleSpecifiers.map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return !importedSymbolHasValueMeaning && isJs && position !== undefined - ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo, isReExport: i > 0 } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, @@ -149232,6 +150733,7 @@ var ts; useRequire: useRequire, addAsTypeOnly: addAsTypeOnly, exportInfo: exportInfo, + isReExport: i > 0, }; }); }); @@ -149253,37 +150755,69 @@ var ts; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); - var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getFixesInfoForUMDImport(context, symbolToken) - : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host, context.preferences) }); + var info; + if (errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + info = getFixesInfoForUMDImport(context, symbolToken); + } + else if (!ts.isIdentifier(symbolToken)) { + return undefined; + } + else if (errorCode === ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { + var symbolName_1 = getSymbolName(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions()); + var fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName_1, context.program); + return fix && { fixes: [fix], symbolName: symbolName_1, errorIdentifierText: symbolToken.text }; + } + else { + info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); + } + var packageJsonImportFilter = ts.createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, packageJsonImportFilter, context.host) }); } - function sortFixes(fixes, sourceFile, program, host, preferences) { - var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; - return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, allowsImportingSpecifier); }); + function sortFixes(fixes, sourceFile, program, packageJsonImportFilter, host) { + var _toPath = function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath); }); } - function getBestFix(fixes, sourceFile, program, host, preferences) { + function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { if (!ts.some(fixes)) return; // These will always be placed first if available, and are better than other kinds if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { return fixes[0]; } - var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { // Takes true branch of conditional if `fix` is better than `best` - return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + return compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }) === -1 /* LessThan */ ? fix : best; }); } /** @returns `Comparison.LessThan` if `a` is better than `b`. */ - function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { + function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) + || ts.compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath)) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } return 0 /* EqualTo */; } + // This is a simple heuristic to try to avoid creating an import cycle with a barrel re-export. + // E.g., do not `import { Foo } from ".."` when you could `import { Foo } from "../Foo"`. + // This can produce false positives or negatives if re-exports cross into sibling directories + // (e.g. `export * from "../whatever"`) or are not named "index" (we don't even try to consider + // this if we're in a resolution mode where you can't drop trailing "/index" from paths). + function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath) { + var _a; + if (fix.isReExport && + ((_a = fix.exportInfo) === null || _a === void 0 ? void 0 : _a.moduleFileName) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + isIndexFileName(fix.exportInfo.moduleFileName)) { + var reExportDir = toPath(ts.getDirectoryPath(fix.exportInfo.moduleFileName)); + return ts.startsWith((importingFile.path), reExportDir); + } + return false; + } + function isIndexFileName(fileName) { + return ts.getBaseFileName(fileName, [".js", ".jsx", ".d.ts", ".ts", ".tsx"], /*ignoreCase*/ true) === "index"; + } function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { if (ts.startsWith(a, "node:") && !ts.startsWith(b, "node:")) return ts.shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */; @@ -149292,6 +150826,7 @@ var ts; return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { + var _b; var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); var umdSymbol = getUmdSymbol(token, checker); @@ -149299,10 +150834,10 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }]; + var exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences); - return { fixes: fixes, symbolName: symbolName }; + var fixes = getImportFixes(exportInfo, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName, errorIdentifierText: (_b = ts.tryCast(token, ts.isIdentifier)) === null || _b === void 0 ? void 0 : _b.text }; } function getUmdSymbol(token, checker) { // try the identifier to see if it is the umd symbol @@ -149356,7 +150891,7 @@ var ts; case ts.ModuleKind.NodeNext: return importingFile.impliedNodeFormat === ts.ModuleKind.ESNext ? 2 /* Namespace */ : 3 /* CommonJS */; default: - return ts.Debug.assertNever(moduleKind, "Unexpected moduleKind " + moduleKind); + return ts.Debug.assertNever(moduleKind, "Unexpected moduleKind ".concat(moduleKind)); } } function getFixesInfoForNonUMDImport(_a, symbolToken, useAutoImportProvider) { @@ -149368,12 +150903,22 @@ var ts; ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); - var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); - var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { + var exportInfo = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); + var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfo.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences); })); - return { fixes: fixes, symbolName: symbolName }; + return { fixes: fixes, symbolName: symbolName, errorIdentifierText: symbolToken.text }; + } + function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program) { + var checker = program.getTypeChecker(); + var symbol = checker.resolveName(symbolName, symbolToken, 111551 /* Value */, /*excludeGlobals*/ true); + if (!symbol) + return undefined; + var typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); + if (!typeOnlyAliasDeclaration || ts.getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) + return undefined; + return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration: typeOnlyAliasDeclaration }; } function jsxModeNeedsExplicitImport(jsx) { return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; @@ -149382,14 +150927,20 @@ var ts; var parent = symbolToken.parent; if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); - if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { + if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { return jsxNamespace; } } return symbolToken.text; } + function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { + if (ts.isIntrinsicJsxName(symbolToken.text)) + return true; // If we were triggered by a matching error code on an intrinsic, the error must have been about missing the JSX factory + var namespaceSymbol = checker.resolveName(jsxNamespace, symbolToken, 111551 /* Value */, /*excludeGlobals*/ true); + return !namespaceSymbol || ts.some(namespaceSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */); + } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { + function getExportInfos(symbolName, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). @@ -149412,7 +150963,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name @@ -149452,18 +151003,18 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference, compilerOptions) { + function codeActionForFix(context, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions) { var diag; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { - diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference, compilerOptions); + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions); }); return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } - function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference, compilerOptions) { + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions) { switch (fix.kind) { case 0 /* UseNamespace */: addNamespaceQualifier(changes, sourceFile, fix); - return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + return [ts.Diagnostics.Change_0_to_1, symbolName, "".concat(fix.namespacePrefix, ".").concat(symbolName)]; case 1 /* JsdocTypeImport */: addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; @@ -149471,11 +151022,9 @@ var ts; var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, addAsTypeOnly = fix.addAsTypeOnly, moduleSpecifier = fix.moduleSpecifier; doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? { name: symbolName, addAsTypeOnly: addAsTypeOnly } : undefined, importKind === 0 /* Named */ ? [{ name: symbolName, addAsTypeOnly: addAsTypeOnly }] : ts.emptyArray, compilerOptions); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - return [ - importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, - symbolName, - moduleSpecifierWithoutQuotes - ]; // you too! + return includeSymbolNameInDescription + ? [ts.Diagnostics.Import_0_from_1, symbolName, moduleSpecifierWithoutQuotes] + : [ts.Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes]; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, addAsTypeOnly = fix.addAsTypeOnly, useRequire = fix.useRequire; @@ -149484,10 +151033,82 @@ var ts; var namedImports = importKind === 0 /* Named */ ? [{ name: symbolName, addAsTypeOnly: addAsTypeOnly }] : undefined; var namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { importKind: importKind, name: symbolName, addAsTypeOnly: addAsTypeOnly } : undefined; ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport), /*blankLineBetween*/ true); - return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + return includeSymbolNameInDescription + ? [ts.Diagnostics.Import_0_from_1, symbolName, moduleSpecifier] + : [ts.Diagnostics.Add_import_from_0, moduleSpecifier]; + } + case 4 /* PromoteTypeOnly */: { + var typeOnlyAliasDeclaration = fix.typeOnlyAliasDeclaration; + var promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile); + return promotedDeclaration.kind === 269 /* ImportSpecifier */ + ? [ts.Diagnostics.Remove_type_from_import_of_0_from_1, symbolName, getModuleSpecifierText(promotedDeclaration.parent.parent)] + : [ts.Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; } default: - return ts.Debug.assertNever(fix, "Unexpected fix kind " + fix.kind); + return ts.Debug.assertNever(fix, "Unexpected fix kind ".concat(fix.kind)); + } + } + function getModuleSpecifierText(promotedDeclaration) { + var _a, _b; + return promotedDeclaration.kind === 264 /* ImportEqualsDeclaration */ + ? ((_b = ts.tryCast((_a = ts.tryCast(promotedDeclaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression, ts.isStringLiteralLike)) === null || _b === void 0 ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() + : ts.cast(promotedDeclaration.parent.moduleSpecifier, ts.isStringLiteral).text; + } + function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile) { + // See comment in `doAddExistingFix` on constant with the same name. + var convertExistingToTypeOnly = compilerOptions.preserveValueImports && compilerOptions.isolatedModules; + switch (aliasDeclaration.kind) { + case 269 /* ImportSpecifier */: + if (aliasDeclaration.isTypeOnly) { + if (aliasDeclaration.parent.elements.length > 1 && ts.OrganizeImports.importSpecifiersAreSorted(aliasDeclaration.parent.elements)) { + changes.delete(sourceFile, aliasDeclaration); + var newSpecifier = ts.factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name); + var insertionIndex = ts.OrganizeImports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier); + changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); + } + else { + changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); + } + return aliasDeclaration; + } + else { + ts.Debug.assert(aliasDeclaration.parent.parent.isTypeOnly); + promoteImportClause(aliasDeclaration.parent.parent); + return aliasDeclaration.parent.parent; + } + case 266 /* ImportClause */: + promoteImportClause(aliasDeclaration); + return aliasDeclaration; + case 267 /* NamespaceImport */: + promoteImportClause(aliasDeclaration.parent); + return aliasDeclaration.parent; + case 264 /* ImportEqualsDeclaration */: + changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1)); + return aliasDeclaration; + default: + ts.Debug.failBadSyntaxKind(aliasDeclaration); + } + function promoteImportClause(importClause) { + changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (convertExistingToTypeOnly) { + var namedImports = ts.tryCast(importClause.namedBindings, ts.isNamedImports); + if (namedImports && namedImports.elements.length > 1) { + if (ts.OrganizeImports.importSpecifiersAreSorted(namedImports.elements) && + aliasDeclaration.kind === 269 /* ImportSpecifier */ && + namedImports.elements.indexOf(aliasDeclaration) !== 0) { + // The import specifier being promoted will be the only non-type-only, + // import in the NamedImports, so it should be moved to the front. + changes.delete(sourceFile, aliasDeclaration); + changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0); + } + for (var _i = 0, _a = namedImports.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element !== aliasDeclaration && !element.isTypeOnly) { + changes.insertModifierBefore(sourceFile, 151 /* TypeKeyword */, element); + } + } + } + } } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, compilerOptions) { @@ -149527,13 +151148,7 @@ var ts; var insertionIndex = convertExistingToTypeOnly && !spec.isTypeOnly ? 0 : ts.OrganizeImports.getImportSpecifierInsertionIndex(existingSpecifiers, spec); - var prevSpecifier = clause.namedBindings.elements[insertionIndex - 1]; - if (prevSpecifier) { - changes.insertNodeInListAfter(sourceFile, prevSpecifier, spec); - } - else { - changes.insertNodeBefore(sourceFile, existingSpecifiers[0], spec, !ts.positionsAreOnSameLine(existingSpecifiers[0].getStart(), clause.parent.getStart(), sourceFile)); - } + changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex); } } else if (existingSpecifiers === null || existingSpecifiers === void 0 ? void 0 : existingSpecifiers.length) { @@ -149583,7 +151198,7 @@ var ts; } function getImportTypePrefix(moduleSpecifier, quotePreference) { var quote = ts.getQuoteFromPreference(quotePreference); - return "import(" + quote + moduleSpecifier + quote + ")."; + return "import(".concat(quote).concat(moduleSpecifier).concat(quote, ")."); } function needsTypeOnly(_a) { var addAsTypeOnly = _a.addAsTypeOnly; @@ -149648,17 +151263,20 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target, forceCapitalize); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; - function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; var firstCharCode = baseName.charCodeAt(0); if (ts.isIdentifierStart(firstCharCode, target)) { res += String.fromCharCode(firstCharCode); + if (forceCapitalize) { + res = res.toUpperCase(); + } } else { lastCharWasValid = false; @@ -149676,7 +151294,7 @@ var ts; lastCharWasValid = isValid; } // Need `|| "_"` to ensure result isn't empty. - return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_".concat(res); } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; })(codefix = ts.codefix || (ts.codefix = {})); @@ -149695,35 +151313,72 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, - ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, + ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code, ]; var errorCodeFixIdMap = (_a = {}, - _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, - ], - _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ - ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], - _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, - ], - _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], - _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ - ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], + // case #1: + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + _a[ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers + }, + // case #2: + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + _a[ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_override_modifier + }, + // case #3: + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + _a[ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + // case #4: + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + // case #5: + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + _a[ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, _a); codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { + var errorCode = context.errorCode, span = context.span; var info = errorCodeFixIdMap[errorCode]; if (!info) return ts.emptyArray; - var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; - if (ts.isSourceFileJS(sourceFile)) - return ts.emptyArray; + var descriptions = info.descriptions, fixId = info.fixId, fixAllDescriptions = info.fixAllDescriptions; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); return [ codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) @@ -149732,9 +151387,9 @@ var ts; fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var code = diag.code, start = diag.start, file = diag.file; + var code = diag.code, start = diag.start; var info = errorCodeFixIdMap[code]; - if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + if (!info || info.fixId !== context.fixId) { return; } dispatchChanges(changes, context, code, start); @@ -149744,11 +151399,15 @@ var ts; function dispatchChanges(changeTracker, context, errorCode, pos) { switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + case ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code: return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); default: ts.Debug.fail("Unexpected error code: " + errorCode); @@ -149756,6 +151415,10 @@ var ts; } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { var classElement = findContainerClassElementLike(sourceFile, pos); + if (ts.isSourceFileJS(sourceFile)) { + changeTracker.addJSDocTags(sourceFile, classElement, [ts.factory.createJSDocOverrideTag(ts.factory.createIdentifier("override"))]); + return; + } var modifiers = classElement.modifiers || ts.emptyArray; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); @@ -149769,6 +151432,10 @@ var ts; } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { var classElement = findContainerClassElementLike(sourceFile, pos); + if (ts.isSourceFileJS(sourceFile)) { + changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); + return; + } var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 158 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); @@ -149842,7 +151509,7 @@ var ts; var errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixImplicitThis(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span; var diagnostic; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { @@ -149857,14 +151524,15 @@ var ts; }); function doChange(changes, sourceFile, pos, checker) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 108 /* ThisKeyword */); + if (!ts.isThis(token)) + return undefined; var fn = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isFunctionDeclaration(fn) && !ts.isFunctionExpression(fn)) return undefined; if (!ts.isSourceFile(ts.getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function - var fnKeyword = ts.Debug.assertDefined(ts.findChildOfKind(fn, 98 /* FunctionKeyword */, sourceFile)); + var fnKeyword = ts.Debug.checkDefined(ts.findChildOfKind(fn, 98 /* FunctionKeyword */, sourceFile)); var name = fn.name; - var body = ts.Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression + var body = ts.Debug.checkDefined(fn.body); // Should be defined because the function contained a 'this' expression if (ts.isFunctionExpression(fn)) { if (name && ts.FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) { // Function expression references itself. To fix we would have to extract it to a const. @@ -149902,7 +151570,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { var sourceFile = context.sourceFile, span = context.span; var namedTupleMember = getNamedTupleMember(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, namedTupleMember); }); @@ -150101,7 +151769,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToCorrectReturnValue(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) @@ -150441,7 +152109,8 @@ var ts; return { kind: 3 /* ObjectLiteral */, token: token, properties: properties, indentation: undefined, parentDeclaration: parent.initializer }; } if (ts.isIdentifier(token) && ts.isJsxOpeningLikeElement(token.parent)) { - var attributes = getUnmatchedAttributes(checker, token.parent); + var target = ts.getEmitScriptTarget(program.getCompilerOptions()); + var attributes = getUnmatchedAttributes(checker, target, token.parent); if (!ts.length(attributes)) return undefined; return { kind: 4 /* JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; @@ -150676,8 +152345,12 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = attr.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(attr.valueDeclaration)) : createUndefined(); - return ts.factory.createJsxAttribute(ts.factory.createIdentifier(attr.name), ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var name = ts.factory.createIdentifier(attr.name); + var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); + // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). + ts.setParent(name, jsxAttribute); + return jsxAttribute; }); var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; @@ -150686,10 +152359,11 @@ var ts; function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var quotePreference = ts.getQuotePreference(context.sourceFile, context.preferences); + var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); - return ts.factory.createPropertyAssignment(prop.name, initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); + return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* Single */), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -150776,7 +152450,7 @@ var ts; return (type.flags & 524288 /* Object */) && ((ts.getObjectFlags(type) & 128 /* ObjectLiteral */) || (type.symbol && ts.tryCast(ts.singleOrUndefined(type.symbol.declarations), ts.isTypeLiteralNode))); } - function getUnmatchedAttributes(checker, source) { + function getUnmatchedAttributes(checker, target, source) { var attrsType = checker.getContextualType(source.attributes); if (attrsType === undefined) return ts.emptyArray; @@ -150798,7 +152472,7 @@ var ts; } } return ts.filter(targetProps, function (targetProp) { - return !((targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */) || seenNames.has(targetProp.escapedName)); + return ts.isIdentifierText(targetProp.name, target, 1 /* JSX */) && !((targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */) || seenNames.has(targetProp.escapedName)); }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150851,7 +152525,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixNotFoundModule(context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; var packageName = tryGetImportedPackageName(sourceFile, start); if (packageName === undefined) @@ -150876,7 +152550,7 @@ var ts; break; } default: - ts.Debug.fail("Bad fixId: " + context.fixId); + ts.Debug.fail("Bad fixId: ".concat(context.fixId)); } }); }, @@ -150912,7 +152586,7 @@ var ts; var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); @@ -150920,7 +152594,7 @@ var ts; return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { var seenClassDeclarations = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); @@ -151053,7 +152727,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToEnableExperimentalDecorators(context) { var configFile = context.program.getCompilerOptions().configFile; if (configFile === undefined) { return undefined; @@ -151084,7 +152758,7 @@ var ts; var errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { var configFile = context.program.getCompilerOptions().configFile; if (configFile === undefined) { return undefined; @@ -151122,7 +152796,7 @@ var ts; ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; if (configFile === undefined) { @@ -151324,13 +152998,102 @@ var ts; if (!isValidCharacter(character)) { return; } - var replacement = useHtmlEntity ? htmlEntity[character] : "{" + ts.quote(sourceFile, preferences, character) + "}"; + var replacement = useHtmlEntity ? htmlEntity[character] : "{".concat(ts.quote(sourceFile, preferences, character), "}"); changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var deleteUnmatchedParameter = "deleteUnmatchedParameter"; + var renameUnmatchedParameter = "renameUnmatchedParameter"; + var errorCodes = [ + ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code, + ]; + codefix.registerCodeFix({ + fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter], + errorCodes: errorCodes, + getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { + var sourceFile = context.sourceFile, span = context.span; + var actions = []; + var info = getInfo(sourceFile, span.start); + if (info) { + ts.append(actions, getDeleteAction(context, info)); + ts.append(actions, getRenameAction(context, info)); + return actions; + } + return undefined; + }, + getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { + var tagsToSignature = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (_a) { + var file = _a.file, start = _a.start; + var info = getInfo(file, start); + if (info) { + tagsToSignature.set(info.signature, ts.append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); + } + }); + tagsToSignature.forEach(function (tags, signature) { + if (context.fixId === deleteUnmatchedParameter) { + var tagsSet_1 = new ts.Set(tags); + changes.filterJSDocTags(signature.getSourceFile(), signature, function (t) { return !tagsSet_1.has(t); }); + } + }); + })); + } + }); + function getDeleteAction(context, _a) { + var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag; + var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { + return changeTracker.filterJSDocTags(context.sourceFile, signature, function (t) { return t !== jsDocParameterTag; }); + }); + return codefix.createCodeFixAction(deleteUnmatchedParameter, changes, [ts.Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], deleteUnmatchedParameter, ts.Diagnostics.Delete_all_unused_param_tags); + } + function getRenameAction(context, _a) { + var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag; + if (!ts.length(signature.parameters)) + return undefined; + var sourceFile = context.sourceFile; + var tags = ts.getJSDocTags(signature); + var names = new ts.Set(); + for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) { + var tag = tags_2[_i]; + if (ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name)) { + names.add(tag.name.escapedText); + } + } + // @todo - match to all available names instead to the first parameter name + // @see /codeFixRenameUnmatchedParameter3.ts + var parameterName = ts.firstDefined(signature.parameters, function (p) { + return ts.isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : undefined; + }); + if (parameterName === undefined) + return undefined; + var newJSDocParameterTag = ts.factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, ts.factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment); + var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { + return changeTracker.replaceJSDocComment(sourceFile, signature, ts.map(tags, function (t) { return t === jsDocParameterTag ? newJSDocParameterTag : t; })); + }); + return codefix.createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [ts.Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); + } + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.parent && ts.isJSDocParameterTag(token.parent) && ts.isIdentifier(token.parent.name)) { + var jsDocParameterTag = token.parent; + var signature = ts.getHostSignatureFromJSDoc(jsDocParameterTag); + if (signature) { + return { signature: signature, name: token.parent.name, jsDocParameterTag: jsDocParameterTag }; + } + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -151515,11 +153278,11 @@ var ts; token = ts.cast(token.parent, ts.isInferTypeNode).typeParameter.name; } if (ts.isIdentifier(token) && canPrefix(token)) { - changes.replaceNode(sourceFile, token, ts.factory.createIdentifier("_" + token.text)); + changes.replaceNode(sourceFile, token, ts.factory.createIdentifier("_".concat(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.factory.createIdentifier("_" + tag.name.text)); + changes.replaceNode(sourceFile, tag.name, ts.factory.createIdentifier("_".concat(tag.name.text))); } }); } @@ -151628,6 +153391,9 @@ var ts; case 172 /* SetAccessor */: // Setter must have a parameter return false; + case 171 /* GetAccessor */: + // Getter cannot have parameters + return true; default: return ts.Debug.failBadSyntaxKind(parent); } @@ -151661,6 +153427,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + var syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); + if (syntacticDiagnostics.length) + return; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length, context.errorCode); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, @@ -151855,7 +153624,7 @@ var ts; }); } }); function doChange(changes, sourceFile, name) { - changes.replaceNodeWithText(sourceFile, name, name.text + "()"); + changes.replaceNodeWithText(sourceFile, name, "".concat(name.text, "()")); } function getCallName(sourceFile, start) { var token = ts.getTokenAtPosition(sourceFile, start); @@ -151882,6 +153651,7 @@ var ts; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -151894,7 +153664,7 @@ var ts; return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { var seen = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var nodes = getNodes(diag.file, diag.start); @@ -152063,7 +153833,7 @@ var ts; }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getTextOfNode(name)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -152132,7 +153902,7 @@ var ts; if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); - addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + changes.addJSDocTags(sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); return parent; @@ -152141,7 +153911,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, importAdder, ts.getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); importAdder.writeFixes(changes); return symbol.valueDeclaration; } @@ -152243,7 +154013,7 @@ var ts; } } function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { - addJSDocTags(changes, sourceFile, containingFunction, [ + changes.addJSDocTags(sourceFile, containingFunction, [ ts.factory.createJSDocThisTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode)), ]); } @@ -152272,7 +154042,7 @@ var ts; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); - addJSDocTags(changes, sourceFile, parent, [typeTag]); + changes.addJSDocTags(sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); @@ -152328,45 +154098,7 @@ var ts; var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); - addJSDocTags(changes, sourceFile, signature, paramTags); - } - } - function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); - var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); - var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { - var merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; - return !!merged; - }); }); - var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray), true), unmergedNewTags, true))); - var jsDocNode = parent.kind === 213 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; - jsDocNode.jsDoc = parent.jsDoc; - jsDocNode.jsDocCache = parent.jsDocCache; - changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); - } - codefix.addJSDocTags = addJSDocTags; - function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 166 /* PropertyDeclaration */) { - return signature.parent; - } - return signature.parent.parent; - } - function tryMergeJsdocTags(oldTag, newTag) { - if (oldTag.kind !== newTag.kind) { - return undefined; - } - switch (oldTag.kind) { - case 338 /* JSDocParameterTag */: { - var oldParam = oldTag; - var newParam = newTag; - return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText - ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) - : undefined; - } - case 339 /* JSDocReturnTag */: - return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + changes.addJSDocTags(sourceFile, signature, paramTags); } } function getReferences(token, program, cancellationToken) { @@ -152878,10 +154610,22 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - 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) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.constructs) === null || _b === void 0 ? void 0 : _b.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } - types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + var candidateTypes = (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }); + var callsType = ((_c = usage.calls) === null || _c === void 0 ? void 0 : _c.length) ? inferStructuralType(usage) : undefined; + if (callsType && candidateTypes) { + types.push(checker.getUnionType(__spreadArray([callsType], candidateTypes, true), 2 /* Subtype */)); + } + else { + if (callsType) { + types.push(callsType); + } + if (ts.length(candidateTypes)) { + types.push.apply(types, candidateTypes); + } + } types.push.apply(types, inferNamedTypesFromProperties(usage)); return types; } @@ -153004,7 +154748,7 @@ var ts; var parameters = []; var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); var _loop_16 = function (i) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg".concat(i))); symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { symbol.flags |= 16777216 /* Optional */; @@ -153042,7 +154786,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixId], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span; var checker = program.getTypeChecker(); var info = getInfo(sourceFile, program.getTypeChecker(), span.start); @@ -153096,7 +154840,7 @@ var ts; }); codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; @@ -153107,7 +154851,7 @@ var ts; 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" + newLineCharacter), + : ts.createTextSpan(0, 0), "// @ts-nocheck".concat(newLineCharacter)), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -153373,7 +155117,7 @@ var ts; var typeParameters = isJs || typeArguments === undefined ? undefined : ts.map(typeArguments, function (_, i) { - return ts.factory.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); + return ts.factory.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T".concat(i)); }); var parameters = createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, isJs); var type = isJs || contextualType === undefined @@ -153408,7 +155152,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - /*name*/ names && names[i] || "arg" + i, + /*name*/ names && names[i] || "arg".concat(i), /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.factory.createToken(57 /* QuestionToken */) : undefined, /*type*/ inJs ? undefined : types && types[i] || ts.factory.createKeywordTypeNode(130 /* AnyKeyword */), /*initializer*/ undefined); @@ -153659,7 +155403,7 @@ var ts; } var name = declaration.name.text; var startWithUnderscore = ts.startsWithUnderscore(name); - var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_".concat(name), file), declaration.name); var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { isStatic: ts.hasStaticModifier(declaration), @@ -153865,36 +155609,35 @@ var ts; var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); - if (!propertyDeclaration) + getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { + var info = getInfo(context.sourceFile, context.span.start); + if (!info) return; - var result = [ - getActionForAddMissingUndefinedType(context, propertyDeclaration), - getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) - ]; - ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + var result = []; + ts.append(result, getActionForAddMissingUndefinedType(context, info)); + ts.append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); + ts.append(result, getActionForAddMissingInitializer(context, info)); return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); - if (!propertyDeclaration) + var info = getInfo(diag.file, diag.start); + if (!info) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + addDefiniteAssignmentAssertion(changes, diag.file, info.prop); break; case fixIdAddUndefinedType: - addUndefinedType(changes, diag.file, propertyDeclaration); + addUndefinedType(changes, diag.file, info); break; case fixIdAddInitializer: var checker = context.program.getTypeChecker(); - var initializer = getInitializer(checker, propertyDeclaration); + var initializer = getInitializer(checker, info.prop); if (!initializer) return; - addInitializer(changes, diag.file, propertyDeclaration, initializer); + addInitializer(changes, diag.file, info.prop, initializer); break; default: ts.Debug.fail(JSON.stringify(context.fixId)); @@ -153902,35 +155645,50 @@ var ts; }); }, }); - function getPropertyDeclaration(sourceFile, pos) { + function getInfo(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + if (ts.isIdentifier(token) && ts.isPropertyDeclaration(token.parent)) { + var type = ts.getEffectiveTypeAnnotationNode(token.parent); + if (type) { + return { type: type, prop: token.parent, isJs: ts.isInJSFile(token.parent) }; + } + } + return undefined; } - function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { + if (info.isJs) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } - function getActionForAddMissingUndefinedType(context, propertyDeclaration) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + function getActionForAddMissingUndefinedType(context, info) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, info); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } - function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + function addUndefinedType(changeTracker, sourceFile, info) { var undefinedTypeNode = ts.factory.createKeywordTypeNode(152 /* UndefinedKeyword */); - var type = propertyDeclaration.type; // TODO: GH#18217 - var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; - changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.factory.createUnionTypeNode(types)); + var types = ts.isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode]; + var unionTypeNode = ts.factory.createUnionTypeNode(types); + if (info.isJs) { + changeTracker.addJSDocTags(sourceFile, info.prop, [ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(unionTypeNode))]); + } + else { + changeTracker.replaceNode(sourceFile, info.type, unionTypeNode); + } } - function getActionForAddMissingInitializer(context, propertyDeclaration) { + function getActionForAddMissingInitializer(context, info) { + if (info.isJs) + return undefined; var checker = context.program.getTypeChecker(); - var initializer = getInitializer(checker, propertyDeclaration); + var initializer = getInitializer(checker, info.prop); if (!initializer) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, info.prop, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); @@ -154088,7 +155846,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToUseBigintLiteral(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_a_bigint_numeric_literal, fixId, ts.Diagnostics.Convert_all_to_bigint_numeric_literals)]; @@ -154120,7 +155878,7 @@ var ts; var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingTypeof(context) { var sourceFile = context.sourceFile, span = context.span; var importType = getImportTypeNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); @@ -154152,7 +155910,7 @@ var ts; var errorCodes = [ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { var sourceFile = context.sourceFile, span = context.span; var node = findNodeToFix(sourceFile, span.start); if (!node) @@ -154224,12 +155982,11 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; - var fixId = fixIdAddMissingTypeof; + var fixId = "fixConvertToMappedObjectType"; var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { var sourceFile = context.sourceFile, span = context.span; var info = getInfo(sourceFile, span.start); if (!info) @@ -154247,10 +156004,12 @@ var ts; }); function getInfo(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); - if (ts.isClassDeclaration(indexSignature.parent)) + var indexSignature = ts.tryCast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (!indexSignature) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.tryCast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + if (!container) return undefined; - var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { @@ -154308,7 +156067,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unnecessary_await, fixId, ts.Diagnostics.Remove_all_unnecessary_uses_of_await)]; @@ -154350,7 +156109,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixId], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context); }); @@ -154386,7 +156145,7 @@ var ts; var errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertConstToLet(context) { var sourceFile = context.sourceFile, span = context.span, program = context.program; var range = getConstTokenRange(sourceFile, span.start, program); if (range === undefined) @@ -154557,7 +156316,7 @@ var ts; defaultToNamedAction.kind, namedToDefaultAction.kind ], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { var info = getInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -154575,7 +156334,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName) { ts.Debug.assert(actionName === defaultToNamedAction.name || actionName === namedToDefaultAction.name, "Unexpected action name"); var info = getInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); @@ -154683,7 +156442,7 @@ var ts; changes.insertNodeAfter(exportingSourceFile, exportNode, ts.factory.createExportDefault(ts.factory.createIdentifier(exportName.text))); break; default: - ts.Debug.fail("Unexpected exportNode kind " + exportNode.kind); + ts.Debug.fail("Unexpected exportNode kind ".concat(exportNode.kind)); } } } @@ -154771,7 +156530,7 @@ var ts; break; } default: - ts.Debug.assertNever(parent, "Unexpected parent kind " + parent.kind); + ts.Debug.assertNever(parent, "Unexpected parent kind ".concat(parent.kind)); } } function makeImportSpecifier(propertyName, name) { @@ -154787,51 +156546,53 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var _a; var refactorName = "Convert import"; - var namespaceToNamedAction = { - name: "Convert namespace import to named imports", - description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named", - }; - var namedToNamespaceAction = { - name: "Convert named imports to namespace import", - description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace", - }; + var actions = (_a = {}, + _a[0 /* Named */] = { + name: "Convert namespace import to named imports", + description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, + kind: "refactor.rewrite.import.named", + }, + _a[2 /* Namespace */] = { + name: "Convert named imports to namespace import", + description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, + kind: "refactor.rewrite.import.namespace", + }, + _a[1 /* Default */] = { + name: "Convert named imports to default import", + description: ts.Diagnostics.Convert_named_imports_to_default_import.message, + kind: "refactor.rewrite.import.default", + }, + _a); refactor.registerRefactor(refactorName, { - kinds: [ - namespaceToNamedAction.kind, - namedToNamespaceAction.kind - ], - getAvailableActions: function (context) { - var info = getImportToConvert(context, context.triggerReason === "invoked"); + kinds: ts.getOwnValues(actions).map(function (a) { return a.kind; }), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + var info = getImportConversionInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 267 /* NamespaceImport */; - var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; + var action = actions[info.convertTo]; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { name: refactorName, description: namespaceToNamedAction.description, - actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, - actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } - ]; + return ts.getOwnValues(actions).map(function (action) { return ({ + name: refactorName, + description: action.description, + actions: [__assign(__assign({}, action), { notApplicableReason: info.error })] + }); }); } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { - ts.Debug.assert(actionName === namespaceToNamedAction.name || actionName === namedToNamespaceAction.name, "Unexpected action name"); - var info = getImportToConvert(context); + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName) { + ts.Debug.assert(ts.some(ts.getOwnValues(actions), function (action) { return action.name === actionName; }), "Unexpected action name"); + var info = getImportConversionInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, info); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. - function getImportToConvert(context, considerPartialSpans) { + function getImportConversionInfo(context, considerPartialSpans) { if (considerPartialSpans === void 0) { considerPartialSpans = true; } var file = context.file; var span = ts.getRefactorContextSpan(context); @@ -154850,15 +156611,23 @@ var ts; if (!importClause.namedBindings) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_namespace_import_or_named_imports) }; } - return importClause.namedBindings; + if (importClause.namedBindings.kind === 267 /* NamespaceImport */) { + return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + } + var compilerOptions = context.program.getCompilerOptions(); + var shouldUseDefault = ts.getAllowSyntheticDefaultImports(compilerOptions) + && isExportEqualsModule(importClause.parent.moduleSpecifier, context.program.getTypeChecker()); + return shouldUseDefault + ? { convertTo: 1 /* Default */, import: importClause.namedBindings } + : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; } - function doChange(sourceFile, program, changes, toConvert) { + function doChange(sourceFile, program, changes, info) { var checker = program.getTypeChecker(); - if (toConvert.kind === 267 /* NamespaceImport */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + if (info.convertTo === 0 /* Named */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { - doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + doChangeNamedToNamespaceOrDefault(sourceFile, checker, changes, info.import, info.convertTo === 1 /* Default */); } } function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { @@ -154908,7 +156677,7 @@ var ts; function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { return ts.isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; } - function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + function doChangeNamedToNamespaceOrDefault(sourceFile, checker, changes, toConvert, shouldUseDefault) { var importDecl = toConvert.parent.parent; var moduleSpecifier = importDecl.moduleSpecifier; var toConvertSymbols = new ts.Set(); @@ -154959,7 +156728,9 @@ var ts; var element = _a[_i]; _loop_17(element); } - changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); + changes.replaceNode(sourceFile, toConvert, shouldUseDefault + ? ts.factory.createIdentifier(namespaceImportName) + : ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { var newNamedImports = ts.arrayFrom(neededNamedImports.values()).map(function (element) { return ts.factory.createImportSpecifier(element.isTypeOnly, element.propertyName && ts.factory.createIdentifier(element.propertyName.text), ts.factory.createIdentifier(element.name.text)); @@ -154967,6 +156738,13 @@ var ts; changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, newNamedImports)); } } + function isExportEqualsModule(moduleSpecifier, checker) { + var externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) + return false; + var exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; + } function updateImport(old, defaultImportName, elements) { return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } @@ -154988,10 +156766,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [toOptionalChainAction.kind], - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain, }); - function getAvailableActions(context) { + function getRefactorActionsToConvertToOptionalChain(context) { var info = getInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -155011,7 +156789,7 @@ var ts; } return ts.emptyArray; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertToOptionalChain(context, actionName) { var info = getInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { @@ -155254,10 +157032,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [functionOverloadAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature }); - function getAvailableActions(context) { + function getRefactorActionsToConvertOverloadsToOneSignature(context) { var file = context.file, startPosition = context.startPosition, program = context.program; var info = getConvertableOverloadListAtPosition(file, startPosition, program); if (!info) @@ -155268,7 +157046,7 @@ var ts; actions: [functionOverloadAction] }]; } - function getEditsForAction(context) { + function getRefactorEditsToConvertOverloadsToOneSignature(context) { var file = context.file, startPosition = context.startPosition, program = context.program; var signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); if (!signatureDecls) @@ -155335,7 +157113,7 @@ var ts; var newComment = ts.displayPartsToString(parameterDocComment); if (newComment.length) { ts.setSyntheticLeadingComments(result, [{ - text: "*\n" + newComment.split("\n").map(function (c) { return " * " + c; }).join("\n") + "\n ", + text: "*\n".concat(newComment.split("\n").map(function (c) { return " * ".concat(c); }).join("\n"), "\n "), kind: 3 /* MultiLineCommentTrivia */, pos: -1, end: -1, @@ -155424,14 +157202,14 @@ var ts; extractConstantAction.kind, extractFunctionAction.kind ], - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol, }); /** * Compute the associated code actions * Exported for tests. */ - function getAvailableActions(context) { + function getRefactorActionsToExtractSymbol(context) { var requestedRefactor = context.kind; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context), context.triggerReason === "invoked"); var targetRange = rangeToExtract.targetRange; @@ -155480,7 +157258,7 @@ var ts; usedFunctionNames.set(description, true); functionActions.push({ description: description, - name: "function_scope_" + i, + name: "function_scope_".concat(i), kind: extractFunctionAction.kind }); } @@ -155488,7 +157266,7 @@ var ts; else if (!innermostErrorFunctionAction) { innermostErrorFunctionAction = { description: description, - name: "function_scope_" + i, + name: "function_scope_".concat(i), notApplicableReason: getStringError(functionExtraction.errors), kind: extractFunctionAction.kind }; @@ -155504,7 +157282,7 @@ var ts; usedConstantNames.set(description_1, true); constantActions.push({ description: description_1, - name: "constant_scope_" + i, + name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); } @@ -155512,7 +157290,7 @@ var ts; else if (!innermostErrorConstantAction) { innermostErrorConstantAction = { description: description, - name: "constant_scope_" + i, + name: "constant_scope_".concat(i), notApplicableReason: getStringError(constantExtraction.errors), kind: extractConstantAction.kind }; @@ -155560,9 +157338,9 @@ var ts; return error; } } - extractSymbol.getAvailableActions = getAvailableActions; + extractSymbol.getRefactorActionsToExtractSymbol = getRefactorActionsToExtractSymbol; /* Exported for tests */ - function getEditsForAction(context, actionName) { + function getRefactorEditsToExtractSymbol(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); @@ -155579,7 +157357,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol.getEditsForAction = getEditsForAction; + extractSymbol.getRefactorEditsToExtractSymbol = getRefactorEditsToExtractSymbol; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -155654,7 +157432,7 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - if (ts.isJSDoc(start)) { + if (start.flags & 4194304 /* JSDoc */) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; } if (start.parent !== end.parent) { @@ -155667,8 +157445,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 - for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -155712,11 +157489,12 @@ var ts; return node.expression; } } - else if (ts.isVariableStatement(node)) { + else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { + var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; + for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -155822,8 +157600,8 @@ var ts; // but a super *method call* simply implies a 'this' reference if (node.parent.kind === 207 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 - if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1 === undefined || containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } @@ -156096,28 +157874,28 @@ var ts; case 212 /* FunctionExpression */: case 255 /* FunctionDeclaration */: return scope.name - ? "function '" + scope.name.text + "'" + ? "function '".concat(scope.name.text, "'") : ts.ANONYMOUS; case 213 /* ArrowFunction */: return "arrow function"; case 168 /* MethodDeclaration */: - return "method '" + scope.name.getText() + "'"; + return "method '".concat(scope.name.getText(), "'"); case 171 /* GetAccessor */: - return "'get " + scope.name.getText() + "'"; + return "'get ".concat(scope.name.getText(), "'"); case 172 /* SetAccessor */: - return "'set " + scope.name.getText() + "'"; + return "'set ".concat(scope.name.getText(), "'"); default: - throw ts.Debug.assertNever(scope, "Unexpected scope kind " + scope.kind); + throw ts.Debug.assertNever(scope, "Unexpected scope kind ".concat(scope.kind)); } } function getDescriptionForClassLikeDeclaration(scope) { return scope.kind === 256 /* ClassDeclaration */ - ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" - : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; + ? scope.name ? "class '".concat(scope.name.text, "'") : "anonymous class declaration" + : scope.name ? "class expression '".concat(scope.name.text, "'") : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { return scope.kind === 261 /* ModuleBlock */ - ? "namespace '" + scope.parent.name.getText() + "'" + ? "namespace '".concat(scope.parent.name.getText(), "'") : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } var SpecialScope; @@ -157130,7 +158908,7 @@ var ts; extractToInterfaceAction.kind, extractToTypeDefAction.kind ], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToExtractType(context) { var info = getRangeToExtract(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -157155,7 +158933,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToExtractType(context, actionName) { var file = context.file; var info = getRangeToExtract(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected to find a range to extract"); @@ -157232,11 +159010,20 @@ var ts; function visitor(node) { if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { - var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { - var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); - if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { - ts.pushIfUnique(result, declaration); + var typeName = node.typeName; + var symbol = checker.resolveName(typeName.text, typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); + for (var _i = 0, _a = (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) || ts.emptyArray; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + // skip extraction if the type node is in the range of the type parameter declaration. + // function foo(): void; + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + return true; + } + if (rangeContainsSkipTrivia(statement, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + ts.pushIfUnique(result, decl); + break; + } } } } @@ -157322,7 +159109,7 @@ var ts; }; refactor.registerRefactor(actionName, { kinds: [generateGetSetAction.kind], - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName) { if (!context.endPosition) return undefined; var info = ts.codefix.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); @@ -157401,7 +159188,7 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [moveToNewFileAction.kind], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { var statements = getStatementsToMove(context); if (context.preferences.allowTextChangesInNewFiles && statements) { return [{ name: refactorName, description: description, actions: [moveToNewFileAction] }]; @@ -157412,7 +159199,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName) { ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked"); var statements = ts.Debug.checkDefined(getStatementsToMove(context)); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); @@ -157584,7 +159371,7 @@ var ts; case 253 /* VariableDeclaration */: return ts.tryCast(node.name, ts.isIdentifier); default: - return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); + return ts.Debug.assertNever(node, "Unexpected node kind ".concat(node.kind)); } } function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { @@ -157621,7 +159408,7 @@ var ts; case 253 /* VariableDeclaration */: return ts.factory.createVariableDeclaration(newNamespaceId, /*exclamationToken*/ undefined, /*type*/ undefined, createRequireCall(newModuleString)); default: - return ts.Debug.assertNever(node, "Unexpected node kind " + node.kind); + return ts.Debug.assertNever(node, "Unexpected node kind ".concat(node.kind)); } } function moduleSpecifierFromImport(i) { @@ -157708,7 +159495,7 @@ var ts; deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); break; default: - ts.Debug.assertNever(importDecl, "Unexpected import decl kind " + importDecl.kind); + ts.Debug.assertNever(importDecl, "Unexpected import decl kind ".concat(importDecl.kind)); } } function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { @@ -157808,7 +159595,7 @@ var ts; var name = ts.combinePaths(inDirectory, newModuleName + extension); if (!host.fileExists(name)) return newModuleName; // TODO: GH#18217 - newModuleName = moduleName + "." + i; + newModuleName = "".concat(moduleName, ".").concat(i); } } function getNewModuleName(movedSymbols) { @@ -157915,7 +159702,7 @@ var ts; return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; } default: - return ts.Debug.assertNever(i, "Unexpected import kind " + i.kind); + return ts.Debug.assertNever(i, "Unexpected import kind ".concat(i.kind)); } } function filterNamedBindings(namedBindings, keep) { @@ -158030,7 +159817,7 @@ var ts; case 200 /* ObjectBindingPattern */: return ts.firstDefined(name.elements, function (em) { return ts.isOmittedExpression(em) ? undefined : forEachTopLevelDeclarationInBindingName(em.name, cb); }); default: - return ts.Debug.assertNever(name, "Unexpected name kind " + name.kind); + return ts.Debug.assertNever(name, "Unexpected name kind ".concat(name.kind)); } } function nameOfTopLevelDeclaration(d) { @@ -158091,7 +159878,7 @@ var ts; case 237 /* ExpressionStatement */: return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: - return ts.Debug.assertNever(d, "Unexpected declaration kind " + d.kind); + return ts.Debug.assertNever(d, "Unexpected declaration kind ".concat(d.kind)); } } function addCommonjsExport(decl) { @@ -158113,7 +159900,7 @@ var ts; case 237 /* ExpressionStatement */: return ts.Debug.fail("Can't export an ExpressionStatement"); // Shouldn't try to add 'export' keyword to `exports.x = ...` default: - return ts.Debug.assertNever(decl, "Unexpected decl kind " + decl.kind); + return ts.Debug.assertNever(decl, "Unexpected decl kind ".concat(decl.kind)); } } /** Creates `exports.x = x;` */ @@ -158143,10 +159930,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [removeBracesAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces }); - function getAvailableActions(context) { + function getRefactorActionsToRemoveFunctionBraces(context) { var file = context.file, startPosition = context.startPosition, triggerReason = context.triggerReason; var info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); if (!info) @@ -158172,7 +159959,7 @@ var ts; } return ts.emptyArray; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToRemoveFunctionBraces(context, actionName) { var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); @@ -158237,7 +160024,7 @@ var ts; var convertParamsToDestructuredObject; (function (convertParamsToDestructuredObject) { var refactorName = "Convert parameters to destructured object"; - var minimumParameterLength = 2; + var minimumParameterLength = 1; var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object); var toDestructuredAction = { name: refactorName, @@ -158246,10 +160033,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [toDestructuredAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject }); - function getAvailableActions(context) { + function getRefactorActionsToConvertParametersToDestructuredObject(context) { var file = context.file, startPosition = context.startPosition; var isJSFile = ts.isSourceFileJS(file); if (isJSFile) @@ -158263,7 +160050,7 @@ var ts; actions: [toDestructuredAction] }]; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName) { ts.Debug.assert(actionName === refactorName, "Unexpected action name"); var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); @@ -158751,7 +160538,7 @@ var ts; return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; default: - return ts.Debug.assertNever(functionDeclaration, "Unexpected function declaration kind " + functionDeclaration.kind); + return ts.Debug.assertNever(functionDeclaration, "Unexpected function declaration kind ".concat(functionDeclaration.kind)); } } })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {})); @@ -158773,10 +160560,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [convertStringAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString }); - function getAvailableActions(context) { + function getRefactorActionsToConvertToTemplateString(context) { var file = context.file, startPosition = context.startPosition; var node = getNodeOrParentOfParentheses(file, startPosition); var maybeBinary = getParentBinaryExpression(node); @@ -158802,7 +160589,7 @@ var ts; } return node; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertToTemplateString(context, actionName) { var file = context.file, startPosition = context.startPosition; var node = getNodeOrParentOfParentheses(file, startPosition); switch (actionName) { @@ -159016,10 +160803,10 @@ var ts; toNamedFunctionAction.kind, toArrowFunctionAction.kind ], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions }); - function getAvailableActions(context) { + function getRefactorActionsToConvertFunctionExpressions(context) { var file = context.file, startPosition = context.startPosition, program = context.program, kind = context.kind; var info = getFunctionInfo(file, startPosition, program); if (!info) @@ -159063,7 +160850,7 @@ var ts; errors : possibleActions }]; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertFunctionExpressions(context, actionName) { var file = context.file, startPosition = context.startPosition, program = context.program; var info = getFunctionInfo(file, startPosition, program); if (!info) @@ -159223,10 +161010,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [inferReturnTypeAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType }); - function getEditsForAction(context) { + function getRefactorEditsToInferReturnType(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); @@ -159234,7 +161021,7 @@ var ts; } return undefined; } - function getAvailableActions(context) { + function getRefactorActionsToInferReturnType(context) { var info = getInfo(context); if (!info) return ts.emptyArray; @@ -159455,7 +161242,7 @@ var ts; var textPos = ts.scanner.getTextPos(); if (textPos <= end) { if (token === 79 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.formatSyntaxKind(parent.kind) + " to have an Identifier in its trivia"); + ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); } nodes.push(createNode(token, pos, textPos, parent)); } @@ -159579,13 +161366,11 @@ var ts; switch (context === null || context === void 0 ? void 0 : context.kind) { case 171 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { - this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; case 172 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { - this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } return this.contextualSetAccessorDocumentationComment; @@ -159595,10 +161380,26 @@ var ts; }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); + this.tags = getJsDocTagsOfDeclarations(this.declarations, checker); } return this.tags; }; + SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { + switch (context === null || context === void 0 ? void 0 : context.kind) { + case 171 /* GetAccessor */: + if (!this.contextualGetAccessorTags) { + this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); + } + return this.contextualGetAccessorTags; + case 172 /* SetAccessor */: + if (!this.contextualSetAccessorTags) { + this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); + } + return this.contextualSetAccessorTags; + default: + return this.getJsDocTags(checker); + } + }; return SymbolObject; }()); var TokenObject = /** @class */ (function (_super) { @@ -159719,6 +161520,9 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + TypeObject.prototype.isIndexType = function () { + return !!(this.flags & 4194304 /* Index */); + }; Object.defineProperty(TypeObject.prototype, "typeArguments", { /** * This polyfills `referenceType.typeArguments` for API consumers @@ -159751,14 +161555,21 @@ var ts; SignatureObject.prototype.getReturnType = function () { return this.checker.getReturnTypeOfSignature(this); }; + SignatureObject.prototype.getTypeParameterAtPosition = function (pos) { + var type = this.checker.getParameterType(this, pos); + if (type.isIndexType() && ts.isThisTypeParameter(type.type)) { + var constraint = type.type.getConstraint(); + if (constraint) { + return this.checker.getIndexType(constraint); + } + } + return type; + }; SignatureObject.prototype.getDocumentationComment = function () { return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); }; SignatureObject.prototype.getJsDocTags = function () { - if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; - } - return this.jsDocTags; + return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(ts.singleElementArray(this.declaration), this.checker)); }; return SignatureObject; }()); @@ -159770,12 +161581,30 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTagsOfSignature(declaration, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); - if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); + function getJsDocTagsOfDeclarations(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); + if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { + var seenSymbols_1 = new ts.Set(); + var _loop_22 = function (declaration) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { + var _a; + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + if (declaration.kind === 171 /* GetAccessor */ || declaration.kind === 172 /* SetAccessor */) { + return symbol.getContextualJsDocTags(declaration, checker); + } + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; + } + }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); + } + }; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + _loop_22(declaration); } } return tags; @@ -159785,28 +161614,35 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - var seenSymbols_1 = new ts.Set(); - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + var seenSymbols_2 = new ts.Set(); + var _loop_23 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { - if (!seenSymbols_1.has(symbol)) { - seenSymbols_1.add(symbol); + if (!seenSymbols_2.has(symbol)) { + seenSymbols_2.add(symbol); + if (declaration.kind === 171 /* GetAccessor */ || declaration.kind === 172 /* SetAccessor */) { + return symbol.getContextualDocumentationComment(declaration, checker); + } return symbol.getDocumentationComment(checker); } }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + }; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_23(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; + if (ts.hasStaticModifier(declaration)) + return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 170 /* Constructor */ ? declaration.parent.parent : declaration.parent; - if (!classOrInterfaceDeclaration) { + if (!classOrInterfaceDeclaration) return; - } return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); return symbol ? cb(symbol) : undefined; @@ -160293,6 +162129,7 @@ var ts; ], false); function createLanguageService(host, documentRegistry, syntaxOnlyOrLanguageServiceMode) { var _a; + var _b; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var languageServiceMode; if (syntaxOnlyOrLanguageServiceMode === undefined) { @@ -160313,10 +162150,8 @@ var ts; ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken; var currentDirectory = host.getCurrentDirectory(); - // Check if the localized messages json is set, otherwise query the host for it - if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { - ts.setLocalizedDiagnosticMessages(host.getLocalizedDiagnosticMessages()); - } + // Checks if the localized messages json is set, and if not, query the host for it + ts.maybeSetLocalizedDiagnosticMessages((_b = host.getLocalizedDiagnosticMessages) === null || _b === void 0 ? void 0 : _b.bind(host)); function log(message) { if (host.log) { host.log(message); @@ -160337,7 +162172,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - var error = new Error("Could not find source file: '" + fileName + "'."); + var error = new Error("Could not find source file: '".concat(fileName, "'.")); // We've been having trouble debugging this, so attach sidecar data for the tsserver log. // See https://github.com/microsoft/TypeScript/issues/30180. error.ProgramFiles = program.getSourceFiles().map(function (f) { return f.fileName; }); @@ -160418,6 +162253,7 @@ var ts; hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), + getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, @@ -160614,12 +162450,12 @@ var ts; synchronizeHostData(); return __spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken), true), program.getGlobalDiagnostics(cancellationToken), true); } - function getCompletionsAtPosition(fileName, position, options) { + function getCompletionsAtPosition(fileName, position, options, formattingSettings) { if (options === void 0) { options = ts.emptyOptions; } // Convert from deprecated options names to new names var fullPreferences = __assign(__assign({}, ts.identity(options)), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken, formattingSettings && ts.formatting.getFormatContext(formattingSettings, host)); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -161012,7 +162848,7 @@ var ts; var element = token.kind === 31 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent : ts.isJsxText(token) && ts.isJsxElement(token.parent) ? token.parent : undefined; if (element && isUnclosedTag(element)) { - return { newText: "" }; + return { newText: "") }; } var fragment = token.kind === 31 /* GreaterThanToken */ && ts.isJsxOpeningFragment(token.parent) ? token.parent.parent : ts.isJsxText(token) && ts.isJsxFragment(token.parent) ? token.parent : undefined; @@ -161118,7 +162954,7 @@ var ts; pos = commentRange.end + 1; } else { // If it's not in a comment range, then we need to comment the uncommented portions. - var newPos = text.substring(pos, textRange.end).search("(" + openMultilineRegex + ")|(" + closeMultilineRegex + ")"); + var newPos = text.substring(pos, textRange.end).search("(".concat(openMultilineRegex, ")|(").concat(closeMultilineRegex, ")")); isCommenting = insertComment !== undefined ? insertComment : isCommenting || !ts.isTextWhiteSpaceLike(text, pos, newPos === -1 ? textRange.end : pos + newPos); // If isCommenting is already true we don't need to check whitespace again. @@ -161513,14 +163349,14 @@ var ts; case ts.LanguageServiceMode.PartialSemantic: invalidOperationsInPartialSemanticMode.forEach(function (key) { return ls[key] = function () { - throw new Error("LanguageService Operation: " + key + " not allowed in LanguageServiceMode.PartialSemantic"); + throw new Error("LanguageService Operation: ".concat(key, " not allowed in LanguageServiceMode.PartialSemantic")); }; }); break; case ts.LanguageServiceMode.Syntactic: invalidOperationsInSyntacticMode.forEach(function (key) { return ls[key] = function () { - throw new Error("LanguageService Operation: " + key + " not allowed in LanguageServiceMode.Syntactic"); + throw new Error("LanguageService Operation: ".concat(key, " not allowed in LanguageServiceMode.Syntactic")); }; }); break; @@ -162502,13 +164338,13 @@ var ts; var result = action(); if (logPerformance) { var end = ts.timestamp(); - logger.log(actionDescription + " completed in " + (end - start) + " msec"); + logger.log("".concat(actionDescription, " completed in ").concat(end - start, " msec")); if (ts.isString(result)) { var str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; } - logger.log(" result.length=" + str.length + ", result='" + JSON.stringify(str) + "'"); + logger.log(" result.length=".concat(str.length, ", result='").concat(JSON.stringify(str), "'")); } } return result; @@ -162590,7 +164426,7 @@ var ts; * Update the list of scripts known to the compiler */ LanguageServiceShimObject.prototype.refresh = function (throwOnError) { - this.forwardJSONCall("refresh(" + throwOnError + ")", function () { return null; } // eslint-disable-line no-null/no-null + this.forwardJSONCall("refresh(".concat(throwOnError, ")"), function () { return null; } // eslint-disable-line no-null/no-null ); }; LanguageServiceShimObject.prototype.cleanupSemanticCache = function () { @@ -162606,43 +164442,43 @@ var ts; }; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); + return this.forwardJSONCall("getSyntacticClassifications('".concat(fileName, "', ").concat(start, ", ").concat(length, ")"), function () { return _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); + return this.forwardJSONCall("getSemanticClassifications('".concat(fileName, "', ").concat(start, ", ").concat(length, ")"), function () { return _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); }); }; LanguageServiceShimObject.prototype.getEncodedSyntacticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", + return this.forwardJSONCall("getEncodedSyntacticClassifications('".concat(fileName, "', ").concat(start, ", ").concat(length, ")"), // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. function () { return convertClassifications(_this.languageService.getEncodedSyntacticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getEncodedSemanticClassifications = function (fileName, start, length) { var _this = this; - return this.forwardJSONCall("getEncodedSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", + return this.forwardJSONCall("getEncodedSemanticClassifications('".concat(fileName, "', ").concat(start, ", ").concat(length, ")"), // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. function () { return convertClassifications(_this.languageService.getEncodedSemanticClassifications(fileName, ts.createTextSpan(start, length))); }); }; LanguageServiceShimObject.prototype.getSyntacticDiagnostics = function (fileName) { var _this = this; - return this.forwardJSONCall("getSyntacticDiagnostics('" + fileName + "')", function () { + return this.forwardJSONCall("getSyntacticDiagnostics('".concat(fileName, "')"), function () { var diagnostics = _this.languageService.getSyntacticDiagnostics(fileName); return _this.realizeDiagnostics(diagnostics); }); }; LanguageServiceShimObject.prototype.getSemanticDiagnostics = function (fileName) { var _this = this; - return this.forwardJSONCall("getSemanticDiagnostics('" + fileName + "')", function () { + return this.forwardJSONCall("getSemanticDiagnostics('".concat(fileName, "')"), function () { var diagnostics = _this.languageService.getSemanticDiagnostics(fileName); return _this.realizeDiagnostics(diagnostics); }); }; LanguageServiceShimObject.prototype.getSuggestionDiagnostics = function (fileName) { var _this = this; - return this.forwardJSONCall("getSuggestionDiagnostics('" + fileName + "')", function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); + return this.forwardJSONCall("getSuggestionDiagnostics('".concat(fileName, "')"), function () { return _this.realizeDiagnostics(_this.languageService.getSuggestionDiagnostics(fileName)); }); }; LanguageServiceShimObject.prototype.getCompilerOptionsDiagnostics = function () { var _this = this; @@ -162658,7 +164494,7 @@ var ts; */ LanguageServiceShimObject.prototype.getQuickInfoAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getQuickInfoAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); + return this.forwardJSONCall("getQuickInfoAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getQuickInfoAtPosition(fileName, position); }); }; /// NAMEORDOTTEDNAMESPAN /** @@ -162667,7 +164503,7 @@ var ts; */ LanguageServiceShimObject.prototype.getNameOrDottedNameSpan = function (fileName, startPos, endPos) { var _this = this; - return this.forwardJSONCall("getNameOrDottedNameSpan('" + fileName + "', " + startPos + ", " + endPos + ")", function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); + return this.forwardJSONCall("getNameOrDottedNameSpan('".concat(fileName, "', ").concat(startPos, ", ").concat(endPos, ")"), function () { return _this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos); }); }; /** * STATEMENTSPAN @@ -162675,12 +164511,12 @@ var ts; */ LanguageServiceShimObject.prototype.getBreakpointStatementAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); + return this.forwardJSONCall("getBreakpointStatementAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); + return this.forwardJSONCall("getSignatureHelpItems('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); }; /// GOTO DEFINITION /** @@ -162689,7 +164525,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); + return this.forwardJSONCall("getDefinitionAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; /** * Computes the definition location and file for the symbol @@ -162697,7 +164533,7 @@ var ts; */ LanguageServiceShimObject.prototype.getDefinitionAndBoundSpan = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getDefinitionAndBoundSpan('" + fileName + "', " + position + ")", function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); + return this.forwardJSONCall("getDefinitionAndBoundSpan('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getDefinitionAndBoundSpan(fileName, position); }); }; /// GOTO Type /** @@ -162706,7 +164542,7 @@ var ts; */ LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); + return this.forwardJSONCall("getTypeDefinitionAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getTypeDefinitionAtPosition(fileName, position); }); }; /// GOTO Implementation /** @@ -162715,37 +164551,37 @@ var ts; */ LanguageServiceShimObject.prototype.getImplementationAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); + return this.forwardJSONCall("getImplementationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); }); + return this.forwardJSONCall("getRenameInfo('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getRenameInfo(fileName, position, options); }); }; LanguageServiceShimObject.prototype.getSmartSelectionRange = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getSmartSelectionRange('" + fileName + "', " + position + ")", function () { return _this.languageService.getSmartSelectionRange(fileName, position); }); + return this.forwardJSONCall("getSmartSelectionRange('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getSmartSelectionRange(fileName, position); }); }; LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); + return this.forwardJSONCall("findRenameLocations('".concat(fileName, "', ").concat(position, ", ").concat(findInStrings, ", ").concat(findInComments, ", ").concat(providePrefixAndSuffixTextForRename, ")"), function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getBraceMatchingAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); + return this.forwardJSONCall("getBraceMatchingAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getBraceMatchingAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.isValidBraceCompletionAtPosition = function (fileName, position, openingBrace) { var _this = this; - return this.forwardJSONCall("isValidBraceCompletionAtPosition('" + fileName + "', " + position + ", " + openingBrace + ")", function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); + return this.forwardJSONCall("isValidBraceCompletionAtPosition('".concat(fileName, "', ").concat(position, ", ").concat(openingBrace, ")"), function () { return _this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace); }); }; LanguageServiceShimObject.prototype.getSpanOfEnclosingComment = function (fileName, position, onlyMultiLine) { var _this = this; - return this.forwardJSONCall("getSpanOfEnclosingComment('" + fileName + "', " + position + ")", function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); + return this.forwardJSONCall("getSpanOfEnclosingComment('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getSpanOfEnclosingComment(fileName, position, onlyMultiLine); }); }; /// GET SMART INDENT LanguageServiceShimObject.prototype.getIndentationAtPosition = function (fileName, position, options /*Services.EditorOptions*/) { var _this = this; - return this.forwardJSONCall("getIndentationAtPosition('" + fileName + "', " + position + ")", function () { + return this.forwardJSONCall("getIndentationAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { var localOptions = JSON.parse(options); return _this.languageService.getIndentationAtPosition(fileName, position, localOptions); }); @@ -162753,23 +164589,23 @@ var ts; /// GET REFERENCES LanguageServiceShimObject.prototype.getReferencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getReferencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); + return this.forwardJSONCall("getReferencesAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getReferencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.findReferences = function (fileName, position) { var _this = this; - return this.forwardJSONCall("findReferences('" + fileName + "', " + position + ")", function () { return _this.languageService.findReferences(fileName, position); }); + return this.forwardJSONCall("findReferences('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.findReferences(fileName, position); }); }; LanguageServiceShimObject.prototype.getFileReferences = function (fileName) { var _this = this; - return this.forwardJSONCall("getFileReferences('" + fileName + ")", function () { return _this.languageService.getFileReferences(fileName); }); + return this.forwardJSONCall("getFileReferences('".concat(fileName, ")"), function () { return _this.languageService.getFileReferences(fileName); }); }; LanguageServiceShimObject.prototype.getOccurrencesAtPosition = function (fileName, position) { var _this = this; - return this.forwardJSONCall("getOccurrencesAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); + return this.forwardJSONCall("getOccurrencesAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getOccurrencesAtPosition(fileName, position); }); }; LanguageServiceShimObject.prototype.getDocumentHighlights = function (fileName, position, filesToSearch) { var _this = this; - return this.forwardJSONCall("getDocumentHighlights('" + fileName + "', " + position + ")", function () { + return this.forwardJSONCall("getDocumentHighlights('".concat(fileName, "', ").concat(position, ")"), function () { var results = _this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); // workaround for VS document highlighting issue - keep only items from the initial file var normalizedName = ts.toFileNameLowerCase(ts.normalizeSlashes(fileName)); @@ -162782,110 +164618,110 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences, formattingSettings) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + return this.forwardJSONCall("getCompletionsAtPosition('".concat(fileName, "', ").concat(position, ", ").concat(preferences, ", ").concat(formattingSettings, ")"), function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { var _this = this; - return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { + return this.forwardJSONCall("getCompletionEntryDetails('".concat(fileName, "', ").concat(position, ", '").concat(entryName, "')"), function () { var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences, data); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getFormattingEditsForRange('" + fileName + "', " + start + ", " + end + ")", function () { + return this.forwardJSONCall("getFormattingEditsForRange('".concat(fileName, "', ").concat(start, ", ").concat(end, ")"), function () { var localOptions = JSON.parse(options); return _this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForDocument = function (fileName, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getFormattingEditsForDocument('" + fileName + "')", function () { + return this.forwardJSONCall("getFormattingEditsForDocument('".concat(fileName, "')"), function () { var localOptions = JSON.parse(options); return _this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); }; LanguageServiceShimObject.prototype.getFormattingEditsAfterKeystroke = function (fileName, position, key, options /*Services.FormatCodeOptions*/) { var _this = this; - return this.forwardJSONCall("getFormattingEditsAfterKeystroke('" + fileName + "', " + position + ", '" + key + "')", function () { + return this.forwardJSONCall("getFormattingEditsAfterKeystroke('".concat(fileName, "', ").concat(position, ", '").concat(key, "')"), function () { var localOptions = JSON.parse(options); return _this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); }; LanguageServiceShimObject.prototype.getDocCommentTemplateAtPosition = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getDocCommentTemplateAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getDocCommentTemplateAtPosition('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.getDocCommentTemplateAtPosition(fileName, position, options); }); }; /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ LanguageServiceShimObject.prototype.getNavigateToItems = function (searchValue, maxResultCount, fileName) { var _this = this; - return this.forwardJSONCall("getNavigateToItems('" + searchValue + "', " + maxResultCount + ", " + fileName + ")", function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); + return this.forwardJSONCall("getNavigateToItems('".concat(searchValue, "', ").concat(maxResultCount, ", ").concat(fileName, ")"), function () { return _this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName); }); }; LanguageServiceShimObject.prototype.getNavigationBarItems = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); + return this.forwardJSONCall("getNavigationBarItems('".concat(fileName, "')"), function () { return _this.languageService.getNavigationBarItems(fileName); }); }; LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { var _this = this; - return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + return this.forwardJSONCall("getNavigationTree('".concat(fileName, "')"), function () { return _this.languageService.getNavigationTree(fileName); }); }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; - return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); + return this.forwardJSONCall("getOutliningSpans('".concat(fileName, "')"), function () { return _this.languageService.getOutliningSpans(fileName); }); }; LanguageServiceShimObject.prototype.getTodoComments = function (fileName, descriptors) { var _this = this; - return this.forwardJSONCall("getTodoComments('" + fileName + "')", function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); + return this.forwardJSONCall("getTodoComments('".concat(fileName, "')"), function () { return _this.languageService.getTodoComments(fileName, JSON.parse(descriptors)); }); }; /// CALL HIERARCHY LanguageServiceShimObject.prototype.prepareCallHierarchy = function (fileName, position) { var _this = this; - return this.forwardJSONCall("prepareCallHierarchy('" + fileName + "', " + position + ")", function () { return _this.languageService.prepareCallHierarchy(fileName, position); }); + return this.forwardJSONCall("prepareCallHierarchy('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.prepareCallHierarchy(fileName, position); }); }; LanguageServiceShimObject.prototype.provideCallHierarchyIncomingCalls = function (fileName, position) { var _this = this; - return this.forwardJSONCall("provideCallHierarchyIncomingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyIncomingCalls(fileName, position); }); + return this.forwardJSONCall("provideCallHierarchyIncomingCalls('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.provideCallHierarchyIncomingCalls(fileName, position); }); }; LanguageServiceShimObject.prototype.provideCallHierarchyOutgoingCalls = function (fileName, position) { var _this = this; - return this.forwardJSONCall("provideCallHierarchyOutgoingCalls('" + fileName + "', " + position + ")", function () { return _this.languageService.provideCallHierarchyOutgoingCalls(fileName, position); }); + return this.forwardJSONCall("provideCallHierarchyOutgoingCalls('".concat(fileName, "', ").concat(position, ")"), function () { return _this.languageService.provideCallHierarchyOutgoingCalls(fileName, position); }); }; LanguageServiceShimObject.prototype.provideInlayHints = function (fileName, span, preference) { var _this = this; - return this.forwardJSONCall("provideInlayHints('" + fileName + "', '" + JSON.stringify(span) + "', " + JSON.stringify(preference) + ")", function () { return _this.languageService.provideInlayHints(fileName, span, preference); }); + return this.forwardJSONCall("provideInlayHints('".concat(fileName, "', '").concat(JSON.stringify(span), "', ").concat(JSON.stringify(preference), ")"), function () { return _this.languageService.provideInlayHints(fileName, span, preference); }); }; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { + return this.forwardJSONCall("getEmitOutput('".concat(fileName, "')"), function () { var _a = _this.languageService.getEmitOutput(fileName), diagnostics = _a.diagnostics, rest = __rest(_a, ["diagnostics"]); return __assign(__assign({}, rest), { diagnostics: _this.realizeDiagnostics(diagnostics) }); }); }; LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { var _this = this; - return forwardCall(this.logger, "getEmitOutput('" + fileName + "')", + return forwardCall(this.logger, "getEmitOutput('".concat(fileName, "')"), /*returnJson*/ false, function () { return _this.languageService.getEmitOutput(fileName); }, this.logPerformance); }; LanguageServiceShimObject.prototype.toggleLineComment = function (fileName, textRange) { var _this = this; - return this.forwardJSONCall("toggleLineComment('" + fileName + "', '" + JSON.stringify(textRange) + "')", function () { return _this.languageService.toggleLineComment(fileName, textRange); }); + return this.forwardJSONCall("toggleLineComment('".concat(fileName, "', '").concat(JSON.stringify(textRange), "')"), function () { return _this.languageService.toggleLineComment(fileName, textRange); }); }; LanguageServiceShimObject.prototype.toggleMultilineComment = function (fileName, textRange) { var _this = this; - return this.forwardJSONCall("toggleMultilineComment('" + fileName + "', '" + JSON.stringify(textRange) + "')", function () { return _this.languageService.toggleMultilineComment(fileName, textRange); }); + return this.forwardJSONCall("toggleMultilineComment('".concat(fileName, "', '").concat(JSON.stringify(textRange), "')"), function () { return _this.languageService.toggleMultilineComment(fileName, textRange); }); }; LanguageServiceShimObject.prototype.commentSelection = function (fileName, textRange) { var _this = this; - return this.forwardJSONCall("commentSelection('" + fileName + "', '" + JSON.stringify(textRange) + "')", function () { return _this.languageService.commentSelection(fileName, textRange); }); + return this.forwardJSONCall("commentSelection('".concat(fileName, "', '").concat(JSON.stringify(textRange), "')"), function () { return _this.languageService.commentSelection(fileName, textRange); }); }; LanguageServiceShimObject.prototype.uncommentSelection = function (fileName, textRange) { var _this = this; - return this.forwardJSONCall("uncommentSelection('" + fileName + "', '" + JSON.stringify(textRange) + "')", function () { return _this.languageService.uncommentSelection(fileName, textRange); }); + return this.forwardJSONCall("uncommentSelection('".concat(fileName, "', '").concat(JSON.stringify(textRange), "')"), function () { return _this.languageService.uncommentSelection(fileName, textRange); }); }; return LanguageServiceShimObject; }(ShimBase)); @@ -162935,7 +164771,7 @@ var ts; }; CoreServicesShimObject.prototype.resolveModuleName = function (fileName, moduleName, compilerOptionsJson) { var _this = this; - return this.forwardJSONCall("resolveModuleName('" + fileName + "')", function () { + return this.forwardJSONCall("resolveModuleName('".concat(fileName, "')"), function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; @@ -162950,7 +164786,7 @@ var ts; }; CoreServicesShimObject.prototype.resolveTypeReferenceDirective = function (fileName, typeReferenceDirective, compilerOptionsJson) { var _this = this; - return this.forwardJSONCall("resolveTypeReferenceDirective(" + fileName + ")", function () { + return this.forwardJSONCall("resolveTypeReferenceDirective(".concat(fileName, ")"), function () { var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveTypeReferenceDirective(typeReferenceDirective, ts.normalizeSlashes(fileName), compilerOptions, _this.host); return { @@ -162962,7 +164798,7 @@ var ts; }; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; - return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { + return this.forwardJSONCall("getPreProcessedFileInfo('".concat(fileName, "')"), function () { // for now treat files as JavaScript var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { @@ -162977,7 +164813,7 @@ var ts; }; CoreServicesShimObject.prototype.getAutomaticTypeDirectiveNames = function (compilerOptionsJson) { var _this = this; - return this.forwardJSONCall("getAutomaticTypeDirectiveNames('" + compilerOptionsJson + "')", function () { + return this.forwardJSONCall("getAutomaticTypeDirectiveNames('".concat(compilerOptionsJson, "')"), function () { var compilerOptions = JSON.parse(compilerOptionsJson); return ts.getAutomaticTypeDirectiveNames(compilerOptions, _this.host); }); @@ -162999,7 +164835,7 @@ var ts; }; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; - return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { + return this.forwardJSONCall("getTSConfigFileInfo('".concat(fileName, "')"), function () { var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); diff --git a/packages/schematics/angular/utility/latest-versions.ts b/packages/schematics/angular/utility/latest-versions.ts index 14480d79de1c..71a2e1b6bd28 100644 --- a/packages/schematics/angular/utility/latest-versions.ts +++ b/packages/schematics/angular/utility/latest-versions.ts @@ -15,7 +15,7 @@ export const latestVersions: Record & { ...require('./latest-versions/package.json')['dependencies'], // As Angular CLI works with same minor versions of Angular Framework, a tilde match for the current - Angular: '~13.2.0', + Angular: '~13.3.0-rc.0', // Since @angular-devkit/build-angular and @schematics/angular are always // published together from the same monorepo, and they are both diff --git a/packages/schematics/angular/utility/latest-versions/package.json b/packages/schematics/angular/utility/latest-versions/package.json index c5add1c2b57f..f5cc28a9a25f 100644 --- a/packages/schematics/angular/utility/latest-versions/package.json +++ b/packages/schematics/angular/utility/latest-versions/package.json @@ -14,7 +14,7 @@ "ng-packagr": "^13.0.0", "rxjs": "~7.5.0", "tslib": "^2.3.0", - "typescript": "~4.5.2", + "typescript": "~4.6.2", "zone.js": "~0.11.4" } } diff --git a/tests/legacy-cli/e2e/ng-snapshot/package.json b/tests/legacy-cli/e2e/ng-snapshot/package.json index 572d4e87eb37..1202e95891b4 100644 --- a/tests/legacy-cli/e2e/ng-snapshot/package.json +++ b/tests/legacy-cli/e2e/ng-snapshot/package.json @@ -2,21 +2,21 @@ "description": "snapshot versions of Angular for e2e testing", "private": true, "dependencies": { - "@angular/animations": "github:angular/animations-builds#0a710238c3d970f957f4c98f32a27f50c2fa6d9b", + "@angular/animations": "github:angular/animations-builds#e563328f975a79575e814c362c616977589e1627", "@angular/cdk": "github:angular/cdk-builds#f6be3441efadf1a618b7bbf14c0130c7bc6964d9", - "@angular/common": "github:angular/common-builds#d476c5b8f8bcb0b64f5720fc65880acec4edd432", - "@angular/compiler": "github:angular/compiler-builds#a7366a76c4e4cd5f498864e9fb67345c3d3cb0d5", - "@angular/compiler-cli": "github:angular/compiler-cli-builds#dd90fb71c538d81ab04194cdc07bf8edeadf5f68", - "@angular/core": "github:angular/core-builds#9eea90031457c7600d34901bb53a98d90295c311", - "@angular/forms": "github:angular/forms-builds#ba125154b807fc8256258e7ff2407c3d1e633ce5", - "@angular/language-service": "github:angular/language-service-builds#dbc2805aa0175bc51854b65596d95dea9005a5b4", - "@angular/localize": "github:angular/localize-builds#5ac5d144ee11b00d5980910dcab4e041c99f5dad", - "@angular/material": "github:angular/material-builds#cede9300b8ff2e7b3d728e49a28084638d9a7533", + "@angular/common": "github:angular/common-builds#75daa58f9c26171e4f40eb64b254a082a0561db4", + "@angular/compiler": "github:angular/compiler-builds#dfc994c00161e08da02ad58ed033d9669ebff814", + "@angular/compiler-cli": "github:angular/compiler-cli-builds#e98c75da1019ce330a70a6071539e615ab019d38", + "@angular/core": "github:angular/core-builds#f8be55c208b260a99cb634b8f67bf9e287cdb695", + "@angular/forms": "github:angular/forms-builds#065a1bf97d135c10a50418dc4f614a37d52bbe96", + "@angular/language-service": "github:angular/language-service-builds#49ca62bfad977cad3b3237c6f8b58df1fad3e0dd", + "@angular/localize": "github:angular/localize-builds#ad6ab79013b18122454cbc47296450836aa991f9", + "@angular/material": "github:angular/material2-builds#cede9300b8ff2e7b3d728e49a28084638d9a7533", "@angular/material-moment-adapter": "github:angular/material-moment-adapter-builds#43c32d9c6b12faf1d4d2c0ec50a5f58eb741de24", - "@angular/platform-browser": "github:angular/platform-browser-builds#415998e6d9040aec5f62b54c41a358fb1d9d7a43", - "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#2065be65d3d8e3018782e16900563cdffa5cfeae", - "@angular/platform-server": "github:angular/platform-server-builds#0dd4cbfd25b75987899caa3e9967e8f7126fb0bb", - "@angular/router": "github:angular/router-builds#cf438ce6e60c2147dc2060c010034bc7788669f4", - "@angular/service-worker": "github:angular/service-worker-builds#4f170125365b7d32b72c6fe84a4936f5b59a4bfa" + "@angular/platform-browser": "github:angular/platform-browser-builds#6e14a60665788e94a888f0ae026fc8727fe75207", + "@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds#190dfc6177e683d678ef38ed6869ac3991dd8a61", + "@angular/platform-server": "github:angular/platform-server-builds#da57e205de79a862443cdbaf2b89ec6d7f390185", + "@angular/router": "github:angular/router-builds#1b50dc910ca18c0eea062cd05d8136d022a68209", + "@angular/service-worker": "github:angular/service-worker-builds#62ed8ca34e178698a5937037e0739b51acc794bd" } } diff --git a/yarn.lock b/yarn.lock index 5f032263e75b..6020c38c14b4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -34,6 +34,13 @@ "@jridgewell/resolve-uri" "^3.0.3" sourcemap-codec "1.4.8" +"@ampproject/remapping@^2.0.0", "@ampproject/remapping@^2.1.0": + version "2.1.2" + resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.1.2.tgz#4edca94973ded9630d20101cd8559cedb8d8bd34" + integrity sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg== + dependencies: + "@jridgewell/trace-mapping" "^0.3.0" + "@angular-devkit/architect@0.1302.0-rc.1": version "0.1302.0-rc.1" resolved "https://registry.yarnpkg.com/@angular-devkit/architect/-/architect-0.1302.0-rc.1.tgz#090e86312f6c57da83e46cda4833b37843f1ebf1" @@ -134,10 +141,10 @@ rxjs "6.6.7" source-map "0.7.3" -"@angular/animations@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/animations/-/animations-13.1.3.tgz#2da6ad99602bfb450624a7499d6f81366c3a4519" - integrity sha512-OwsVQsNHubIgRcxnjti4CU3QJnqd7Z2b+2iu3M349Oxyqxz4DNCqKXalDuJZt/b0yNfirvYO3kCgBfj4PF43QQ== +"@angular/animations@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/animations/-/animations-13.3.0-rc.0.tgz#2fb38d0b6fd7e40387e6f7d5cd1e9dfb0caa47f1" + integrity sha512-lWsLdvOEl1GtUzbCFfIaZkQlepnSNVrsShlq8pwEUt3Y7KVsXB5LqFqzO5yA8SuxzLgqqthwdC8Op6UYZWn1nA== dependencies: tslib "^2.3.0" @@ -158,41 +165,40 @@ optionalDependencies: parse5 "^5.0.0" -"@angular/common@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/common/-/common-13.1.3.tgz#4c80f45cfd00a17543559c5fbebe0a7a7cf403ed" - integrity sha512-8qf5syeXUogf3+GSu6IRJjrk46UKh9L0QuLx+OSIl/df0y1ewx7e28q3BAUEEnOnKrLzpPNxWs2iwModc4KYfg== +"@angular/common@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/common/-/common-13.3.0-rc.0.tgz#5c72aade2b6c87b122f1eec4cc0b287cd851e519" + integrity sha512-uGDZjqkzqrWcGUP0tauiXnVKzwc7Vt5VxHZuYRjwmVOyJBULe4g6y8blKF/1J+KRU7LPZ9hLwsAOMRHupV7cbw== dependencies: tslib "^2.3.0" -"@angular/compiler-cli@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/compiler-cli/-/compiler-cli-13.1.3.tgz#0269370350e928f22f3150523f95bc490a1e7a7a" - integrity sha512-ALURaJATc54DzPuiZBvALf/alEp1wr7Hjmw4FuMn2cU7p8lwKkra1Dz5dAZOxh7jAcD1GJfrK/+Sb7A3cuuKjQ== +"@angular/compiler-cli@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/compiler-cli/-/compiler-cli-13.3.0-rc.0.tgz#549016fb28c1657eb089d7836efaebf158497cb1" + integrity sha512-cbHjsYKnxtdkXhd7yKAO2PiA86BNBwnaEqo74CkG5mfRWUIVyOeRKLLGTrMDCUsJyCUs3+wEH1B9bkcB6jEdnQ== dependencies: - "@babel/core" "^7.8.6" - canonical-path "1.0.0" + "@babel/core" "^7.17.2" chokidar "^3.0.0" convert-source-map "^1.5.1" dependency-graph "^0.11.0" - magic-string "^0.25.0" + magic-string "^0.26.0" reflect-metadata "^0.1.2" semver "^7.0.0" sourcemap-codec "^1.4.8" tslib "^2.3.0" yargs "^17.2.1" -"@angular/compiler@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/compiler/-/compiler-13.1.3.tgz#fc33b06046599ecc943f55049e0a121d5ab46d4f" - integrity sha512-dbHs/Oa+Dn+7i0jKtlVDE0lD0DaUC+lVzAcTK/zS37LrckrTMn1CA+z9bZ4gpHig9RU0wgV3YORxv0wokyiB8A== +"@angular/compiler@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/compiler/-/compiler-13.3.0-rc.0.tgz#7d7a3dbe3824d0b09408ebc6f6d822e9c6e99e5a" + integrity sha512-cKC7DDVCdP/IyvNImHaSQZ5MGqEX89A+QNQ6jhA0Z7cxNDAtA3SpRU4xHNsWsB583iuxLGUSg7UgCxjtv3gM0w== dependencies: tslib "^2.3.0" -"@angular/core@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/core/-/core-13.1.3.tgz#4afd71f674f9ead1aada81315f84846cdba10fa4" - integrity sha512-rvCnIAonRx7VnH2Mv9lQR+UYdlFQQetZCjPw8QOswOspEpHpEPDrp1HxDIqJnHxNqW0n8J3Zev/VgQYr0481UA== +"@angular/core@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/core/-/core-13.3.0-rc.0.tgz#2dce904d58b28795a7546b29da866fac7b5e0fa0" + integrity sha512-PzH48NF1zPAIwoUFzGXsMb/WHsRrtkkLk7w+JgzUttVfaxQLh+SZJWgKZ10M9JSTdlfbxUuTo1A9zkJTnEX9SA== dependencies: tslib "^2.3.0" @@ -266,19 +272,19 @@ yaml "^1.10.0" yargs "^17.0.0" -"@angular/forms@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/forms/-/forms-13.1.3.tgz#4b31d1208e2b191766efbbe1a502193e28e89240" - integrity sha512-c4N9zZSILyEbomY2CJo1WAMxiHu/qlycvzxKH5NFS2P2+fieORlbKUJ2p1CbYqcIxVnLYRSdWH8f1JpoaG0ETw== +"@angular/forms@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/forms/-/forms-13.3.0-rc.0.tgz#c7f99fe274aea37c7654a3d592c37d3bf5b51fa4" + integrity sha512-alqhcA6GZSqQ8IdAR/ev+rpKcJEV6KRyhETCI7aN8KrI9jtZc8x7hkvesQktbTWt8RNTfbpQ6O5xC4uI2MsRZQ== dependencies: tslib "^2.3.0" -"@angular/localize@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/localize/-/localize-13.1.3.tgz#05c27275aec7d461e1b2ae2f0b19fef7d0265df8" - integrity sha512-SGKdVtFnMtwQK3BebsOWf9rJjczVDKDbuO+5xXivD9k0gu5zrRy7x7mwLR7cGlWNDEmoiId705ItC+Mm5n+FVQ== +"@angular/localize@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/localize/-/localize-13.3.0-rc.0.tgz#89641afcee09c7260fb494b16f0c48aa1a2e581e" + integrity sha512-wV8gInuC0bKyFChDi3ss2UzkQg7Vdi9Y/C/nU6Q9Z9VarEjhnOKRfN4x2oep9N/KghHTyZDVn8u5iSWzVfaBWw== dependencies: - "@babel/core" "7.8.6" + "@babel/core" "7.17.2" glob "7.2.0" yargs "^17.2.1" @@ -289,40 +295,40 @@ dependencies: tslib "^2.3.0" -"@angular/platform-browser-dynamic@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/platform-browser-dynamic/-/platform-browser-dynamic-13.1.3.tgz#08cbe321e5f39636a08eb77606ff496df478a21e" - integrity sha512-vEWyJ+2gkwh2N6KOJfxUNSdSO51ROlzCqqzCfHrPYQrlOFUfKsYKA1uoiB5UGfFEU0HBtIRWn6xoUy3wzVOZbw== +"@angular/platform-browser-dynamic@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/platform-browser-dynamic/-/platform-browser-dynamic-13.3.0-rc.0.tgz#58a026ccb334635ba110b465406f5b60cedd1df7" + integrity sha512-wbhKytZ5lZAwIc5EKaK/sDxiDO+9qfMrS9NoetCeLic3jR8NSsfh/HSR8EDVOyd79BZJcu2+UmrEE2B+0BTaPw== dependencies: tslib "^2.3.0" -"@angular/platform-browser@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-13.1.3.tgz#69d90b10e89e11f14f5798d1b6fd788255a6114e" - integrity sha512-mnWjdr9UTNZvGk8jPI6O9FIhun8Q/0ghy3dg3I9AfRzEG4vPiIZW1ICksTiB+jV9etzhKpidtmg71bwgeXax1A== +"@angular/platform-browser@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/platform-browser/-/platform-browser-13.3.0-rc.0.tgz#6947744322e75e1261726d62b241c0841c268475" + integrity sha512-j67E3/hUpQRaCFtvZMJjdpp/fYPVYgH5PCgVS2VWaxcKhIWFtGIYlirnyKyfz+eJl8hxcSZhJkyIOAP+zdDebA== dependencies: tslib "^2.3.0" -"@angular/platform-server@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/platform-server/-/platform-server-13.1.3.tgz#8cda1104622ae2a12cb34cbd72d268f2905b8bba" - integrity sha512-uwfz5UJLUtvhIk83Ecdx0rkhyNg3rdjmbgtWvf2os4Q4lDnbg9y77MKQ9rKJtHqXtrhD9a4W/hAEsFJjexNQBg== +"@angular/platform-server@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/platform-server/-/platform-server-13.3.0-rc.0.tgz#7644f5c282fe3ed0186946d58cc3fce8dc92c6d0" + integrity sha512-n2gcJT52zGQuWBe4SYwIsHBrA5dc+rDyfPr8yTB8aXhi1whzARXZFHKnTcrqp57rkoKe6LNvtnOimA98QddwTw== dependencies: domino "^2.1.2" tslib "^2.3.0" xhr2 "^0.2.0" -"@angular/router@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/router/-/router-13.1.3.tgz#2330254febabce55061236f1761a03aae9a9418f" - integrity sha512-L86kARlc5UNi5KeI0O8PO7wFbTzjEI8ouz+z+aNmCnMUUNX0rbvbuXiPdDvLc71nKZznsPCl2IuO8ojyHrSPsQ== +"@angular/router@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/router/-/router-13.3.0-rc.0.tgz#27668447a7433360b437e7785bd3594cf6444ba3" + integrity sha512-3v+irs21mU1uVgw+HktaKtM67uCkY8zOmnCwMqbpoDz+EAcnqbkdRUeLNmNXPALVp5mGxCvwtsWgf+8AH52NaA== dependencies: tslib "^2.3.0" -"@angular/service-worker@13.1.3": - version "13.1.3" - resolved "https://registry.yarnpkg.com/@angular/service-worker/-/service-worker-13.1.3.tgz#a673d28d97cf6e1a245f24a70e84d6c3fb8cc909" - integrity sha512-R9Oaw/ao62J9OlVKaAMB6WF0n+PD/Jg98c5I04DE14YMcGO32pYOCLPA6oTubwW3gJndk+WSNqijSBXMvaVFsw== +"@angular/service-worker@13.3.0-rc.0": + version "13.3.0-rc.0" + resolved "https://registry.yarnpkg.com/@angular/service-worker/-/service-worker-13.3.0-rc.0.tgz#57c66bb2e48fa4e89c8d2d1bd46be06f51e9ab6c" + integrity sha512-obd7v5HJPHpN6RNAAzUk9ccS9c7icvt6T3lfYsBBd+sGFlaUfSXDtC2xg7lGcEr6k1H4HEBZPG07DP+TorUlEg== dependencies: tslib "^2.3.0" @@ -331,7 +337,7 @@ resolved "https://registry.yarnpkg.com/@assemblyscript/loader/-/loader-0.10.1.tgz#70e45678f06c72fa2e350e8553ec4a4d72b92e06" integrity sha512-H71nDOOL8Y7kWRLqf6Sums+01Q5msqBW2KhDUTemh1tvY04eSkSXrK0uj/4mmY0Xr16/3zyZmsrxN7CKuRbNRg== -"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.16.7", "@babel/code-frame@^7.8.3": +"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.16.7.tgz#44416b6bd7624b998f5b1af5d470856c40138789" integrity sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg== @@ -343,7 +349,7 @@ resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.16.8.tgz#31560f9f29fdf1868de8cb55049538a1b9732a60" integrity sha512-m7OkX0IdKLKPpBlJtF561YJal5y/jyI5fNfWbPxh2D/nbzzGI4qRyrD8xO2jB24u7l+5I2a43scCG2IrfjC50Q== -"@babel/core@7.16.12", "@babel/core@^7.12.3", "@babel/core@^7.16.0", "@babel/core@^7.7.5", "@babel/core@^7.8.6": +"@babel/core@7.16.12", "@babel/core@^7.12.3", "@babel/core@^7.16.0", "@babel/core@^7.7.5": version "7.16.12" resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.16.12.tgz#5edc53c1b71e54881315923ae2aedea2522bb784" integrity sha512-dK5PtG1uiN2ikk++5OzSYsitZKny4wOCD0nrO4TqnW4BVBTQ2NGS3NgilvT/TEyxTST7LNyWV/T4tXDoD3fOgg== @@ -364,28 +370,49 @@ semver "^6.3.0" source-map "^0.5.0" -"@babel/core@7.8.6": - version "7.8.6" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.8.6.tgz#27d7df9258a45c2e686b6f18b6c659e563aa4636" - integrity sha512-Sheg7yEJD51YHAvLEV/7Uvw95AeWqYPL3Vk3zGujJKIhJ+8oLw2ALaf3hbucILhKsgSoADOvtKRJuNVdcJkOrg== - dependencies: - "@babel/code-frame" "^7.8.3" - "@babel/generator" "^7.8.6" - "@babel/helpers" "^7.8.4" - "@babel/parser" "^7.8.6" - "@babel/template" "^7.8.6" - "@babel/traverse" "^7.8.6" - "@babel/types" "^7.8.6" +"@babel/core@7.17.2": + version "7.17.2" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.17.2.tgz#2c77fc430e95139d816d39b113b31bf40fb22337" + integrity sha512-R3VH5G42VSDolRHyUO4V2cfag8WHcZyxdq5Z/m8Xyb92lW/Erm/6kM+XtRFGf3Mulre3mveni2NHfEUws8wSvw== + dependencies: + "@ampproject/remapping" "^2.0.0" + "@babel/code-frame" "^7.16.7" + "@babel/generator" "^7.17.0" + "@babel/helper-compilation-targets" "^7.16.7" + "@babel/helper-module-transforms" "^7.16.7" + "@babel/helpers" "^7.17.2" + "@babel/parser" "^7.17.0" + "@babel/template" "^7.16.7" + "@babel/traverse" "^7.17.0" + "@babel/types" "^7.17.0" + convert-source-map "^1.7.0" + debug "^4.1.0" + gensync "^1.0.0-beta.2" + json5 "^2.1.2" + semver "^6.3.0" + +"@babel/core@^7.17.2": + version "7.17.5" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.17.5.tgz#6cd2e836058c28f06a4ca8ee7ed955bbf37c8225" + integrity sha512-/BBMw4EvjmyquN5O+t5eh0+YqB3XXJkYD2cjKpYtWOfFy4lQ4UozNSmxAcWT8r2XtZs0ewG+zrfsqeR15i1ajA== + dependencies: + "@ampproject/remapping" "^2.1.0" + "@babel/code-frame" "^7.16.7" + "@babel/generator" "^7.17.3" + "@babel/helper-compilation-targets" "^7.16.7" + "@babel/helper-module-transforms" "^7.16.7" + "@babel/helpers" "^7.17.2" + "@babel/parser" "^7.17.3" + "@babel/template" "^7.16.7" + "@babel/traverse" "^7.17.3" + "@babel/types" "^7.17.0" convert-source-map "^1.7.0" debug "^4.1.0" - gensync "^1.0.0-beta.1" - json5 "^2.1.0" - lodash "^4.17.13" - resolve "^1.3.2" - semver "^5.4.1" - source-map "^0.5.0" + gensync "^1.0.0-beta.2" + json5 "^2.1.2" + semver "^6.3.0" -"@babel/generator@7.16.8", "@babel/generator@^7.16.8", "@babel/generator@^7.8.6": +"@babel/generator@7.16.8", "@babel/generator@^7.16.8": version "7.16.8" resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.16.8.tgz#359d44d966b8cd059d543250ce79596f792f2ebe" integrity sha512-1ojZwE9+lOXzcWdWmO6TbUzDfqLD39CmEhN8+2cX9XkDo5yW1OpgfejfliysR2AWLpMamTiOiAp/mtroaymhpw== @@ -394,6 +421,15 @@ jsesc "^2.5.1" source-map "^0.5.0" +"@babel/generator@^7.17.0", "@babel/generator@^7.17.3": + version "7.17.3" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.17.3.tgz#a2c30b0c4f89858cb87050c3ffdfd36bdf443200" + integrity sha512-+R6Dctil/MgUsZsZAkYgK+ADNSZzJRRy0TvY65T71z/CR854xHQ1EweBYXdfT+HNeN7w0cSJJEzgxZMv40pxsg== + dependencies: + "@babel/types" "^7.17.0" + jsesc "^2.5.1" + source-map "^0.5.0" + "@babel/helper-annotate-as-pure@7.16.7", "@babel/helper-annotate-as-pure@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz#bb2339a7534a9c128e3102024c60760a3a7f3862" @@ -592,7 +628,7 @@ "@babel/traverse" "^7.16.8" "@babel/types" "^7.16.8" -"@babel/helpers@^7.16.7", "@babel/helpers@^7.8.4": +"@babel/helpers@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.16.7.tgz#7e3504d708d50344112767c3542fc5e357fffefc" integrity sha512-9ZDoqtfY7AuEOt3cxchfii6C7GDyyMBffktR5B2jvWv8u2+efwvpnVKXMWzNehqy68tKgAfSwfdw/lWpthS2bw== @@ -601,6 +637,15 @@ "@babel/traverse" "^7.16.7" "@babel/types" "^7.16.7" +"@babel/helpers@^7.17.2": + version "7.17.2" + resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.17.2.tgz#23f0a0746c8e287773ccd27c14be428891f63417" + integrity sha512-0Qu7RLR1dILozr/6M0xgj+DFPmi6Bnulgm9M8BVa9ZCWxDqlSnqt3cf8IDPB5m45sVXUZ0kuQAgUrdSFFH79fQ== + dependencies: + "@babel/template" "^7.16.7" + "@babel/traverse" "^7.17.0" + "@babel/types" "^7.17.0" + "@babel/highlight@^7.16.7": version "7.16.10" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.16.10.tgz#744f2eb81579d6eea753c227b0f570ad785aba88" @@ -610,11 +655,16 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.16.10", "@babel/parser@^7.16.12", "@babel/parser@^7.16.7", "@babel/parser@^7.8.6": +"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.16.10", "@babel/parser@^7.16.12", "@babel/parser@^7.16.7": version "7.16.12" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.16.12.tgz#9474794f9a650cf5e2f892444227f98e28cdf8b6" integrity sha512-VfaV15po8RiZssrkPweyvbGVSe4x2y+aciFCgn0n0/SJMR22cwofRV1mtnJQYcSB1wUTaA/X1LnA3es66MCO5A== +"@babel/parser@^7.17.0", "@babel/parser@^7.17.3": + version "7.17.3" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.17.3.tgz#b07702b982990bf6fdc1da5049a23fece4c5c3d0" + integrity sha512-7yJPvPV+ESz2IUTPbOL+YkIGyCqOyNIzdguKQuJGnH7bg1WTIifuM21YqokFt/THWh1AkCRn9IgoykTRCBVpzA== + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.16.7.tgz#4eda6d6c2a0aa79c70fa7b6da67763dfe2141050" @@ -1217,7 +1267,7 @@ dependencies: regenerator-runtime "^0.13.4" -"@babel/template@7.16.7", "@babel/template@^7.16.7", "@babel/template@^7.8.6": +"@babel/template@7.16.7", "@babel/template@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.16.7.tgz#8d126c8701fde4d66b264b3eba3d96f07666d155" integrity sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w== @@ -1226,7 +1276,7 @@ "@babel/parser" "^7.16.7" "@babel/types" "^7.16.7" -"@babel/traverse@^7.13.0", "@babel/traverse@^7.16.10", "@babel/traverse@^7.16.7", "@babel/traverse@^7.16.8", "@babel/traverse@^7.8.6": +"@babel/traverse@^7.13.0", "@babel/traverse@^7.16.10", "@babel/traverse@^7.16.7", "@babel/traverse@^7.16.8": version "7.16.10" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.16.10.tgz#448f940defbe95b5a8029975b051f75993e8239f" integrity sha512-yzuaYXoRJBGMlBhsMJoUW7G1UmSb/eXr/JHYM/MsOJgavJibLwASijW7oXBdw3NQ6T0bW7Ty5P/VarOs9cHmqw== @@ -1242,7 +1292,23 @@ debug "^4.1.0" globals "^11.1.0" -"@babel/types@^7.0.0", "@babel/types@^7.16.0", "@babel/types@^7.16.7", "@babel/types@^7.16.8", "@babel/types@^7.3.0", "@babel/types@^7.4.4", "@babel/types@^7.8.6": +"@babel/traverse@^7.17.0", "@babel/traverse@^7.17.3": + version "7.17.3" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.17.3.tgz#0ae0f15b27d9a92ba1f2263358ea7c4e7db47b57" + integrity sha512-5irClVky7TxRWIRtxlh2WPUUOLhcPN06AGgaQSB8AEwuyEBgJVuJ5imdHm5zxk8w0QS5T+tDfnDxAlhWjpb7cw== + dependencies: + "@babel/code-frame" "^7.16.7" + "@babel/generator" "^7.17.3" + "@babel/helper-environment-visitor" "^7.16.7" + "@babel/helper-function-name" "^7.16.7" + "@babel/helper-hoist-variables" "^7.16.7" + "@babel/helper-split-export-declaration" "^7.16.7" + "@babel/parser" "^7.17.3" + "@babel/types" "^7.17.0" + debug "^4.1.0" + globals "^11.1.0" + +"@babel/types@^7.0.0", "@babel/types@^7.16.0", "@babel/types@^7.16.7", "@babel/types@^7.16.8", "@babel/types@^7.3.0", "@babel/types@^7.4.4": version "7.16.8" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.16.8.tgz#0ba5da91dd71e0a4e7781a30f22770831062e3c1" integrity sha512-smN2DQc5s4M7fntyjGtyIPbRJv6wW4rU/94fmYJ7PKQuZkC0qGMHXJbg6sNGt12JmVr4k5YaptI/XtiLJBnmIg== @@ -1250,6 +1316,14 @@ "@babel/helper-validator-identifier" "^7.16.7" to-fast-properties "^2.0.0" +"@babel/types@^7.17.0": + version "7.17.0" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.17.0.tgz#a826e368bccb6b3d84acd76acad5c0d87342390b" + integrity sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw== + dependencies: + "@babel/helper-validator-identifier" "^7.16.7" + to-fast-properties "^2.0.0" + "@bazel/bazelisk@1.11.0", "@bazel/bazelisk@^1.10.1": version "1.11.0" resolved "https://registry.yarnpkg.com/@bazel/bazelisk/-/bazelisk-1.11.0.tgz#f98d8438b4c14e3328126618b96775d271caa5f8" @@ -1418,6 +1492,19 @@ resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.3.tgz#b80093f4edbb5490c49746231513669c8f518acb" integrity sha512-fuIOnc81C5iRNevb/XPiM8Khp9bVjreydRQ37rt0C/dY0PAW1DRvEM3WrKX/5rStS5lbgwS0FCgqSndh9tvK5w== +"@jridgewell/sourcemap-codec@^1.4.10": + version "1.4.11" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz#771a1d8d744eeb71b6adb35808e1a6c7b9b8c8ec" + integrity sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg== + +"@jridgewell/trace-mapping@^0.3.0": + version "0.3.4" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.4.tgz#f6a0832dffd5b8a6aaa633b7d9f8e8e94c83a0c3" + integrity sha512-vFv9ttIedivx0ux3QSjhgtCVjPZd5l46ZOMDSCwnH1yUO2e964gO8LZGyv2QkqcgR6TnBU1v+1IFqmeoG+0UJQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@mark.probst/unicode-properties@~1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@mark.probst/unicode-properties/-/unicode-properties-1.1.0.tgz#5caafeab4737df93163d6d288007df33f9939b80" @@ -3564,11 +3651,6 @@ caniuse-lite@^1.0.30001286, caniuse-lite@^1.0.30001297, caniuse-lite@^1.0.300012 resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001301.tgz#ebc9086026534cab0dab99425d9c3b4425e5f450" integrity sha512-csfD/GpHMqgEL3V3uIgosvh+SVIQvCh43SNu9HRbP1lnxkKm1kjDG4f32PP571JplkLjfS+mg2p1gxR7MYrrIA== -canonical-path@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/canonical-path/-/canonical-path-1.0.0.tgz#fcb470c23958def85081856be7a86e904f180d1d" - integrity sha512-feylzsbDxi1gPZ1IjystzIQZagYYLvfKrSuygUCgf7z6x790VEzze5QEkdSV1U58RA7Hi0+v6fv4K54atOzATg== - caseless@~0.12.0: version "0.12.0" resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" @@ -5675,7 +5757,7 @@ gauge@^4.0.0: strip-ansi "^6.0.1" wide-align "^1.1.2" -gensync@^1.0.0-beta.1, gensync@^1.0.0-beta.2: +gensync@^1.0.0-beta.2: version "1.0.0-beta.2" resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== @@ -6880,7 +6962,7 @@ json5@^1.0.1: dependencies: minimist "^1.2.0" -json5@^2.1.0, json5@^2.1.2: +json5@^2.1.2: version "2.2.0" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.0.tgz#2dfefe720c6ba525d9ebd909950f0515316c89a3" integrity sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA== @@ -7293,7 +7375,7 @@ lodash.sortby@^4.7.0: resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438" integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg= -lodash@4, lodash@4.17.21, lodash@^4.17.10, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@~4.17.15: +lodash@4, lodash@4.17.21, lodash@^4.17.10, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@~4.17.15: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== @@ -7364,7 +7446,7 @@ lunr-mutable-indexes@2.3.2: resolved "https://registry.yarnpkg.com/lunr/-/lunr-2.3.9.tgz#18b123142832337dd6e964df1a5a7707b25d35e1" integrity sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow== -magic-string@0.25.7, magic-string@^0.25.0: +magic-string@0.25.7: version "0.25.7" resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.25.7.tgz#3f497d6fd34c669c6798dcb821f2ef31f5445051" integrity sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA== @@ -7378,6 +7460,13 @@ magic-string@^0.22.4: dependencies: vlq "^0.2.2" +magic-string@^0.26.0: + version "0.26.1" + resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.26.1.tgz#ba9b651354fa9512474199acecf9c6dbe93f97fd" + integrity sha512-ndThHmvgtieXe8J/VGPjG+Apu7v7ItcD5mhEIvOscWjPF/ccOiLxHaSuCAS2G+3x4GKsAbT8u7zdyamupui8Tg== + dependencies: + sourcemap-codec "^1.4.8" + make-dir@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-2.1.0.tgz#5f0310e18b8be898cc07009295a30ae41e91e6f5" @@ -9725,7 +9814,7 @@ selfsigned@^2.0.0: dependencies: node-forge "^1.2.0" -"semver@2 || 3 || 4 || 5", semver@^5.3.0, semver@^5.4.1, semver@^5.5.0, semver@^5.6.0: +"semver@2 || 3 || 4 || 5", semver@^5.3.0, semver@^5.5.0, semver@^5.6.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== @@ -10877,7 +10966,12 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@4.5.5, typescript@~4.5.0, typescript@~4.5.2: +typescript@4.6.2: + version "4.6.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.6.2.tgz#fe12d2727b708f4eef40f51598b3398baa9611d4" + integrity sha512-HM/hFigTBHZhLXshn9sN37H085+hQGeJHJ/X7LpBWLID/fbc2acUMfU+lGD98X81sKP+pFa9f0DZmCwB9GnbAg== + +typescript@~4.5.0, typescript@~4.5.2: version "4.5.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== From fd55a001e456a6c09af2dab6eeffc69f426cd31a Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 14 Mar 2022 09:12:33 +0100 Subject: [PATCH 10/63] build: update version to 13.3.0 Bumps up the version to 13.3.0-next.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 320b7b9d083e..2b0b961dcf67 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.2.6", + "version": "13.3.0-next.0", "private": true, "description": "Software Development Kit for Angular", "bin": { From 3367ec796f4fffbcba5168cfc95036f523fd91d4 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 14 Mar 2022 19:07:29 +0100 Subject: [PATCH 11/63] build: update webpack to 5.70.0 This brings a couple of fixes to HMR, one of which is double reloaded. See: https://github.com/webpack/webpack/releases/tag/v5.70.0 Closes #22839 --- package.json | 2 +- .../angular_devkit/build_angular/package.json | 2 +- .../build_optimizer/package.json | 2 +- .../angular_devkit/build_webpack/package.json | 2 +- packages/ngtools/webpack/package.json | 2 +- yarn.lock | 45 ++++++++++++++++++- 6 files changed, 49 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 2b0b961dcf67..1cf895f9ca47 100644 --- a/package.json +++ b/package.json @@ -218,7 +218,7 @@ "typescript": "4.6.2", "verdaccio": "5.5.1", "verdaccio-auth-memory": "^10.0.0", - "webpack": "5.67.0", + "webpack": "5.70.0", "webpack-dev-middleware": "5.3.0", "webpack-dev-server": "4.7.3", "webpack-merge": "5.8.0", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index fb18e8a53a40..20a1862d242e 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -65,7 +65,7 @@ "text-table": "0.2.0", "tree-kill": "1.2.2", "tslib": "2.3.1", - "webpack": "5.67.0", + "webpack": "5.70.0", "webpack-dev-middleware": "5.3.0", "webpack-dev-server": "4.7.3", "webpack-merge": "5.8.0", diff --git a/packages/angular_devkit/build_optimizer/package.json b/packages/angular_devkit/build_optimizer/package.json index dcf647c7724b..4d67ea7bca98 100644 --- a/packages/angular_devkit/build_optimizer/package.json +++ b/packages/angular_devkit/build_optimizer/package.json @@ -23,6 +23,6 @@ } }, "devDependencies": { - "webpack": "5.67.0" + "webpack": "5.70.0" } } diff --git a/packages/angular_devkit/build_webpack/package.json b/packages/angular_devkit/build_webpack/package.json index ee17ede63032..33cec43e3232 100644 --- a/packages/angular_devkit/build_webpack/package.json +++ b/packages/angular_devkit/build_webpack/package.json @@ -13,7 +13,7 @@ "devDependencies": { "@angular-devkit/core": "0.0.0-PLACEHOLDER", "node-fetch": "2.6.7", - "webpack": "5.67.0" + "webpack": "5.70.0" }, "peerDependencies": { "webpack": "^5.30.0", diff --git a/packages/ngtools/webpack/package.json b/packages/ngtools/webpack/package.json index a6712bd45e61..2a567d6134d6 100644 --- a/packages/ngtools/webpack/package.json +++ b/packages/ngtools/webpack/package.json @@ -31,6 +31,6 @@ "@angular/compiler": "13.3.0-rc.0", "@angular/compiler-cli": "13.3.0-rc.0", "typescript": "4.6.2", - "webpack": "5.67.0" + "webpack": "5.70.0" } } diff --git a/yarn.lock b/yarn.lock index 6020c38c14b4..ebc5e67f6698 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2107,7 +2107,7 @@ dependencies: "@types/ms" "*" -"@types/eslint-scope@^3.7.0": +"@types/eslint-scope@^3.7.0", "@types/eslint-scope@^3.7.3": version "3.7.3" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.3.tgz#125b88504b61e3c8bc6f870882003253005c3224" integrity sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g== @@ -2133,6 +2133,11 @@ resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f" integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw== +"@types/estree@^0.0.51": + version "0.0.51" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" + integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== + "@types/express-serve-static-core@*", "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" @@ -4720,6 +4725,14 @@ enhanced-resolve@^5.8.3: graceful-fs "^4.2.4" tapable "^2.2.0" +enhanced-resolve@^5.9.2: + version "5.9.2" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.9.2.tgz#0224dcd6a43389ebfb2d55efee517e5466772dd9" + integrity sha512-GIm3fQfwLJ8YZx2smuHpBKkXC1yOk+OBEmKckVyL0i/ea8mqDEykK3ld5dgH1QYPNyT/lIllxV2LULnxCHaHkA== + dependencies: + graceful-fs "^4.2.4" + tapable "^2.2.0" + ent@~2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/ent/-/ent-2.2.0.tgz#e964219325a21d05f44466a2f686ed6ce5f5dd1d" @@ -11427,6 +11440,36 @@ webpack@5.67.0: watchpack "^2.3.1" webpack-sources "^3.2.3" +webpack@5.70.0: + version "5.70.0" + resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.70.0.tgz#3461e6287a72b5e6e2f4872700bc8de0d7500e6d" + integrity sha512-ZMWWy8CeuTTjCxbeaQI21xSswseF2oNOwc70QSKNePvmxE7XW36i7vpBMYZFAUHPwQiEbNGCEYIOOlyRbdGmxw== + dependencies: + "@types/eslint-scope" "^3.7.3" + "@types/estree" "^0.0.51" + "@webassemblyjs/ast" "1.11.1" + "@webassemblyjs/wasm-edit" "1.11.1" + "@webassemblyjs/wasm-parser" "1.11.1" + acorn "^8.4.1" + acorn-import-assertions "^1.7.6" + browserslist "^4.14.5" + chrome-trace-event "^1.0.2" + enhanced-resolve "^5.9.2" + es-module-lexer "^0.9.0" + eslint-scope "5.1.1" + events "^3.2.0" + glob-to-regexp "^0.4.1" + graceful-fs "^4.2.9" + json-parse-better-errors "^1.0.2" + loader-runner "^4.2.0" + mime-types "^2.1.27" + neo-async "^2.6.2" + schema-utils "^3.1.0" + tapable "^2.1.1" + terser-webpack-plugin "^5.1.3" + watchpack "^2.3.1" + webpack-sources "^3.2.3" + websocket-driver@>=0.5.1, websocket-driver@^0.7.4: version "0.7.4" resolved "https://registry.yarnpkg.com/websocket-driver/-/websocket-driver-0.7.4.tgz#89ad5295bbf64b480abcba31e4953aca706f5760" From 501aee739301f9c7b479c8dbbc43fd839ef90706 Mon Sep 17 00:00:00 2001 From: Doug Parker Date: Wed, 16 Mar 2022 12:02:53 -0700 Subject: [PATCH 12/63] refactor: bump CLI version to `13.3.0-rc.0` We won't actually be releasing an RC, but this is necessary for the release tool to understand that it will do a minor release from this branch. --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1cf895f9ca47..21d2bd1cf7ce 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.0-next.0", + "version": "13.3.0-rc.0", "private": true, "description": "Software Development Kit for Angular", "bin": { From 983271f536d60b4171ca04542103b6c9b637e44a Mon Sep 17 00:00:00 2001 From: Doug Parker Date: Wed, 16 Mar 2022 12:20:28 -0700 Subject: [PATCH 13/63] release: cut the v13.3.0 release Also bumps FW dependency to `13.3.0`. --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- .../angular/utility/latest-versions.ts | 2 +- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 534afad68ae9..8231980a1a7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.0 (2022-03-16) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------- | +| [c995ed5e8](https://github.com/angular/angular-cli/commit/c995ed5e8a8e1b20cf376f4c48c5141fd5f4548a) | feat | support TypeScript 4.6 | + +## Special Thanks + +Alan Agius and Doug Parker + + + # 13.2.6 (2022-03-09) diff --git a/package.json b/package.json index 21d2bd1cf7ce..aa752ddef23a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.0-rc.0", + "version": "13.3.0", "private": true, "description": "Software Development Kit for Angular", "bin": { diff --git a/packages/schematics/angular/utility/latest-versions.ts b/packages/schematics/angular/utility/latest-versions.ts index 71a2e1b6bd28..8f6d273ae4ff 100644 --- a/packages/schematics/angular/utility/latest-versions.ts +++ b/packages/schematics/angular/utility/latest-versions.ts @@ -15,7 +15,7 @@ export const latestVersions: Record & { ...require('./latest-versions/package.json')['dependencies'], // As Angular CLI works with same minor versions of Angular Framework, a tilde match for the current - Angular: '~13.3.0-rc.0', + Angular: '~13.3.0', // Since @angular-devkit/build-angular and @schematics/angular are always // published together from the same monorepo, and they are both From 9f8d4dea0449e236de7b928c5cc97e597a6f5844 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 22 Mar 2022 13:07:12 +0100 Subject: [PATCH 14/63] fix(@angular-devkit/architect-cli): update `minimist` to `1.2.6` Closes #22872 --- packages/angular_devkit/architect_cli/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/angular_devkit/architect_cli/package.json b/packages/angular_devkit/architect_cli/package.json index cf4eb5b91c76..87473b4d380f 100644 --- a/packages/angular_devkit/architect_cli/package.json +++ b/packages/angular_devkit/architect_cli/package.json @@ -17,7 +17,7 @@ "@angular-devkit/architect": "0.0.0-EXPERIMENTAL-PLACEHOLDER", "@angular-devkit/core": "0.0.0-PLACEHOLDER", "ansi-colors": "4.1.1", - "minimist": "1.2.5", + "minimist": "1.2.6", "progress": "2.0.3", "rxjs": "6.6.7", "symbol-observable": "4.0.0" From ba3486de94e733addf0ac17706b806dd813c9046 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 22 Mar 2022 13:07:34 +0100 Subject: [PATCH 15/63] fix(@angular-devkit/schematics-cli): update `minimist` to `1.2.6` Closes #22872 --- packages/angular_devkit/schematics_cli/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/angular_devkit/schematics_cli/package.json b/packages/angular_devkit/schematics_cli/package.json index bc89f9a4db8a..91cdf2df3cb4 100644 --- a/packages/angular_devkit/schematics_cli/package.json +++ b/packages/angular_devkit/schematics_cli/package.json @@ -20,7 +20,7 @@ "@angular-devkit/schematics": "0.0.0-PLACEHOLDER", "ansi-colors": "4.1.1", "inquirer": "8.2.0", - "minimist": "1.2.5", + "minimist": "1.2.6", "symbol-observable": "4.0.0" } } From 1f7fa6970e8cddb2ba0c42df0e048a57292b7fe8 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 22 Mar 2022 13:08:00 +0100 Subject: [PATCH 16/63] fix(@angular-devkit/benchmark): update `minimist` to `1.2.6` Closes #22872 --- packages/angular_devkit/benchmark/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/angular_devkit/benchmark/package.json b/packages/angular_devkit/benchmark/package.json index 46e224be3e82..ea0da287fec2 100644 --- a/packages/angular_devkit/benchmark/package.json +++ b/packages/angular_devkit/benchmark/package.json @@ -12,7 +12,7 @@ "dependencies": { "@angular-devkit/core": "0.0.0-PLACEHOLDER", "ansi-colors": "4.1.1", - "minimist": "1.2.5", + "minimist": "1.2.6", "pidusage": "3.0.0", "pidtree": "0.5.0", "rxjs": "6.6.7", From ff0430d48bf8dbaf77c5895b05bdfdce6227c351 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 22 Mar 2022 13:15:10 +0100 Subject: [PATCH 17/63] build: update `minimist` to `1.2.6` --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index aa752ddef23a..25577f63dab5 100644 --- a/package.json +++ b/package.json @@ -173,7 +173,7 @@ "magic-string": "0.25.7", "mini-css-extract-plugin": "2.5.3", "minimatch": "3.0.4", - "minimist": "^1.2.0", + "minimist": "1.2.6", "ng-packagr": "13.1.3", "node-fetch": "^2.2.0", "npm-package-arg": "8.1.5", diff --git a/yarn.lock b/yarn.lock index ebc5e67f6698..1857dfd2b604 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7729,10 +7729,10 @@ minimist-options@4.1.0: is-plain-obj "^1.1.0" kind-of "^6.0.3" -minimist@1.2.5, minimist@^1.1.3, minimist@^1.2.0, minimist@^1.2.5: - version "1.2.5" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602" - integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw== +minimist@1.2.6, minimist@^1.1.3, minimist@^1.2.0, minimist@^1.2.5: + version "1.2.6" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" + integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minipass-collect@^1.0.2: version "1.0.2" From c7c75820f1d4ef827336626b78c8c3e5c0bd1f00 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 10 Nov 2021 15:53:47 +0100 Subject: [PATCH 18/63] fix(@angular-devkit/core): add Angular CLI major version as analytics dimension With this change we replace the custom dimension 8 `AOT Enabled`, with `Angular CLI Major Version`. The motivation behind replacing this dimension is that the there is already an `aot` dimension with id 13 which serves for the same purpose. More information to why we need a new dimension for the Angular CLI major version can be found #22130 Closes #22130 (cherry picked from commit 455aeea12d8509a526a28cf126899e60c4a21cef) --- docs/design/analytics.md | 2 +- goldens/public-api/angular_devkit/core/src/index.md | 2 +- packages/angular/cli/models/analytics-collector.ts | 3 +++ .../build_angular/src/webpack/configs/analytics.ts | 9 +-------- .../build_angular/src/webpack/plugins/analytics.ts | 3 --- packages/angular_devkit/core/src/analytics/index.ts | 4 ++-- 6 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/design/analytics.md b/docs/design/analytics.md index a3a2785eeba5..67772ea01787 100644 --- a/docs/design/analytics.md +++ b/docs/design/analytics.md @@ -51,7 +51,7 @@ Note: There's a limit of 20 custom dimensions. | 5 | `Flag: --style` | `string` | | 6 | `--collection` | `string` | | 7 | `Flag: --strict` | `boolean` | -| 8 | `AOT Enabled` | `boolean` | +| 8 | `Angular CLI Major Version` | `string` | | 9 | `Flag: --inline-style` | `boolean` | | 10 | `Flag: --inline-template` | `boolean` | | 11 | `Flag: --view-encapsulation` | `string` | diff --git a/goldens/public-api/angular_devkit/core/src/index.md b/goldens/public-api/angular_devkit/core/src/index.md index d69e42a702fe..1e8b875cf721 100644 --- a/goldens/public-api/angular_devkit/core/src/index.md +++ b/goldens/public-api/angular_devkit/core/src/index.md @@ -1074,7 +1074,7 @@ class MultiAnalytics implements Analytics { // @public enum NgCliAnalyticsDimensions { // (undocumented) - AotEnabled = 8, + AngularCLIMajorVersion = 8, // (undocumented) BuildErrors = 20, // (undocumented) diff --git a/packages/angular/cli/models/analytics-collector.ts b/packages/angular/cli/models/analytics-collector.ts index 6754d5037059..fb5fbc2fae88 100644 --- a/packages/angular/cli/models/analytics-collector.ts +++ b/packages/angular/cli/models/analytics-collector.ts @@ -117,6 +117,9 @@ export class AnalyticsCollector implements analytics.Analytics { os.totalmem() / (1024 * 1024 * 1024), ); this.parameters['cd' + analytics.NgCliAnalyticsDimensions.NodeVersion] = nodeVersion; + + this.parameters['cd' + analytics.NgCliAnalyticsDimensions.AngularCLIMajorVersion] = + VERSION.major; } event(ec: string, ea: string, options: analytics.EventOptions = {}): void { diff --git a/packages/angular_devkit/build_angular/src/webpack/configs/analytics.ts b/packages/angular_devkit/build_angular/src/webpack/configs/analytics.ts index 06bbf2d5d505..05a8e7aa3831 100644 --- a/packages/angular_devkit/build_angular/src/webpack/configs/analytics.ts +++ b/packages/angular_devkit/build_angular/src/webpack/configs/analytics.ts @@ -28,13 +28,6 @@ export function getAnalyticsConfig( // The category is the builder name if it's an angular builder. return { - plugins: [ - new NgBuildAnalyticsPlugin( - wco.projectRoot, - context.analytics, - category, - wco.buildOptions.aot ?? false, - ), - ], + plugins: [new NgBuildAnalyticsPlugin(wco.projectRoot, context.analytics, category)], }; } diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/analytics.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/analytics.ts index d793455fc537..185ac24e440c 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/analytics.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/analytics.ts @@ -81,7 +81,6 @@ export class NgBuildAnalyticsPlugin { protected _projectRoot: string, protected _analytics: analytics.Analytics, protected _category: string, - private aotEnabled: boolean, ) {} protected _reset() { @@ -115,8 +114,6 @@ export class NgBuildAnalyticsPlugin { dimensions[analytics.NgCliAnalyticsDimensions.BuildErrors] = `,${this._stats.errors.join()},`; } - dimensions[analytics.NgCliAnalyticsDimensions.AotEnabled] = this.aotEnabled; - return dimensions; } diff --git a/packages/angular_devkit/core/src/analytics/index.ts b/packages/angular_devkit/core/src/analytics/index.ts index f99cef1b213a..223c79b93aca 100644 --- a/packages/angular_devkit/core/src/analytics/index.ts +++ b/packages/angular_devkit/core/src/analytics/index.ts @@ -27,7 +27,7 @@ export enum NgCliAnalyticsDimensions { RamInGigabytes = 3, NodeVersion = 4, NgAddCollection = 6, - AotEnabled = 8, + AngularCLIMajorVersion = 8, BuildErrors = 20, } @@ -57,7 +57,7 @@ export const NgCliAnalyticsDimensionsFlagInfo: { [name: string]: [string, string RamInGigabytes: ['RAM (In GB)', 'number'], NodeVersion: ['Node Version', 'number'], NgAddCollection: ['--collection', 'string'], - AotEnabled: ['AOT Enabled', 'boolean'], + AngularCLIMajorVersion: ['Angular CLI Major Version', 'string'], BuildErrors: ['Build Errors (comma separated)', 'string'], }; From 3814df56812ce79d34640e1c1e3c2d4ce5beb375 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 23 Mar 2022 14:53:36 +0100 Subject: [PATCH 19/63] refactor(@angular-devkit/build-angular): remove types for `@discoveryjs/json-ext` This package now ships TypeScript declaration files. (cherry picked from commit 56b44aba744bd9241b1d030e4f15a64fda396425) --- packages/angular_devkit/build_angular/src/typings.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/typings.d.ts b/packages/angular_devkit/build_angular/src/typings.d.ts index 78ac0d8ee009..204fa0d207d0 100644 --- a/packages/angular_devkit/build_angular/src/typings.d.ts +++ b/packages/angular_devkit/build_angular/src/typings.d.ts @@ -6,10 +6,6 @@ * found in the LICENSE file at https://angular.io/license */ -declare module '@discoveryjs/json-ext' { - export function stringifyStream(value: unknown): import('stream').Readable; -} - declare module '@babel/helper-annotate-as-pure' { export default function annotateAsPure( pathOrNode: import('@babel/types').Node | { node: import('@babel/types').Node }, From 6ef9e2a4fa61a37b5cbed925aa6b08e3522c6c65 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 28 Mar 2022 14:52:05 +0200 Subject: [PATCH 20/63] build: update `sass` to `1.49.9` Includes a fix where inspecting the Sass module in the Node.js console crashed on Node 16 and 17. --- package.json | 2 +- packages/angular_devkit/build_angular/package.json | 2 +- yarn.lock | 9 +++++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 25577f63dab5..ac7a359f18fe 100644 --- a/package.json +++ b/package.json @@ -196,7 +196,7 @@ "regenerator-runtime": "0.13.9", "resolve-url-loader": "5.0.0", "rxjs": "6.6.7", - "sass": "1.49.0", + "sass": "1.49.9", "sass-loader": "12.4.0", "sauce-connect-proxy": "https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz", "semver": "7.3.5", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 20a1862d242e..ce39934dbf5c 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -54,7 +54,7 @@ "regenerator-runtime": "0.13.9", "resolve-url-loader": "5.0.0", "rxjs": "6.6.7", - "sass": "1.49.0", + "sass": "1.49.9", "sass-loader": "12.4.0", "semver": "7.3.5", "source-map-loader": "3.0.1", diff --git a/yarn.lock b/yarn.lock index 1857dfd2b604..b002d256b4cb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9740,6 +9740,15 @@ sass@1.49.0, sass@^1.32.8: immutable "^4.0.0" source-map-js ">=0.6.2 <2.0.0" +sass@1.49.9: + version "1.49.9" + resolved "https://registry.yarnpkg.com/sass/-/sass-1.49.9.tgz#b15a189ecb0ca9e24634bae5d1ebc191809712f9" + integrity sha512-YlYWkkHP9fbwaFRZQRXgDi3mXZShslVmmo+FVK3kHLUELHHEYrCmL1x6IUjC7wLS6VuJSAFXRQS/DxdsC4xL1A== + dependencies: + chokidar ">=3.0.0 <4.0.0" + immutable "^4.0.0" + source-map-js ">=0.6.2 <2.0.0" + "sauce-connect-proxy@https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz": version "0.0.0" resolved "https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz#992e2cb0d91e54b27a4f5bbd2049f3b774718115" From 58ed97410b760909d523b05c3b4a06364e3c9a0f Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 28 Mar 2022 20:48:44 +0200 Subject: [PATCH 21/63] fix(@angular-devkit/build-angular): allow Workers in Stackblitz This is no longer needed as Stackblitz implemented the missing Node.Js worker APIs. (cherry picked from commit 2ab77429bb213a515a2334ff6c577be561117108) --- .../src/webpack/configs/styles.ts | 29 +++++-------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/webpack/configs/styles.ts b/packages/angular_devkit/build_angular/src/webpack/configs/styles.ts index 742cc7f83993..113813b6493c 100644 --- a/packages/angular_devkit/build_angular/src/webpack/configs/styles.ts +++ b/packages/angular_devkit/build_angular/src/webpack/configs/styles.ts @@ -107,16 +107,14 @@ export function getStylesConfig(wco: WebpackConfigOptions): Configuration { ); } - const sassImplementation = getSassImplementation(); - if (sassImplementation instanceof SassWorkerImplementation) { - extraPlugins.push({ - apply(compiler) { - compiler.hooks.shutdown.tap('sass-worker', () => { - sassImplementation?.close(); - }); - }, - }); - } + const sassImplementation = new SassWorkerImplementation(); + extraPlugins.push({ + apply(compiler) { + compiler.hooks.shutdown.tap('sass-worker', () => { + sassImplementation.close(); + }); + }, + }); const assetNameTemplate = assetNameTemplateFactory(hashFormat); @@ -403,14 +401,3 @@ export function getStylesConfig(wco: WebpackConfigOptions): Configuration { plugins: extraPlugins, }; } - -function getSassImplementation(): SassWorkerImplementation | typeof import('sass') { - const { webcontainer } = process.versions as unknown as Record; - - // When `webcontainer` is a truthy it means that we are running in a StackBlitz webcontainer. - // `SassWorkerImplementation` uses `receiveMessageOnPort` Node.js `worker_thread` API to ensure sync behavior which is ~2x faster. - // However, it is non trivial to support this in a webcontainer and while slower we choose to use `dart-sass` - // which in Webpack uses the slower async path. - // We should periodically check with StackBlitz folks (Mark Whitfeld / Dominic Elm) to determine if this workaround is still needed. - return webcontainer ? require('sass') : new SassWorkerImplementation(); -} From 4cd2331d34e2a9ab2ed78edf0284dbfefef511a5 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 30 Mar 2022 12:11:12 +0200 Subject: [PATCH 22/63] fix(@angular-devkit/build-angular): don't override asset info when updating assets Currently, we are overriding asset info instead of appending additional data to it. (cherry picked from commit fac9cca66bef73ce403314609a51e63a2764ccbe) --- .../src/webpack/plugins/css-optimizer-plugin.ts | 10 +++++++--- .../webpack/plugins/javascript-optimizer-plugin.ts | 10 +++++++--- .../src/webpack/plugins/transfer-size-plugin.ts | 11 ++++++++--- 3 files changed, 22 insertions(+), 9 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts index 00ecefdc5676..e87c611c91dc 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts @@ -71,9 +71,10 @@ export class CssOptimizerPlugin { if (cachedOutput) { await this.addWarnings(compilation, cachedOutput.warnings); - compilation.updateAsset(name, cachedOutput.source, { + compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({ + ...assetInfo, minimized: true, - }); + })); continue; } } @@ -93,7 +94,10 @@ export class CssOptimizerPlugin { const optimizedAsset = map ? new SourceMapSource(code, name, map) : new OriginalSource(code, name); - compilation.updateAsset(name, optimizedAsset, { minimized: true }); + compilation.updateAsset(name, optimizedAsset, (assetInfo) => ({ + ...assetInfo, + minimized: true, + })); await cacheItem?.storePromise({ source: optimizedAsset, diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts index 8b78f86c5da6..bc252387f1f8 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts @@ -123,9 +123,10 @@ export class JavaScriptOptimizerPlugin { >(); if (cachedOutput) { - compilation.updateAsset(name, cachedOutput.source, { + compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({ + ...assetInfo, minimized: true, - }); + })); continue; } } @@ -209,7 +210,10 @@ export class JavaScriptOptimizerPlugin { const optimizedAsset = map ? new SourceMapSource(code, name, map) : new OriginalSource(code, name); - compilation.updateAsset(name, optimizedAsset, { minimized: true }); + compilation.updateAsset(name, optimizedAsset, (assetInfo) => ({ + ...assetInfo, + minimized: true, + })); return cacheItem?.storePromise({ source: optimizedAsset, diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/transfer-size-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/transfer-size-plugin.ts index 2d61b27d7634..246bab0db6fc 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/transfer-size-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/transfer-size-plugin.ts @@ -39,9 +39,14 @@ export class TransferSizePlugin { actions.push( brotliCompressAsync(scriptAsset.source.source()) .then((result) => { - compilation.updateAsset(assetName, (s) => s, { - estimatedTransferSize: result.length, - }); + compilation.updateAsset( + assetName, + (s) => s, + (assetInfo) => ({ + ...assetInfo, + estimatedTransferSize: result.length, + }), + ); }) .catch((error) => { compilation.warnings.push( From cf3cb2ecf9ca47a984c4272f0094f2a1c68c7dfe Mon Sep 17 00:00:00 2001 From: gauravsoni119 Date: Tue, 29 Mar 2022 22:46:47 +0200 Subject: [PATCH 23/63] fix(@schematics/angular): fix extra comma added when use --change-detection=onPush and --style=none to generate a component (cherry picked from commit a5e99762ef0bb05a23823d4923a2863e0b232ec9) --- ...dasherize__.__type@dasherize__.ts.template | 6 ++--- .../angular/component/index_spec.ts | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template b/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template index e972ffdcb2b2..442a76f98278 100644 --- a/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template +++ b/packages/schematics/angular/component/files/__name@dasherize@if-flat__/__name@dasherize__.__type@dasherize__.ts.template @@ -6,15 +6,15 @@ import { Component, OnInit<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }

<%= dasherize(name) %> works!

- `,<% } else { %> - templateUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.html',<% } if(inlineStyle) { %> + `<% } else { %> + templateUrl: './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.html'<% } if(inlineStyle) { %>, styles: [<% if(displayBlock){ %> ` :host { display: block; } `<% } %> - ]<% } else if (style !== 'none') { %> + ]<% } else if (style !== 'none') { %>, styleUrls: ['./<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>.<%= style %>']<% } %><% if(!!viewEncapsulation) { %>, encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>, changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %> diff --git a/packages/schematics/angular/component/index_spec.ts b/packages/schematics/angular/component/index_spec.ts index 233d3ea1836f..14235575b3b0 100644 --- a/packages/schematics/angular/component/index_spec.ts +++ b/packages/schematics/angular/component/index_spec.ts @@ -397,4 +397,27 @@ describe('Component Schematic', () => { ); expect(tree.files).not.toContain('/projects/bar/src/app/foo/foo.component.spec.ts'); }); + + it('should respect templateUrl when style=none and changeDetection=OnPush', async () => { + const options = { ...defaultOptions, style: Style.None, changeDetection: 'OnPush' }; + const tree = await schematicRunner.runSchematicAsync('component', options, appTree).toPromise(); + const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); + expect(content).not.toMatch(/styleUrls: /); + expect(content).toMatch(/templateUrl: '.\/foo.component.html',\n/); + expect(content).toMatch(/changeDetection: ChangeDetectionStrategy.OnPush/); + }); + + it('should respect inlineTemplate when style=none and changeDetection=OnPush', async () => { + const options = { + ...defaultOptions, + style: Style.None, + changeDetection: 'OnPush', + inlineTemplate: true, + }; + const tree = await schematicRunner.runSchematicAsync('component', options, appTree).toPromise(); + const content = tree.readContent('/projects/bar/src/app/foo/foo.component.ts'); + expect(content).not.toMatch(/styleUrls: /); + expect(content).toMatch(/template: `(\n(.|)*){3}\n\s*`,\n/); + expect(content).toMatch(/changeDetection: ChangeDetectionStrategy.OnPush/); + }); }); From 293526c31db9f0becc0ffc2d60999c80afa8a308 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 30 Mar 2022 17:15:15 +0200 Subject: [PATCH 24/63] fix(@angular-devkit/build-angular): add `node_modules` prefix to excludes RegExp Without the `node_modules` prefix, projects named the same as the excluded package names ex: `webpack` will not compile successfully as all files under the mentioned project will be excluded from being requested by the respective loaders. Closes #22902 (cherry picked from commit 371da23be0d0b1fd880d93c68049fcac97685120) --- .../build_angular/src/webpack/configs/common.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/webpack/configs/common.ts b/packages/angular_devkit/build_angular/src/webpack/configs/common.ts index 545d877a4c80..446bfcfdc663 100644 --- a/packages/angular_devkit/build_angular/src/webpack/configs/common.ts +++ b/packages/angular_devkit/build_angular/src/webpack/configs/common.ts @@ -261,7 +261,9 @@ export async function getCommonConfig(wco: WebpackConfigOptions): Promise Date: Wed, 30 Mar 2022 11:55:19 -0700 Subject: [PATCH 25/63] release: cut the v13.3.1 release --- CHANGELOG.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8231980a1a7e..50dffbff352a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,51 @@ + + +# 13.3.1 (2022-03-30) + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------- | +| [cf3cb2ecf](https://github.com/angular/angular-cli/commit/cf3cb2ecf9ca47a984c4272f0094f2a1c68c7dfe) | fix | fix extra comma added when use --change-detection=onPush and --style=none to generate a component | + +### @angular-devkit/architect-cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------- | +| [9f8d4dea0](https://github.com/angular/angular-cli/commit/9f8d4dea0449e236de7b928c5cc97e597a6f5844) | fix | update `minimist` to `1.2.6` | + +### @angular-devkit/schematics-cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------- | +| [ba3486de9](https://github.com/angular/angular-cli/commit/ba3486de94e733addf0ac17706b806dd813c9046) | fix | update `minimist` to `1.2.6` | + +### @angular-devkit/benchmark + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------- | +| [1f7fa6970](https://github.com/angular/angular-cli/commit/1f7fa6970e8cddb2ba0c42df0e048a57292b7fe8) | fix | update `minimist` to `1.2.6` | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------- | +| [293526c31](https://github.com/angular/angular-cli/commit/293526c31db9f0becc0ffc2d60999c80afa8a308) | fix | add `node_modules` prefix to excludes RegExp | +| [58ed97410](https://github.com/angular/angular-cli/commit/58ed97410b760909d523b05c3b4a06364e3c9a0f) | fix | allow Workers in Stackblitz | +| [4cd2331d3](https://github.com/angular/angular-cli/commit/4cd2331d34e2a9ab2ed78edf0284dbfefef511a5) | fix | don't override asset info when updating assets | + +### @angular-devkit/core + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------- | +| [c7c75820f](https://github.com/angular/angular-cli/commit/c7c75820f1d4ef827336626b78c8c3e5c0bd1f00) | fix | add Angular CLI major version as analytics dimension | + +## Special Thanks + +Alan Agius and gauravsoni119 + + + # 13.3.0 (2022-03-16) diff --git a/package.json b/package.json index ac7a359f18fe..d2f94159b874 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.0", + "version": "13.3.1", "private": true, "description": "Software Development Kit for Angular", "bin": { From c97c8e7c9bbcad66ba80967681cac46042c3aca7 Mon Sep 17 00:00:00 2001 From: Morga Cezary Date: Fri, 1 Apr 2022 09:46:06 +0200 Subject: [PATCH 26/63] fix(@angular-devkit/build-angular): update `minimatch` dependency to `3.0.5` Update build-angular's minimatch dependency to v3.0.5 as a result of VULNDB-282782. See: https://huntr.dev/bounties/e4e1393c-d590-4492-9f43-8be3f3321629/ --- package.json | 2 +- packages/angular_devkit/build_angular/package.json | 2 +- yarn.lock | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index d2f94159b874..cbc8b2c06cf5 100644 --- a/package.json +++ b/package.json @@ -172,7 +172,7 @@ "loader-utils": "3.2.0", "magic-string": "0.25.7", "mini-css-extract-plugin": "2.5.3", - "minimatch": "3.0.4", + "minimatch": "3.0.5", "minimist": "1.2.6", "ng-packagr": "13.1.3", "node-fetch": "^2.2.0", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index ce39934dbf5c..3c83f5db86fe 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -42,7 +42,7 @@ "license-webpack-plugin": "4.0.2", "loader-utils": "3.2.0", "mini-css-extract-plugin": "2.5.3", - "minimatch": "3.0.4", + "minimatch": "3.0.5", "open": "8.4.0", "ora": "5.4.1", "parse5-html-rewriting-stream": "6.0.1", diff --git a/yarn.lock b/yarn.lock index b002d256b4cb..2a87ca7597e9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7713,10 +7713,10 @@ minimalistic-assert@^1.0.0: resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== -"minimatch@2 || 3", minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== +"minimatch@2 || 3", minimatch@3.0.5, minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.5: + version "3.0.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.5.tgz#4da8f1290ee0f0f8e83d60ca69f8f134068604a3" + integrity sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw== dependencies: brace-expansion "^1.1.7" From bbe74b87e52579c06b911db6173f33c67b8010a6 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 1 Apr 2022 15:20:24 +0200 Subject: [PATCH 27/63] fix(@schematics/angular): provide actionable error message when routing declaration cannot be found Due to incorrect castings previously the code would crash when the module doesn't contain an routing module with the following error: ``` Cannot read property 'properties' of undefined ``` Closes #21397 (cherry picked from commit 7db433bb066cc077d0c1cff7668d557c1c17160f) --- .../schematics/angular/utility/ast-utils.ts | 63 ++++++++++--------- .../angular/utility/ast-utils_spec.ts | 17 ++++- .../schematics/angular/utility/find-module.ts | 14 ++--- 3 files changed, 54 insertions(+), 40 deletions(-) diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index cec6ab579cd6..56bde71bc187 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -189,7 +189,6 @@ export function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] { export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.Node | null { if (node.kind === kind && node.getText() === text) { - // throw new Error(node.getText()); return node; } @@ -367,29 +366,28 @@ export function addSymbolToNgModuleMetadata( importPath: string | null = null, ): Change[] { const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core'); - let node: any = nodes[0]; // eslint-disable-line @typescript-eslint/no-explicit-any + const node = nodes[0]; // Find the decorator declaration. - if (!node) { + if (!node || !ts.isObjectLiteralExpression(node)) { return []; } // Get all the children property assignment of object literals. - const matchingProperties = getMetadataField(node as ts.ObjectLiteralExpression, metadataField); + const matchingProperties = getMetadataField(node, metadataField); if (matchingProperties.length == 0) { // We haven't found the field in the metadata declaration. Insert a new field. - const expr = node as ts.ObjectLiteralExpression; let position: number; let toInsert: string; - if (expr.properties.length == 0) { - position = expr.getEnd() - 1; + if (node.properties.length == 0) { + position = node.getEnd() - 1; toInsert = `\n ${metadataField}: [\n${tags.indentBy(4)`${symbolName}`}\n ]\n`; } else { - node = expr.properties[expr.properties.length - 1]; - position = node.getEnd(); + const childNode = node.properties[node.properties.length - 1]; + position = childNode.getEnd(); // Get the indentation of the last element, if any. - const text = node.getFullText(source); + const text = childNode.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = @@ -408,40 +406,40 @@ export function addSymbolToNgModuleMetadata( return [new InsertChange(ngModulePath, position, toInsert)]; } } - const assignment = matchingProperties[0] as ts.PropertyAssignment; + const assignment = matchingProperties[0]; // If it's not an array, nothing we can do really. - if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { + if ( + !ts.isPropertyAssignment(assignment) || + !ts.isArrayLiteralExpression(assignment.initializer) + ) { return []; } - const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression; - if (arrLiteral.elements.length == 0) { - // Forward the property. - node = arrLiteral; - } else { - node = arrLiteral.elements; - } + let expresssion: ts.Expression | ts.ArrayLiteralExpression; + const assignmentInit = assignment.initializer; + const elements = assignmentInit.elements; - if (Array.isArray(node)) { - const nodeArray = (node as {}) as Array; - const symbolsArray = nodeArray.map((node) => tags.oneLine`${node.getText()}`); + if (elements.length) { + const symbolsArray = elements.map((node) => tags.oneLine`${node.getText()}`); if (symbolsArray.includes(tags.oneLine`${symbolName}`)) { return []; } - node = node[node.length - 1]; + expresssion = elements[elements.length - 1]; + } else { + expresssion = assignmentInit; } let toInsert: string; - let position = node.getEnd(); - if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) { + let position = expresssion.getEnd(); + if (ts.isArrayLiteralExpression(expresssion)) { // We found the field but it's empty. Insert it just before the `]`. position--; toInsert = `\n${tags.indentBy(4)`${symbolName}`}\n `; } else { // Get the indentation of the last element, if any. - const text = node.getFullText(source); + const text = expresssion.getFullText(source); const matches = text.match(/^(\r?\n)(\s*)/); if (matches) { toInsert = `,${matches[1]}${tags.indentBy(matches[2].length)`${symbolName}`}`; @@ -449,6 +447,7 @@ export function addSymbolToNgModuleMetadata( toInsert = `, ${symbolName}`; } } + if (importPath !== null) { return [ new InsertChange(ngModulePath, position, toInsert), @@ -604,9 +603,12 @@ export function getEnvironmentExportName(source: ts.SourceFile): string | null { */ export function getRouterModuleDeclaration(source: ts.SourceFile): ts.Expression | undefined { const result = getDecoratorMetadata(source, 'NgModule', '@angular/core'); - const node = result[0] as ts.ObjectLiteralExpression; - const matchingProperties = getMetadataField(node, 'imports'); + const node = result[0]; + if (!node || !ts.isObjectLiteralExpression(node)) { + return undefined; + } + const matchingProperties = getMetadataField(node, 'imports'); if (!matchingProperties) { return; } @@ -634,7 +636,10 @@ export function addRouteDeclarationToModule( ): Change { const routerModuleExpr = getRouterModuleDeclaration(source); if (!routerModuleExpr) { - throw new Error(`Couldn't find a route declaration in ${fileToAdd}.`); + throw new Error( + `Couldn't find a route declaration in ${fileToAdd}.\n` + + `Use the '--module' option to specify a different routing module.`, + ); } const scopeConfigMethodArgs = (routerModuleExpr as ts.CallExpression).arguments; if (!scopeConfigMethodArgs.length) { diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts index 54ed6d6d936d..fd305aa355b5 100644 --- a/packages/schematics/angular/utility/ast-utils_spec.ts +++ b/packages/schematics/angular/utility/ast-utils_spec.ts @@ -260,7 +260,7 @@ describe('ast utils', () => { const elements = (arrayNode.pop() as ts.ArrayLiteralExpression).elements; const change = insertAfterLastOccurrence( - (elements as unknown) as ts.Node[], + elements as unknown as ts.Node[], `, 'bar'`, filePath, elements.pos, @@ -281,7 +281,7 @@ describe('ast utils', () => { const elements = (arrayNode.pop() as ts.ArrayLiteralExpression).elements; const change = insertAfterLastOccurrence( - (elements as unknown) as ts.Node[], + elements as unknown as ts.Node[], `'bar'`, filePath, elements.pos, @@ -312,7 +312,7 @@ describe('ast utils', () => { const source = getTsSource(modulePath, moduleContent); const change = () => addRouteDeclarationToModule(source, './src/app', ''); - expect(change).toThrowError(`Couldn't find a route declaration in ./src/app.`); + expect(change).toThrowError(/Couldn't find a route declaration in \.\/src\/app/); }); it(`should throw an error when router module doesn't have arguments`, () => { @@ -632,6 +632,17 @@ describe('ast utils', () => { /RouterModule\.forRoot\(\[\r?\n?\s*{ path: 'foo', component: FooComponent },\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]\)/, ); }); + + it('should error if sourcefile is empty', () => { + const change = () => + addRouteDeclarationToModule( + getTsSource(modulePath, ''), + './src/app', + `{ path: 'foo', component: FooComponent }`, + ); + + expect(change).toThrowError(/Couldn't find a route declaration in \.\/src\/app/); + }); }); describe('findNodes', () => { diff --git a/packages/schematics/angular/utility/find-module.ts b/packages/schematics/angular/utility/find-module.ts index 3c87085f5452..a420f07eb052 100644 --- a/packages/schematics/angular/utility/find-module.ts +++ b/packages/schematics/angular/utility/find-module.ts @@ -54,11 +54,9 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path const candidatesDirs = [...candidateSet].sort((a, b) => b.length - a.length); for (const c of candidatesDirs) { - const candidateFiles = [ - '', - `${moduleBaseName}.ts`, - `${moduleBaseName}${moduleExt}`, - ].map((x) => join(c, x)); + const candidateFiles = ['', `${moduleBaseName}.ts`, `${moduleBaseName}${moduleExt}`].map( + (x) => join(c, x), + ); for (const sc of candidateFiles) { if (host.exists(sc)) { @@ -96,7 +94,7 @@ export function findModule( return join(dir.path, filteredMatches[0]); } else if (filteredMatches.length > 1) { throw new Error( - 'More than one module matches. Use the skip-import option to skip importing ' + + `More than one module matches. Use the '--skip-import' option to skip importing ` + 'the component into the closest module or use the module option to specify a module.', ); } @@ -107,8 +105,8 @@ export function findModule( const errorMsg = foundRoutingModule ? 'Could not find a non Routing NgModule.' + `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.` + - '\nUse the skip-import option to skip importing in NgModule.' - : 'Could not find an NgModule. Use the skip-import option to skip importing in NgModule.'; + `\nUse the '--skip-import' option to skip importing in NgModule.` + : `Could not find an NgModule. Use the '--skip-import' option to skip importing in NgModule.`; throw new Error(errorMsg); } From 49dc63d09a7a7f2b7759b47e79fac934b867e9b4 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Mon, 4 Apr 2022 11:04:10 -0400 Subject: [PATCH 28/63] fix(@angular/cli): ensure lint command auto-add exits after completion When no lint target is present for a project, the command will ask if linting should be added to the project. However, after adding the package, the command incorrectly kept executing and then failing due to the lint command not being fully setup yet. Instead, the command will now exit after adding the linting package. This also allows inspection and/or adjustment of the linting configuration prior to actually linting. Fixes: #22937 --- packages/angular/cli/commands/lint-impl.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/angular/cli/commands/lint-impl.ts b/packages/angular/cli/commands/lint-impl.ts index e9fb4dc801b3..eb4c5d5fcfc1 100644 --- a/packages/angular/cli/commands/lint-impl.ts +++ b/packages/angular/cli/commands/lint-impl.ts @@ -50,8 +50,9 @@ export class LintCommand extends ArchitectCommand { if (error) { throw error; } - - return status ?? 0; } + + // Return an exit code to force the command to exit after adding the package + return 1; } } From 2715aa76070f314626b1bd4b04ca29ea6d979930 Mon Sep 17 00:00:00 2001 From: Joey Perrott Date: Wed, 6 Apr 2022 10:22:52 -0700 Subject: [PATCH 29/63] release: cut the v13.3.2 release --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50dffbff352a..b529df95b721 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,31 @@ + + +# 13.3.2 (2022-04-06) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------- | +| [49dc63d09](https://github.com/angular/angular-cli/commit/49dc63d09a7a7f2b7759b47e79fac934b867e9b4) | fix | ensure lint command auto-add exits after completion | + +### @schematics/angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------- | +| [bbe74b87e](https://github.com/angular/angular-cli/commit/bbe74b87e52579c06b911db6173f33c67b8010a6) | fix | provide actionable error message when routing declaration cannot be found | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------- | +| [c97c8e7c9](https://github.com/angular/angular-cli/commit/c97c8e7c9bbcad66ba80967681cac46042c3aca7) | fix | update `minimatch` dependency to `3.0.5` | + +## Special Thanks + +Alan Agius, Charles Lyding and Morga Cezary + + + # 13.3.1 (2022-03-30) diff --git a/package.json b/package.json index cbc8b2c06cf5..363825132847 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.1", + "version": "13.3.2", "private": true, "description": "Software Development Kit for Angular", "bin": { From 5682baee4b562b314dad781403dcc0c46e0a8abb Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 11 Apr 2022 11:21:29 +0200 Subject: [PATCH 30/63] fix(@angular-devkit/build-webpack): emit devserver setup errors Closes #22969 (cherry picked from commit 3afd1ab9c0a347950c8477608ad9b81cf75fa891) --- .../build_webpack/src/webpack-dev-server/index.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts b/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts index 353536039f9c..43569f916a9e 100644 --- a/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts +++ b/packages/angular_devkit/build_webpack/src/webpack-dev-server/index.ts @@ -82,7 +82,13 @@ export function runWebpackDevServer( }); const devServer = createWebpackDevServer(webpackCompiler, devServerConfig); - devServer.startCallback(() => { + devServer.startCallback((err) => { + if (err) { + obs.error(err); + + return; + } + const address = devServer.server?.address(); if (!address) { obs.error(new Error(`Dev-server address info is not defined.`)); From d38b247cf19edf5ecf7792343fa2bc8c05a3a8b8 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 11 Apr 2022 12:00:19 +0200 Subject: [PATCH 31/63] fix(@angular-devkit/build-angular): display debug logs when using the `--verbose` option Webpack doesn't display debug logs when setting the log level to verbose. See: https://webpack.js.org/configuration/other-options/#debug and https://webpack.js.org/configuration/other-options/#level (cherry picked from commit be2b268c36f9ae465b9233f7bf705717712e3cf1) --- .../angular_devkit/build_angular/src/webpack/configs/common.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/angular_devkit/build_angular/src/webpack/configs/common.ts b/packages/angular_devkit/build_angular/src/webpack/configs/common.ts index 446bfcfdc663..c99afbf91d3b 100644 --- a/packages/angular_devkit/build_angular/src/webpack/configs/common.ts +++ b/packages/angular_devkit/build_angular/src/webpack/configs/common.ts @@ -415,6 +415,7 @@ export async function getCommonConfig(wco: WebpackConfigOptions): Promise Date: Wed, 13 Apr 2022 15:14:58 -0400 Subject: [PATCH 32/63] release: cut the v13.3.3 release --- CHANGELOG.md | 22 ++++++++++++++++++++++ package.json | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b529df95b721..8b096149e42f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,25 @@ + + +# 13.3.3 (2022-04-13) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------- | +| [d38b247cf](https://github.com/angular/angular-cli/commit/d38b247cf19edf5ecf7792343fa2bc8c05a3a8b8) | fix | display debug logs when using the `--verbose` option | + +### @angular-devkit/build-webpack + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------- | +| [5682baee4](https://github.com/angular/angular-cli/commit/5682baee4b562b314dad781403dcc0c46e0a8abb) | fix | emit devserver setup errors | + +## Special Thanks + +Alan Agius + + + # 13.3.2 (2022-04-06) diff --git a/package.json b/package.json index 363825132847..0abd43ab0f3b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.2", + "version": "13.3.3", "private": true, "description": "Software Development Kit for Angular", "bin": { From f4da756560358273098df2a5cae7848201206c77 Mon Sep 17 00:00:00 2001 From: Wagner Maciel Date: Tue, 26 Apr 2022 11:09:29 -0700 Subject: [PATCH 33/63] fix(@angular/cli): change wrapping of schematic code (cherry picked from commit 4b07aa345d18ae6cb92284cdf13941b61ae69008) --- packages/angular/cli/models/schematic-engine-host.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/angular/cli/models/schematic-engine-host.ts b/packages/angular/cli/models/schematic-engine-host.ts index 57d678321d76..51047475a15d 100644 --- a/packages/angular/cli/models/schematic-engine-host.ts +++ b/packages/angular/cli/models/schematic-engine-host.ts @@ -178,7 +178,9 @@ function wrap( const schematicCode = readFileSync(schematicFile, 'utf8'); // `module` is required due to @angular/localize ng-add being in UMD format const headerCode = '(function() {\nvar exports = {};\nvar module = { exports };\n'; - const footerCode = exportName ? `\nreturn exports['${exportName}'];});` : '\nreturn exports;});'; + const footerCode = exportName + ? `\nreturn module.exports['${exportName}'];});` + : '\nreturn module.exports;});'; const script = new Script(headerCode + schematicCode + footerCode, { filename: schematicFile, From 5d0141bfb4ae80b1a7543eab64e9c381c932eaef Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Wed, 27 Apr 2022 13:43:32 -0400 Subject: [PATCH 34/63] fix(@angular-devkit/build-angular): correctly resolve custom service worker configuration file Paths within the `angular.json` file should be relative to the location of the `angular.json` file. The `ngswConfigPath` option was incorrectly using the current working directory for a base path when a relative configuration path was specified. Most of the time this would work as a build command usually is executed from the root of the workspace. However, this may not always be the case and for those cases the actual workspace root is now used to resolve the full path for the service worker configuration file. --- .../src/builders/app-shell/index.ts | 1 + .../src/builders/browser/index.ts | 1 + .../browser/specs/service-worker_spec.ts | 18 ++++++++++++++++++ .../build_angular/src/utils/service-worker.ts | 3 ++- 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts b/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts index 952d5f392c2e..65df5d19cda7 100644 --- a/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts +++ b/packages/angular_devkit/build_angular/src/builders/app-shell/index.ts @@ -115,6 +115,7 @@ async function _renderUniversal( if (browserOptions.serviceWorker) { await augmentAppWithServiceWorker( projectRoot, + context.workspaceRoot, normalize(outputPath), browserOptions.baseHref || '/', browserOptions.ngswConfigPath, diff --git a/packages/angular_devkit/build_angular/src/builders/browser/index.ts b/packages/angular_devkit/build_angular/src/builders/browser/index.ts index 7aa57d8090fc..2fae066b1914 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/index.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/index.ts @@ -354,6 +354,7 @@ export function buildWebpackBrowser( try { await augmentAppWithServiceWorker( normalize(projectRoot), + context.workspaceRoot, normalize(outputPath), getLocaleBaseHref(i18n, locale) || options.baseHref || '/', options.ngswConfigPath, diff --git a/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts b/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts index ed868f9c3a05..185b0f172b54 100644 --- a/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts +++ b/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts @@ -52,6 +52,24 @@ describe('Browser Builder service worker', () => { await run.stop(); }); + it('supports specifying a custom service worker configuration file', async () => { + host.writeMultipleFiles({ + 'src/configs/ngsw.json': JSON.stringify(manifest), + 'src/assets/folder-asset.txt': 'folder-asset.txt', + 'src/styles.css': `body { background: url(./spectrum.png); }`, + }); + + const overrides = { serviceWorker: true, ngswConfigPath: 'src/configs/ngsw.json' }; + + const run = await architect.scheduleTarget(target, overrides); + + await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); + + await run.stop(); + + expect(host.scopedSync().exists(normalize('dist/ngsw.json'))).toBeTrue(); + }); + it('works with service worker', async () => { host.writeMultipleFiles({ 'src/ngsw-config.json': JSON.stringify(manifest), diff --git a/packages/angular_devkit/build_angular/src/utils/service-worker.ts b/packages/angular_devkit/build_angular/src/utils/service-worker.ts index fef7d9d45adb..765f66d26429 100644 --- a/packages/angular_devkit/build_angular/src/utils/service-worker.ts +++ b/packages/angular_devkit/build_angular/src/utils/service-worker.ts @@ -63,6 +63,7 @@ class CliFilesystem implements Filesystem { export async function augmentAppWithServiceWorker( appRoot: Path, + workspaceRoot: string, outputPath: Path, baseHref: string, ngswConfigPath?: string, @@ -71,7 +72,7 @@ export async function augmentAppWithServiceWorker( // Determine the configuration file path const configPath = ngswConfigPath - ? getSystemPath(normalize(ngswConfigPath)) + ? path.join(workspaceRoot, getSystemPath(normalize(ngswConfigPath))) : path.join(getSystemPath(appRoot), 'ngsw-config.json'); // Read the configuration file From 2caf1ea72204caeeeb87c2197d1ad36dbe3207f7 Mon Sep 17 00:00:00 2001 From: Doug Parker Date: Wed, 27 Apr 2022 13:13:32 -0700 Subject: [PATCH 35/63] release: cut the v13.3.4 release --- CHANGELOG.md | 22 ++++++++++++++++++++++ package.json | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b096149e42f..2f101a20e1dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,25 @@ + + +# 13.3.4 (2022-04-27) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------- | +| [f4da75656](https://github.com/angular/angular-cli/commit/f4da756560358273098df2a5cae7848201206c77) | fix | change wrapping of schematic code | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------- | +| [5d0141bfb](https://github.com/angular/angular-cli/commit/5d0141bfb4ae80b1a7543eab64e9c381c932eaef) | fix | correctly resolve custom service worker configuration file | + +## Special Thanks + +Charles Lyding and Wagner Maciel + + + # 13.3.3 (2022-04-13) diff --git a/package.json b/package.json index 0abd43ab0f3b..10653d992443 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.3", + "version": "13.3.4", "private": true, "description": "Software Development Kit for Angular", "bin": { From f4ecef800f69e1cb67cadd57643e841e6c23a170 Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Mon, 25 Apr 2022 13:15:22 +0000 Subject: [PATCH 36/63] build: changes for primary branch rename to `main`. Changes part of the `DIRECT` phase of the "renaming master to main" planning doc. (cherry picked from commit 8da926966e9f414ceecf60b89acd475ce1b55fc5) --- .ng-dev/github.ts | 2 +- renovate.json | 2 +- scripts/publish.ts | 4 ++-- scripts/snapshots.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.ng-dev/github.ts b/.ng-dev/github.ts index dd8254813ab2..b1af287af493 100644 --- a/.ng-dev/github.ts +++ b/.ng-dev/github.ts @@ -7,5 +7,5 @@ import { GithubConfig } from '@angular/dev-infra-private/ng-dev/utils/config'; export const github: GithubConfig = { owner: 'angular', name: 'angular-cli', - mainBranchName: 'master', + mainBranchName: 'main', }; diff --git a/renovate.json b/renovate.json index ddfaa9bd3e94..bdb893fe33f8 100644 --- a/renovate.json +++ b/renovate.json @@ -10,7 +10,7 @@ "enabled": true }, "schedule": ["after 10pm every weekday", "before 4am every weekday", "every weekend"], - "baseBranches": ["master"], + "baseBranches": ["main"], "ignoreDeps": ["@types/node", "quicktype-core"], "packageFiles": [ "WORKSPACE", diff --git a/scripts/publish.ts b/scripts/publish.ts index 12d4a32fbe7d..631e2bd705b2 100644 --- a/scripts/publish.ts +++ b/scripts/publish.ts @@ -65,10 +65,10 @@ function _branchCheck(args: PublishArgs, logger: logging.Logger) { const branch = ref.trim().replace(/^refs\/heads\//, ''); switch (branch) { - case 'master': + case 'main': if (args.tag !== 'next') { throw new Error(tags.oneLine` - Releasing from master requires a next tag. Use --no-branchCheck to + Releasing from main requires a next tag. Use --no-branchCheck to skip this check. `); } diff --git a/scripts/snapshots.ts b/scripts/snapshots.ts index c1de7a60956c..b9b58046830d 100644 --- a/scripts/snapshots.ts +++ b/scripts/snapshots.ts @@ -144,7 +144,7 @@ export default async function (opts: SnapshotsOptions, logger: logging.Logger) { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'angular-cli-publish-')); const message = execSync(`git log --format="%h %s" -n1`).toString().trim(); - let branch = opts.branch || 'master'; + let branch = opts.branch || 'main'; // CIRCLE_BRANCH if (typeof process.env['CIRCLE_BRANCH'] == 'string') { From 6da0910d345eb84084e32a462432a508d518f402 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 2 May 2022 10:56:48 +0200 Subject: [PATCH 37/63] fix(@angular-devkit/build-angular): update `@ampproject/remapping` to `2.2.0` Closes #22998 --- package.json | 2 +- .../angular_devkit/build_angular/package.json | 2 +- yarn.lock | 45 ++++++++++++++++++- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 10653d992443..6f0f979fe458 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ "ajv-formats/ajv": "8.9.0" }, "devDependencies": { - "@ampproject/remapping": "1.1.1", + "@ampproject/remapping": "2.2.0", "@angular/animations": "13.3.0-rc.0", "@angular/cdk": "13.1.3", "@angular/common": "13.3.0-rc.0", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 3c83f5db86fe..a11d6cbbfd9d 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -6,7 +6,7 @@ "typings": "src/index.d.ts", "builders": "builders.json", "dependencies": { - "@ampproject/remapping": "1.1.1", + "@ampproject/remapping": "2.2.0", "@angular-devkit/architect": "0.0.0-EXPERIMENTAL-PLACEHOLDER", "@angular-devkit/build-webpack": "0.0.0-EXPERIMENTAL-PLACEHOLDER", "@angular-devkit/core": "0.0.0-PLACEHOLDER", diff --git a/yarn.lock b/yarn.lock index 2a87ca7597e9..b01af7c41a11 100644 --- a/yarn.lock +++ b/yarn.lock @@ -34,6 +34,14 @@ "@jridgewell/resolve-uri" "^3.0.3" sourcemap-codec "1.4.8" +"@ampproject/remapping@2.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.2.0.tgz#56c133824780de3174aed5ab6834f3026790154d" + integrity sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w== + dependencies: + "@jridgewell/gen-mapping" "^0.1.0" + "@jridgewell/trace-mapping" "^0.3.9" + "@ampproject/remapping@^2.0.0", "@ampproject/remapping@^2.1.0": version "2.1.2" resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.1.2.tgz#4edca94973ded9630d20101cd8559cedb8d8bd34" @@ -1487,11 +1495,24 @@ resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.3.tgz#e45e384e4b8ec16bce2fd903af78450f6bf7ec98" integrity sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA== +"@jridgewell/gen-mapping@^0.1.0": + version "0.1.1" + resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz#e5d2e450306a9491e3bd77e323e38d7aff315996" + integrity sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w== + dependencies: + "@jridgewell/set-array" "^1.0.0" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@jridgewell/resolve-uri@^3.0.3": version "3.0.3" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.3.tgz#b80093f4edbb5490c49746231513669c8f518acb" integrity sha512-fuIOnc81C5iRNevb/XPiM8Khp9bVjreydRQ37rt0C/dY0PAW1DRvEM3WrKX/5rStS5lbgwS0FCgqSndh9tvK5w== +"@jridgewell/set-array@^1.0.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.0.tgz#1179863356ac8fbea64a5a4bcde93a4871012c01" + integrity sha512-SfJxIxNVYLTsKwzB3MoOQ1yxf4w/E6MdkvTgrgAt1bfxjSrLUoHMKrDOykwN14q65waezZIdqDneUIPh4/sKxg== + "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.11" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz#771a1d8d744eeb71b6adb35808e1a6c7b9b8c8ec" @@ -1505,6 +1526,14 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" +"@jridgewell/trace-mapping@^0.3.9": + version "0.3.9" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@mark.probst/unicode-properties@~1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@mark.probst/unicode-properties/-/unicode-properties-1.1.0.tgz#5caafeab4737df93163d6d288007df33f9939b80" @@ -7713,13 +7742,27 @@ minimalistic-assert@^1.0.0: resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== -"minimatch@2 || 3", minimatch@3.0.5, minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.5: +"minimatch@2 || 3", minimatch@3.0.5, minimatch@^3.0.2, minimatch@^3.0.4: version "3.0.5" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.5.tgz#4da8f1290ee0f0f8e83d60ca69f8f134068604a3" integrity sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw== dependencies: brace-expansion "^1.1.7" +minimatch@3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== + dependencies: + brace-expansion "^1.1.7" + +minimatch@~3.0.4: + version "3.0.8" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.8.tgz#5e6a59bd11e2ab0de1cfb843eb2d82e546c321c1" + integrity sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q== + dependencies: + brace-expansion "^1.1.7" + minimist-options@4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/minimist-options/-/minimist-options-4.1.0.tgz#c0655713c53a8a2ebd77ffa247d342c40f010619" From b5043a7a76a4b52fe9295b508883ce83fa95d363 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Tue, 3 May 2022 16:49:50 -0400 Subject: [PATCH 38/63] build: update SauceLabs connect proxy version to 4.7.1 (cherry picked from commit a2bc9fab33d4a54b8188da7cf8d801ce54b0c6a6) --- package.json | 2 +- yarn.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 6f0f979fe458..0165de4acf2d 100644 --- a/package.json +++ b/package.json @@ -198,7 +198,7 @@ "rxjs": "6.6.7", "sass": "1.49.9", "sass-loader": "12.4.0", - "sauce-connect-proxy": "https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz", + "sauce-connect-proxy": "https://saucelabs.com/downloads/sc-4.7.1-linux.tar.gz", "semver": "7.3.5", "shelljs": "^0.8.5", "source-map": "0.7.3", diff --git a/yarn.lock b/yarn.lock index b01af7c41a11..d5f204d22d2e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9792,9 +9792,9 @@ sass@1.49.9: immutable "^4.0.0" source-map-js ">=0.6.2 <2.0.0" -"sauce-connect-proxy@https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz": +"sauce-connect-proxy@https://saucelabs.com/downloads/sc-4.7.1-linux.tar.gz": version "0.0.0" - resolved "https://saucelabs.com/downloads/sc-4.6.4-linux.tar.gz#992e2cb0d91e54b27a4f5bbd2049f3b774718115" + resolved "https://saucelabs.com/downloads/sc-4.7.1-linux.tar.gz#e5d7f82ad98251a653d1b0537f1103e49eda5e11" saucelabs@^1.5.0: version "1.5.0" From afa1228058920609ed756f004dc123ae413a3804 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Tue, 3 May 2022 17:01:29 -0400 Subject: [PATCH 39/63] ci: remove unneeded view engine browser tests View Engine application builds are no longer supported and the E2E `--ve` option is a no-op. This test execution was running a duplicate Ivy application test as a result. (cherry picked from commit 6ceaaea4f51c5f9fd772598c5046fa7b15c3f183) --- .circleci/config.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 9e3c3960a1d6..aaf1f05ab2b4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -241,7 +241,6 @@ jobs: # Waits for the Saucelabs tunnel to be ready. This ensures that we don't run tests # too early without Saucelabs not being ready. - run: ./scripts/saucelabs/wait-for-tunnel.sh - - run: node ./tests/legacy-cli/run_e2e ./tests/legacy-cli/e2e/tests/misc/browsers.ts --ve - run: node ./tests/legacy-cli/run_e2e ./tests/legacy-cli/e2e/tests/misc/browsers.ts - run: ./scripts/saucelabs/stop-tunnel.sh - fail_fast From 8e3b551bed32ab403490ce588059389f5dbadf39 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Wed, 4 May 2022 15:21:40 -0400 Subject: [PATCH 40/63] release: cut the v13.3.5 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f101a20e1dd..b2d96c151828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.5 (2022-05-04) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------- | +| [6da0910d3](https://github.com/angular/angular-cli/commit/6da0910d345eb84084e32a462432a508d518f402) | fix | update `@ampproject/remapping` to `2.2.0` | + +## Special Thanks + +Alan Agius, Charles Lyding and Paul Gschwendtner + + + # 13.3.4 (2022-04-27) diff --git a/package.json b/package.json index 0165de4acf2d..e976206ad855 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.4", + "version": "13.3.5", "private": true, "description": "Software Development Kit for Angular", "bin": { From 0b39eee897e5278949d84f332fe2c38c771304fb Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Thu, 21 Apr 2022 13:15:20 +0000 Subject: [PATCH 41/63] build: preparation for primary branch rename in the Angular repos Preparation for the framework repo as outlined our planning document. --- .circleci/config.yml | 4 ++++ .github/workflows/scorecard.yml | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index aaf1f05ab2b4..bf49e9a9e77c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -29,6 +29,8 @@ var_5: &only_release_branches filters: branches: only: + - main + # TODO(BRANCH_RENAME_CLEANUP): remove - master - /\d+\.\d+\.x/ @@ -354,6 +356,8 @@ workflows: branches: only: - renovate/angular + - main + # TODO(BRANCH_RENAME_CLEANUP): remove - master - e2e-cli: name: e2e-cli-node-12 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 596a7eafb0fb..b153558e10dc 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -4,7 +4,11 @@ on: schedule: - cron: '0 2 * * 0' push: - branches: [master] + branches: [ + main, + # TODO(BRANCH_RENAME_CLEANUP): remove + master, + ] workflow_dispatch: # Declare default permissions as read only. From 3b484b1b804ff1bd0f1d502af6afbb0edf85e1bf Mon Sep 17 00:00:00 2001 From: Paul Gschwendtner Date: Wed, 4 May 2022 15:40:53 +0000 Subject: [PATCH 42/63] build: cleanup references to old `master` branch Cleans up all referneces to the old `master` branch. --- .circleci/config.yml | 4 --- .github/ISSUE_TEMPLATE/1-bug-report.md | 2 +- .github/ISSUE_TEMPLATE/5-support-request.md | 2 +- .github/SAVED_REPLIES.md | 6 ++-- .github/angular-robot.yml | 8 +++--- .github/workflows/scorecard.yml | 6 +--- CONTRIBUTING.md | 28 +++++++++---------- README.md | 8 +++--- docs/DEVELOPER.md | 2 +- docs/design/build-system.md | 4 +-- docs/process/release.md | 2 +- .../test/hello-world-app/README.md | 2 +- packages/angular_devkit/schematics/README.md | 2 +- packages/ngtools/webpack/package.json | 2 +- scripts/templates/contributing.ejs | 26 ++++++++--------- scripts/templates/readme.ejs | 8 +++--- .../schema/serializers/schema_benchmark.json | 2 +- tests/legacy-cli/e2e_runner.ts | 2 +- 18 files changed, 54 insertions(+), 62 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index bf49e9a9e77c..59a27f1ef258 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -30,8 +30,6 @@ var_5: &only_release_branches branches: only: - main - # TODO(BRANCH_RENAME_CLEANUP): remove - - master - /\d+\.\d+\.x/ # Executor Definitions @@ -357,8 +355,6 @@ workflows: only: - renovate/angular - main - # TODO(BRANCH_RENAME_CLEANUP): remove - - master - e2e-cli: name: e2e-cli-node-12 nodeversion: '12.20' diff --git a/.github/ISSUE_TEMPLATE/1-bug-report.md b/.github/ISSUE_TEMPLATE/1-bug-report.md index bc0cec42df0e..66828cd92bb8 100644 --- a/.github/ISSUE_TEMPLATE/1-bug-report.md +++ b/.github/ISSUE_TEMPLATE/1-bug-report.md @@ -57,7 +57,7 @@ Share the link to the repo below along with step-by-step instructions to reprodu Issues that don't have enough info and can't be reproduced will be closed. -You can read more about issue submission guidelines here: https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#-submitting-an-issue +You can read more about issue submission guidelines here: https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#-submitting-an-issue --> ## 🔥 Exception or Error diff --git a/.github/ISSUE_TEMPLATE/5-support-request.md b/.github/ISSUE_TEMPLATE/5-support-request.md index 509f8d4797bc..3d88b3df0daf 100644 --- a/.github/ISSUE_TEMPLATE/5-support-request.md +++ b/.github/ISSUE_TEMPLATE/5-support-request.md @@ -8,7 +8,7 @@ about: Questions and requests for support Please do not file questions or support requests on the GitHub issues tracker. You can get your questions answered using other communication channels. Please see: -https://github.com/angular/angular-cli/blob/master/CONTRIBUTING.md#question +https://github.com/angular/angular-cli/blob/main/CONTRIBUTING.md#question Thank you! diff --git a/.github/SAVED_REPLIES.md b/.github/SAVED_REPLIES.md index 466b8ad5ee52..06fb24cd1cd6 100644 --- a/.github/SAVED_REPLIES.md +++ b/.github/SAVED_REPLIES.md @@ -29,7 +29,7 @@ Thanks for reporting this issue. However, this issue is a duplicate of # Coding Rules @@ -192,15 +192,15 @@ If the commit reverts a previous commit, it should begin with `revert: `, follow ### Type Must be one of the following: -* **build**: Changes to local repository build system and tooling +* **build**: Changes to local repository build system and tooling * **ci**: Changes to CI configuration and CI specific tooling [2] -* **docs**: Changes which exclusively affects documentation. +* **docs**: Changes which exclusively affects documentation. * **feat**: Creates a new feature [1] * **fix**: Fixes a previously discovered failure/bug [1] * **perf**: Improves performance without any change in functionality or API [1] -* **refactor**: Refactor without any change in functionality or API (includes style changes) +* **refactor**: Refactor without any change in functionality or API (includes style changes) * **release**: A release point in the repository [2] -* **test**: Improvements or corrections made to the project's test suite +* **test**: Improvements or corrections made to the project's test suite [1] This type MUST have a scope. See the next section for more information.
@@ -293,7 +293,7 @@ changes to be accepted, the CLA must be signed. It's a quick process, we promise [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html -[dev-doc]: https://github.com/angular/angular-cli/blob/master/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli +[dev-doc]: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli [GitHub]: https://github.com/angular/angular-cli [gitter]: https://gitter.im/angular/angular-cli [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html diff --git a/README.md b/README.md index 3f3fc0dfff21..0113a346e324 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@
Angular CLI logo

- The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, + The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold,
and maintain Angular applications directly from a command shell.

@@ -37,8 +37,8 @@

- - CI status + + CI status   Discord conversation @@ -194,7 +194,7 @@ This is a monorepo which contains many tools and packages: [filestructure]: https://angular.io/guide/file-structure [node.js]: https://nodejs.org/ [npm]: https://www.npmjs.com/get-npm -[codeofconduct]: https://github.com/angular/angular/blob/master/CODE_OF_CONDUCT.md +[codeofconduct]: https://github.com/angular/angular/blob/main/CODE_OF_CONDUCT.md [twitter]: https://www.twitter.com/angular [discord]: https://discord.gg/angular [gitter]: https://gitter.im/angular/angular-cli diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index c8c58812bebb..bd21df52d6c5 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -78,7 +78,7 @@ There are two different test suites which can be run locally: - Run a subset of the tests, use the full Bazel target example: `yarn bazel test //packages/schematics/angular:angular_test` - For a complete list of test targets use the following Bazel query: `yarn bazel query "tests(//packages/...)"` -You can find more info about debugging [tests with Bazel in the docs.](https://github.com/angular/angular-cli/blob/master/docs/process/bazel.md#debugging-jasmine_node_test) +You can find more info about debugging [tests with Bazel in the docs.](https://github.com/angular/angular-cli/blob/main/docs/process/bazel.md#debugging-jasmine_node_test) ### End to end tests diff --git a/docs/design/build-system.md b/docs/design/build-system.md index fe730f3f9fdd..fbe437ee5157 100644 --- a/docs/design/build-system.md +++ b/docs/design/build-system.md @@ -24,7 +24,7 @@ It's not strictly accurate because some options remove certain processing stages This diagram doesn't show these conditionals and only shows the possible processing steps. Relative paths, such as `./raw-css-loader.ts`, refer to internal plugins, while other names usually refer to public npm packages. -![Overview diagram](https://g.gravizo.com/source/svg?https://raw.githubusercontent.com/angular/angular-cli/master/docs/design/build-system-overview.dot) +![Overview diagram](https://g.gravizo.com/source/svg?https://raw.githubusercontent.com/angular/angular-cli/main/docs/design/build-system-overview.dot) ## Loading and processing sources @@ -128,7 +128,7 @@ We also use Terser's mangling, by which names, but not properties, are renamed t The main characteristics of Terser to keep in mind is that it operates via static analysis and does not support the indirection introduced by module loading. Thus the rest of the pipeline is directed towards providing Terser with code that can be removed via static analysis in large single modules scopes. -To this end we developed [@angular-devkit/build-optimizer](https://github.com/angular/angular-cli/tree/master/packages/angular_devkit/build_optimizer), a post-processing tool for TS code. +To this end we developed [@angular-devkit/build-optimizer](https://github.com/angular/angular-cli/tree/main/packages/angular_devkit/build_optimizer), a post-processing tool for TS code. Build Optimizer searches for code patterns produced by the TypeScript and Angular compiler that are known to inhibit dead code elimination, and converts them into equivalent structures that enable it instead (the link above contains some examples). It also adds Terser [annotations](https://github.com/terser/terser#annotations) marking top-level functions as free from side effects for libraries that have the `sideEffects` flag set to false in `package.json`. diff --git a/docs/process/release.md b/docs/process/release.md index 089edd9983cb..bddd2039e310 100644 --- a/docs/process/release.md +++ b/docs/process/release.md @@ -14,7 +14,7 @@ The caretaker should triage issues, merge PR, and sheppard the release. Caretaker calendar can be found [here](https://calendar.google.com/calendar/embed?src=angular.io_jf53juok1lhpm84hv6bo6fmgbc%40group.calendar.google.com&ctz=America%2FLos_Angeles). Each shift consists of two caretakers. The primary caretaker is responsible for -merging PRs to master and patch whereas the secondary caretaker is responsible +merging PRs to `main` and patch whereas the secondary caretaker is responsible for the release. Primary-secondary pairs are as follows: | Primary | Secondary | diff --git a/packages/angular_devkit/build_angular/test/hello-world-app/README.md b/packages/angular_devkit/build_angular/test/hello-world-app/README.md index fa1c5ca7d3f1..563afe4d4160 100644 --- a/packages/angular_devkit/build_angular/test/hello-world-app/README.md +++ b/packages/angular_devkit/build_angular/test/hello-world-app/README.md @@ -24,4 +24,4 @@ Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protrac ## Further help -To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/main/README.md). diff --git a/packages/angular_devkit/schematics/README.md b/packages/angular_devkit/schematics/README.md index 7fce70c8b80d..b4f47a101e7f 100644 --- a/packages/angular_devkit/schematics/README.md +++ b/packages/angular_devkit/schematics/README.md @@ -23,7 +23,7 @@ What distinguishes Schematics from other generators, such as Yeoman or Yarn Crea # Tooling -Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself. +Schematics is a library, and does not work by itself. A [reference CLI](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics_cli/bin/schematics.ts) is available on this repository, and is published on NPM at [@angular-devkit/schematics-cli](https://www.npmjs.com/package/@angular-devkit/schematics-cli). This document explains the library usage and the tooling API, but does not go into the tool implementation itself. The tooling is responsible for the following tasks: diff --git a/packages/ngtools/webpack/package.json b/packages/ngtools/webpack/package.json index 2a567d6134d6..f0d477594680 100644 --- a/packages/ngtools/webpack/package.json +++ b/packages/ngtools/webpack/package.json @@ -19,7 +19,7 @@ "bugs": { "url": "https://github.com/angular/angular-cli/issues" }, - "homepage": "https://github.com/angular/angular-cli/tree/master/packages/@ngtools/webpack", + "homepage": "https://github.com/angular/angular-cli/tree/main/packages/ngtools/webpack", "dependencies": {}, "peerDependencies": { "@angular/compiler-cli": "^13.0.0", diff --git a/scripts/templates/contributing.ejs b/scripts/templates/contributing.ejs index da62628c12af..34118e8e4af9 100644 --- a/scripts/templates/contributing.ejs +++ b/scripts/templates/contributing.ejs @@ -84,7 +84,7 @@ Before you submit your Pull Request (PR) consider the following guidelines: * Make your changes in a new git branch: ```shell - git checkout -b my-fix-branch master + git checkout -b my-fix-branch main ``` * Create your patch, **including appropriate test cases**. @@ -106,19 +106,19 @@ Before you submit your Pull Request (PR) consider the following guidelines: git push origin my-fix-branch ``` -* In GitHub, send a pull request to `angular/angular-cli:master`. +* In GitHub, send a pull request to `angular/angular-cli:main`. * If we suggest changes then: * Make the required updates. * Re-run the Angular DevKit test suites to ensure tests are still passing. * Once your PR is approved and you are done with any follow up changes: - * Rebase to the current master to pre-emptively address any merge conflicts. + * Rebase to the current main to pre-emptively address any merge conflicts. ```shell - git rebase master -i + git rebase upstream/main -i git push -f ``` * Add the `action: merge` label and the correct -[target label](https://github.com/angular/angular/blob/master/docs/TRIAGE_AND_LABELS.md#pr-target) +[target label](https://github.com/angular/angular/blob/main/docs/TRIAGE_AND_LABELS.md#pr-target) (if PR author has the project collaborator status, or else the last reviewer should do this). * The current caretaker will merge the PR to the target branch(es) within 1-2 @@ -137,10 +137,10 @@ from the main (upstream) repository: git push origin --delete my-fix-branch ``` -* Check out the master branch: +* Check out the main branch: ```shell - git checkout master -f + git checkout main -f ``` * Delete the local branch: @@ -149,10 +149,10 @@ from the main (upstream) repository: git branch -D my-fix-branch ``` -* Update your master with the latest upstream version: +* Update your local `main` with the latest upstream version: ```shell - git pull --ff upstream master + git pull --ff upstream main ``` ## Coding Rules @@ -196,11 +196,11 @@ Must be one of the following: const { COMMIT_TYPES, ScopeRequirement } = require('../../.ng-dev/commit-message'); for (const typeName of Object.keys(COMMIT_TYPES).sort()) { const type = COMMIT_TYPES[typeName]; -%>* **<%= typeName %>**: <%= type.description %> <% +%>* **<%= typeName %>**: <%= type.description %><% if (type.scope == ScopeRequirement.Required) { - %>[1]<% + %> [1]<% } else if (type.scope == ScopeRequirement.Forbidden) { - %>[2]<% + %> [2]<% } %> <% } %> @@ -286,7 +286,7 @@ changes to be accepted, the CLA must be signed. It's a quick process, we promise [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html -[dev-doc]: https://github.com/angular/angular-cli/blob/master/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli +[dev-doc]: https://github.com/angular/angular-cli/blob/main/packages/angular/cli/README.md#development-hints-for-working-on-angular-cli [GitHub]: https://github.com/angular/angular-cli [gitter]: https://gitter.im/angular/angular-cli [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html diff --git a/scripts/templates/readme.ejs b/scripts/templates/readme.ejs index 481a0175c720..8083cbc39961 100644 --- a/scripts/templates/readme.ejs +++ b/scripts/templates/readme.ejs @@ -16,7 +16,7 @@
Angular CLI logo

- The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, + The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold,
and maintain Angular applications directly from a command shell.

@@ -37,8 +37,8 @@

- - CI status + + CI status   Discord conversation @@ -222,7 +222,7 @@ for (const pkgName of Object.keys(packages)) { [filestructure]: https://angular.io/guide/file-structure [node.js]: https://nodejs.org/ [npm]: https://www.npmjs.com/get-npm -[codeofconduct]: https://github.com/angular/angular/blob/master/CODE_OF_CONDUCT.md +[codeofconduct]: https://github.com/angular/angular/blob/main/CODE_OF_CONDUCT.md [twitter]: https://www.twitter.com/angular [discord]: https://discord.gg/angular [gitter]: https://gitter.im/angular/angular-cli diff --git a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json index 8e39ec498f1b..7ec5d5af8a7f 100644 --- a/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json +++ b/tests/angular_devkit/core/json/schema/serializers/schema_benchmark.json @@ -1,6 +1,6 @@ { "$schema": "http://json-schema.org/draft-07/schema", - "$id": "https://github.com/angular/angular-cli/blob/master/packages/@angular/cli/lib/config/schema.json#CliConfig", + "$id": "https://github.com/angular/angular-cli/blob/main/packages/@angular/cli/lib/config/schema.json#CliConfig", "title": "Angular CLI Config Schema", "type": "object", "properties": { diff --git a/tests/legacy-cli/e2e_runner.ts b/tests/legacy-cli/e2e_runner.ts index 6fdc31ec6bdf..7eb9a4f232e2 100644 --- a/tests/legacy-cli/e2e_runner.ts +++ b/tests/legacy-cli/e2e_runner.ts @@ -23,7 +23,7 @@ Error.stackTraceLimit = Infinity; * --noglobal Skip linking your local @angular/cli directory. Can save a few seconds. * --nosilent Never silence ng commands. * --ng-tag=TAG Use a specific tag for build snapshots. Similar to ng-snapshots but point to a - * tag instead of using the latest master. + * tag instead of using the latest `main`. * --ng-snapshots Install angular snapshot builds in the test project. * --ve Use the View Engine compiler. * --glob Run tests matching this glob pattern (relative to tests/e2e/). From b9a8e918cdf1e584a95207c87e420587f6652345 Mon Sep 17 00:00:00 2001 From: Jason Bedard Date: Mon, 9 May 2022 15:22:14 -0700 Subject: [PATCH 43/63] test: allow Artistic-2.0 license (cherry picked from commit e72fbcdfacbb04a129a23c4be1b165499d8a416b) --- scripts/validate-licenses.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/validate-licenses.ts b/scripts/validate-licenses.ts index 8cc1eb0341e9..c72145e2b478 100644 --- a/scripts/validate-licenses.ts +++ b/scripts/validate-licenses.ts @@ -32,6 +32,7 @@ const allowedLicenses = [ 'ISC', 'Apache-2.0', 'Python-2.0', + 'Artistic-2.0', 'BSD-2-Clause', 'BSD-3-Clause', From e20964c43c52125b6d2bfa9bbea444fb2eea1e15 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 18 May 2022 11:48:17 +0000 Subject: [PATCH 44/63] fix(@angular/cli): resolve relative schematic from `angular.json` instead of current working directory Relative schematics referenced in `angular.json` `schematicCollections` and `defaultCollection` were always resolved from the current working directory, which is not correct and caused the collection not to be resolved when the this is different from the location of the workspace config. Closes #23136 --- packages/angular/cli/models/schematic-command.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/angular/cli/models/schematic-command.ts b/packages/angular/cli/models/schematic-command.ts index 884ba71f7d9d..fdda9b9d5905 100644 --- a/packages/angular/cli/models/schematic-command.ts +++ b/packages/angular/cli/models/schematic-command.ts @@ -21,6 +21,7 @@ import { } from '@angular-devkit/schematics/tools'; import * as inquirer from 'inquirer'; import * as systemPath from 'path'; +import { resolve } from 'path'; import { colors } from '../utilities/color'; import { getProjectByCwd, getSchematicDefaults, getWorkspace } from '../utilities/config'; import { parseJsonSchemaToOptions } from '../utilities/json-schema'; @@ -373,6 +374,12 @@ export abstract class SchematicCommand< } protected async getDefaultSchematicCollection(): Promise { + // Resolve relative collections from the location of `angular.json` + const resolveRelativeCollection = (collectionName: string) => + collectionName.charAt(0) === '.' + ? resolve(this.context.root, collectionName) + : collectionName; + let workspace = await getWorkspace('local'); if (workspace) { @@ -380,13 +387,13 @@ export abstract class SchematicCommand< if (project && workspace.getProjectCli(project)) { const value = workspace.getProjectCli(project)['defaultCollection']; if (typeof value == 'string') { - return value; + return resolveRelativeCollection(value); } } if (workspace.getCli()) { const value = workspace.getCli()['defaultCollection']; if (typeof value == 'string') { - return value; + return resolveRelativeCollection(value); } } } @@ -395,7 +402,7 @@ export abstract class SchematicCommand< if (workspace && workspace.getCli()) { const value = workspace.getCli()['defaultCollection']; if (typeof value == 'string') { - return value; + return resolveRelativeCollection(value); } } From 16fec8d58b6ec421df5e7809c45838baf232b4a9 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Wed, 18 May 2022 09:49:23 -0400 Subject: [PATCH 45/63] fix(@angular-devkit/build-angular): update `babel-loader` to 8.2.5 The newer version of `babel-loader` contains a fix for its hash function usage that will cause it to not use MD4 on Node.js versions that no longer support that hashing algorithm. Fixes #23134 --- package.json | 2 +- packages/angular_devkit/build_angular/package.json | 2 +- yarn.lock | 10 ++++++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index e976206ad855..51901e9d57e4 100644 --- a/package.json +++ b/package.json @@ -123,7 +123,7 @@ "ajv": "8.9.0", "ajv-formats": "2.1.1", "ansi-colors": "4.1.1", - "babel-loader": "8.2.3", + "babel-loader": "8.2.5", "babel-plugin-istanbul": "6.1.1", "bootstrap": "^4.0.0", "browserslist": "^4.9.1", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index a11d6cbbfd9d..c5b7da0498f3 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -22,7 +22,7 @@ "@discoveryjs/json-ext": "0.5.6", "@ngtools/webpack": "0.0.0-PLACEHOLDER", "ansi-colors": "4.1.1", - "babel-loader": "8.2.3", + "babel-loader": "8.2.5", "babel-plugin-istanbul": "6.1.1", "browserslist": "^4.9.1", "cacache": "15.3.0", diff --git a/yarn.lock b/yarn.lock index d5f204d22d2e..b73ad4debb42 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3247,6 +3247,16 @@ babel-loader@8.2.3: make-dir "^3.1.0" schema-utils "^2.6.5" +babel-loader@8.2.5: + version "8.2.5" + resolved "https://registry.yarnpkg.com/babel-loader/-/babel-loader-8.2.5.tgz#d45f585e654d5a5d90f5350a779d7647c5ed512e" + integrity sha512-OSiFfH89LrEMiWd4pLNqGz4CwJDtbs2ZVc+iGu2HrkRfPxId9F2anQj38IxWpmRfsUY0aBZYi1EFcd3mhtRMLQ== + dependencies: + find-cache-dir "^3.3.1" + loader-utils "^2.0.0" + make-dir "^3.1.0" + schema-utils "^2.6.5" + babel-plugin-dynamic-import-node@^2.3.3: version "2.3.3" resolved "https://registry.yarnpkg.com/babel-plugin-dynamic-import-node/-/babel-plugin-dynamic-import-node-2.3.3.tgz#84fda19c976ec5c6defef57f9427b3def66e17a3" From 7ffa2f26d1ad82fc57c19cb35539f011f19a7988 Mon Sep 17 00:00:00 2001 From: Doug Parker Date: Wed, 18 May 2022 11:27:40 -0700 Subject: [PATCH 46/63] release: cut the v13.3.6 release --- CHANGELOG.md | 22 ++++++++++++++++++++++ package.json | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d96c151828..ba3e26132e1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,25 @@ + + +# 13.3.6 (2022-05-18) + +### @angular/cli + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------------------- | +| [e20964c43](https://github.com/angular/angular-cli/commit/e20964c43c52125b6d2bfa9bbea444fb2eea1e15) | fix | resolve relative schematic from `angular.json` instead of current working directory | + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------ | +| [16fec8d58](https://github.com/angular/angular-cli/commit/16fec8d58b6ec421df5e7809c45838baf232b4a9) | fix | update `babel-loader` to 8.2.5 | + +## Special Thanks + +Alan Agius, Charles Lyding, Jason Bedard and Paul Gschwendtner + + + # 13.3.5 (2022-05-04) diff --git a/package.json b/package.json index 51901e9d57e4..593bc9d0f54c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.5", + "version": "13.3.6", "private": true, "description": "Software Development Kit for Angular", "bin": { From a54018d8f5f976034bf0a33f826245b7a6b74bbe Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 20 May 2022 12:11:01 +0000 Subject: [PATCH 47/63] fix(@angular-devkit/build-angular): add debugging and timing information in JavaScript and CSS optimization plugins This can be useful to debug slow builds. Example of output ``` LOG from build-angular.JavaScriptOptimizerPlugin optimize asset: runtime.ad5c30339e926c89.js: 221.959564 ms optimize asset: polyfills.ec3ffae5bac27204.js: 1071.080092 ms optimize asset: main.aa8a15155ca2133f.js: 3391.588635 ms optimize js assets: 3483.799739 ms LOG from build-angular.CssOptimizerPlugin optimize asset: styles.d251c5bf54715558.css: 26.569907 ms optimize css assets: 34.441737 ms ``` ``` LOG from build-angular.JavaScriptOptimizerPlugin polyfills.ec3ffae5bac27204.js restored from cache. runtime.ad5c30339e926c89.js restored from cache. optimize asset: main.69fb55a243b46bfa.js: 2618.5191210000003 ms optimize js assets: 2721.226144 ms LOG from build-angular.CssOptimizerPlugin styles.d251c5bf54715558.css restored from cache. optimize css assets: 12.149169 ms ``` (cherry picked from commit 6cbb9413d00db70946421fb44dde218d3e9631dc) --- .../src/webpack/plugins/css-optimizer-plugin.ts | 8 ++++++++ .../src/webpack/plugins/javascript-optimizer-plugin.ts | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts index e87c611c91dc..bd1f6744d341 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/css-optimizer-plugin.ts @@ -40,6 +40,8 @@ export class CssOptimizerPlugin { const { OriginalSource, SourceMapSource } = compiler.webpack.sources; compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const logger = compilation.getLogger('build-angular.CssOptimizerPlugin'); + compilation.hooks.processAssets.tapPromise( { name: PLUGIN_NAME, @@ -48,6 +50,7 @@ export class CssOptimizerPlugin { async (compilationAssets) => { const cache = compilation.options.cache && compilation.getCache(PLUGIN_NAME); + logger.time('optimize css assets'); for (const assetName of Object.keys(compilationAssets)) { if (!/\.(?:css|scss|sass|less|styl)$/.test(assetName)) { continue; @@ -70,6 +73,7 @@ export class CssOptimizerPlugin { >(); if (cachedOutput) { + logger.debug(`${name} restored from cache`); await this.addWarnings(compilation, cachedOutput.warnings); compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({ ...assetInfo, @@ -82,12 +86,15 @@ export class CssOptimizerPlugin { const { source, map: inputMap } = styleAssetSource.sourceAndMap(); const input = typeof source === 'string' ? source : source.toString(); + const optimizeAssetLabel = `optimize asset: ${asset.name}`; + logger.time(optimizeAssetLabel); const { code, warnings, map } = await this.optimize( input, asset.name, inputMap, this.targets, ); + logger.timeEnd(optimizeAssetLabel); await this.addWarnings(compilation, warnings); @@ -104,6 +111,7 @@ export class CssOptimizerPlugin { warnings, }); } + logger.timeEnd('optimize css assets'); }, ); }); diff --git a/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts b/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts index bc252387f1f8..8eb3b4c371e1 100644 --- a/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts +++ b/packages/angular_devkit/build_angular/src/webpack/plugins/javascript-optimizer-plugin.ts @@ -90,12 +90,15 @@ export class JavaScriptOptimizerPlugin { const { OriginalSource, SourceMapSource } = compiler.webpack.sources; compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + const logger = compilation.getLogger('build-angular.JavaScriptOptimizerPlugin'); + compilation.hooks.processAssets.tapPromise( { name: PLUGIN_NAME, stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, }, async (compilationAssets) => { + logger.time('optimize js assets'); const scriptsToOptimize = []; const cache = compilation.options.cache && compilation.getCache('JavaScriptOptimizerPlugin'); @@ -123,6 +126,7 @@ export class JavaScriptOptimizerPlugin { >(); if (cachedOutput) { + logger.debug(`${name} restored from cache`); compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({ ...assetInfo, minimized: true, @@ -195,6 +199,8 @@ export class JavaScriptOptimizerPlugin { try { const tasks = []; for (const { name, code, map, cacheItem } of scriptsToOptimize) { + logger.time(`optimize asset: ${name}`); + tasks.push( workerPool .run({ @@ -215,6 +221,8 @@ export class JavaScriptOptimizerPlugin { minimized: true, })); + logger.timeEnd(`optimize asset: ${name}`); + return cacheItem?.storePromise({ source: optimizedAsset, }); @@ -233,6 +241,8 @@ export class JavaScriptOptimizerPlugin { } finally { void workerPool.destroy(); } + + logger.timeEnd('optimize js assets'); }, ); }); From 6e7ad3e8074f8a425600642ee5a8015985aafec9 Mon Sep 17 00:00:00 2001 From: Joey Perrott Date: Sat, 21 May 2022 20:31:03 +0000 Subject: [PATCH 48/63] build: update saucelabs key Update the saucelabs key for the newly generated key (cherry picked from commit fe3d8ca0b6433f7fd85c6adef3e1ce209e84783d) --- .circleci/env.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/env.sh b/.circleci/env.sh index d24334473255..eef417500d18 100755 --- a/.circleci/env.sh +++ b/.circleci/env.sh @@ -22,7 +22,7 @@ setPublicVar PATH "${HOME}/.npm-global/bin:${PATH}"; # Define SauceLabs environment variables for CircleCI. #################################################################################################### setPublicVar SAUCE_USERNAME "angular-tooling"; -setSecretVar SAUCE_ACCESS_KEY "8c4ffce86ae6-c419-8ef4-0513-54267305"; +setSecretVar SAUCE_ACCESS_KEY "e05dabf6fe0e-2c18-abf4-496d-1d010490"; setPublicVar SAUCE_LOG_FILE /tmp/angular/sauce-connect.log setPublicVar SAUCE_READY_FILE /tmp/angular/sauce-connect-ready-file.lock setPublicVar SAUCE_PID_FILE /tmp/angular/sauce-connect-pid-file.lock From 588b742897e092f3dd726d213f37bd0d92cd341e Mon Sep 17 00:00:00 2001 From: Joey Perrott Date: Wed, 18 May 2022 15:32:21 +0000 Subject: [PATCH 49/63] build: add caretaker configuration to ng-dev config Add the caretaker configuration to set up being able to run both the carataker check and the handoff commands. The caretaker handoff command will operate using the angular-cli-caretaker group which has already been seeded with the current information. (cherry picked from commit 3d76cef369b936a6d01108802cfe7dabca602f2e) --- .ng-dev/caretaker.ts | 16 ++++++++++++++++ .ng-dev/config.ts | 1 + docs/process/release.md | 9 +++++++++ 3 files changed, 26 insertions(+) create mode 100644 .ng-dev/caretaker.ts diff --git a/.ng-dev/caretaker.ts b/.ng-dev/caretaker.ts new file mode 100644 index 000000000000..4feac7d530f5 --- /dev/null +++ b/.ng-dev/caretaker.ts @@ -0,0 +1,16 @@ +import { CaretakerConfig } from '@angular/dev-infra-private/ng-dev'; + +/** The configuration for `ng-dev caretaker` commands. */ +export const caretaker: CaretakerConfig = { + githubQueries: [ + { + name: 'Merge Queue', + query: `is:pr is:open status:success label:"action: merge"`, + }, + { + name: 'Merge Assistance Queue', + query: `is:pr is:open label:"action: merge-assistance"`, + }, + ], + caretakerGroup: 'angular-cli-caretaker', +}; diff --git a/.ng-dev/config.ts b/.ng-dev/config.ts index ea2fc26105a8..681ebe8b510f 100644 --- a/.ng-dev/config.ts +++ b/.ng-dev/config.ts @@ -3,3 +3,4 @@ export { format } from './format'; export { github } from './github'; export { pullRequest } from './pull-request'; export { release } from './release'; +export { caretaker } from './caretaker'; diff --git a/docs/process/release.md b/docs/process/release.md index bddd2039e310..0bb9244b62ec 100644 --- a/docs/process/release.md +++ b/docs/process/release.md @@ -23,6 +23,15 @@ for the release. Primary-secondary pairs are as follows: | Charles | Keen | | Filipe | Joey | +At the end of each caretaker's rotation, they should peform a handoff in which they provide +information to the next caretaker about the current state of the repository and update the +access group to now include the next caretaker and their secondary. To perform this update +to the access group, the caretaker can run: + +```bash +$ yarn ng-dev caretaker handoff +``` + ## Merging PRs The list of PRs which are currently ready to merge (approved with passing status checks) can From 209a49e902d4af3b1179f589adb2437c7ae70959 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 24 May 2022 07:20:23 +0000 Subject: [PATCH 50/63] ci: add nightly CI configuration for version 13 This version will become LTS soon and therefore we enable a nightly CI run. --- .circleci/config.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 59a27f1ef258..ef35fb031659 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -391,3 +391,25 @@ workflows: - build - test - e2e-cli + + nightly: + triggers: + - schedule: + cron: '0 0 * * *' + filters: + branches: + only: + - 13.3.x + jobs: + # Linux jobs + - setup + - build: + requires: + - setup + - e2e-cli: + name: e2e-cli-nightly + requires: + - build + - test-browsers: + requires: + - build From 3168ab6f11da9180ff4fa51a5d2b884173f4ee95 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Tue, 24 May 2022 17:34:51 +0000 Subject: [PATCH 51/63] build: update `CaretakerConfig` import patch Version 13 branch uses an older version of `@angular/dev-infra-private` where configs were exported from a different location. --- .ng-dev/caretaker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ng-dev/caretaker.ts b/.ng-dev/caretaker.ts index 4feac7d530f5..9ce06456f173 100644 --- a/.ng-dev/caretaker.ts +++ b/.ng-dev/caretaker.ts @@ -1,4 +1,4 @@ -import { CaretakerConfig } from '@angular/dev-infra-private/ng-dev'; +import { CaretakerConfig } from '@angular/dev-infra-private/ng-dev/caretaker/config'; /** The configuration for `ng-dev caretaker` commands. */ export const caretaker: CaretakerConfig = { From 8f5a20ab402fe15261d7f4e32a5a4278baa39570 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Wed, 25 May 2022 15:07:18 -0400 Subject: [PATCH 52/63] release: cut the v13.3.7 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba3e26132e1c..1213e723ed62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.7 (2022-05-25) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------- | +| [a54018d8f](https://github.com/angular/angular-cli/commit/a54018d8f5f976034bf0a33f826245b7a6b74bbe) | fix | add debugging and timing information in JavaScript and CSS optimization plugins | + +## Special Thanks + +Alan Agius and Joey Perrott + + + # 13.3.6 (2022-05-18) diff --git a/package.json b/package.json index 593bc9d0f54c..3f2adf50b7a3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.6", + "version": "13.3.7", "private": true, "description": "Software Development Kit for Angular", "bin": { From c7f994f88a396be96c01da1017a15083d5f544fb Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 10 Jun 2022 09:35:58 +0000 Subject: [PATCH 53/63] fix(@angular/pwa): add peer dependency on Angular CLI The peer dependency is needed so that the correct version that matches the installed Angular CLI is installed. (cherry picked from commit d59ba3110b7a12b8f64427609decefbe9d693e90) Closes #23343 --- packages/angular/pwa/package.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/angular/pwa/package.json b/packages/angular/pwa/package.json index 89a4e1fe04c8..36646d56ff0d 100644 --- a/packages/angular/pwa/package.json +++ b/packages/angular/pwa/package.json @@ -15,5 +15,13 @@ "@angular-devkit/schematics": "0.0.0-PLACEHOLDER", "@schematics/angular": "0.0.0-PLACEHOLDER", "parse5-html-rewriting-stream": "6.0.1" + }, + "peerDependencies": { + "@angular/cli": "^13.0.0" + }, + "peerDependenciesMeta": { + "@angular/cli": { + "optional": true + } } } From d27fc7ed0e515295fe6af5a782ed38a227edfbf2 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Fri, 10 Jun 2022 10:30:00 +0000 Subject: [PATCH 54/63] test: always install a compatible version of `@angular/material-moment-adapter` When not install a compatible version tests can fail due example https://app.circleci.com/pipelines/github/angular/angular-cli/23342/workflows/77ac48f1-1445-4722-9294-7841afc0b2cc/jobs/309894 (cherry picked from commit 6c19f2640667c913382cad1d62b88bf5cb8a23c0) --- tests/legacy-cli/e2e/tests/build/material.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/legacy-cli/e2e/tests/build/material.ts b/tests/legacy-cli/e2e/tests/build/material.ts index 5963d3411d89..94a50f06bfc7 100644 --- a/tests/legacy-cli/e2e/tests/build/material.ts +++ b/tests/legacy-cli/e2e/tests/build/material.ts @@ -1,5 +1,5 @@ import { getGlobalVariable } from '../../utils/env'; -import { replaceInFile } from '../../utils/fs'; +import { readFile, replaceInFile } from '../../utils/fs'; import { installPackage, installWorkspacePackages } from '../../utils/packages'; import { ng } from '../../utils/process'; import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; @@ -7,7 +7,7 @@ import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; const snapshots = require('../../ng-snapshot/package.json'); export default async function () { - const tag = await isPrereleaseCli() ? '@next' : ''; + let tag = (await isPrereleaseCli()) ? '@next' : ''; await ng('add', `@angular/material${tag}`, '--skip-confirmation'); const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; @@ -25,10 +25,15 @@ export default async function () { dependencies['@angular/material-moment-adapter'] = snapshots.dependencies['@angular/material-moment-adapter']; }); - await installWorkspacePackages(); } else { - await installPackage('@angular/material-moment-adapter'); + if (!tag) { + const installedMaterialVersion = JSON.parse(await readFile('package.json'))['dependencies'][ + '@angular/material' + ]; + tag = `@${installedMaterialVersion}`; + } + await installPackage(`@angular/material-moment-adapter${tag}`); } await installPackage('moment'); From 62f46c8a81225452688e144374af9b4a6551c7ef Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 15 Jun 2022 07:56:25 +0000 Subject: [PATCH 55/63] release: cut the v13.3.8 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1213e723ed62..0a675b13d517 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.8 (2022-06-15) + +### @angular/pwa + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | ---------------------------------- | +| [c7f994f88](https://github.com/angular/angular-cli/commit/c7f994f88a396be96c01da1017a15083d5f544fb) | fix | add peer dependency on Angular CLI | + +## Special Thanks + +Alan Agius + + + # 13.3.7 (2022-05-25) diff --git a/package.json b/package.json index 3f2adf50b7a3..2e1c8e18338e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.7", + "version": "13.3.8", "private": true, "description": "Software Development Kit for Angular", "bin": { From 0bb875ddae9b3aba3c2fedb70e0222bc333f435a Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Thu, 16 Jun 2022 18:03:10 -0400 Subject: [PATCH 56/63] build: mark external only bazel rules (cherry picked from commit 1e21440c10066d771066ac5eed195d749384d45f) --- packages/angular/cli/BUILD.bazel | 9 ++++++++- packages/angular_devkit/architect/BUILD.bazel | 7 +++++++ packages/angular_devkit/core/BUILD.bazel | 5 +++++ packages/angular_devkit/schematics/BUILD.bazel | 5 +++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/angular/cli/BUILD.bazel b/packages/angular/cli/BUILD.bazel index ba4a82bd9839..b56f88a992ef 100644 --- a/packages/angular/cli/BUILD.bazel +++ b/packages/angular/cli/BUILD.bazel @@ -4,9 +4,12 @@ # found in the LICENSE file at https://angular.io/license load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") +load("//tools:defaults.bzl", "pkg_npm", "ts_library") + +# @external_begin load("//tools:ts_json_schema.bzl", "ts_json_schema") load("//tools:ng_cli_schema_generator.bzl", "cli_json_schema") -load("//tools:defaults.bzl", "pkg_npm", "ts_library") +# @external_end licenses(["notice"]) # MIT @@ -91,6 +94,7 @@ ts_library( ], ) +# @external_begin CLI_SCHEMA_DATA = [ "//packages/angular_devkit/build_angular:src/builders/app-shell/schema.json", "//packages/angular_devkit/build_angular:src/builders/browser/schema.json", @@ -280,6 +284,7 @@ ts_json_schema( name = "update_schematic_schema", src = "src/commands/update/schematic/schema.json", ) +# @external_end ts_library( name = "angular-cli_test_lib", @@ -307,6 +312,7 @@ jasmine_node_test( srcs = [":angular-cli_test_lib"], ) +# @external_begin genrule( name = "license", srcs = ["//:LICENSE"], @@ -333,3 +339,4 @@ pkg_npm( ":utilities/INITIAL_COMMIT_MESSAGE.txt", ], ) +# @external_end diff --git a/packages/angular_devkit/architect/BUILD.bazel b/packages/angular_devkit/architect/BUILD.bazel index d59a08ff91fc..81b5eaf16583 100644 --- a/packages/angular_devkit/architect/BUILD.bazel +++ b/packages/angular_devkit/architect/BUILD.bazel @@ -5,13 +5,17 @@ load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") + +# @external_begin load("//tools:ts_json_schema.bzl", "ts_json_schema") load("@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl", "api_golden_test_npm_package") +# @external_end licenses(["notice"]) # MIT package(default_visibility = ["//visibility:public"]) +# @external_begin ts_json_schema( name = "builder_input_schema", src = "src/input-schema.json", @@ -36,6 +40,7 @@ ts_json_schema( name = "operator_schema", src = "builders/operator-schema.json", ) +# @external_end ts_library( name = "architect", @@ -90,6 +95,7 @@ jasmine_node_test( srcs = [":architect_test_lib"], ) +# @external_begin genrule( name = "license", srcs = ["//:LICENSE"], @@ -120,3 +126,4 @@ api_golden_test_npm_package( golden_dir = "angular_cli/goldens/public-api/angular_devkit/architect", npm_package = "angular_cli/packages/angular_devkit/architect/npm_package", ) +# @external_end diff --git a/packages/angular_devkit/core/BUILD.bazel b/packages/angular_devkit/core/BUILD.bazel index abf0abe9ed06..6d753bf236a2 100644 --- a/packages/angular_devkit/core/BUILD.bazel +++ b/packages/angular_devkit/core/BUILD.bazel @@ -1,6 +1,9 @@ load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") + +# @external_begin load("@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl", "api_golden_test_npm_package") +# @external_end # Copyright Google Inc. All Rights Reserved. # @@ -76,6 +79,7 @@ jasmine_node_test( ], ) +# @external_begin genrule( name = "license", srcs = ["//:LICENSE"], @@ -107,3 +111,4 @@ api_golden_test_npm_package( npm_package = "angular_cli/packages/angular_devkit/core/npm_package", types = ["@npm//@types/node"], ) +# @external_end diff --git a/packages/angular_devkit/schematics/BUILD.bazel b/packages/angular_devkit/schematics/BUILD.bazel index 0cccea0629fc..8aade96a9a97 100644 --- a/packages/angular_devkit/schematics/BUILD.bazel +++ b/packages/angular_devkit/schematics/BUILD.bazel @@ -1,6 +1,9 @@ load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") + +# @external_begin load("@npm//@angular/dev-infra-private/bazel/api-golden:index.bzl", "api_golden_test_npm_package") +# @external_end # Copyright Google Inc. All Rights Reserved. # @@ -64,6 +67,7 @@ jasmine_node_test( ], ) +# @external_begin genrule( name = "license", srcs = ["//:LICENSE"], @@ -99,3 +103,4 @@ api_golden_test_npm_package( npm_package = "angular_cli/packages/angular_devkit/schematics/npm_package", types = ["@npm//@types/node"], ) +# @external_end From 0d62716ae3753bb463de6b176ae07520ebb24fc9 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 20 Jul 2022 08:10:56 +0000 Subject: [PATCH 57/63] fix(@angular-devkit/build-angular): update terser to address CVE-2022-25858 While this vulnerability cannot be exploited through the Angular CLI as we don't expect it to be run on production servers. We update terser to remove the unnecessary vulnerability noise. Closes #23593 --- package.json | 2 +- .../angular_devkit/build_angular/package.json | 2 +- yarn.lock | 32 ++++++++++++++++--- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 2e1c8e18338e..ede923924d30 100644 --- a/package.json +++ b/package.json @@ -210,7 +210,7 @@ "symbol-observable": "4.0.0", "tar": "^6.1.6", "temp": "^0.9.0", - "terser": "5.11.0", + "terser": "5.14.2", "text-table": "0.2.0", "tree-kill": "1.2.2", "ts-node": "^10.0.0", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index c5b7da0498f3..902d92b3c957 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -61,7 +61,7 @@ "source-map-support": "0.5.21", "stylus": "0.56.0", "stylus-loader": "6.2.0", - "terser": "5.11.0", + "terser": "5.14.2", "text-table": "0.2.0", "tree-kill": "1.2.2", "tslib": "2.3.1", diff --git a/yarn.lock b/yarn.lock index b73ad4debb42..1a802d174f72 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1503,6 +1503,15 @@ "@jridgewell/set-array" "^1.0.0" "@jridgewell/sourcemap-codec" "^1.4.10" +"@jridgewell/gen-mapping@^0.3.0": + version "0.3.2" + resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" + integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== + dependencies: + "@jridgewell/set-array" "^1.0.1" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@jridgewell/trace-mapping" "^0.3.9" + "@jridgewell/resolve-uri@^3.0.3": version "3.0.3" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.0.3.tgz#b80093f4edbb5490c49746231513669c8f518acb" @@ -1513,6 +1522,19 @@ resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.0.tgz#1179863356ac8fbea64a5a4bcde93a4871012c01" integrity sha512-SfJxIxNVYLTsKwzB3MoOQ1yxf4w/E6MdkvTgrgAt1bfxjSrLUoHMKrDOykwN14q65waezZIdqDneUIPh4/sKxg== +"@jridgewell/set-array@^1.0.1": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" + integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== + +"@jridgewell/source-map@^0.3.2": + version "0.3.2" + resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" + integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== + dependencies: + "@jridgewell/gen-mapping" "^0.3.0" + "@jridgewell/trace-mapping" "^0.3.9" + "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.11" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz#771a1d8d744eeb71b6adb35808e1a6c7b9b8c8ec" @@ -10681,14 +10703,14 @@ terser@5.10.0, terser@^5.7.2: source-map "~0.7.2" source-map-support "~0.5.20" -terser@5.11.0: - version "5.11.0" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.11.0.tgz#2da5506c02e12cd8799947f30ce9c5b760be000f" - integrity sha512-uCA9DLanzzWSsN1UirKwylhhRz3aKPInlfmpGfw8VN6jHsAtu8HJtIpeeHHK23rxnE/cDc+yvmq5wqkIC6Kn0A== +terser@5.14.2: + version "5.14.2" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" + integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== dependencies: + "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" commander "^2.20.0" - source-map "~0.7.2" source-map-support "~0.5.20" test-exclude@^6.0.0: From d091bb0c7b76a73e1b7d4b5690c532c68452b1d6 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Wed, 20 Jul 2022 12:26:41 -0400 Subject: [PATCH 58/63] release: cut the v13.3.9 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a675b13d517..3b3cc18fbacc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.9 (2022-07-20) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | --------------------------------------- | +| [0d62716ae](https://github.com/angular/angular-cli/commit/0d62716ae3753bb463de6b176ae07520ebb24fc9) | fix | update terser to address CVE-2022-25858 | + +## Special Thanks + +Alan Agius and Charles Lyding + + + # 13.3.8 (2022-06-15) diff --git a/package.json b/package.json index ede923924d30..ca13329b5d5e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.8", + "version": "13.3.9", "private": true, "description": "Software Development Kit for Angular", "bin": { From f298ebbd5f86077985d994662314379df92b6771 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 16 Nov 2022 11:24:22 +0000 Subject: [PATCH 59/63] fix(@angular-devkit/build-angular): update `loader-utils` to `3.2.1` `loader-utils` is vulnerable to Regular Expression Denial of Service (ReDoS) via url variable. See: https://github.com/advisories/GHSA-3rfm-jhwj-7488 Closes #24241 --- package.json | 2 +- packages/angular_devkit/build_angular/package.json | 2 +- yarn.lock | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index ca13329b5d5e..48bdfb48bb07 100644 --- a/package.json +++ b/package.json @@ -169,7 +169,7 @@ "less-loader": "10.2.0", "license-checker": "^25.0.0", "license-webpack-plugin": "4.0.2", - "loader-utils": "3.2.0", + "loader-utils": "3.2.1", "magic-string": "0.25.7", "mini-css-extract-plugin": "2.5.3", "minimatch": "3.0.5", diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 902d92b3c957..fef7e601e66c 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -40,7 +40,7 @@ "less": "4.1.2", "less-loader": "10.2.0", "license-webpack-plugin": "4.0.2", - "loader-utils": "3.2.0", + "loader-utils": "3.2.1", "mini-css-extract-plugin": "2.5.3", "minimatch": "3.0.5", "open": "8.4.0", diff --git a/yarn.lock b/yarn.lock index 1a802d174f72..670147c2a030 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7322,6 +7322,11 @@ loader-utils@3.2.0: resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-3.2.0.tgz#bcecc51a7898bee7473d4bc6b845b23af8304d4f" integrity sha512-HVl9ZqccQihZ7JM85dco1MvO9G+ONvxoGa9rkhzFsneGLKSUg1gJf9bWzhRhcvm2qChhWpebQhP44qxjKIUCaQ== +loader-utils@3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-3.2.1.tgz#4fb104b599daafd82ef3e1a41fb9265f87e1f576" + integrity sha512-ZvFw1KWS3GVyYBYb7qkmRM/WwL2TQQBxgCK62rlvm4WpVQ23Nb4tYjApUlfjrEGvOs7KHEsmyUn75OHZrJMWPw== + loader-utils@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.0.tgz#c579b5e34cb34b1a74edc6c1fb36bfa371d5a613" From 2fbeb041fa43cd87c4083e47e2b82979b30ce7b8 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 17 Nov 2022 09:00:15 +0000 Subject: [PATCH 60/63] ci: replace scheduled jobs with scheduled pipelines This is easier to manage from Circle CI UI and align with the version 14.2.x branch setup See: https://circleci.com/docs/scheduled-pipelines/?utm_source=google&utm_medium=sem&utm_campaign=sem-google-dg--emea-en-dsa-maxConv-auth-nb&utm_term=g_-_c__dsa_&utm_content=&gclid=Cj0KCQiA1NebBhDDARIsAANiDD2Ja2WCBYtxifWx9d8uD2bEZzDjtO4mB2aq7fEtvoUKZZ8GeQbeNtgaAoW5EALw_wcB and https://app.circleci.com/settings/project/github/angular/angular-cli/triggers?return-to=https%3A%2F%2Fapp.circleci.com%2Fpipelines%2Fgithub%2Fangular%2Fangular-cli&triggerSource=&scheduledTriggerId=8e3e6898-fd55-41b1-a3e8-85c52981d941&success=true --- .circleci/config.yml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ef35fb031659..031a97b31df5 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -324,6 +324,9 @@ jobs: workflows: version: 2 default_workflow: + when: + not: + equal: [scheduled_pipeline, << pipeline.trigger_source >>] jobs: # Linux jobs - setup @@ -392,16 +395,12 @@ workflows: - test - e2e-cli - nightly: - triggers: - - schedule: - cron: '0 0 * * *' - filters: - branches: - only: - - 13.3.x + daily_run_workflow: + when: + and: + - equal: [scheduled_pipeline, << pipeline.trigger_source >>] + - equal: ['13.3.x nightly run', << pipeline.schedule.name >>] jobs: - # Linux jobs - setup - build: requires: From e8824b019425f521a358e5d890eb1f2f050d1be7 Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 17 Nov 2022 18:22:50 +0000 Subject: [PATCH 61/63] test(@angular/cli): update the update test to address node.js incompatability failures --- tests/legacy-cli/e2e/tests/update/update-9.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/legacy-cli/e2e/tests/update/update-9.ts b/tests/legacy-cli/e2e/tests/update/update-9.ts index 69623ea76f49..00b9303f5c08 100644 --- a/tests/legacy-cli/e2e/tests/update/update-9.ts +++ b/tests/legacy-cli/e2e/tests/update/update-9.ts @@ -13,6 +13,8 @@ export default async function () { await setRegistry(false); await installWorkspacePackages(); + process.env['NG_DISABLE_VERSION_CHECK'] = '1'; + // Update Angular to 10 await installPackage('@angular/cli@9'); const { stdout } = await ng('update', '@angular/cli@10.x', '@angular/core@10.x'); @@ -23,6 +25,8 @@ export default async function () { // Update Angular to 11 await ng('update', '@angular/cli@11', '@angular/core@11'); + delete process.env['NG_DISABLE_VERSION_CHECK']; + // Update Angular to 12 await ng('update', '@angular/cli@12', '@angular/core@12'); } finally { From 7eac5a4795bfd8f5a998b1be0c2b40c158b5881d Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 17 Nov 2022 10:46:51 +0000 Subject: [PATCH 62/63] test(@angular/cli): fix version specifier test Remove `ng add @angular/localize@latest` test. This is currently failing as `@angular/localize@latest` does not support Node.js version 14.15 (cherry picked from commit ab6bb1d6a6996c809bc55751564da5d044f8e4a3) --- tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts b/tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts index 1078302590b8..c8316333ea8f 100644 --- a/tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts +++ b/tests/legacy-cli/e2e/tests/commands/add/version-specifier.ts @@ -17,11 +17,6 @@ export default async function () { throw new Error('Installation was not skipped'); } - const output2 = await ng('add', '@angular/localize@latest', '--skip-confirmation'); - if (output2.stdout.includes('Skipping installation: Package already installed')) { - throw new Error('Installation should not have been skipped'); - } - // v12.2.0 has a package.json engine field that supports Node.js v16+ const output3 = await ng('add', '@angular/localize@12.2.0', '--skip-confirmation'); if (output3.stdout.includes('Skipping installation: Package already installed')) { From bc78fcd7eda79f96fd42446cb54c203f155c6e34 Mon Sep 17 00:00:00 2001 From: Doug Parker Date: Thu, 17 Nov 2022 13:28:34 -0800 Subject: [PATCH 63/63] release: cut the v13.3.10 release --- CHANGELOG.md | 16 ++++++++++++++++ package.json | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b3cc18fbacc..8298e6ac1700 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,19 @@ + + +# 13.3.10 (2022-11-17) + +### @angular-devkit/build-angular + +| Commit | Type | Description | +| --------------------------------------------------------------------------------------------------- | ---- | -------------------------------- | +| [f298ebbd5](https://github.com/angular/angular-cli/commit/f298ebbd5f86077985d994662314379df92b6771) | fix | update `loader-utils` to `3.2.1` | + +## Special Thanks + +Alan Agius + + + # 13.3.9 (2022-07-20) diff --git a/package.json b/package.json index 48bdfb48bb07..b3defd29243c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@angular/devkit-repo", - "version": "13.3.9", + "version": "13.3.10", "private": true, "description": "Software Development Kit for Angular", "bin": {