mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'master' of https://github.com/RyanCavanaugh/TypeScript into fix36984
This commit is contained in:
+11
-1
@@ -26,6 +26,10 @@
|
||||
"@typescript-eslint/no-inferrable-types": "error",
|
||||
"@typescript-eslint/no-misused-new": "error",
|
||||
"@typescript-eslint/no-this-alias": "error",
|
||||
|
||||
"no-unused-expressions": "off",
|
||||
"@typescript-eslint/no-unused-expressions": ["error", { "allowTernary": true }],
|
||||
|
||||
"@typescript-eslint/prefer-for-of": "error",
|
||||
"@typescript-eslint/prefer-function-type": "error",
|
||||
"@typescript-eslint/prefer-namespace-keyword": "error",
|
||||
@@ -36,6 +40,13 @@
|
||||
"semi": "off",
|
||||
"@typescript-eslint/semi": "error",
|
||||
|
||||
"space-before-function-paren": "off",
|
||||
"@typescript-eslint/space-before-function-paren": ["error", {
|
||||
"asyncArrow": "always",
|
||||
"anonymous": "always",
|
||||
"named": "never"
|
||||
}],
|
||||
|
||||
"@typescript-eslint/triple-slash-reference": "error",
|
||||
"@typescript-eslint/type-annotation-spacing": "error",
|
||||
"@typescript-eslint/unified-signatures": "error",
|
||||
@@ -97,7 +108,6 @@
|
||||
"no-trailing-spaces": "error",
|
||||
"no-undef-init": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unused-expressions": ["error", { "allowTernary": true }],
|
||||
"no-unused-labels": "error",
|
||||
"no-var": "error",
|
||||
"object-shorthand": "error",
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
---
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question
|
||||
url: https://stackoverflow.com/questions/tagged/typescript
|
||||
about: Please ask and answer questions here.
|
||||
- name: TypeScript FAQ
|
||||
url: https://github.com/microsoft/TypeScript/wiki/FAQ
|
||||
about: Please check the FAQ before filing new issues
|
||||
- name: Website
|
||||
url: https://github.com/microsoft/TypeScript-Website/issues/new
|
||||
about: Please raise issues about the site on it's own repo.
|
||||
contact_links:
|
||||
-
|
||||
about: "Please ask and answer usage questions on Stack Overflow."
|
||||
name: Question
|
||||
url: "https://stackoverflow.com/questions/tagged/typescript"
|
||||
-
|
||||
about: "Alternatively, you can use the TypeScript Community Discord."
|
||||
name: Chat
|
||||
url: "https://discord.gg/typescript"
|
||||
-
|
||||
about: "Please check the FAQ before filing new issues"
|
||||
name: "TypeScript FAQ"
|
||||
url: "https://github.com/microsoft/TypeScript/wiki/FAQ"
|
||||
-
|
||||
about: "Please raise issues about the site on it's own repo."
|
||||
name: Website
|
||||
url: "https://github.com/microsoft/TypeScript-Website/issues/new"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
sandersn
|
||||
elibarzilay
|
||||
weswigham
|
||||
andrewbranch
|
||||
RyanCavanaugh
|
||||
sheetalkamat
|
||||
orta
|
||||
rbuckton
|
||||
@@ -35,3 +35,6 @@ jobs:
|
||||
npm install
|
||||
npm update
|
||||
npm test
|
||||
- name: Validate the browser can import TypeScript
|
||||
run: gulp test-browser-integration
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
name: New Release Branch
|
||||
|
||||
on:
|
||||
repository_dispatch:
|
||||
types: new-release-branch
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Use node version 12.x
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12.x
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 5
|
||||
- run: |
|
||||
git checkout -b ${{ github.event.client_payload.branch_name }}
|
||||
sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts
|
||||
sed -i -e 's/const version = `${versionMajorMinor}.0-.*`/const version = `${versionMajorMinor}.0-${{ github.event.client_payload.core_tag || 'dev' }}`/g' src/compiler/corePublic.ts
|
||||
npm install
|
||||
gulp LKG
|
||||
npm test
|
||||
git diff
|
||||
git add package.json
|
||||
git add src/compiler/corePublic.ts
|
||||
git add tests/baselines/reference/api/typescript.d.ts
|
||||
git add tests/baselines/reference/api/tsserverlibrary.d.ts
|
||||
git add ./lib
|
||||
git config user.email "ts_bot@rcavanaugh.com"
|
||||
git config user.name "TypeScript Bot"
|
||||
git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG'
|
||||
git push --set-upstream origin ${{ github.event.client_payload.branch_name }}
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Publish Nightly
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 7 * * *'
|
||||
repository_dispatch:
|
||||
types: publish-nightly
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use node version 12
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- name: Setup and publish nightly
|
||||
run: |
|
||||
npm whoami
|
||||
npm i
|
||||
gulp configure-nightly
|
||||
gulp LKG
|
||||
gulp runtests-parallel
|
||||
gulp clean
|
||||
npm publish --tag next
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.npm_token}}
|
||||
CI: true
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
name: Create Releasable Package Drop
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- release-*
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Use node version 12
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
- name: Remove existing TypeScript
|
||||
run: |
|
||||
npm uninstall typescript --no-save
|
||||
npm uninstall tslint --no-save
|
||||
- name: npm install and test
|
||||
run: |
|
||||
npm install
|
||||
npm update
|
||||
npm test
|
||||
env:
|
||||
CI: true
|
||||
- name: Validate the browser can import TypeScript
|
||||
run: gulp test-browser-integration
|
||||
- name: LKG, clean, and pack
|
||||
run: |
|
||||
gulp LKG
|
||||
gulp clean
|
||||
npm pack ./
|
||||
mv typescript-*.tgz typescript.tgz
|
||||
env:
|
||||
CI: true
|
||||
- name: Upload built tarfile
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: tgz
|
||||
path: typescript.tgz
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
name: Set branch version
|
||||
|
||||
on:
|
||||
repository_dispatch:
|
||||
types: set-version
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Use node version 12.x
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12.x
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
ref: ${{ github.event.client_payload.branch_name }}
|
||||
# notably, this is essentially the same script as `new-release-branch.yaml` (with fewer inputs), but it assumes the branch already exists
|
||||
# do note that executing the transform below will prevent the `configurePrerelease` script from running on the source, as it makes the
|
||||
# `version` identifier no longer match the regex it uses
|
||||
# required client_payload members:
|
||||
# branch_name - the target branch
|
||||
# package_version - the full version string (eg, `3.9.1-rc` or `3.9.2`)
|
||||
# core_major_minor - the major.minor pair associated with the desired package_version (eg, `3.9` for `3.9.3`)
|
||||
- run: |
|
||||
sed -i -e 's/"version": ".*"/"version": "${{ github.event.client_payload.package_version }}"/g' package.json
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' src/compiler/corePublic.ts
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/typescript.d.ts
|
||||
sed -i -e 's/const versionMajorMinor = ".*"/const versionMajorMinor = "${{ github.event.client_payload.core_major_minor }}"/g' tests/baselines/reference/api/tsserverlibrary.d.ts
|
||||
sed -i -e 's/const version = .*;/const version = "${{ github.event.client_payload.package_version }}" as string;/g' src/compiler/corePublic.ts
|
||||
npm install
|
||||
gulp LKG
|
||||
npm test
|
||||
git diff
|
||||
git add package.json
|
||||
git add src/compiler/corePublic.ts
|
||||
git add tests/baselines/reference/api/typescript.d.ts
|
||||
git add tests/baselines/reference/api/tsserverlibrary.d.ts
|
||||
git add ./lib
|
||||
git config user.email "ts_bot@rcavanaugh.com"
|
||||
git config user.name "TypeScript Bot"
|
||||
git commit -m 'Bump version to ${{ github.event.client_payload.package_version }} and LKG'
|
||||
git push
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Sync branch with master
|
||||
|
||||
on:
|
||||
repository_dispatch:
|
||||
types: sync-branch
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Use node version 12.x
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12.x
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
ref: ${{ github.event.client_payload.branch_name }}
|
||||
# This does a test post-merge and only pushes the result if the test succeeds
|
||||
# required client_payload members:
|
||||
# branch_name - the target branch
|
||||
- run: |
|
||||
git config user.email "ts_bot@rcavanaugh.com"
|
||||
git config user.name "TypeScript Bot"
|
||||
git fetch origin master
|
||||
git merge master --no-ff
|
||||
npm install
|
||||
npm test
|
||||
git push
|
||||
Vendored
+2
-1
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"dbaeumer.vscode-eslint"
|
||||
"dbaeumer.vscode-eslint",
|
||||
"rbuckton.tsserver-live-reload"
|
||||
],
|
||||
|
||||
"unwantedRecommendations": [
|
||||
|
||||
+1
-3
@@ -69,9 +69,7 @@ Design changes will not be accepted at this time. If you have a design change pr
|
||||
|
||||
## Legal
|
||||
|
||||
You will need to complete a Contributor License Agreement (CLA). Briefly, this agreement testifies that you are granting us permission to use the submitted change according to the terms of the project's license, and that the work being submitted is under appropriate copyright.
|
||||
|
||||
Please submit a Contributor License Agreement (CLA) before submitting a pull request. You may visit https://cla.microsoft.com to sign digitally. Alternatively, download the agreement ([Microsoft Contribution License Agreement.pdf](https://opensource.microsoft.com/pdf/microsoft-contribution-license-agreement.pdf)), sign, scan, and email it back to <cla@microsoft.com>. Be sure to include your GitHub user name along with the agreement. Once we have received the signed CLA, we'll review the request.
|
||||
You will need to complete a Contributor License Agreement (CLA). Briefly, this agreement testifies that you are granting us permission to use the submitted change according to the terms of the project's license, and that the work being submitted is under appropriate copyright. Upon submitting a pull request, you will automatically be given instructions on how to sign the CLA.
|
||||
|
||||
## Housekeeping
|
||||
|
||||
|
||||
+6
-6
@@ -1,14 +1,14 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
+19
-12
@@ -346,8 +346,6 @@ const lintFoldEnd = async () => { if (fold.isTravis()) console.log(fold.end("lin
|
||||
|
||||
/** @type { (folder: string) => { (): Promise<any>; displayName?: string } } */
|
||||
const eslint = (folder) => async () => {
|
||||
const ESLINTRC_CI = ".eslintrc.ci.json";
|
||||
const isCIEnv = cmdLineOptions.ci || process.env.CI === "true";
|
||||
|
||||
const args = [
|
||||
"node_modules/eslint/bin/eslint",
|
||||
@@ -358,13 +356,6 @@ const eslint = (folder) => async () => {
|
||||
"--ext", ".ts",
|
||||
];
|
||||
|
||||
if (
|
||||
isCIEnv &&
|
||||
fs.existsSync(path.resolve(folder, ESLINTRC_CI))
|
||||
) {
|
||||
args.push("--config", path.resolve(folder, ESLINTRC_CI));
|
||||
}
|
||||
|
||||
if (cmdLineOptions.fix) {
|
||||
args.push("--fix");
|
||||
}
|
||||
@@ -417,7 +408,18 @@ task("generate-types-map", generateTypesMap);
|
||||
const cleanTypesMap = () => del("built/local/typesMap.json");
|
||||
cleanTasks.push(cleanTypesMap);
|
||||
|
||||
const buildOtherOutputs = parallel(buildCancellationToken, buildTypingsInstaller, buildWatchGuard, generateTypesMap);
|
||||
// Drop a copy of diagnosticMessages.generated.json into the built/local folder. This allows
|
||||
// it to be synced to the Azure DevOps repo, so that it can get picked up by the build
|
||||
// pipeline that generates the localization artifacts that are then fed into the translation process.
|
||||
const builtLocalDiagnosticMessagesGeneratedJson = "built/local/diagnosticMessages.generated.json";
|
||||
const copyBuiltLocalDiagnosticMessages = () => src(diagnosticMessagesGeneratedJson)
|
||||
.pipe(newer(builtLocalDiagnosticMessagesGeneratedJson))
|
||||
.pipe(dest("built/local"));
|
||||
|
||||
const cleanBuiltLocalDiagnosticMessages = () => del(builtLocalDiagnosticMessagesGeneratedJson);
|
||||
cleanTasks.push(cleanBuiltLocalDiagnosticMessages);
|
||||
|
||||
const buildOtherOutputs = parallel(buildCancellationToken, buildTypingsInstaller, buildWatchGuard, generateTypesMap, copyBuiltLocalDiagnosticMessages);
|
||||
task("other-outputs", series(preBuild, buildOtherOutputs));
|
||||
task("other-outputs").description = "Builds miscelaneous scripts and documents distributed with the LKG";
|
||||
|
||||
@@ -439,7 +441,7 @@ const generateCodeCoverage = () => exec("istanbul", ["cover", "node_modules/moch
|
||||
task("generate-code-coverage", series(preBuild, buildTests, generateCodeCoverage));
|
||||
task("generate-code-coverage").description = "Generates code coverage data via istanbul";
|
||||
|
||||
const preTest = parallel(buildTests, buildServices, buildLssl);
|
||||
const preTest = parallel(buildTsc, buildTests, buildServices, buildLssl);
|
||||
preTest.displayName = "preTest";
|
||||
|
||||
const postTest = (done) => cmdLineOptions.lint ? lint(done) : done();
|
||||
@@ -465,7 +467,7 @@ task("runtests").flags = {
|
||||
" --shardId": "1-based ID of this shard (default: 1)",
|
||||
};
|
||||
|
||||
const runTestsParallel = () => runConsoleTests("built/local/run.js", "min", /*runInParallel*/ true, /*watchMode*/ false);
|
||||
const runTestsParallel = () => runConsoleTests("built/local/run.js", "min", /*runInParallel*/ cmdLineOptions.workers > 1, /*watchMode*/ false);
|
||||
task("runtests-parallel", series(preBuild, preTest, runTestsParallel, postTest));
|
||||
task("runtests-parallel").description = "Runs all the tests in parallel using the built run.js file.";
|
||||
task("runtests-parallel").flags = {
|
||||
@@ -481,6 +483,11 @@ task("runtests-parallel").flags = {
|
||||
" --shardId": "1-based ID of this shard (default: 1)",
|
||||
};
|
||||
|
||||
|
||||
task("test-browser-integration", () => exec(process.execPath, ["scripts/browserIntegrationTest.js"]));
|
||||
task("test-browser-integration").description = "Runs scripts/browserIntegrationTest.ts which tests that typescript.js loads in a browser";
|
||||
|
||||
|
||||
task("diff", () => exec(getDiffTool(), [refBaseline, localBaseline], { ignoreExitCode: true, waitForExit: false }));
|
||||
task("diff").description = "Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable";
|
||||
|
||||
|
||||
@@ -17,13 +17,7 @@ and limitations under the License.
|
||||
"use strict";
|
||||
var fs = require("fs");
|
||||
function pipeExists(name) {
|
||||
try {
|
||||
fs.statSync(name);
|
||||
return true;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
return fs.existsSync(name);
|
||||
}
|
||||
function createCancellationToken(args) {
|
||||
var cancellationPipeName;
|
||||
|
||||
@@ -454,7 +454,7 @@
|
||||
"Generic_type_0_requires_1_type_argument_s_2314": "ジェネリック型 '{0}' には {1} 個の型引数が必要です。",
|
||||
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "ジェネリック型 '{0}' には、{1} 個から {2} 個までの型引数が必要です。",
|
||||
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "ジェネリック型のインスタンス化は非常に深く、無限である可能性があります。",
|
||||
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターで表示が許可されていません。",
|
||||
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターでの表示が許可されていません。",
|
||||
"Global_module_exports_may_only_appear_at_top_level_1316": "グローバル モジュールのエクスポートは最上位レベルにのみ出現可能です。",
|
||||
"Global_module_exports_may_only_appear_in_declaration_files_1315": "グローバル モジュールのエクスポートは宣言ファイルにのみ出現可能です。",
|
||||
"Global_module_exports_may_only_appear_in_module_files_1314": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。",
|
||||
|
||||
Vendored
+310
-248
File diff suppressed because it is too large
Load Diff
Vendored
+7
-7
@@ -1,14 +1,14 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
@@ -91,7 +91,7 @@ interface Array<T> {
|
||||
* Returns an object whose properties have the value 'true'
|
||||
* when they will be absent when used in a 'with' statement.
|
||||
*/
|
||||
[Symbol.unscopables](): {
|
||||
[Symbol.unscopables]: {
|
||||
copyWithin: boolean;
|
||||
entries: boolean;
|
||||
fill: boolean;
|
||||
|
||||
Vendored
+629
@@ -0,0 +1,629 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
|
||||
interface BigInt {
|
||||
/**
|
||||
* Returns a string representation of an object.
|
||||
* @param radix Specifies a radix for converting numeric values to strings.
|
||||
*/
|
||||
toString(radix?: number): string;
|
||||
|
||||
/** Returns a string representation appropriate to the host environment's current locale. */
|
||||
toLocaleString(): string;
|
||||
|
||||
/** Returns the primitive value of the specified object. */
|
||||
valueOf(): bigint;
|
||||
|
||||
readonly [Symbol.toStringTag]: "BigInt";
|
||||
}
|
||||
|
||||
interface BigIntConstructor {
|
||||
(value?: any): bigint;
|
||||
readonly prototype: BigInt;
|
||||
|
||||
/**
|
||||
* Interprets the low bits of a BigInt as a 2's-complement signed integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
asIntN(bits: number, int: bigint): bigint;
|
||||
/**
|
||||
* Interprets the low bits of a BigInt as an unsigned integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
asUintN(bits: number, int: bigint): bigint;
|
||||
}
|
||||
|
||||
declare var BigInt: BigIntConstructor;
|
||||
|
||||
/**
|
||||
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
interface BigInt64Array {
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/** The ArrayBuffer instance referenced by the array. */
|
||||
readonly buffer: ArrayBufferLike;
|
||||
|
||||
/** The length in bytes of the array. */
|
||||
readonly byteLength: number;
|
||||
|
||||
/** The offset in bytes of the array. */
|
||||
readonly byteOffset: number;
|
||||
|
||||
/**
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
|
||||
/** Yields index, value pairs for every entry in the array. */
|
||||
entries(): IterableIterator<[number, bigint]>;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
fill(value: bigint, start?: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
includes(searchElement: bigint, fromIndex?: number): boolean;
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
indexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
join(separator?: string): string;
|
||||
|
||||
/** Yields each index in the array. */
|
||||
keys(): IterableIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/** The length of the array. */
|
||||
readonly length: number;
|
||||
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
|
||||
|
||||
/** Reverses the elements in the array. */
|
||||
reverse(): this;
|
||||
|
||||
/**
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
set(array: ArrayLike<bigint>, offset?: number): void;
|
||||
|
||||
/**
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
slice(start?: number, end?: number): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
|
||||
|
||||
/**
|
||||
* Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin?: number, end?: number): BigInt64Array;
|
||||
|
||||
/** Converts the array to a string by using the current locale. */
|
||||
toLocaleString(): string;
|
||||
|
||||
/** Returns a string representation of the array. */
|
||||
toString(): string;
|
||||
|
||||
/** Yields each value in the array. */
|
||||
values(): IterableIterator<bigint>;
|
||||
|
||||
[Symbol.iterator](): IterableIterator<bigint>;
|
||||
|
||||
readonly [Symbol.toStringTag]: "BigInt64Array";
|
||||
|
||||
[index: number]: bigint;
|
||||
}
|
||||
|
||||
interface BigInt64ArrayConstructor {
|
||||
readonly prototype: BigInt64Array;
|
||||
new(length?: number): BigInt64Array;
|
||||
new(array: Iterable<bigint>): BigInt64Array;
|
||||
new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array;
|
||||
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
of(...items: bigint[]): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<bigint>): BigInt64Array;
|
||||
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array;
|
||||
}
|
||||
|
||||
declare var BigInt64Array: BigInt64ArrayConstructor;
|
||||
|
||||
/**
|
||||
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
interface BigUint64Array {
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/** The ArrayBuffer instance referenced by the array. */
|
||||
readonly buffer: ArrayBufferLike;
|
||||
|
||||
/** The length in bytes of the array. */
|
||||
readonly byteLength: number;
|
||||
|
||||
/** The offset in bytes of the array. */
|
||||
readonly byteOffset: number;
|
||||
|
||||
/**
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
|
||||
/** Yields index, value pairs for every entry in the array. */
|
||||
entries(): IterableIterator<[number, bigint]>;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
fill(value: bigint, start?: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(callbackfn: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
includes(searchElement: bigint, fromIndex?: number): boolean;
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
indexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
join(separator?: string): string;
|
||||
|
||||
/** Yields each index in the array. */
|
||||
keys(): IterableIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/** The length of the array. */
|
||||
readonly length: number;
|
||||
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U;
|
||||
|
||||
/** Reverses the elements in the array. */
|
||||
reverse(): this;
|
||||
|
||||
/**
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
set(array: ArrayLike<bigint>, offset?: number): void;
|
||||
|
||||
/**
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
slice(start?: number, end?: number): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
|
||||
|
||||
/**
|
||||
* Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin?: number, end?: number): BigUint64Array;
|
||||
|
||||
/** Converts the array to a string by using the current locale. */
|
||||
toLocaleString(): string;
|
||||
|
||||
/** Returns a string representation of the array. */
|
||||
toString(): string;
|
||||
|
||||
/** Yields each value in the array. */
|
||||
values(): IterableIterator<bigint>;
|
||||
|
||||
[Symbol.iterator](): IterableIterator<bigint>;
|
||||
|
||||
readonly [Symbol.toStringTag]: "BigUint64Array";
|
||||
|
||||
[index: number]: bigint;
|
||||
}
|
||||
|
||||
interface BigUint64ArrayConstructor {
|
||||
readonly prototype: BigUint64Array;
|
||||
new(length?: number): BigUint64Array;
|
||||
new(array: Iterable<bigint>): BigUint64Array;
|
||||
new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array;
|
||||
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
of(...items: bigint[]): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<bigint>): BigUint64Array;
|
||||
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array;
|
||||
}
|
||||
|
||||
declare var BigUint64Array: BigUint64ArrayConstructor;
|
||||
|
||||
interface DataView {
|
||||
/**
|
||||
* Gets the BigInt64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
getBigInt64(byteOffset: number, littleEndian?: boolean): bigint;
|
||||
|
||||
/**
|
||||
* Gets the BigUint64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
getBigUint64(byteOffset: number, littleEndian?: boolean): bigint;
|
||||
|
||||
/**
|
||||
* Stores a BigInt64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
|
||||
|
||||
/**
|
||||
* Stores a BigUint64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
|
||||
}
|
||||
Vendored
+2
@@ -19,5 +19,7 @@ and limitations under the License.
|
||||
|
||||
|
||||
/// <reference lib="es2019" />
|
||||
/// <reference lib="es2020.bigint" />
|
||||
/// <reference lib="es2020.promise" />
|
||||
/// <reference lib="es2020.string" />
|
||||
/// <reference lib="es2020.symbol.wellknown" />
|
||||
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
|
||||
interface PromiseFulfilledResult<T> {
|
||||
status: "fulfilled";
|
||||
value: T;
|
||||
}
|
||||
|
||||
interface PromiseRejectedResult {
|
||||
status: "rejected";
|
||||
reason: any;
|
||||
}
|
||||
|
||||
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
|
||||
|
||||
interface PromiseConstructor {
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all
|
||||
* of the provided Promises resolve or reject.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
allSettled<T extends readonly unknown[] | readonly [unknown]>(values: T):
|
||||
Promise<{ -readonly [P in keyof T]: PromiseSettledResult<T[P] extends PromiseLike<infer U> ? U : T[P]> }>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all
|
||||
* of the provided Promises resolve or reject.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
allSettled<T>(values: Iterable<T>): Promise<PromiseSettledResult<T extends PromiseLike<infer U> ? U : T>[]>;
|
||||
}
|
||||
Vendored
+1
-1
@@ -318,7 +318,7 @@ declare var Function: FunctionConstructor;
|
||||
/**
|
||||
* Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
|
||||
*/
|
||||
type ThisParameterType<T> = T extends (this: unknown, ...args: any[]) => any ? unknown : T extends (this: infer U, ...args: any[]) => any ? U : unknown;
|
||||
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
|
||||
|
||||
/**
|
||||
* Removes the 'this' parameter from a function type.
|
||||
|
||||
Vendored
+325
-325
@@ -20,9 +20,9 @@ and limitations under the License.
|
||||
|
||||
interface BigInt {
|
||||
/**
|
||||
* Returns a string representation of an object.
|
||||
* @param radix Specifies a radix for converting numeric values to strings.
|
||||
*/
|
||||
* Returns a string representation of an object.
|
||||
* @param radix Specifies a radix for converting numeric values to strings.
|
||||
*/
|
||||
toString(radix?: number): string;
|
||||
|
||||
/** Returns a string representation appropriate to the host environment's current locale. */
|
||||
@@ -39,27 +39,27 @@ interface BigIntConstructor {
|
||||
readonly prototype: BigInt;
|
||||
|
||||
/**
|
||||
* Interprets the low bits of a BigInt as a 2's-complement signed integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
* Interprets the low bits of a BigInt as a 2's-complement signed integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
asIntN(bits: number, int: bigint): bigint;
|
||||
/**
|
||||
* Interprets the low bits of a BigInt as an unsigned integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
* Interprets the low bits of a BigInt as an unsigned integer.
|
||||
* All higher bits are discarded.
|
||||
* @param bits The number of low bits to use
|
||||
* @param int The BigInt whose bits to extract
|
||||
*/
|
||||
asUintN(bits: number, int: bigint): bigint;
|
||||
}
|
||||
|
||||
declare var BigInt: BigIntConstructor;
|
||||
|
||||
/**
|
||||
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
interface BigInt64Array {
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
@@ -74,213 +74,213 @@ interface BigInt64Array {
|
||||
readonly byteOffset: number;
|
||||
|
||||
/**
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
|
||||
/** Yields index, value pairs for every entry in the array. */
|
||||
entries(): IterableIterator<[number, bigint]>;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
fill(value: bigint, start?: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
includes(searchElement: bigint, fromIndex?: number): boolean;
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
indexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
join(separator?: string): string;
|
||||
|
||||
/** Yields each index in the array. */
|
||||
keys(): IterableIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/** The length of the array. */
|
||||
readonly length: number;
|
||||
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
|
||||
|
||||
/** Reverses the elements in the array. */
|
||||
reverse(): this;
|
||||
|
||||
/**
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
set(array: ArrayLike<bigint>, offset?: number): void;
|
||||
|
||||
/**
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
slice(start?: number, end?: number): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
|
||||
|
||||
/**
|
||||
* Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin?: number, end?: number): BigInt64Array;
|
||||
* Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin: number, end?: number): BigInt64Array;
|
||||
|
||||
/** Converts the array to a string by using the current locale. */
|
||||
toLocaleString(): string;
|
||||
@@ -308,17 +308,17 @@ interface BigInt64ArrayConstructor {
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
of(...items: bigint[]): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<bigint>): BigInt64Array;
|
||||
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array;
|
||||
}
|
||||
@@ -326,9 +326,9 @@ interface BigInt64ArrayConstructor {
|
||||
declare var BigInt64Array: BigInt64ArrayConstructor;
|
||||
|
||||
/**
|
||||
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
|
||||
* requested number of bytes could not be allocated, an exception is raised.
|
||||
*/
|
||||
interface BigUint64Array {
|
||||
/** The size in bytes of each element in the array. */
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
@@ -343,213 +343,213 @@ interface BigUint64Array {
|
||||
readonly byteOffset: number;
|
||||
|
||||
/**
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
* Returns the this object after copying a section of the array identified by start and end
|
||||
* to the same array starting at position target
|
||||
* @param target If target is negative, it is treated as length+target where length is the
|
||||
* length of the array.
|
||||
* @param start If start is negative, it is treated as length+start. If end is negative, it
|
||||
* is treated as length+end.
|
||||
* @param end If not specified, length of the this object is used as its default value.
|
||||
*/
|
||||
copyWithin(target: number, start: number, end?: number): this;
|
||||
|
||||
/** Yields index, value pairs for every entry in the array. */
|
||||
entries(): IterableIterator<[number, bigint]>;
|
||||
|
||||
/**
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Determines whether all the members of an array satisfy the specified test.
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls
|
||||
* the callbackfn function for each element in the array until the callbackfn returns false,
|
||||
* or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
* Returns the this object after filling the section identified by start and end with value
|
||||
* @param value value to fill array section with
|
||||
* @param start index to start filling the array at. If start is negative, it is treated as
|
||||
* length+start where length is the length of the array.
|
||||
* @param end index to stop filling the array at. If end is negative, it is treated as
|
||||
* length+end.
|
||||
*/
|
||||
fill(value: bigint, start?: number, end?: number): this;
|
||||
|
||||
/**
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Returns the elements of an array that meet the condition specified in a callback function.
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(callbackfn: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
* Returns the value of the first element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, find
|
||||
* immediately returns that element value. Otherwise, find returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
* Returns the index of the first element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate find calls predicate once for each element of the array, in ascending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
* Determines whether an array includes a certain element, returning true or false as appropriate.
|
||||
* @param searchElement The element to search for.
|
||||
* @param fromIndex The position in this array at which to begin searching for searchElement.
|
||||
*/
|
||||
includes(searchElement: bigint, fromIndex?: number): boolean;
|
||||
|
||||
/**
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
* Returns the index of the first occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
indexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/**
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
* Adds all the elements of an array separated by the specified separator string.
|
||||
* @param separator A string used to separate one element of an array from the next in the
|
||||
* resulting String. If omitted, the array elements are separated with a comma.
|
||||
*/
|
||||
join(separator?: string): string;
|
||||
|
||||
/** Yields each index in the array. */
|
||||
keys(): IterableIterator<number>;
|
||||
|
||||
/**
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
* Returns the index of the last occurrence of a value in an array.
|
||||
* @param searchElement The value to locate in the array.
|
||||
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
|
||||
* search starts at index 0.
|
||||
*/
|
||||
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
|
||||
|
||||
/** The length of the array. */
|
||||
readonly length: number;
|
||||
|
||||
/**
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Calls a defined callback function on each element of an array, and returns an array that
|
||||
* contains the results.
|
||||
* @param callbackfn A function that accepts up to three arguments. The map method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array. The return value of
|
||||
* the callback function is the accumulated result, and is provided as an argument in the next
|
||||
* call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
|
||||
* callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an
|
||||
* argument instead of an array value.
|
||||
*/
|
||||
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint;
|
||||
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
* Calls the specified callback function for all the elements in an array, in descending order.
|
||||
* The return value of the callback function is the accumulated result, and is provided as an
|
||||
* argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
|
||||
* the callbackfn function one time for each element in the array.
|
||||
* @param initialValue If initialValue is specified, it is used as the initial value to start
|
||||
* the accumulation. The first call to the callbackfn function provides this value as an argument
|
||||
* instead of an array value.
|
||||
*/
|
||||
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U;
|
||||
|
||||
/** Reverses the elements in the array. */
|
||||
reverse(): this;
|
||||
|
||||
/**
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
* Sets a value or an array of values.
|
||||
* @param array A typed or untyped array of values to set.
|
||||
* @param offset The index in the current array at which the values are to be written.
|
||||
*/
|
||||
set(array: ArrayLike<bigint>, offset?: number): void;
|
||||
|
||||
/**
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
* Returns a section of an array.
|
||||
* @param start The beginning of the specified portion of the array.
|
||||
* @param end The end of the specified portion of the array.
|
||||
*/
|
||||
slice(start?: number, end?: number): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the
|
||||
* callbackfn function for each element in the array until the callbackfn returns true, or until
|
||||
* the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
|
||||
* If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
|
||||
|
||||
/**
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
* Sorts the array.
|
||||
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
|
||||
*/
|
||||
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
|
||||
|
||||
/**
|
||||
* Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin?: number, end?: number): BigUint64Array;
|
||||
* Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements
|
||||
* at begin, inclusive, up to end, exclusive.
|
||||
* @param begin The index of the beginning of the array.
|
||||
* @param end The index of the end of the array.
|
||||
*/
|
||||
subarray(begin: number, end?: number): BigUint64Array;
|
||||
|
||||
/** Converts the array to a string by using the current locale. */
|
||||
toLocaleString(): string;
|
||||
@@ -577,17 +577,17 @@ interface BigUint64ArrayConstructor {
|
||||
readonly BYTES_PER_ELEMENT: number;
|
||||
|
||||
/**
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
* Returns a new array from a set of elements.
|
||||
* @param items A set of elements to include in the new array object.
|
||||
*/
|
||||
of(...items: bigint[]): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<bigint>): BigUint64Array;
|
||||
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array;
|
||||
}
|
||||
@@ -596,34 +596,34 @@ declare var BigUint64Array: BigUint64ArrayConstructor;
|
||||
|
||||
interface DataView {
|
||||
/**
|
||||
* Gets the BigInt64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
* Gets the BigInt64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
getBigInt64(byteOffset: number, littleEndian?: boolean): bigint;
|
||||
|
||||
/**
|
||||
* Gets the BigUint64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
* Gets the BigUint64 value at the specified byte offset from the start of the view. There is
|
||||
* no alignment constraint; multi-byte values may be fetched from any offset.
|
||||
* @param byteOffset The place in the buffer at which the value should be retrieved.
|
||||
*/
|
||||
getBigUint64(byteOffset: number, littleEndian?: boolean): bigint;
|
||||
|
||||
/**
|
||||
* Stores a BigInt64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
* Stores a BigInt64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
|
||||
|
||||
/**
|
||||
* Stores a BigUint64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
* Stores a BigUint64 value at the specified byte offset from the start of the view.
|
||||
* @param byteOffset The place in the buffer at which the value should be set.
|
||||
* @param value The value to set.
|
||||
* @param littleEndian If false or undefined, a big-endian value should be written,
|
||||
* otherwise a little-endian value should be written.
|
||||
*/
|
||||
setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
|
||||
}
|
||||
|
||||
Vendored
-1
@@ -19,5 +19,4 @@ and limitations under the License.
|
||||
|
||||
|
||||
/// <reference lib="es2020" />
|
||||
/// <reference lib="esnext.bigint" />
|
||||
/// <reference lib="esnext.intl" />
|
||||
|
||||
Vendored
+102
-43
@@ -370,7 +370,7 @@ interface PushPermissionDescriptor extends PermissionDescriptor {
|
||||
userVisibleOnly?: boolean;
|
||||
}
|
||||
|
||||
interface PushSubscriptionChangeInit extends ExtendableEventInit {
|
||||
interface PushSubscriptionChangeEventInit extends ExtendableEventInit {
|
||||
newSubscription?: PushSubscription;
|
||||
oldSubscription?: PushSubscription;
|
||||
}
|
||||
@@ -391,6 +391,16 @@ interface QueuingStrategy<T = any> {
|
||||
size?: QueuingStrategySizeCallback<T>;
|
||||
}
|
||||
|
||||
interface ReadableStreamReadDoneResult<T> {
|
||||
done: true;
|
||||
value?: T;
|
||||
}
|
||||
|
||||
interface ReadableStreamReadValueResult<T> {
|
||||
done: false;
|
||||
value: T;
|
||||
}
|
||||
|
||||
interface RegistrationOptions {
|
||||
scope?: string;
|
||||
type?: WorkerType;
|
||||
@@ -642,7 +652,10 @@ interface AnimationFrameProvider {
|
||||
interface Blob {
|
||||
readonly size: number;
|
||||
readonly type: string;
|
||||
arrayBuffer(): Promise<ArrayBuffer>;
|
||||
slice(start?: number, end?: number, contentType?: string): Blob;
|
||||
stream(): ReadableStream;
|
||||
text(): Promise<string>;
|
||||
}
|
||||
|
||||
declare var Blob: {
|
||||
@@ -723,7 +736,7 @@ interface CacheStorage {
|
||||
delete(cacheName: string): Promise<boolean>;
|
||||
has(cacheName: string): Promise<boolean>;
|
||||
keys(): Promise<string[]>;
|
||||
match(request: RequestInfo, options?: CacheQueryOptions): Promise<Response | undefined>;
|
||||
match(request: RequestInfo, options?: MultiCacheQueryOptions): Promise<Response | undefined>;
|
||||
open(cacheName: string): Promise<Cache>;
|
||||
}
|
||||
|
||||
@@ -903,11 +916,18 @@ declare var Clients: {
|
||||
|
||||
/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
|
||||
interface CloseEvent extends Event {
|
||||
/**
|
||||
* Returns the WebSocket connection close code provided by the server.
|
||||
*/
|
||||
readonly code: number;
|
||||
/**
|
||||
* Returns the WebSocket connection close reason provided by the server.
|
||||
*/
|
||||
readonly reason: string;
|
||||
/**
|
||||
* Returns true if the connection closed cleanly; false otherwise.
|
||||
*/
|
||||
readonly wasClean: boolean;
|
||||
/** @deprecated */
|
||||
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;
|
||||
}
|
||||
|
||||
declare var CloseEvent: {
|
||||
@@ -1475,7 +1495,7 @@ interface EventTarget {
|
||||
*
|
||||
* When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
|
||||
*
|
||||
* When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in §2.8 Observing event listeners.
|
||||
* When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
|
||||
*
|
||||
* When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
|
||||
*
|
||||
@@ -1636,7 +1656,7 @@ interface GenericTransformStream {
|
||||
*/
|
||||
readonly readable: ReadableStream;
|
||||
/**
|
||||
* Returns a writable stream which accepts BufferSource chunks and runs them through encoding's decoder before making them available to readable.
|
||||
* Returns a writable stream which accepts [AllowShared] BufferSource chunks and runs them through encoding's decoder before making them available to readable.
|
||||
*
|
||||
* Typically this will be used via the pipeThrough() method on a ReadableStream source.
|
||||
*
|
||||
@@ -2715,7 +2735,7 @@ interface PushSubscriptionChangeEvent extends ExtendableEvent {
|
||||
|
||||
declare var PushSubscriptionChangeEvent: {
|
||||
prototype: PushSubscriptionChangeEvent;
|
||||
new(type: string, eventInitDict?: PushSubscriptionChangeInit): PushSubscriptionChangeEvent;
|
||||
new(type: string, eventInitDict?: PushSubscriptionChangeEventInit): PushSubscriptionChangeEvent;
|
||||
};
|
||||
|
||||
interface PushSubscriptionOptions {
|
||||
@@ -2780,11 +2800,6 @@ interface ReadableStreamDefaultReader<R = any> {
|
||||
releaseLock(): void;
|
||||
}
|
||||
|
||||
interface ReadableStreamReadResult<T> {
|
||||
done: boolean;
|
||||
value: T;
|
||||
}
|
||||
|
||||
interface ReadableStreamReader<R = any> {
|
||||
cancel(): Promise<void>;
|
||||
read(): Promise<ReadableStreamReadResult<R>>;
|
||||
@@ -2963,6 +2978,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
|
||||
onpushsubscriptionchange: ((this: ServiceWorkerGlobalScope, ev: PushSubscriptionChangeEvent) => any) | null;
|
||||
onsync: ((this: ServiceWorkerGlobalScope, ev: SyncEvent) => any) | null;
|
||||
readonly registration: ServiceWorkerRegistration;
|
||||
readonly serviceWorker: ServiceWorker;
|
||||
skipWaiting(): Promise<void>;
|
||||
addEventListener<K extends keyof ServiceWorkerGlobalScopeEventMap>(type: K, listener: (this: ServiceWorkerGlobalScope, ev: ServiceWorkerGlobalScopeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
|
||||
@@ -3103,6 +3119,8 @@ interface TextDecoderCommon {
|
||||
}
|
||||
|
||||
interface TextDecoderStream extends GenericTransformStream, TextDecoderCommon {
|
||||
readonly readable: ReadableStream<string>;
|
||||
readonly writable: WritableStream<BufferSource>;
|
||||
}
|
||||
|
||||
declare var TextDecoderStream: {
|
||||
@@ -3135,6 +3153,8 @@ interface TextEncoderCommon {
|
||||
}
|
||||
|
||||
interface TextEncoderStream extends GenericTransformStream, TextEncoderCommon {
|
||||
readonly readable: ReadableStream<Uint8Array>;
|
||||
readonly writable: WritableStream<string>;
|
||||
}
|
||||
|
||||
declare var TextEncoderStream: {
|
||||
@@ -3222,6 +3242,7 @@ interface URL {
|
||||
host: string;
|
||||
hostname: string;
|
||||
href: string;
|
||||
toString(): string;
|
||||
readonly origin: string;
|
||||
password: string;
|
||||
pathname: string;
|
||||
@@ -3266,12 +3287,17 @@ interface URLSearchParams {
|
||||
*/
|
||||
set(name: string, value: string): void;
|
||||
sort(): void;
|
||||
/**
|
||||
* Returns a string containing a query string suitable for use in a URL. Does not include the question mark.
|
||||
*/
|
||||
toString(): string;
|
||||
forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void;
|
||||
}
|
||||
|
||||
declare var URLSearchParams: {
|
||||
prototype: URLSearchParams;
|
||||
new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
|
||||
toString(): string;
|
||||
};
|
||||
|
||||
interface WEBGL_color_buffer_float {
|
||||
@@ -5277,17 +5303,45 @@ interface WebSocketEventMap {
|
||||
|
||||
/** Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */
|
||||
interface WebSocket extends EventTarget {
|
||||
/**
|
||||
* Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:
|
||||
*
|
||||
* Can be set, to change how binary data is returned. The default is "blob".
|
||||
*/
|
||||
binaryType: BinaryType;
|
||||
/**
|
||||
* Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
|
||||
*
|
||||
* If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
|
||||
*/
|
||||
readonly bufferedAmount: number;
|
||||
/**
|
||||
* Returns the extensions selected by the server, if any.
|
||||
*/
|
||||
readonly extensions: string;
|
||||
onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;
|
||||
onerror: ((this: WebSocket, ev: Event) => any) | null;
|
||||
onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;
|
||||
onopen: ((this: WebSocket, ev: Event) => any) | null;
|
||||
/**
|
||||
* Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
|
||||
*/
|
||||
readonly protocol: string;
|
||||
/**
|
||||
* Returns the state of the WebSocket object's connection. It can have the values described below.
|
||||
*/
|
||||
readonly readyState: number;
|
||||
/**
|
||||
* Returns the URL that was used to establish the WebSocket connection.
|
||||
*/
|
||||
readonly url: string;
|
||||
/**
|
||||
* Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
|
||||
*/
|
||||
close(code?: number, reason?: string): void;
|
||||
/**
|
||||
* Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
|
||||
*/
|
||||
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
|
||||
readonly CLOSED: number;
|
||||
readonly CLOSING: number;
|
||||
@@ -5344,7 +5398,7 @@ interface WindowOrWorkerGlobalScope {
|
||||
createImageBitmap(image: ImageBitmapSource): Promise<ImageBitmap>;
|
||||
createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise<ImageBitmap>;
|
||||
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
|
||||
queueMicrotask(callback: Function): void;
|
||||
queueMicrotask(callback: VoidFunction): void;
|
||||
setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
|
||||
setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
|
||||
}
|
||||
@@ -5400,12 +5454,12 @@ interface WorkerLocation {
|
||||
readonly host: string;
|
||||
readonly hostname: string;
|
||||
readonly href: string;
|
||||
toString(): string;
|
||||
readonly origin: string;
|
||||
readonly pathname: string;
|
||||
readonly port: string;
|
||||
readonly protocol: string;
|
||||
readonly search: string;
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
declare var WorkerLocation: {
|
||||
@@ -5697,9 +5751,9 @@ declare namespace WebAssembly {
|
||||
module: Module;
|
||||
}
|
||||
|
||||
type ImportExportKind = "function" | "table" | "memory" | "global";
|
||||
type ImportExportKind = "function" | "global" | "memory" | "table";
|
||||
type TableKind = "anyfunc";
|
||||
type ValueType = "i32" | "i64" | "f32" | "f64";
|
||||
type ValueType = "f32" | "f64" | "i32" | "i64";
|
||||
type ExportValue = Function | Global | Memory | Table;
|
||||
type Exports = Record<string, ExportValue>;
|
||||
type ImportValue = ExportValue | number;
|
||||
@@ -5749,6 +5803,10 @@ interface TransformStreamDefaultControllerTransformCallback<I, O> {
|
||||
(chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
|
||||
}
|
||||
|
||||
interface VoidFunction {
|
||||
(): void;
|
||||
}
|
||||
|
||||
interface WritableStreamDefaultControllerCloseCallback {
|
||||
(): void | PromiseLike<void>;
|
||||
}
|
||||
@@ -5803,7 +5861,7 @@ declare function clearTimeout(handle?: number): void;
|
||||
declare function createImageBitmap(image: ImageBitmapSource): Promise<ImageBitmap>;
|
||||
declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise<ImageBitmap>;
|
||||
declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
|
||||
declare function queueMicrotask(callback: Function): void;
|
||||
declare function queueMicrotask(callback: VoidFunction): void;
|
||||
declare function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
|
||||
declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
|
||||
declare function cancelAnimationFrame(handle: number): void;
|
||||
@@ -5824,6 +5882,7 @@ type ImageBitmapSource = CanvasImageSource | Blob | ImageData;
|
||||
type TimerHandler = string | Function;
|
||||
type PerformanceEntryList = PerformanceEntry[];
|
||||
type PushMessageDataInit = BufferSource | string;
|
||||
type ReadableStreamReadResult<T> = ReadableStreamReadValueResult<T> | ReadableStreamReadDoneResult<T>;
|
||||
type VibratePattern = number | number[];
|
||||
type AlgorithmIdentifier = string | Algorithm;
|
||||
type HashAlgorithmIdentifier = AlgorithmIdentifier;
|
||||
@@ -5849,41 +5908,41 @@ type BufferSource = ArrayBufferView | ArrayBuffer;
|
||||
type DOMTimeStamp = number;
|
||||
type FormDataEntryValue = File | string;
|
||||
type IDBValidKey = number | string | Date | BufferSource | IDBArrayKey;
|
||||
type Transferable = ArrayBuffer | MessagePort | ImageBitmap;
|
||||
type BinaryType = "blob" | "arraybuffer";
|
||||
type CanvasDirection = "ltr" | "rtl" | "inherit";
|
||||
type CanvasFillRule = "nonzero" | "evenodd";
|
||||
type Transferable = ArrayBuffer | MessagePort | ImageBitmap | OffscreenCanvas;
|
||||
type BinaryType = "arraybuffer" | "blob";
|
||||
type CanvasDirection = "inherit" | "ltr" | "rtl";
|
||||
type CanvasFillRule = "evenodd" | "nonzero";
|
||||
type CanvasLineCap = "butt" | "round" | "square";
|
||||
type CanvasLineJoin = "round" | "bevel" | "miter";
|
||||
type CanvasTextAlign = "start" | "end" | "left" | "right" | "center";
|
||||
type CanvasTextBaseline = "top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom";
|
||||
type ClientTypes = "window" | "worker" | "sharedworker" | "all";
|
||||
type EndingType = "transparent" | "native";
|
||||
type FrameType = "auxiliary" | "top-level" | "nested" | "none";
|
||||
type CanvasLineJoin = "bevel" | "miter" | "round";
|
||||
type CanvasTextAlign = "center" | "end" | "left" | "right" | "start";
|
||||
type CanvasTextBaseline = "alphabetic" | "bottom" | "hanging" | "ideographic" | "middle" | "top";
|
||||
type ClientTypes = "all" | "sharedworker" | "window" | "worker";
|
||||
type EndingType = "native" | "transparent";
|
||||
type FrameType = "auxiliary" | "nested" | "none" | "top-level";
|
||||
type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique";
|
||||
type IDBRequestReadyState = "pending" | "done";
|
||||
type IDBRequestReadyState = "done" | "pending";
|
||||
type IDBTransactionMode = "readonly" | "readwrite" | "versionchange";
|
||||
type ImageSmoothingQuality = "low" | "medium" | "high";
|
||||
type KeyFormat = "raw" | "spki" | "pkcs8" | "jwk";
|
||||
type KeyType = "public" | "private" | "secret";
|
||||
type KeyUsage = "encrypt" | "decrypt" | "sign" | "verify" | "deriveKey" | "deriveBits" | "wrapKey" | "unwrapKey";
|
||||
type ImageSmoothingQuality = "high" | "low" | "medium";
|
||||
type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
|
||||
type KeyType = "private" | "public" | "secret";
|
||||
type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey";
|
||||
type NotificationDirection = "auto" | "ltr" | "rtl";
|
||||
type NotificationPermission = "default" | "denied" | "granted";
|
||||
type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2";
|
||||
type PermissionName = "geolocation" | "notifications" | "push" | "midi" | "camera" | "microphone" | "speaker" | "device-info" | "background-sync" | "bluetooth" | "persistent-storage" | "ambient-light-sensor" | "accelerometer" | "gyroscope" | "magnetometer" | "clipboard";
|
||||
type PermissionState = "granted" | "denied" | "prompt";
|
||||
type PushEncryptionKeyName = "p256dh" | "auth";
|
||||
type PermissionName = "accelerometer" | "ambient-light-sensor" | "background-sync" | "bluetooth" | "camera" | "clipboard" | "device-info" | "geolocation" | "gyroscope" | "magnetometer" | "microphone" | "midi" | "notifications" | "persistent-storage" | "push" | "speaker";
|
||||
type PermissionState = "denied" | "granted" | "prompt";
|
||||
type PushEncryptionKeyName = "auth" | "p256dh";
|
||||
type PushPermissionState = "denied" | "granted" | "prompt";
|
||||
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
|
||||
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
|
||||
type RequestCredentials = "omit" | "same-origin" | "include";
|
||||
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
|
||||
type RequestCache = "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload";
|
||||
type RequestCredentials = "include" | "omit" | "same-origin";
|
||||
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";
|
||||
type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors";
|
||||
type RequestRedirect = "follow" | "error" | "manual";
|
||||
type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin";
|
||||
type RequestRedirect = "error" | "follow" | "manual";
|
||||
type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";
|
||||
type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant";
|
||||
type ServiceWorkerUpdateViaCache = "imports" | "all" | "none";
|
||||
type ServiceWorkerState = "activated" | "activating" | "installed" | "installing" | "parsed" | "redundant";
|
||||
type ServiceWorkerUpdateViaCache = "all" | "imports" | "none";
|
||||
type VisibilityState = "hidden" | "visible";
|
||||
type WebGLPowerPreference = "default" | "low-power" | "high-performance";
|
||||
type WebGLPowerPreference = "default" | "high-performance" | "low-power";
|
||||
type WorkerType = "classic" | "module";
|
||||
type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
|
||||
|
||||
Vendored
+68
-4
@@ -64,7 +64,10 @@ declare namespace ts.server.protocol {
|
||||
OrganizeImports = "organizeImports",
|
||||
GetEditsForFileRename = "getEditsForFileRename",
|
||||
ConfigurePlugin = "configurePlugin",
|
||||
SelectionRange = "selectionRange"
|
||||
SelectionRange = "selectionRange",
|
||||
PrepareCallHierarchy = "prepareCallHierarchy",
|
||||
ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls",
|
||||
ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls"
|
||||
}
|
||||
/**
|
||||
* A TypeScript Server message
|
||||
@@ -957,7 +960,7 @@ declare namespace ts.server.protocol {
|
||||
* For external projects, some of the project settings are sent together with
|
||||
* compiler settings.
|
||||
*/
|
||||
type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin;
|
||||
type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin & WatchOptions;
|
||||
/**
|
||||
* Represents a set of changes that happen in project
|
||||
*/
|
||||
@@ -997,6 +1000,31 @@ declare namespace ts.server.protocol {
|
||||
* The host's additional supported .js file extensions
|
||||
*/
|
||||
extraFileExtensions?: FileExtensionInfo[];
|
||||
watchOptions?: WatchOptions;
|
||||
}
|
||||
const enum WatchFileKind {
|
||||
FixedPollingInterval = "FixedPollingInterval",
|
||||
PriorityPollingInterval = "PriorityPollingInterval",
|
||||
DynamicPriorityPolling = "DynamicPriorityPolling",
|
||||
UseFsEvents = "UseFsEvents",
|
||||
UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory"
|
||||
}
|
||||
const enum WatchDirectoryKind {
|
||||
UseFsEvents = "UseFsEvents",
|
||||
FixedPollingInterval = "FixedPollingInterval",
|
||||
DynamicPriorityPolling = "DynamicPriorityPolling"
|
||||
}
|
||||
const enum PollingWatchKind {
|
||||
FixedInterval = "FixedInterval",
|
||||
PriorityInterval = "PriorityInterval",
|
||||
DynamicPriority = "DynamicPriority"
|
||||
}
|
||||
interface WatchOptions {
|
||||
watchFile?: WatchFileKind | ts.WatchFileKind;
|
||||
watchDirectory?: WatchDirectoryKind | ts.WatchDirectoryKind;
|
||||
fallbackPolling?: PollingWatchKind | ts.PollingWatchKind;
|
||||
synchronousWatchDirectory?: boolean;
|
||||
[option: string]: CompilerOptionsValue | undefined;
|
||||
}
|
||||
/**
|
||||
* Configure request; value of command field is "configure". Specifies
|
||||
@@ -2269,6 +2297,39 @@ declare namespace ts.server.protocol {
|
||||
interface NavTreeResponse extends Response {
|
||||
body?: NavigationTree;
|
||||
}
|
||||
interface CallHierarchyItem {
|
||||
name: string;
|
||||
kind: ScriptElementKind;
|
||||
file: string;
|
||||
span: TextSpan;
|
||||
selectionSpan: TextSpan;
|
||||
}
|
||||
interface CallHierarchyIncomingCall {
|
||||
from: CallHierarchyItem;
|
||||
fromSpans: TextSpan[];
|
||||
}
|
||||
interface CallHierarchyOutgoingCall {
|
||||
to: CallHierarchyItem;
|
||||
fromSpans: TextSpan[];
|
||||
}
|
||||
interface PrepareCallHierarchyRequest extends FileLocationRequest {
|
||||
command: CommandTypes.PrepareCallHierarchy;
|
||||
}
|
||||
interface PrepareCallHierarchyResponse extends Response {
|
||||
readonly body: CallHierarchyItem | CallHierarchyItem[];
|
||||
}
|
||||
interface ProvideCallHierarchyIncomingCallsRequest extends FileLocationRequest {
|
||||
command: CommandTypes.ProvideCallHierarchyIncomingCalls;
|
||||
}
|
||||
interface ProvideCallHierarchyIncomingCallsResponse extends Response {
|
||||
readonly body: CallHierarchyIncomingCall[];
|
||||
}
|
||||
interface ProvideCallHierarchyOutgoingCallsRequest extends FileLocationRequest {
|
||||
command: CommandTypes.ProvideCallHierarchyOutgoingCalls;
|
||||
}
|
||||
interface ProvideCallHierarchyOutgoingCallsResponse extends Response {
|
||||
readonly body: CallHierarchyOutgoingCall[];
|
||||
}
|
||||
const enum IndentStyle {
|
||||
None = "None",
|
||||
Block = "Block",
|
||||
@@ -2565,6 +2626,8 @@ declare namespace ts.server.protocol {
|
||||
scriptKind?: ScriptKind;
|
||||
}
|
||||
|
||||
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
|
||||
|
||||
interface JSDocTagInfo {
|
||||
name: string;
|
||||
text?: string;
|
||||
@@ -2593,12 +2656,13 @@ declare namespace ts.server.protocol {
|
||||
/** True if it is intended that this reference form a circularity */
|
||||
circular?: boolean;
|
||||
}
|
||||
|
||||
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
|
||||
}
|
||||
declare namespace ts {
|
||||
// these types are empty stubs for types from services and should not be used directly
|
||||
export type ScriptKind = never;
|
||||
export type WatchFileKind = never;
|
||||
export type WatchDirectoryKind = never;
|
||||
export type PollingWatchKind = never;
|
||||
export type IndentStyle = never;
|
||||
export type JsxEmit = never;
|
||||
export type ModuleKind = never;
|
||||
|
||||
+10438
-8529
File diff suppressed because it is too large
Load Diff
+15604
-11869
File diff suppressed because it is too large
Load Diff
Vendored
+505
-318
File diff suppressed because it is too large
Load Diff
+15600
-11865
File diff suppressed because it is too large
Load Diff
Vendored
+419
-307
File diff suppressed because it is too large
Load Diff
+15072
-11686
File diff suppressed because it is too large
Load Diff
Vendored
+419
-307
File diff suppressed because it is too large
Load Diff
+15072
-11686
File diff suppressed because it is too large
Load Diff
+11661
-9498
File diff suppressed because it is too large
Load Diff
@@ -454,7 +454,7 @@
|
||||
"Generic_type_0_requires_1_type_argument_s_2314": "泛型類型 '{0}' 需要 {1} 個型別引數。",
|
||||
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型型別 '{0}' 需要介於 {1} 和 {2} 之間的型別引數。",
|
||||
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型類型具現化的深度過深,而且可能是無限深。",
|
||||
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可視性不符。",
|
||||
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可見度不符。",
|
||||
"Global_module_exports_may_only_appear_at_top_level_1316": "全域模組匯出只能顯示在最上層。",
|
||||
"Global_module_exports_may_only_appear_in_declaration_files_1315": "全域模組匯出只能顯示在宣告檔案中。",
|
||||
"Global_module_exports_may_only_appear_in_module_files_1314": "全域模組匯出只能顯示在模組檔案中。",
|
||||
|
||||
+9
-8
@@ -2,7 +2,7 @@
|
||||
"name": "typescript",
|
||||
"author": "Microsoft Corp.",
|
||||
"homepage": "https://www.typescriptlang.org/",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"license": "Apache-2.0",
|
||||
"description": "TypeScript is a language for application scale JavaScript development",
|
||||
"keywords": [
|
||||
@@ -54,9 +54,9 @@
|
||||
"@types/through2": "latest",
|
||||
"@types/travis-fold": "latest",
|
||||
"@types/xml2js": "^0.4.0",
|
||||
"@typescript-eslint/eslint-plugin": "2.3.2",
|
||||
"@typescript-eslint/experimental-utils": "2.3.2",
|
||||
"@typescript-eslint/parser": "2.3.2",
|
||||
"@typescript-eslint/eslint-plugin": "2.18.0",
|
||||
"@typescript-eslint/experimental-utils": "2.18.0",
|
||||
"@typescript-eslint/parser": "2.18.0",
|
||||
"async": "latest",
|
||||
"azure-devops-node-api": "^8.0.0",
|
||||
"browser-resolve": "^1.11.2",
|
||||
@@ -65,10 +65,10 @@
|
||||
"chalk": "latest",
|
||||
"convert-source-map": "latest",
|
||||
"del": "5.1.0",
|
||||
"eslint": "6.5.1",
|
||||
"eslint-formatter-autolinkable-stylish": "1.0.3",
|
||||
"eslint-plugin-import": "2.18.2",
|
||||
"eslint-plugin-jsdoc": "15.9.9",
|
||||
"eslint": "6.8.0",
|
||||
"eslint-formatter-autolinkable-stylish": "1.1.1",
|
||||
"eslint-plugin-import": "2.20.0",
|
||||
"eslint-plugin-jsdoc": "21.0.0",
|
||||
"eslint-plugin-no-null": "1.0.2",
|
||||
"fancy-log": "latest",
|
||||
"fs-extra": "^6.0.1",
|
||||
@@ -87,6 +87,7 @@
|
||||
"mocha-fivemat-progress-reporter": "latest",
|
||||
"ms": "latest",
|
||||
"node-fetch": "^2.6.0",
|
||||
"playwright": "latest",
|
||||
"plugin-error": "latest",
|
||||
"pretty-hrtime": "^1.0.3",
|
||||
"prex": "^0.4.3",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
const playwright = require("playwright");
|
||||
const chalk = require("chalk");
|
||||
const { join } = require("path");
|
||||
const { readFileSync } = require("fs");
|
||||
|
||||
// Turning this on will leave the Chromium browser open, giving you the
|
||||
// chance to open up the web inspector.
|
||||
const debugging = false;
|
||||
|
||||
(async () => {
|
||||
for (const browserType of ["chromium", "firefox", "webkit"]) {
|
||||
const browser = await playwright[browserType].launch({ headless: !debugging });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
const errorCaught = err => {
|
||||
console.error(chalk.red("There was an error running built/typescript.js in " + browserType));
|
||||
console.log(err.toString());
|
||||
process.exitCode = 1;
|
||||
};
|
||||
|
||||
page.on("error", errorCaught);
|
||||
page.on("pageerror", errorCaught);
|
||||
page.on("console", log => console[log._type](log._text));
|
||||
|
||||
await page.setContent(`
|
||||
<html>
|
||||
<script>${readFileSync(join("built", "local", "typescript.js"), "utf8")}</script>
|
||||
</html>
|
||||
`);
|
||||
|
||||
if (!debugging) {
|
||||
await browser.close();
|
||||
}
|
||||
else {
|
||||
console.log("Not closing the browser, you'll need to exit the process in your terminal manually");
|
||||
}
|
||||
}
|
||||
})();
|
||||
@@ -60,7 +60,7 @@ function updateTsFile(tsFilePath: string, tsFileContents: string, majorMinor: st
|
||||
const parsedMajorMinor = majorMinorMatch![1];
|
||||
assert(parsedMajorMinor === majorMinor, `versionMajorMinor does not match. ${tsFilePath}: '${parsedMajorMinor}'; package.json: '${majorMinor}'`);
|
||||
|
||||
const versionRgx = /export const version = `\$\{versionMajorMinor\}\.(\d)(-dev)?`;/;
|
||||
const versionRgx = /export const version = `\$\{versionMajorMinor\}\.(\d)(-\w+)?`;/;
|
||||
const patchMatch = versionRgx.exec(tsFileContents);
|
||||
assert(patchMatch !== null, `The file '${tsFilePath}' seems to no longer have a string matching '${versionRgx.toString()}'.`);
|
||||
const parsedPatch = patchMatch![1];
|
||||
|
||||
@@ -10,7 +10,7 @@ export = createRule({
|
||||
recommended: "error",
|
||||
},
|
||||
messages: {
|
||||
excessNamespaceError: `All but one of these namespaces should be moved into seperate files.`,
|
||||
excessNamespaceError: `All but one of these namespaces should be moved into separate files.`,
|
||||
},
|
||||
schema: [],
|
||||
type: "problem",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
|
||||
/// <reference types="node" />
|
||||
|
||||
import Octokit = require("@octokit/rest");
|
||||
import { Octokit } from "@octokit/rest";
|
||||
const {runSequence} = require("./run-sequence");
|
||||
import fs = require("fs");
|
||||
import path = require("path");
|
||||
@@ -26,18 +26,32 @@ async function main() {
|
||||
const currentAuthor = runSequence([
|
||||
["git", ["log", "-1", `--pretty="%aN <%aE>"`]]
|
||||
]);
|
||||
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
|
||||
const inputPR = (await gh.pulls.get({ pull_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript" })).data;
|
||||
let remoteName = "origin";
|
||||
if (inputPR.base.repo.git_url !== `git:github.com/microsoft/TypeScript`) {
|
||||
runSequence([
|
||||
["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url]]
|
||||
]);
|
||||
remoteName = "nonlocal";
|
||||
}
|
||||
const baseBranchName = inputPR.base.ref;
|
||||
runSequence([
|
||||
["git", ["fetch", "origin", "master"]]
|
||||
["git", ["fetch", remoteName, baseBranchName]]
|
||||
]);
|
||||
let logText = runSequence([
|
||||
["git", ["log", `origin/master..${currentSha.trim()}`, `--pretty="%h %s%n%b"`, "--reverse"]]
|
||||
["git", ["log", `${remoteName}/${baseBranchName}..${currentSha.trim()}`, `--pretty="%h %s%n%b"`, "--reverse"]]
|
||||
]);
|
||||
logText = `Cherry-pick PR #${process.env.SOURCE_ISSUE} into ${process.env.TARGET_BRANCH}
|
||||
|
||||
Component commits:
|
||||
${logText.trim()}`;
|
||||
const logpath = path.join(__dirname, "../", "logmessage.txt");
|
||||
const mergebase = runSequence([["git", ["merge-base", "origin/master", currentSha]]]).trim();
|
||||
const mergebase = runSequence([["git", ["merge-base", `${remoteName}/${baseBranchName}`, currentSha]]]).trim();
|
||||
runSequence([
|
||||
["git", ["checkout", "-b", "temp-branch"]],
|
||||
["git", ["reset", mergebase, "--soft"]]
|
||||
@@ -67,11 +81,6 @@ ${logText.trim()}`;
|
||||
["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch
|
||||
]);
|
||||
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
});
|
||||
const r = await gh.pulls.create({
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
@@ -80,7 +89,7 @@ ${logText.trim()}`;
|
||||
head: `${userName}:${branchName}`,
|
||||
base: process.env.TARGET_BRANCH,
|
||||
body:
|
||||
`This cherry-pick was triggerd by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE}
|
||||
`This cherry-pick was triggered by a request on https://github.com/Microsoft/TypeScript/pull/${process.env.SOURCE_ISSUE}
|
||||
Please review the diff and merge if no changes are unexpected.${produceLKG ? ` An LKG update commit is included seperately from the base change.` : ""}
|
||||
You can view the cherry-pick log [here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary).
|
||||
|
||||
@@ -90,7 +99,7 @@ cc ${reviewers.map(r => "@" + r).join(" ")}`,
|
||||
console.log(`Pull request ${num} created.`);
|
||||
|
||||
await gh.issues.createComment({
|
||||
number: +process.env.SOURCE_ISSUE,
|
||||
issue_number: +process.env.SOURCE_ISSUE,
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
body: `Hey @${process.env.REQUESTING_USER}, I've opened #${num} for you.`
|
||||
@@ -101,13 +110,11 @@ main().catch(async e => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
if (process.env.SOURCE_ISSUE) {
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
await gh.issues.createComment({
|
||||
number: +process.env.SOURCE_ISSUE,
|
||||
issue_number: +process.env.SOURCE_ISSUE,
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
body: `Hey @${process.env.REQUESTING_USER}, I couldn't open a PR with the cherry-pick. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)). You may need to squash and pick this PR into ${process.env.TARGET_BRANCH} manually.`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
/// <reference lib="es2015.promise" />
|
||||
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
|
||||
import Octokit = require("@octokit/rest");
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import {runSequence} from "./run-sequence";
|
||||
|
||||
function padNum(num: number) {
|
||||
@@ -12,7 +12,7 @@ function padNum(num: number) {
|
||||
const userName = process.env.GH_USERNAME;
|
||||
const reviewers = process.env.REQUESTING_USER ? [process.env.REQUESTING_USER] : ["weswigham", "sandersn", "RyanCavanaugh"];
|
||||
const now = new Date();
|
||||
const branchName = `user-update-${process.env.TARGET_FORK}-${now.getFullYear()}${padNum(now.getMonth())}${padNum(now.getDay())}${process.env.TARGET_BRANCH ? "-" + process.env.TARGET_BRANCH : ""}`;
|
||||
const branchName = `user-update-${process.env.TARGET_FORK}-${now.getFullYear()}${padNum(now.getMonth() + 1)}${padNum(now.getDate())}${process.env.TARGET_BRANCH ? "-" + process.env.TARGET_BRANCH : ""}`;
|
||||
const remoteUrl = `https://${process.argv[2]}@github.com/${userName}/TypeScript.git`;
|
||||
runSequence([
|
||||
["git", ["checkout", "."]], // reset any changes
|
||||
@@ -24,10 +24,8 @@ runSequence([
|
||||
["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch
|
||||
]);
|
||||
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
gh.pulls.create({
|
||||
owner: process.env.TARGET_FORK!,
|
||||
@@ -54,7 +52,7 @@ cc ${reviewers.map(r => "@" + r).join(" ")}`,
|
||||
}
|
||||
else {
|
||||
await gh.issues.createComment({
|
||||
number: +process.env.SOURCE_ISSUE,
|
||||
issue_number: +process.env.SOURCE_ISSUE,
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
body: `The user suite test run you requested has finished and _failed_. I've opened a [PR with the baseline diff from master](${r.data.html_url}).`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-check
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
|
||||
const Octokit = require("@octokit/rest");
|
||||
const { Octokit } = require("@octokit/rest");
|
||||
const fs = require("fs");
|
||||
|
||||
const requester = process.env.requesting_user;
|
||||
@@ -12,13 +12,11 @@ const outputTableText = fs.readFileSync(process.argv[3], { encoding: "utf8" });
|
||||
console.log(`Fragment contents:
|
||||
${outputTableText}`);
|
||||
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
gh.issues.createComment({
|
||||
number: +source,
|
||||
issue_number: +source,
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
body: `@${requester}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-check
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
|
||||
const Octokit = require("@octokit/rest");
|
||||
const { Octokit } = require("@octokit/rest");
|
||||
const ado = require("azure-devops-node-api");
|
||||
const { default: fetch } = require("node-fetch");
|
||||
|
||||
@@ -23,10 +23,8 @@ async function main() {
|
||||
const tgzUrl = new URL(artifact.resource.url);
|
||||
tgzUrl.search = `artifactName=tgz&fileId=${file.blob.id}&fileName=${file.path}`;
|
||||
const link = "" + tgzUrl;
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
|
||||
// Please keep the strings "an installable tgz" and "packed" in this message, as well as the devDependencies section,
|
||||
@@ -57,13 +55,11 @@ main().catch(async e => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
if (process.env.SOURCE_ISSUE) {
|
||||
const gh = new Octokit();
|
||||
gh.authenticate({
|
||||
type: "token",
|
||||
token: process.argv[2]
|
||||
const gh = new Octokit({
|
||||
auth: process.argv[2]
|
||||
});
|
||||
await gh.issues.createComment({
|
||||
number: +process.env.SOURCE_ISSUE,
|
||||
issue_number: +process.env.SOURCE_ISSUE,
|
||||
owner: "Microsoft",
|
||||
repo: "TypeScript",
|
||||
body: `Hey @${process.env.REQUESTING_USER}, something went wrong when looking for the build artifact. ([You can check the log here](https://typescript.visualstudio.com/TypeScript/_build/index?buildId=${process.env.BUILD_BUILDID}&_a=summary)).`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @ts-check
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
const Octokit = require("@octokit/rest");
|
||||
const { Octokit } = require("@octokit/rest");
|
||||
const { runSequence } = require("./run-sequence");
|
||||
|
||||
// The first is used by bot-based kickoffs, the second by automatic triggers
|
||||
@@ -76,7 +76,8 @@ async function main() {
|
||||
]);
|
||||
|
||||
// Merge each branch into `experimental` (which, if there is a conflict, we now know is from inter-experiment conflict)
|
||||
for (const branch of prnums) {
|
||||
for (const branchnum of prnums) {
|
||||
const branch = "" + branchnum;
|
||||
// Find the merge base
|
||||
const mergeBase = runSequence([
|
||||
["git", ["merge-base", branch, "experimental"]],
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"extends": "./.eslintrc.json",
|
||||
"parserOptions": {
|
||||
"tsconfigRootDir": "src",
|
||||
"project": "./tsconfig-base.json"
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/no-unnecessary-qualifier": "error",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": "error"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
{
|
||||
"extends": "../.eslintrc.json",
|
||||
"parserOptions": {
|
||||
"tsconfigRootDir": "src",
|
||||
"project": "./tsconfig-base.json"
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/no-unnecessary-qualifier": "error",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["lib/*.d.ts"],
|
||||
|
||||
@@ -9,13 +9,14 @@ interface ServerCancellationToken {
|
||||
}
|
||||
|
||||
function pipeExists(name: string): boolean {
|
||||
try {
|
||||
fs.statSync(name);
|
||||
return true;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
// Unlike statSync, existsSync doesn't throw an exception if the target doesn't exist.
|
||||
// A comment in the node code suggests they're stuck with that decision for back compat
|
||||
// (https://github.com/nodejs/node/blob/9da241b600182a9ff400f6efc24f11a6303c27f7/lib/fs.js#L222).
|
||||
// Caveat: If a named pipe does exist, the first call to existsSync will return true, as for
|
||||
// statSync. Subsequent calls will return false, whereas statSync would throw an exception
|
||||
// indicating that the pipe was busy. The difference is immaterial, since our statSync
|
||||
// implementation returned false from its catch block.
|
||||
return fs.existsSync(name);
|
||||
}
|
||||
|
||||
function createCancellationToken(args: string[]): ServerCancellationToken {
|
||||
|
||||
+174
-28
@@ -409,7 +409,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getDisplayName(node: Declaration): string {
|
||||
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.assertDefined(getDeclarationName(node)));
|
||||
return isNamedDeclaration(node) ? declarationNameToString(node.name) : unescapeLeadingUnderscores(Debug.checkDefined(getDeclarationName(node)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -861,7 +861,7 @@ namespace ts {
|
||||
case SyntaxKind.ThisKeyword:
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
case SyntaxKind.ElementAccessExpression:
|
||||
return isNarrowableReference(expr);
|
||||
return containsNarrowableReference(expr);
|
||||
case SyntaxKind.CallExpression:
|
||||
return hasNarrowableArgument(<CallExpression>expr);
|
||||
case SyntaxKind.ParenthesizedExpression:
|
||||
@@ -879,20 +879,23 @@ namespace ts {
|
||||
function isNarrowableReference(expr: Expression): boolean {
|
||||
return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword ||
|
||||
(isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
|
||||
isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
|
||||
isOptionalChain(expr);
|
||||
isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
|
||||
}
|
||||
|
||||
function containsNarrowableReference(expr: Expression): boolean {
|
||||
return isNarrowableReference(expr) || isOptionalChain(expr) && containsNarrowableReference(expr.expression);
|
||||
}
|
||||
|
||||
function hasNarrowableArgument(expr: CallExpression) {
|
||||
if (expr.arguments) {
|
||||
for (const argument of expr.arguments) {
|
||||
if (isNarrowableReference(argument)) {
|
||||
if (containsNarrowableReference(argument)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (expr.expression.kind === SyntaxKind.PropertyAccessExpression &&
|
||||
isNarrowableReference((<PropertyAccessExpression>expr.expression).expression)) {
|
||||
containsNarrowableReference((<PropertyAccessExpression>expr.expression).expression)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -909,7 +912,7 @@ namespace ts {
|
||||
function isNarrowingBinaryExpression(expr: BinaryExpression) {
|
||||
switch (expr.operatorToken.kind) {
|
||||
case SyntaxKind.EqualsToken:
|
||||
return isNarrowableReference(expr.left);
|
||||
return containsNarrowableReference(expr.left);
|
||||
case SyntaxKind.EqualsEqualsToken:
|
||||
case SyntaxKind.ExclamationEqualsToken:
|
||||
case SyntaxKind.EqualsEqualsEqualsToken:
|
||||
@@ -938,7 +941,7 @@ namespace ts {
|
||||
return isNarrowableOperand((<BinaryExpression>expr).right);
|
||||
}
|
||||
}
|
||||
return isNarrowableReference(expr);
|
||||
return containsNarrowableReference(expr);
|
||||
}
|
||||
|
||||
function createBranchLabel(): FlowLabel {
|
||||
@@ -1442,28 +1445,156 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const enum BindBinaryExpressionFlowState {
|
||||
BindThenBindChildren,
|
||||
MaybeBindLeft,
|
||||
BindToken,
|
||||
BindRight,
|
||||
FinishBind
|
||||
}
|
||||
|
||||
function bindBinaryExpressionFlow(node: BinaryExpression) {
|
||||
const operator = node.operatorToken.kind;
|
||||
if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken) {
|
||||
if (isTopLevelLogicalExpression(node)) {
|
||||
const postExpressionLabel = createBranchLabel();
|
||||
bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
|
||||
currentFlow = finishFlowLabel(postExpressionLabel);
|
||||
}
|
||||
else {
|
||||
bindLogicalExpression(node, currentTrueTarget!, currentFalseTarget!);
|
||||
const workStacks: {
|
||||
expr: BinaryExpression[],
|
||||
state: BindBinaryExpressionFlowState[],
|
||||
inStrictMode: (boolean | undefined)[],
|
||||
parent: (Node | undefined)[],
|
||||
subtreeFlags: (number | undefined)[]
|
||||
} = {
|
||||
expr: [node],
|
||||
state: [BindBinaryExpressionFlowState.MaybeBindLeft],
|
||||
inStrictMode: [undefined],
|
||||
parent: [undefined],
|
||||
subtreeFlags: [undefined]
|
||||
};
|
||||
let stackIndex = 0;
|
||||
while (stackIndex >= 0) {
|
||||
node = workStacks.expr[stackIndex];
|
||||
switch (workStacks.state[stackIndex]) {
|
||||
case BindBinaryExpressionFlowState.BindThenBindChildren: {
|
||||
// This state is used only when recuring, to emulate the work that `bind` does before
|
||||
// reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
|
||||
node.parent = parent;
|
||||
const saveInStrictMode = inStrictMode;
|
||||
bindWorker(node);
|
||||
const saveParent = parent;
|
||||
parent = node;
|
||||
|
||||
let subtreeFlagsState: number | undefined;
|
||||
// While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
|
||||
// and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
|
||||
if (skipTransformFlagAggregation) {
|
||||
// do nothing extra
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
|
||||
skipTransformFlagAggregation = true;
|
||||
subtreeFlagsState = -1;
|
||||
}
|
||||
else {
|
||||
const savedSubtreeTransformFlags = subtreeTransformFlags;
|
||||
subtreeTransformFlags = 0;
|
||||
subtreeFlagsState = savedSubtreeTransformFlags;
|
||||
}
|
||||
|
||||
advanceState(BindBinaryExpressionFlowState.MaybeBindLeft, saveInStrictMode, saveParent, subtreeFlagsState);
|
||||
break;
|
||||
}
|
||||
case BindBinaryExpressionFlowState.MaybeBindLeft: {
|
||||
const operator = node.operatorToken.kind;
|
||||
// TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
|
||||
// we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
|
||||
// For now, though, since the common cases are chained `+`, leaving it recursive is fine
|
||||
if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.QuestionQuestionToken) {
|
||||
if (isTopLevelLogicalExpression(node)) {
|
||||
const postExpressionLabel = createBranchLabel();
|
||||
bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
|
||||
currentFlow = finishFlowLabel(postExpressionLabel);
|
||||
}
|
||||
else {
|
||||
bindLogicalExpression(node, currentTrueTarget!, currentFalseTarget!);
|
||||
}
|
||||
completeNode();
|
||||
}
|
||||
else {
|
||||
advanceState(BindBinaryExpressionFlowState.BindToken);
|
||||
maybeBind(node.left);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case BindBinaryExpressionFlowState.BindToken: {
|
||||
advanceState(BindBinaryExpressionFlowState.BindRight);
|
||||
maybeBind(node.operatorToken);
|
||||
break;
|
||||
}
|
||||
case BindBinaryExpressionFlowState.BindRight: {
|
||||
advanceState(BindBinaryExpressionFlowState.FinishBind);
|
||||
maybeBind(node.right);
|
||||
break;
|
||||
}
|
||||
case BindBinaryExpressionFlowState.FinishBind: {
|
||||
const operator = node.operatorToken.kind;
|
||||
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
|
||||
bindAssignmentTargetFlow(node.left);
|
||||
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
|
||||
const elementAccess = <ElementAccessExpression>node.left;
|
||||
if (isNarrowableOperand(elementAccess.expression)) {
|
||||
currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
completeNode();
|
||||
break;
|
||||
}
|
||||
default: return Debug.fail(`Invalid state ${workStacks.state[stackIndex]} for bindBinaryExpressionFlow`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
bindEachChild(node);
|
||||
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
|
||||
bindAssignmentTargetFlow(node.left);
|
||||
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
|
||||
const elementAccess = <ElementAccessExpression>node.left;
|
||||
if (isNarrowableOperand(elementAccess.expression)) {
|
||||
currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
|
||||
* head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
|
||||
*/
|
||||
function advanceState(state: BindBinaryExpressionFlowState, isInStrictMode?: boolean, parent?: Node, subtreeFlags?: number) {
|
||||
workStacks.state[stackIndex] = state;
|
||||
if (isInStrictMode !== undefined) {
|
||||
workStacks.inStrictMode[stackIndex] = isInStrictMode;
|
||||
}
|
||||
if (parent !== undefined) {
|
||||
workStacks.parent[stackIndex] = parent;
|
||||
}
|
||||
if (subtreeFlags !== undefined) {
|
||||
workStacks.subtreeFlags[stackIndex] = subtreeFlags;
|
||||
}
|
||||
}
|
||||
|
||||
function completeNode() {
|
||||
if (workStacks.inStrictMode[stackIndex] !== undefined) {
|
||||
if (workStacks.subtreeFlags[stackIndex] === -1) {
|
||||
skipTransformFlagAggregation = false;
|
||||
subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
|
||||
}
|
||||
else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
|
||||
subtreeTransformFlags = workStacks.subtreeFlags[stackIndex]! | computeTransformFlagsForNode(node, subtreeTransformFlags);
|
||||
}
|
||||
inStrictMode = workStacks.inStrictMode[stackIndex]!;
|
||||
parent = workStacks.parent[stackIndex]!;
|
||||
}
|
||||
stackIndex--;
|
||||
}
|
||||
|
||||
/**
|
||||
* If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
|
||||
*/
|
||||
function maybeBind(node: Node) {
|
||||
if (node && isBinaryExpression(node)) {
|
||||
stackIndex++;
|
||||
workStacks.expr[stackIndex] = node;
|
||||
workStacks.state[stackIndex] = BindBinaryExpressionFlowState.BindThenBindChildren;
|
||||
workStacks.inStrictMode[stackIndex] = undefined;
|
||||
workStacks.parent[stackIndex] = undefined;
|
||||
workStacks.subtreeFlags[stackIndex] = undefined;
|
||||
}
|
||||
else {
|
||||
bind(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1982,7 +2113,9 @@ namespace ts {
|
||||
container = (declName.parent.expression as PropertyAccessExpression).name;
|
||||
break;
|
||||
case AssignmentDeclarationKind.Property:
|
||||
container = isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name : declName.parent.expression;
|
||||
container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
|
||||
: isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
|
||||
: declName.parent.expression;
|
||||
break;
|
||||
case AssignmentDeclarationKind.None:
|
||||
return Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
|
||||
@@ -2605,6 +2738,9 @@ namespace ts {
|
||||
declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.ExportStar, SymbolFlags.None);
|
||||
}
|
||||
else if (isNamespaceExport(node.exportClause)) {
|
||||
// declareSymbol walks up parents to find name text, parent _must_ be set
|
||||
// but won't be set by the normal binder walk until `bindChildren` later on.
|
||||
node.exportClause.parent = node;
|
||||
declareSymbol(container.symbol.exports, container.symbol, node.exportClause, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
|
||||
}
|
||||
}
|
||||
@@ -3990,8 +4126,18 @@ namespace ts {
|
||||
case SyntaxKind.TemplateHead:
|
||||
case SyntaxKind.TemplateMiddle:
|
||||
case SyntaxKind.TemplateTail:
|
||||
case SyntaxKind.TemplateExpression:
|
||||
if ((<NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail>node).templateFlags) {
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
break;
|
||||
}
|
||||
// falls through
|
||||
case SyntaxKind.TaggedTemplateExpression:
|
||||
if (hasInvalidEscape((<TaggedTemplateExpression>node).template)) {
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
break;
|
||||
}
|
||||
// falls through
|
||||
case SyntaxKind.TemplateExpression:
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
case SyntaxKind.StaticKeyword:
|
||||
case SyntaxKind.MetaProperty:
|
||||
|
||||
+24
-24
@@ -366,7 +366,7 @@ namespace ts {
|
||||
|
||||
// With --out or --outFile all outputs go into single file
|
||||
// so operations are performed directly on program, return program
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const compilerOptions = program.getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
@@ -393,10 +393,10 @@ namespace ts {
|
||||
if (affectedFilesPendingEmit) {
|
||||
const seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = createMap());
|
||||
for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) {
|
||||
const affectedFile = Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
|
||||
const affectedFile = Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
|
||||
if (affectedFile) {
|
||||
const seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
|
||||
const emitKind = Debug.assertDefined(Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
|
||||
const emitKind = Debug.checkDefined(Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
|
||||
if (seenKind === undefined || seenKind < emitKind) {
|
||||
// emit this file
|
||||
state.affectedFilesPendingEmitIndex = i;
|
||||
@@ -422,7 +422,7 @@ namespace ts {
|
||||
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
|
||||
if (!state.cleanedDiagnosticsOfLibFiles) {
|
||||
state.cleanedDiagnosticsOfLibFiles = true;
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const options = program.getCompilerOptions();
|
||||
forEach(program.getSourceFiles(), f =>
|
||||
program.isSourceFileDefaultLibrary(f) &&
|
||||
@@ -446,7 +446,7 @@ namespace ts {
|
||||
removeSemanticDiagnosticsOf(state, path);
|
||||
|
||||
if (!state.changedFilesSet.has(path)) {
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
const sourceFile = program.getSourceFileByPath(path);
|
||||
if (sourceFile) {
|
||||
// Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
|
||||
@@ -457,7 +457,7 @@ namespace ts {
|
||||
state,
|
||||
program,
|
||||
sourceFile,
|
||||
Debug.assertDefined(state.currentAffectedFilesSignatures),
|
||||
Debug.checkDefined(state.currentAffectedFilesSignatures),
|
||||
cancellationToken,
|
||||
computeHash,
|
||||
state.currentAffectedFilesExportedModulesMap
|
||||
@@ -486,8 +486,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
function isChangedSignagure(state: BuilderProgramState, path: Path) {
|
||||
const newSignature = Debug.assertDefined(state.currentAffectedFilesSignatures).get(path);
|
||||
const oldSignagure = Debug.assertDefined(state.fileInfos.get(path)).signature;
|
||||
const newSignature = Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
|
||||
const oldSignagure = Debug.checkDefined(state.fileInfos.get(path)).signature;
|
||||
return newSignature !== oldSignagure;
|
||||
}
|
||||
|
||||
@@ -515,7 +515,7 @@ namespace ts {
|
||||
seenFileNamesMap.set(currentPath, true);
|
||||
const result = fn(state, currentPath);
|
||||
if (result && isChangedSignagure(state, currentPath)) {
|
||||
const currentSourceFile = Debug.assertDefined(state.program).getSourceFileByPath(currentPath)!;
|
||||
const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath)!;
|
||||
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
|
||||
}
|
||||
}
|
||||
@@ -526,7 +526,7 @@ namespace ts {
|
||||
const seenFileAndExportsOfFile = createMap<true>();
|
||||
// Go through exported modules from cache first
|
||||
// If exported modules has path, all files referencing file exported from are affected
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
|
||||
exportedModules &&
|
||||
exportedModules.has(affectedFile.resolvedPath) &&
|
||||
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
|
||||
@@ -567,7 +567,7 @@ namespace ts {
|
||||
Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
|
||||
// Go through exported modules from cache first
|
||||
// If exported modules has path, all files referencing file exported from are affected
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
|
||||
exportedModules &&
|
||||
exportedModules.has(filePath) &&
|
||||
forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
|
||||
@@ -655,7 +655,7 @@ namespace ts {
|
||||
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
|
||||
return concatenate(
|
||||
getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken),
|
||||
Debug.assertDefined(state.program).getProgramDiagnostics(sourceFile)
|
||||
Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -674,7 +674,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Diagnostics werent cached, get them from program, and cache the result
|
||||
const diagnostics = Debug.assertDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
|
||||
const diagnostics = Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
|
||||
if (state.semanticDiagnosticsPerFile) {
|
||||
state.semanticDiagnosticsPerFile.set(path, diagnostics);
|
||||
}
|
||||
@@ -695,7 +695,7 @@ namespace ts {
|
||||
*/
|
||||
function getProgramBuildInfo(state: Readonly<ReusableBuilderProgramState>, getCanonicalFileName: GetCanonicalFileName): ProgramBuildInfo | undefined {
|
||||
if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined;
|
||||
const currentDirectory = Debug.assertDefined(state.program).getCurrentDirectory();
|
||||
const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory();
|
||||
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory));
|
||||
const fileInfos: MapLike<BuilderState.FileInfo> = {};
|
||||
state.fileInfos.forEach((value, key) => {
|
||||
@@ -891,10 +891,10 @@ namespace ts {
|
||||
backupState = cloneBuilderProgramState(state);
|
||||
};
|
||||
builderProgram.restoreState = () => {
|
||||
state = Debug.assertDefined(backupState);
|
||||
state = Debug.checkDefined(backupState);
|
||||
backupState = undefined;
|
||||
};
|
||||
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile);
|
||||
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile);
|
||||
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
|
||||
builderProgram.emit = emit;
|
||||
builderProgram.releaseProgram = () => {
|
||||
@@ -932,7 +932,7 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const affected = Debug.assertDefined(state.program);
|
||||
const affected = Debug.checkDefined(state.program);
|
||||
return toAffectedFileEmitResult(
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
@@ -948,7 +948,7 @@ namespace ts {
|
||||
isPendingEmitFile = true;
|
||||
}
|
||||
else {
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const program = Debug.checkDefined(state.program);
|
||||
if (state.programEmitComplete) return undefined;
|
||||
affected = program;
|
||||
}
|
||||
@@ -958,7 +958,7 @@ namespace ts {
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
// Otherwise just affected file
|
||||
Debug.assertDefined(state.program).emit(
|
||||
Debug.checkDefined(state.program).emit(
|
||||
affected === state.program ? undefined : affected as SourceFile,
|
||||
writeFile || maybeBind(host, host.writeFile),
|
||||
cancellationToken,
|
||||
@@ -1009,7 +1009,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
}
|
||||
return Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
return Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1062,11 +1062,11 @@ namespace ts {
|
||||
*/
|
||||
function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
|
||||
assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
|
||||
const compilerOptions = Debug.assertDefined(state.program).getCompilerOptions();
|
||||
const compilerOptions = Debug.checkDefined(state.program).getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
// We dont need to cache the diagnostics just return them from program
|
||||
return Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
return Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
}
|
||||
|
||||
if (sourceFile) {
|
||||
@@ -1080,7 +1080,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
let diagnostics: Diagnostic[] | undefined;
|
||||
for (const sourceFile of Debug.assertDefined(state.program).getSourceFiles()) {
|
||||
for (const sourceFile of Debug.checkDefined(state.program).getSourceFiles()) {
|
||||
diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken));
|
||||
}
|
||||
return diagnostics || emptyArray;
|
||||
@@ -1193,7 +1193,7 @@ namespace ts {
|
||||
};
|
||||
|
||||
function getProgram() {
|
||||
return Debug.assertDefined(state.program);
|
||||
return Debug.checkDefined(state.program);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +210,7 @@ namespace ts {
|
||||
|
||||
// Create the reference map, and set the file infos
|
||||
for (const sourceFile of newProgram.getSourceFiles()) {
|
||||
const version = Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
|
||||
const version = Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
|
||||
const oldInfo = useOldState ? oldState!.fileInfos.get(sourceFile.resolvedPath) : undefined;
|
||||
if (referencedMap) {
|
||||
const newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
|
||||
|
||||
+1027
-592
File diff suppressed because it is too large
Load Diff
@@ -475,11 +475,12 @@ namespace ts {
|
||||
{
|
||||
name: "importsNotUsedAsValues",
|
||||
type: createMapFromTemplate({
|
||||
remove: importsNotUsedAsValues.Remove,
|
||||
preserve: importsNotUsedAsValues.Preserve,
|
||||
error: importsNotUsedAsValues.Error
|
||||
remove: ImportsNotUsedAsValues.Remove,
|
||||
preserve: ImportsNotUsedAsValues.Preserve,
|
||||
error: ImportsNotUsedAsValues.Error
|
||||
}),
|
||||
affectsEmit: true,
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
|
||||
},
|
||||
@@ -742,12 +743,15 @@ namespace ts {
|
||||
{
|
||||
name: "experimentalDecorators",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Experimental_Options,
|
||||
description: Diagnostics.Enables_experimental_support_for_ES7_decorators
|
||||
},
|
||||
{
|
||||
name: "emitDecoratorMetadata",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Experimental_Options,
|
||||
description: Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
|
||||
},
|
||||
@@ -762,6 +766,7 @@ namespace ts {
|
||||
{
|
||||
name: "resolveJsonModule",
|
||||
type: "boolean",
|
||||
affectsModuleResolution: true,
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Include_modules_imported_with_json_extension
|
||||
},
|
||||
@@ -817,6 +822,7 @@ namespace ts {
|
||||
{
|
||||
name: "noErrorTruncation",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Do_not_truncate_error_messages
|
||||
},
|
||||
@@ -946,6 +952,7 @@ namespace ts {
|
||||
{
|
||||
name: "forceConsistentCasingInFileNames",
|
||||
type: "boolean",
|
||||
affectsModuleResolution: true,
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
|
||||
},
|
||||
@@ -967,6 +974,7 @@ namespace ts {
|
||||
name: "useDefineForClassFields",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
|
||||
},
|
||||
@@ -2610,7 +2618,7 @@ namespace ts {
|
||||
errors: Push<Diagnostic>,
|
||||
extendedConfigCache?: Map<ExtendedConfigCacheEntry>
|
||||
): ParsedTsconfig | undefined {
|
||||
const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toLowerCase(extendedConfigPath);
|
||||
const path = host.useCaseSensitiveFileNames ? extendedConfigPath : toFileNameLowerCase(extendedConfigPath);
|
||||
let value: ExtendedConfigCacheEntry | undefined;
|
||||
let extendedResult: TsConfigSourceFile;
|
||||
let extendedConfig: ParsedTsconfig | undefined;
|
||||
@@ -2914,7 +2922,7 @@ namespace ts {
|
||||
export function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: readonly FileExtensionInfo[] = []): ExpandResult {
|
||||
basePath = normalizePath(basePath);
|
||||
|
||||
const keyMapper = host.useCaseSensitiveFileNames ? identity : toLowerCase;
|
||||
const keyMapper = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
|
||||
|
||||
// Literal file names (provided via the "files" array in tsconfig.json) are stored in a
|
||||
// file map with a possibly case insensitive key. We use this map later when when including
|
||||
@@ -3083,7 +3091,7 @@ namespace ts {
|
||||
const match = wildcardDirectoryPattern.exec(spec);
|
||||
if (match) {
|
||||
return {
|
||||
key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(),
|
||||
key: useCaseSensitiveFileNames ? match[0] : toFileNameLowerCase(match[0]),
|
||||
flags: watchRecursivePattern.test(spec) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None
|
||||
};
|
||||
}
|
||||
|
||||
+62
-2
@@ -1269,6 +1269,11 @@ namespace ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new object by adding the own properties of `second`, then the own properties of `first`.
|
||||
*
|
||||
* NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
|
||||
*/
|
||||
export function extend<T1, T2>(first: T1, second: T2): T1 & T2 {
|
||||
const result: T1 & T2 = <any>{};
|
||||
for (const id in second) {
|
||||
@@ -1399,6 +1404,46 @@ namespace ts {
|
||||
/** Returns lower case string */
|
||||
export function toLowerCase(x: string) { return x.toLowerCase(); }
|
||||
|
||||
// We convert the file names to lower case as key for file name on case insensitive file system
|
||||
// While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
|
||||
// it to lower case, fileName with its lowercase form can exist along side it.
|
||||
// Handle special characters and make those case sensitive instead
|
||||
//
|
||||
// |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
|
||||
// | 1. | i | 105 | Ascii i |
|
||||
// | 2. | I | 73 | Ascii I |
|
||||
// |-------- Special characters ------------------------------------------------------------------------|
|
||||
// | 3. | \u0130 | 304 | Uppper case I with dot above |
|
||||
// | 4. | i,\u0307 | 105,775 | i, followed by 775: Lower case of (3rd item) |
|
||||
// | 5. | I,\u0307 | 73,775 | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
|
||||
// | 6. | \u0131 | 305 | Lower case i without dot, upper case is I (2nd item) |
|
||||
// | 7. | \u00DF | 223 | Lower case sharp s |
|
||||
//
|
||||
// Because item 3 is special where in its lowercase character has its own
|
||||
// upper case form we cant convert its case.
|
||||
// Rest special characters are either already in lower case format or
|
||||
// they have corresponding upper case character so they dont need special handling
|
||||
//
|
||||
// But to avoid having to do string building for most common cases, also ignore
|
||||
// a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
|
||||
const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
|
||||
/**
|
||||
* Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
|
||||
* This function is used in places where we want to make file name as a key on these systems
|
||||
* It is possible on mac to be able to refer to file name with I with dot on top as a fileName with its lower case form
|
||||
* But on windows we cannot. Windows can have fileName with I with dot on top next to its lower case and they can not each be referred with the lowercase forms
|
||||
* Technically we would want this function to be platform sepcific as well but
|
||||
* our api has till now only taken caseSensitive as the only input and just for some characters we dont want to update API and ensure all customers use those api
|
||||
* We could use upper case and we would still need to deal with the descripencies but
|
||||
* we want to continue using lower case since in most cases filenames are lowercasewe and wont need any case changes and avoid having to store another string for the key
|
||||
* So for this function purpose, we go ahead and assume character I with dot on top it as case sensitive since its very unlikely to use lower case form of that special character
|
||||
*/
|
||||
export function toFileNameLowerCase(x: string) {
|
||||
return fileNameLowerCaseRegExp.test(x) ?
|
||||
x.replace(fileNameLowerCaseRegExp, toLowerCase) :
|
||||
x;
|
||||
}
|
||||
|
||||
/** Throws an error because a function is not implemented. */
|
||||
export function notImplemented(): never {
|
||||
throw new Error("Not implemented");
|
||||
@@ -1860,7 +1905,7 @@ namespace ts {
|
||||
|
||||
export type GetCanonicalFileName = (fileName: string) => string;
|
||||
export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): GetCanonicalFileName {
|
||||
return useCaseSensitiveFileNames ? identity : toLowerCase;
|
||||
return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
|
||||
}
|
||||
|
||||
/** Represents a "prefix*suffix" pattern. */
|
||||
@@ -2006,4 +2051,19 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function padLeft(s: string, length: number) {
|
||||
while (s.length < length) {
|
||||
s = " " + s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export function padRight(s: string, length: number) {
|
||||
while (s.length < length) {
|
||||
s = s + " ";
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace 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.
|
||||
export const versionMajorMinor = "3.8";
|
||||
export const versionMajorMinor = "3.9";
|
||||
/** The version of the TypeScript compiler release */
|
||||
export const version = `${versionMajorMinor}.0-dev`;
|
||||
|
||||
|
||||
+182
-92
@@ -1,47 +1,52 @@
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
export namespace Debug {
|
||||
/* eslint-disable prefer-const */
|
||||
export let currentAssertionLevel = AssertionLevel.None;
|
||||
let currentAssertionLevel = AssertionLevel.None;
|
||||
|
||||
// eslint-disable-next-line prefer-const
|
||||
export let isDebugging = false;
|
||||
/* eslint-enable prefer-const */
|
||||
|
||||
type AssertionKeys = MatchingKeys<typeof Debug, AnyFunction>;
|
||||
|
||||
const assertionCache: Partial<Record<AssertionKeys, { level: AssertionLevel, assertion: AnyFunction }>> = {};
|
||||
|
||||
export function getAssertionLevel() {
|
||||
return currentAssertionLevel;
|
||||
}
|
||||
|
||||
export function setAssertionLevel(level: AssertionLevel) {
|
||||
const prevAssertionLevel = currentAssertionLevel;
|
||||
currentAssertionLevel = level;
|
||||
|
||||
if (level > prevAssertionLevel) {
|
||||
// restore assertion functions for the current assertion level (see `shouldAssertFunction`).
|
||||
for (const key of getOwnKeys(assertionCache) as AssertionKeys[]) {
|
||||
const cachedFunc = assertionCache[key];
|
||||
if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
|
||||
(Debug as any)[key] = cachedFunc;
|
||||
assertionCache[key] = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldAssert(level: AssertionLevel): boolean {
|
||||
return currentAssertionLevel >= level;
|
||||
}
|
||||
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): void {
|
||||
if (!expression) {
|
||||
if (verboseDebugInfo) {
|
||||
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
|
||||
}
|
||||
fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string): void {
|
||||
if (a !== b) {
|
||||
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
|
||||
fail(`Expected ${a} === ${b}. ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThan(a: number, b: number, msg?: string): void {
|
||||
if (a >= b) {
|
||||
fail(`Expected ${a} < ${b}. ${msg || ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThanOrEqual(a: number, b: number): void {
|
||||
if (a > b) {
|
||||
fail(`Expected ${a} <= ${b}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertGreaterThanOrEqual(a: number, b: number): void {
|
||||
if (a < b) {
|
||||
fail(`Expected ${a} >= ${b}`);
|
||||
/**
|
||||
* Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
|
||||
* Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
|
||||
* @param level The minimum assertion level required.
|
||||
* @param name The name of the current assertion function.
|
||||
*/
|
||||
function shouldAssertFunction<K extends AssertionKeys>(level: AssertionLevel, name: K): boolean {
|
||||
if (!shouldAssert(level)) {
|
||||
assertionCache[name] = { level, assertion: Debug[name] };
|
||||
(Debug as any)[name] = noop;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
|
||||
@@ -53,24 +58,163 @@ namespace ts {
|
||||
throw e;
|
||||
}
|
||||
|
||||
export function assertDefined<T>(value: T | null | undefined, message?: string): T {
|
||||
export function failBadSyntaxKind(node: Node, message?: string, stackCrawlMark?: AnyFunction): never {
|
||||
return fail(
|
||||
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
|
||||
stackCrawlMark || failBadSyntaxKind);
|
||||
}
|
||||
|
||||
export function assert(expression: boolean, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): asserts expression {
|
||||
if (!expression) {
|
||||
message = message ? `False expression: ${message}` : "False expression.";
|
||||
if (verboseDebugInfo) {
|
||||
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
|
||||
}
|
||||
fail(message, stackCrawlMark || assert);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string, stackCrawlMark?: AnyFunction): void {
|
||||
if (a !== b) {
|
||||
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
|
||||
fail(`Expected ${a} === ${b}. ${message}`, stackCrawlMark || assertEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThan(a: number, b: number, msg?: string, stackCrawlMark?: AnyFunction): void {
|
||||
if (a >= b) {
|
||||
fail(`Expected ${a} < ${b}. ${msg || ""}`, stackCrawlMark || assertLessThan);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertLessThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
|
||||
if (a > b) {
|
||||
fail(`Expected ${a} <= ${b}`, stackCrawlMark || assertLessThanOrEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertGreaterThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
|
||||
if (a < b) {
|
||||
fail(`Expected ${a} >= ${b}`, stackCrawlMark || assertGreaterThanOrEqual);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertIsDefined<T>(value: T, message?: string, stackCrawlMark?: AnyFunction): asserts value is NonNullable<T> {
|
||||
// eslint-disable-next-line no-null/no-null
|
||||
if (value === undefined || value === null) return fail(message);
|
||||
if (value === undefined || value === null) {
|
||||
fail(message, stackCrawlMark || assertIsDefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function checkDefined<T>(value: T | null | undefined, message?: string, stackCrawlMark?: AnyFunction): T {
|
||||
assertIsDefined(value, message, stackCrawlMark || checkDefined);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function assertEachDefined<T, A extends readonly T[]>(value: A, message?: string): A {
|
||||
/**
|
||||
* @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
|
||||
* a value is defined at the statement level.
|
||||
*/
|
||||
export const assertDefined = checkDefined;
|
||||
|
||||
export function assertEachIsDefined<T extends Node>(value: NodeArray<T>, message?: string, stackCrawlMark?: AnyFunction): asserts value is NodeArray<T>;
|
||||
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[];
|
||||
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) {
|
||||
for (const v of value) {
|
||||
assertDefined(v, message);
|
||||
assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function checkEachDefined<T, A extends readonly T[]>(value: A, message?: string, stackCrawlMark?: AnyFunction): A {
|
||||
assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
export const assertEachDefined = checkEachDefined;
|
||||
|
||||
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
|
||||
const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member);
|
||||
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
|
||||
}
|
||||
|
||||
export function assertEachNode<T extends Node, U extends T>(nodes: NodeArray<T>, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is NodeArray<U>;
|
||||
export function assertEachNode<T extends Node, U extends T>(nodes: readonly T[], test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is readonly U[];
|
||||
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertEachNode")) {
|
||||
assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`,
|
||||
stackCrawlMark || assertEachNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
|
||||
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertNode")) {
|
||||
assert(
|
||||
node !== undefined && (test === undefined || test(node)),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertNotNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is Exclude<T, U>;
|
||||
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertNotNode")) {
|
||||
assert(
|
||||
node === undefined || test === undefined || !test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertNotNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertOptionalNode<T extends Node, U extends T>(node: T, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
|
||||
export function assertOptionalNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U | undefined;
|
||||
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalNode")) {
|
||||
assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
stackCrawlMark || assertOptionalNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }>;
|
||||
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T | undefined, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }> | undefined;
|
||||
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
|
||||
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalToken")) {
|
||||
assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
|
||||
stackCrawlMark || assertOptionalToken);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction): asserts node is undefined;
|
||||
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction) {
|
||||
if (shouldAssertFunction(AssertionLevel.Normal, "assertMissingNode")) {
|
||||
assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} was unexpected'.`,
|
||||
stackCrawlMark || assertMissingNode);
|
||||
}
|
||||
}
|
||||
|
||||
export function getFunctionName(func: AnyFunction) {
|
||||
if (typeof func !== "function") {
|
||||
return "";
|
||||
@@ -167,60 +311,6 @@ namespace ts {
|
||||
return formatEnum(flags, (<any>ts).ObjectFlags, /*isFlags*/ true);
|
||||
}
|
||||
|
||||
export function failBadSyntaxKind(node: Node, message?: string): never {
|
||||
return fail(
|
||||
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
|
||||
failBadSyntaxKind);
|
||||
}
|
||||
|
||||
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (nodes: Node[], test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || every(nodes, test),
|
||||
message || "Unexpected node.",
|
||||
() => `Node array did not pass test '${getFunctionName(test)}'.`,
|
||||
assertEachNode)
|
||||
: noop;
|
||||
|
||||
export const assertNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
|
||||
test === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} did not pass test '${getFunctionName(test!)}'.`,
|
||||
assertNode)
|
||||
: noop;
|
||||
|
||||
export const assertNotNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node | undefined, test: ((node: Node | undefined) => boolean) | undefined, message?: string): void => assert(
|
||||
test === undefined || !test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`,
|
||||
assertNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, test: (node: Node) => boolean, message?: string): void => assert(
|
||||
test === undefined || node === undefined || test(node),
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`,
|
||||
assertOptionalNode)
|
||||
: noop;
|
||||
|
||||
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, kind: SyntaxKind, message?: string): void => assert(
|
||||
kind === undefined || node === undefined || node.kind === kind,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
|
||||
assertOptionalToken)
|
||||
: noop;
|
||||
|
||||
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
|
||||
? (node: Node, message?: string): void => assert(
|
||||
node === undefined,
|
||||
message || "Unexpected node.",
|
||||
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`,
|
||||
assertMissingNode)
|
||||
: noop;
|
||||
|
||||
let isDebugInfoEnabled = false;
|
||||
|
||||
interface ExtendedDebugModule {
|
||||
|
||||
@@ -863,7 +863,7 @@
|
||||
"category": "Error",
|
||||
"code": 1300
|
||||
},
|
||||
"'await' expression is only allowed within an async function.": {
|
||||
"'await' expressions are only allowed within async functions and at the top levels of modules.": {
|
||||
"category": "Error",
|
||||
"code": 1308
|
||||
},
|
||||
@@ -1059,11 +1059,11 @@
|
||||
"category": "Error",
|
||||
"code": 1360
|
||||
},
|
||||
"Type-only {0} must reference a type, but '{1}' is a value.": {
|
||||
"'{0}' cannot be used as a value because it was imported using 'import type'.": {
|
||||
"category": "Error",
|
||||
"code": 1361
|
||||
},
|
||||
"Enum '{0}' cannot be used as a value because only its type has been imported.": {
|
||||
"'{0}' cannot be used as a value because it was exported using 'export type'.": {
|
||||
"category": "Error",
|
||||
"code": 1362
|
||||
},
|
||||
@@ -1085,7 +1085,7 @@
|
||||
},
|
||||
"Split all invalid type-only imports": {
|
||||
"category": "Message",
|
||||
"code": 1377
|
||||
"code": 1367
|
||||
},
|
||||
"Specify emit/checking behavior for imports that are only used for types": {
|
||||
"category": "Message",
|
||||
@@ -1103,10 +1103,6 @@
|
||||
"category": "Error",
|
||||
"code": 1371
|
||||
},
|
||||
"This import may be converted to a type-only import.": {
|
||||
"category": "Suggestion",
|
||||
"code": 1372
|
||||
},
|
||||
"Convert to type-only import": {
|
||||
"category": "Message",
|
||||
"code": 1373
|
||||
@@ -1115,10 +1111,38 @@
|
||||
"category": "Message",
|
||||
"code": 1374
|
||||
},
|
||||
"'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher.": {
|
||||
"'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.": {
|
||||
"category": "Error",
|
||||
"code": 1375
|
||||
},
|
||||
"'{0}' was imported here.": {
|
||||
"category": "Message",
|
||||
"code": 1376
|
||||
},
|
||||
"'{0}' was exported here.": {
|
||||
"category": "Message",
|
||||
"code": 1377
|
||||
},
|
||||
"Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.": {
|
||||
"category": "Error",
|
||||
"code": 1378
|
||||
},
|
||||
"An import alias cannot reference a declaration that was exported using 'export type'.": {
|
||||
"category": "Error",
|
||||
"code": 1379
|
||||
},
|
||||
"An import alias cannot reference a declaration that was imported using 'import type'.": {
|
||||
"category": "Error",
|
||||
"code": 1380
|
||||
},
|
||||
"Unexpected token. Did you mean `{'}'}` or `}`?": {
|
||||
"category": "Error",
|
||||
"code": 1381
|
||||
},
|
||||
"Unexpected token. Did you mean `{'>'}` or `>`?": {
|
||||
"category": "Error",
|
||||
"code": 1382
|
||||
},
|
||||
|
||||
"The types of '{0}' are incompatible between these types.": {
|
||||
"category": "Error",
|
||||
@@ -1765,6 +1789,14 @@
|
||||
"category": "Error",
|
||||
"code": 2458
|
||||
},
|
||||
"Module '{0}' declares '{1}' locally, but it is not exported.": {
|
||||
"category": "Error",
|
||||
"code": 2459
|
||||
},
|
||||
"Module '{0}' declares '{1}' locally, but it is exported as '{2}'.": {
|
||||
"category": "Error",
|
||||
"code": 2460
|
||||
},
|
||||
"Type '{0}' is not an array type.": {
|
||||
"category": "Error",
|
||||
"code": 2461
|
||||
@@ -2659,7 +2691,7 @@
|
||||
"category": "Error",
|
||||
"code": 2733
|
||||
},
|
||||
"It is highly likely that you are missing a semicolon.": {
|
||||
"Are you missing a semicolon?": {
|
||||
"category": "Error",
|
||||
"code": 2734
|
||||
},
|
||||
@@ -2855,6 +2887,10 @@
|
||||
"category": "Message",
|
||||
"code": 2782
|
||||
},
|
||||
"'{0}' is specified more than once, so this usage will be overwritten.": {
|
||||
"category": "Error",
|
||||
"code": 2783
|
||||
},
|
||||
|
||||
"Import declaration '{0}' is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
@@ -4925,7 +4961,7 @@
|
||||
"category": "Message",
|
||||
"code": 90003
|
||||
},
|
||||
"Remove declaration for: '{0}'": {
|
||||
"Remove unused declaration for: '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 90004
|
||||
},
|
||||
@@ -5049,6 +5085,10 @@
|
||||
"category": "Message",
|
||||
"code": 90034
|
||||
},
|
||||
"Declare a private field named '{0}'.": {
|
||||
"category": "Message",
|
||||
"code": 90053
|
||||
},
|
||||
"Convert function to an ES2015 class": {
|
||||
"category": "Message",
|
||||
"code": 95001
|
||||
@@ -5417,6 +5457,26 @@
|
||||
"category": "Message",
|
||||
"code": 95096
|
||||
},
|
||||
"Add 'export {}' to make this file into a module": {
|
||||
"category": "Message",
|
||||
"code": 95097
|
||||
},
|
||||
"Set the 'target' option in your configuration file to '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 95098
|
||||
},
|
||||
"Set the 'module' option in your configuration file to '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 95099
|
||||
},
|
||||
"Convert invalid character to its html entity code": {
|
||||
"category": "Message",
|
||||
"code": 95100
|
||||
},
|
||||
"Wrap invalid character in an expression container": {
|
||||
"category": "Message",
|
||||
"code": 95101
|
||||
},
|
||||
|
||||
"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
|
||||
"category": "Error",
|
||||
@@ -5430,10 +5490,6 @@
|
||||
"category": "Error",
|
||||
"code": 18007
|
||||
},
|
||||
"'#!' can only be used at the start of a file.": {
|
||||
"category": "Error",
|
||||
"code": 18008
|
||||
},
|
||||
"Private identifiers cannot be used as parameters": {
|
||||
"category": "Error",
|
||||
"code": 18009
|
||||
|
||||
+121
-49
@@ -131,7 +131,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function rootDirOfOptions(configFile: ParsedCommandLine) {
|
||||
return configFile.options.rootDir || getDirectoryPath(Debug.assertDefined(configFile.options.configFilePath));
|
||||
return configFile.options.rootDir || getDirectoryPath(Debug.checkDefined(configFile.options.configFilePath));
|
||||
}
|
||||
|
||||
function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined) {
|
||||
@@ -163,7 +163,7 @@ namespace ts {
|
||||
Extension.Jsx :
|
||||
Extension.Js
|
||||
);
|
||||
return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ?
|
||||
return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ?
|
||||
outputFileName :
|
||||
undefined;
|
||||
}
|
||||
@@ -239,7 +239,7 @@ namespace ts {
|
||||
export function getFirstProjectOutput(configFile: ParsedCommandLine, ignoreCase: boolean): string {
|
||||
if (configFile.options.outFile || configFile.options.out) {
|
||||
const { jsFilePath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false);
|
||||
return Debug.assertDefined(jsFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`);
|
||||
return Debug.checkDefined(jsFilePath, `project ${configFile.options.configFilePath} expected to have at least one output`);
|
||||
}
|
||||
|
||||
for (const inputFileName of configFile.fileNames) {
|
||||
@@ -379,6 +379,7 @@ namespace ts {
|
||||
|
||||
// transform hooks
|
||||
onEmitNode: transform.emitNodeWithNotification,
|
||||
isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
|
||||
substituteNode: transform.substituteNode,
|
||||
});
|
||||
|
||||
@@ -437,6 +438,7 @@ namespace ts {
|
||||
|
||||
// transform hooks
|
||||
onEmitNode: declarationTransform.emitNodeWithNotification,
|
||||
isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
|
||||
substituteNode: declarationTransform.substituteNode,
|
||||
});
|
||||
const declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
|
||||
@@ -585,7 +587,7 @@ namespace ts {
|
||||
return `data:application/json;base64,${base64SourceMapText}`;
|
||||
}
|
||||
|
||||
const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.assertDefined(sourceMapFilePath)));
|
||||
const sourceMapFile = getBaseFileName(normalizeSlashes(Debug.checkDefined(sourceMapFilePath)));
|
||||
if (mapOptions.mapRoot) {
|
||||
let sourceMapDir = normalizeSlashes(mapOptions.mapRoot);
|
||||
if (sourceFile) {
|
||||
@@ -688,7 +690,7 @@ namespace ts {
|
||||
sourceFile.statements = createNodeArray();
|
||||
return sourceFile;
|
||||
});
|
||||
const jsBundle = Debug.assertDefined(bundle.js);
|
||||
const jsBundle = Debug.checkDefined(bundle.js);
|
||||
forEach(jsBundle.sources && jsBundle.sources.prologues, prologueInfo => {
|
||||
const sourceFile = sourceFiles[prologueInfo.file];
|
||||
sourceFile.text = prologueInfo.text;
|
||||
@@ -711,9 +713,9 @@ namespace ts {
|
||||
customTransformers?: CustomTransformers
|
||||
): EmitUsingBuildInfoResult {
|
||||
const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false);
|
||||
const buildInfoText = host.readFile(Debug.assertDefined(buildInfoPath));
|
||||
const buildInfoText = host.readFile(Debug.checkDefined(buildInfoPath));
|
||||
if (!buildInfoText) return buildInfoPath!;
|
||||
const jsFileText = host.readFile(Debug.assertDefined(jsFilePath));
|
||||
const jsFileText = host.readFile(Debug.checkDefined(jsFilePath));
|
||||
if (!jsFileText) return jsFilePath!;
|
||||
const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
|
||||
// error if no source map or for now if inline sourcemap
|
||||
@@ -819,6 +821,7 @@ namespace ts {
|
||||
const {
|
||||
hasGlobalName,
|
||||
onEmitNode = noEmitNotification,
|
||||
isEmitNotificationEnabled,
|
||||
substituteNode = noEmitSubstitution,
|
||||
onBeforeEmitNodeArray,
|
||||
onAfterEmitNodeArray,
|
||||
@@ -845,7 +848,7 @@ namespace ts {
|
||||
let write = writeBase;
|
||||
let isOwnFileEmit: boolean;
|
||||
const bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } as BundleFileInfo : undefined;
|
||||
const relativeToBuildInfo = bundleFileInfo ? Debug.assertDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
const relativeToBuildInfo = bundleFileInfo ? Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
|
||||
const recordInternalSection = printerOptions.recordInternalSection;
|
||||
let sourceFileTextPos = 0;
|
||||
let sourceFileTextKind: BundleFileTextLikeKind = BundleFileSectionKind.Text;
|
||||
@@ -1154,13 +1157,17 @@ namespace ts {
|
||||
return pipelineEmit(EmitHint.Expression, node);
|
||||
}
|
||||
|
||||
function emitJsxAttributeValue(node: StringLiteral | JsxExpression): Node {
|
||||
return pipelineEmit(isStringLiteral(node) ? EmitHint.JsxAttributeValue : EmitHint.Unspecified, node);
|
||||
}
|
||||
|
||||
function pipelineEmit(emitHint: EmitHint, node: Node) {
|
||||
const savedLastNode = lastNode;
|
||||
const savedLastSubstitution = lastSubstitution;
|
||||
lastNode = node;
|
||||
lastSubstitution = undefined;
|
||||
|
||||
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
|
||||
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, emitHint, node);
|
||||
pipelinePhase(emitHint, node);
|
||||
|
||||
Debug.assert(lastNode === node);
|
||||
@@ -1172,16 +1179,16 @@ namespace ts {
|
||||
return substitute || node;
|
||||
}
|
||||
|
||||
function getPipelinePhase(phase: PipelinePhase, node: Node) {
|
||||
function getPipelinePhase(phase: PipelinePhase, emitHint: EmitHint, node: Node) {
|
||||
switch (phase) {
|
||||
case PipelinePhase.Notification:
|
||||
if (onEmitNode !== noEmitNotification) {
|
||||
if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
|
||||
return pipelineEmitWithNotification;
|
||||
}
|
||||
// falls through
|
||||
|
||||
case PipelinePhase.Substitution:
|
||||
if (substituteNode !== noEmitSubstitution) {
|
||||
if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
|
||||
return pipelineEmitWithSubstitution;
|
||||
}
|
||||
// falls through
|
||||
@@ -1206,13 +1213,13 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getNextPipelinePhase(currentPhase: PipelinePhase, node: Node) {
|
||||
return getPipelinePhase(currentPhase + 1, node);
|
||||
function getNextPipelinePhase(currentPhase: PipelinePhase, emitHint: EmitHint, node: Node) {
|
||||
return getPipelinePhase(currentPhase + 1, emitHint, node);
|
||||
}
|
||||
|
||||
function pipelineEmitWithNotification(hint: EmitHint, node: Node) {
|
||||
Debug.assert(lastNode === node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, hint, node);
|
||||
onEmitNode(hint, node, pipelinePhase);
|
||||
Debug.assert(lastNode === node);
|
||||
}
|
||||
@@ -1221,6 +1228,7 @@ namespace ts {
|
||||
Debug.assert(lastNode === node || lastSubstitution === node);
|
||||
if (hint === EmitHint.SourceFile) return emitSourceFile(cast(node, isSourceFile));
|
||||
if (hint === EmitHint.IdentifierName) return emitIdentifier(cast(node, isIdentifier));
|
||||
if (hint === EmitHint.JsxAttributeValue) return emitLiteral(cast(node, isStringLiteral), /*jsxAttributeEscape*/ true);
|
||||
if (hint === EmitHint.MappedTypeParameter) return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration));
|
||||
if (hint === EmitHint.EmbeddedStatement) {
|
||||
Debug.assertNode(node, isEmptyStatement);
|
||||
@@ -1234,7 +1242,7 @@ namespace ts {
|
||||
case SyntaxKind.TemplateHead:
|
||||
case SyntaxKind.TemplateMiddle:
|
||||
case SyntaxKind.TemplateTail:
|
||||
return emitLiteral(<LiteralExpression>node);
|
||||
return emitLiteral(<LiteralExpression>node, /*jsxAttributeEscape*/ false);
|
||||
|
||||
case SyntaxKind.UnparsedSource:
|
||||
case SyntaxKind.UnparsedPrepend:
|
||||
@@ -1553,7 +1561,7 @@ namespace ts {
|
||||
case SyntaxKind.StringLiteral:
|
||||
case SyntaxKind.RegularExpressionLiteral:
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
return emitLiteral(<LiteralExpression>node);
|
||||
return emitLiteral(<LiteralExpression>node, /*jsxAttributeEscape*/ false);
|
||||
|
||||
// Identifiers
|
||||
case SyntaxKind.Identifier:
|
||||
@@ -1653,9 +1661,8 @@ namespace ts {
|
||||
|
||||
function pipelineEmitWithSubstitution(hint: EmitHint, node: Node) {
|
||||
Debug.assert(lastNode === node || lastSubstitution === node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, node);
|
||||
lastSubstitution = substituteNode(hint, node);
|
||||
pipelinePhase(hint, lastSubstitution);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, hint, node);
|
||||
pipelinePhase(hint, lastSubstitution!);
|
||||
Debug.assert(lastNode === node || lastSubstitution === node);
|
||||
}
|
||||
|
||||
@@ -1744,7 +1751,7 @@ namespace ts {
|
||||
// SyntaxKind.NumericLiteral
|
||||
// SyntaxKind.BigIntLiteral
|
||||
function emitNumericOrBigIntLiteral(node: NumericLiteral | BigIntLiteral) {
|
||||
emitLiteral(node);
|
||||
emitLiteral(node, /*jsxAttributeEscape*/ false);
|
||||
}
|
||||
|
||||
// SyntaxKind.StringLiteral
|
||||
@@ -1753,8 +1760,8 @@ namespace ts {
|
||||
// SyntaxKind.TemplateHead
|
||||
// SyntaxKind.TemplateMiddle
|
||||
// SyntaxKind.TemplateTail
|
||||
function emitLiteral(node: LiteralLikeNode) {
|
||||
const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape);
|
||||
function emitLiteral(node: LiteralLikeNode, jsxAttributeEscape: boolean) {
|
||||
const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
|
||||
if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
|
||||
&& (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) {
|
||||
writeLiteral(text);
|
||||
@@ -2293,7 +2300,7 @@ namespace ts {
|
||||
expression = skipPartiallyEmittedExpressions(expression);
|
||||
if (isNumericLiteral(expression)) {
|
||||
// check if numeric literal is a decimal literal that was originally written with a dot
|
||||
const text = getLiteralTextOfNode(<LiteralExpression>expression, /*neverAsciiEscape*/ true);
|
||||
const text = getLiteralTextOfNode(<LiteralExpression>expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
|
||||
// If he number will be printed verbatim and it doesn't already contain a dot, add one
|
||||
// if the expression doesn't have any comments that will be emitted.
|
||||
return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!);
|
||||
@@ -2425,19 +2432,84 @@ namespace ts {
|
||||
writeTokenText(node.operator, writeOperator);
|
||||
}
|
||||
|
||||
function emitBinaryExpression(node: BinaryExpression) {
|
||||
const isCommaOperator = node.operatorToken.kind !== SyntaxKind.CommaToken;
|
||||
const indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
|
||||
const indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
|
||||
const enum EmitBinaryExpressionState {
|
||||
EmitLeft,
|
||||
EmitRight,
|
||||
FinishEmit
|
||||
}
|
||||
|
||||
emitExpression(node.left);
|
||||
increaseIndentIf(indentBeforeOperator, isCommaOperator);
|
||||
emitLeadingCommentsOfPosition(node.operatorToken.pos);
|
||||
writeTokenNode(node.operatorToken, node.operatorToken.kind === SyntaxKind.InKeyword ? writeKeyword : writeOperator);
|
||||
emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
|
||||
increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true);
|
||||
emitExpression(node.right);
|
||||
decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
|
||||
/**
|
||||
* emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
|
||||
* as possible without creating any additional stack frames. This can only be done when the emit pipeline does
|
||||
* not require notification/substitution/comment/sourcemap decorations.
|
||||
*/
|
||||
function emitBinaryExpression(node: BinaryExpression) {
|
||||
const nodeStack = [node];
|
||||
const stateStack = [EmitBinaryExpressionState.EmitLeft];
|
||||
let stackIndex = 0;
|
||||
while (stackIndex >= 0) {
|
||||
node = nodeStack[stackIndex];
|
||||
switch (stateStack[stackIndex]) {
|
||||
case EmitBinaryExpressionState.EmitLeft: {
|
||||
maybePipelineEmitExpression(node.left);
|
||||
break;
|
||||
}
|
||||
case EmitBinaryExpressionState.EmitRight: {
|
||||
const isCommaOperator = node.operatorToken.kind !== SyntaxKind.CommaToken;
|
||||
const indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
|
||||
const indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
|
||||
increaseIndentIf(indentBeforeOperator, isCommaOperator);
|
||||
emitLeadingCommentsOfPosition(node.operatorToken.pos);
|
||||
writeTokenNode(node.operatorToken, node.operatorToken.kind === SyntaxKind.InKeyword ? writeKeyword : writeOperator);
|
||||
emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
|
||||
increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true);
|
||||
maybePipelineEmitExpression(node.right);
|
||||
break;
|
||||
}
|
||||
case EmitBinaryExpressionState.FinishEmit: {
|
||||
const indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken);
|
||||
const indentAfterOperator = needsIndentation(node, node.operatorToken, node.right);
|
||||
decreaseIndentIf(indentBeforeOperator, indentAfterOperator);
|
||||
stackIndex--;
|
||||
break;
|
||||
}
|
||||
default: return Debug.fail(`Invalid state ${stateStack[stackIndex]} for emitBinaryExpressionWorker`);
|
||||
}
|
||||
}
|
||||
|
||||
function maybePipelineEmitExpression(next: Expression) {
|
||||
// Advance the state of this unit of work,
|
||||
stateStack[stackIndex]++;
|
||||
|
||||
// Then actually do the work of emitting the node `next` returned by the prior state
|
||||
|
||||
// The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
|
||||
// binary expression handling, where possible, to the contained work queue
|
||||
|
||||
// #region trampolinePipelineEmit
|
||||
const savedLastNode = lastNode;
|
||||
const savedLastSubstitution = lastSubstitution;
|
||||
lastNode = next;
|
||||
lastSubstitution = undefined;
|
||||
|
||||
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, EmitHint.Expression, next);
|
||||
if (pipelinePhase === pipelineEmitWithHint && isBinaryExpression(next)) {
|
||||
// If the target pipeline phase is emit directly, and the next node's also a binary expression,
|
||||
// skip all the intermediate indirection and push the expression directly onto the work stack
|
||||
stackIndex++;
|
||||
stateStack[stackIndex] = EmitBinaryExpressionState.EmitLeft;
|
||||
nodeStack[stackIndex] = next;
|
||||
}
|
||||
else {
|
||||
pipelinePhase(EmitHint.Expression, next);
|
||||
}
|
||||
|
||||
Debug.assert(lastNode === next);
|
||||
|
||||
lastNode = savedLastNode;
|
||||
lastSubstitution = savedLastSubstitution;
|
||||
// #endregion trampolinePipelineEmit
|
||||
}
|
||||
}
|
||||
|
||||
function emitConditionalExpression(node: ConditionalExpression) {
|
||||
@@ -2672,11 +2744,11 @@ namespace ts {
|
||||
const node = getParseTreeNode(contextNode);
|
||||
const isSimilarNode = node && node.kind === contextNode.kind;
|
||||
const startPos = pos;
|
||||
if (isSimilarNode) {
|
||||
pos = skipTrivia(currentSourceFile!.text, pos);
|
||||
if (isSimilarNode && currentSourceFile) {
|
||||
pos = skipTrivia(currentSourceFile.text, pos);
|
||||
}
|
||||
if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
|
||||
const needsIndent = indentLeading && !positionsAreOnSameLine(startPos, pos, currentSourceFile!);
|
||||
const needsIndent = indentLeading && currentSourceFile && !positionsAreOnSameLine(startPos, pos, currentSourceFile);
|
||||
if (needsIndent) {
|
||||
increaseIndent();
|
||||
}
|
||||
@@ -3228,7 +3300,7 @@ namespace ts {
|
||||
|
||||
function emitJsxAttribute(node: JsxAttribute) {
|
||||
emit(node.name);
|
||||
emitNodeWithPrefix("=", writePunctuation, node.initializer!, emit); // TODO: GH#18217
|
||||
emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
|
||||
}
|
||||
|
||||
function emitJsxSpreadAttribute(node: JsxSpreadAttribute) {
|
||||
@@ -3712,7 +3784,7 @@ namespace ts {
|
||||
else {
|
||||
for (const prepend of sourceFileOrBundle.prepends) {
|
||||
Debug.assertNode(prepend, isUnparsedSource);
|
||||
if (emitShebangIfNeeded(prepend as UnparsedSource)) {
|
||||
if (emitShebangIfNeeded(prepend)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -3761,7 +3833,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function emitNodeWithPrefix(prefix: string, prefixWriter: (s: string) => void, node: Node, emit: (node: Node) => void) {
|
||||
function emitNodeWithPrefix<T extends Node>(prefix: string, prefixWriter: (s: string) => void, node: T | undefined, emit: (node: T) => void) {
|
||||
if (node) {
|
||||
prefixWriter(prefix);
|
||||
emit(node);
|
||||
@@ -4318,20 +4390,20 @@ namespace ts {
|
||||
return getSourceTextOfNodeFromSourceFile(currentSourceFile!, node, includeTrivia);
|
||||
}
|
||||
|
||||
function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined): string {
|
||||
function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean): string {
|
||||
if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
|
||||
const textSourceNode = (<StringLiteral>node).textSourceNode!;
|
||||
if (isIdentifier(textSourceNode)) {
|
||||
return neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ?
|
||||
`"${escapeString(getTextOfNode(textSourceNode))}"` :
|
||||
return jsxAttributeEscape ? `"${escapeJsxAttributeString(getTextOfNode(textSourceNode))}"` :
|
||||
neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? `"${escapeString(getTextOfNode(textSourceNode))}"` :
|
||||
`"${escapeNonAsciiString(getTextOfNode(textSourceNode))}"`;
|
||||
}
|
||||
else {
|
||||
return getLiteralTextOfNode(textSourceNode, neverAsciiEscape);
|
||||
return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
|
||||
}
|
||||
}
|
||||
|
||||
return getLiteralText(node, currentSourceFile!, neverAsciiEscape);
|
||||
return getLiteralText(node, currentSourceFile!, neverAsciiEscape, jsxAttributeEscape);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4773,7 +4845,7 @@ namespace ts {
|
||||
forEach(getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
|
||||
exitComment();
|
||||
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Comments, hint, node);
|
||||
if (emitFlags & EmitFlags.NoNestedComments) {
|
||||
commentsDisabled = true;
|
||||
pipelinePhase(hint, node);
|
||||
@@ -5046,7 +5118,7 @@ namespace ts {
|
||||
|
||||
function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) {
|
||||
Debug.assert(lastNode === node || lastSubstitution === node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, node);
|
||||
const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, hint, node);
|
||||
if (isUnparsedSource(node) || isUnparsedPrepend(node)) {
|
||||
pipelinePhase(hint, node);
|
||||
}
|
||||
|
||||
@@ -1829,7 +1829,7 @@ namespace ts {
|
||||
if (isBindingElement(element)) {
|
||||
if (element.dotDotDotToken) {
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createSpread(<Identifier>element.name), element), element);
|
||||
return setOriginalNode(setTextRange(createSpread(element.name), element), element);
|
||||
}
|
||||
const expression = convertToAssignmentElementTarget(element.name);
|
||||
return element.initializer
|
||||
@@ -1850,14 +1850,14 @@ namespace ts {
|
||||
if (isBindingElement(element)) {
|
||||
if (element.dotDotDotToken) {
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createSpreadAssignment(<Identifier>element.name), element), element);
|
||||
return setOriginalNode(setTextRange(createSpreadAssignment(element.name), element), element);
|
||||
}
|
||||
if (element.propertyName) {
|
||||
const expression = convertToAssignmentElementTarget(element.name);
|
||||
return setOriginalNode(setTextRange(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression), element), element);
|
||||
}
|
||||
Debug.assertNode(element.name, isIdentifier);
|
||||
return setOriginalNode(setTextRange(createShorthandPropertyAssignment(<Identifier>element.name, element.initializer), element), element);
|
||||
return setOriginalNode(setTextRange(createShorthandPropertyAssignment(element.name, element.initializer), element), element);
|
||||
}
|
||||
Debug.assertNode(element, isObjectLiteralElementLike);
|
||||
return <ObjectLiteralElementLike>element;
|
||||
|
||||
@@ -218,6 +218,9 @@ namespace ts {
|
||||
|
||||
// Private Identifiers
|
||||
export function createPrivateIdentifier(text: string): PrivateIdentifier {
|
||||
if (text[0] !== "#") {
|
||||
Debug.fail("First character of private identifier must be #: " + text);
|
||||
}
|
||||
const node = createSynthesizedNode(SyntaxKind.PrivateIdentifier) as PrivateIdentifier;
|
||||
node.escapedText = escapeLeadingUnderscores(text);
|
||||
return node;
|
||||
@@ -1483,7 +1486,7 @@ namespace ts {
|
||||
|
||||
let token = rawTextScanner.scan();
|
||||
if (token === SyntaxKind.CloseBracketToken) {
|
||||
token = rawTextScanner.reScanTemplateToken();
|
||||
token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
|
||||
}
|
||||
|
||||
if (rawTextScanner.isUnterminated()) {
|
||||
@@ -2972,10 +2975,10 @@ namespace ts {
|
||||
if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
|
||||
node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
|
||||
Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
|
||||
stripInternal = mapTextOrStripInternal as boolean | undefined;
|
||||
stripInternal = mapTextOrStripInternal;
|
||||
bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
|
||||
if (node.oldFileOfCurrentEmit) {
|
||||
parseOldFileOfCurrentEmit(node, Debug.assertDefined(bundleFileInfo));
|
||||
parseOldFileOfCurrentEmit(node, Debug.checkDefined(bundleFileInfo));
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -3194,13 +3197,13 @@ namespace ts {
|
||||
};
|
||||
node.javascriptPath = declarationTextOrJavascriptPath;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationPath = Debug.checkDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.buildInfoPath = declarationMapTextOrBuildInfoPath;
|
||||
Object.defineProperties(node, {
|
||||
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
|
||||
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
|
||||
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
|
||||
declarationText: { get() { return definedTextGetter(Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
|
||||
declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that
|
||||
buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
|
||||
});
|
||||
|
||||
@@ -112,8 +112,6 @@ namespace ts {
|
||||
version?: string;
|
||||
}
|
||||
|
||||
type MatchingKeys<TRecord, TMatch, K extends keyof TRecord = keyof TRecord> = K extends (TRecord[K] extends TMatch ? K : never) ? K : never;
|
||||
|
||||
function readPackageJsonField<TMatch, K extends MatchingKeys<PackageJson, string | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined;
|
||||
function readPackageJsonField<K extends MatchingKeys<PackageJson, object | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined;
|
||||
function readPackageJsonField<K extends keyof PackageJson>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined {
|
||||
|
||||
@@ -342,7 +342,7 @@ namespace ts.moduleSpecifiers {
|
||||
// If the file is the main module, it can be imported by the package name
|
||||
if (packageJsonContent) {
|
||||
const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
|
||||
if (mainFileRelative) {
|
||||
if (isString(mainFileRelative)) {
|
||||
const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
|
||||
if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) {
|
||||
return packageRootPath;
|
||||
|
||||
+75
-49
@@ -904,28 +904,31 @@ namespace ts {
|
||||
// overhead. This functions allows us to set all the parents, without all the expense of
|
||||
// binding.
|
||||
|
||||
let parent: Node = rootNode;
|
||||
forEachChild(rootNode, visitNode);
|
||||
const stack: Node[] = [rootNode];
|
||||
while (stack.length) {
|
||||
const parent = stack.pop()!;
|
||||
bindParentToChildren(parent, gatherChildren(parent));
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
function visitNode(n: Node): void {
|
||||
// walk down setting parents that differ from the parent we think it should be. This
|
||||
// allows us to quickly bail out of setting parents for subtrees during incremental
|
||||
// parsing
|
||||
if (n.parent !== parent) {
|
||||
n.parent = parent;
|
||||
function gatherChildren(node: Node) {
|
||||
const children: Node[] = [];
|
||||
forEachChild(node, n => { children.unshift(n); }); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
|
||||
return children;
|
||||
}
|
||||
|
||||
const saveParent = parent;
|
||||
parent = n;
|
||||
forEachChild(n, visitNode);
|
||||
if (hasJSDocNodes(n)) {
|
||||
for (const jsDoc of n.jsDoc!) {
|
||||
jsDoc.parent = n;
|
||||
parent = jsDoc;
|
||||
forEachChild(jsDoc, visitNode);
|
||||
function bindParentToChildren(parent: Node, children: readonly Node[]) {
|
||||
for (const child of children) {
|
||||
if (child.parent === parent) continue; // already bound, assume subtree is bound
|
||||
child.parent = parent;
|
||||
stack.push(child);
|
||||
if (hasJSDocNodes(child)) {
|
||||
for (const jsDoc of child.jsDoc!) {
|
||||
jsDoc.parent = child;
|
||||
stack.push(jsDoc);
|
||||
}
|
||||
}
|
||||
parent = saveParent;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1134,8 +1137,12 @@ namespace ts {
|
||||
return currentToken = scanner.reScanSlashToken();
|
||||
}
|
||||
|
||||
function reScanTemplateToken(): SyntaxKind {
|
||||
return currentToken = scanner.reScanTemplateToken();
|
||||
function reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind {
|
||||
return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
|
||||
}
|
||||
|
||||
function reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind {
|
||||
return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
|
||||
}
|
||||
|
||||
function reScanLessThanToken(): SyntaxKind {
|
||||
@@ -1403,7 +1410,7 @@ namespace ts {
|
||||
// An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
|
||||
// with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
|
||||
// each identifier in order to reduce memory consumption.
|
||||
function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage): Identifier {
|
||||
function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage, privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier {
|
||||
identifierCount++;
|
||||
if (isIdentifier) {
|
||||
const node = <Identifier>createNode(SyntaxKind.Identifier);
|
||||
@@ -1417,6 +1424,11 @@ namespace ts {
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
if (token() === SyntaxKind.PrivateIdentifier) {
|
||||
parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
|
||||
return createIdentifier(/*isIdentifier*/ true);
|
||||
}
|
||||
|
||||
// Only for end of file because the error gets reported incorrectly on embedded script tags.
|
||||
const reportAtCurrentPosition = token() === SyntaxKind.EndOfFileToken;
|
||||
|
||||
@@ -1430,8 +1442,8 @@ namespace ts {
|
||||
return createMissingNode<Identifier>(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
|
||||
}
|
||||
|
||||
function parseIdentifier(diagnosticMessage?: DiagnosticMessage): Identifier {
|
||||
return createIdentifier(isIdentifier(), diagnosticMessage);
|
||||
function parseIdentifier(diagnosticMessage?: DiagnosticMessage, privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier {
|
||||
return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
|
||||
}
|
||||
|
||||
function parseIdentifierName(diagnosticMessage?: DiagnosticMessage): Identifier {
|
||||
@@ -1627,9 +1639,9 @@ namespace ts {
|
||||
return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
|
||||
}
|
||||
case ParsingContext.VariableDeclarations:
|
||||
return isIdentifierOrPattern();
|
||||
return isIdentifierOrPrivateIdentifierOrPattern();
|
||||
case ParsingContext.ArrayBindingElements:
|
||||
return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isIdentifierOrPattern();
|
||||
return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isIdentifierOrPrivateIdentifierOrPattern();
|
||||
case ParsingContext.TypeParameters:
|
||||
return isIdentifier();
|
||||
case ParsingContext.ArrayLiteralMembers:
|
||||
@@ -2321,17 +2333,17 @@ namespace ts {
|
||||
return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
|
||||
}
|
||||
|
||||
function parseTemplateExpression(): TemplateExpression {
|
||||
function parseTemplateExpression(isTaggedTemplate: boolean): TemplateExpression {
|
||||
const template = <TemplateExpression>createNode(SyntaxKind.TemplateExpression);
|
||||
|
||||
template.head = parseTemplateHead();
|
||||
template.head = parseTemplateHead(isTaggedTemplate);
|
||||
Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
|
||||
|
||||
const list = [];
|
||||
const listPos = getNodePos();
|
||||
|
||||
do {
|
||||
list.push(parseTemplateSpan());
|
||||
list.push(parseTemplateSpan(isTaggedTemplate));
|
||||
}
|
||||
while (last(list).literal.kind === SyntaxKind.TemplateMiddle);
|
||||
|
||||
@@ -2340,13 +2352,13 @@ namespace ts {
|
||||
return finishNode(template);
|
||||
}
|
||||
|
||||
function parseTemplateSpan(): TemplateSpan {
|
||||
function parseTemplateSpan(isTaggedTemplate: boolean): TemplateSpan {
|
||||
const span = <TemplateSpan>createNode(SyntaxKind.TemplateSpan);
|
||||
span.expression = allowInAnd(parseExpression);
|
||||
|
||||
let literal: TemplateMiddle | TemplateTail;
|
||||
if (token() === SyntaxKind.CloseBraceToken) {
|
||||
reScanTemplateToken();
|
||||
reScanTemplateToken(isTaggedTemplate);
|
||||
literal = parseTemplateMiddleOrTemplateTail();
|
||||
}
|
||||
else {
|
||||
@@ -2361,7 +2373,10 @@ namespace ts {
|
||||
return <LiteralExpression>parseLiteralLikeNode(token());
|
||||
}
|
||||
|
||||
function parseTemplateHead(): TemplateHead {
|
||||
function parseTemplateHead(isTaggedTemplate: boolean): TemplateHead {
|
||||
if (isTaggedTemplate) {
|
||||
reScanTemplateHeadOrNoSubstitutionTemplate();
|
||||
}
|
||||
const fragment = parseLiteralLikeNode(token());
|
||||
Debug.assert(fragment.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind");
|
||||
return <TemplateHead>fragment;
|
||||
@@ -2405,6 +2420,10 @@ namespace ts {
|
||||
(<NumericLiteral>node).numericLiteralFlags = scanner.getTokenFlags() & TokenFlags.NumericLiteralFlags;
|
||||
}
|
||||
|
||||
if (isTemplateLiteralKind(node.kind)) {
|
||||
(<TemplateHead | TemplateMiddle | TemplateTail | NoSubstitutionTemplateLiteral>node).templateFlags = scanner.getTokenFlags() & TokenFlags.ContainsInvalidEscape;
|
||||
}
|
||||
|
||||
nextToken();
|
||||
finishNode(node);
|
||||
|
||||
@@ -2613,7 +2632,7 @@ namespace ts {
|
||||
|
||||
function isStartOfParameter(isJSDocParameter: boolean): boolean {
|
||||
return token() === SyntaxKind.DotDotDotToken ||
|
||||
isIdentifierOrPattern() ||
|
||||
isIdentifierOrPrivateIdentifierOrPattern() ||
|
||||
isModifierKind(token()) ||
|
||||
token() === SyntaxKind.AtToken ||
|
||||
isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
|
||||
@@ -2633,7 +2652,7 @@ namespace ts {
|
||||
|
||||
// FormalParameter [Yield,Await]:
|
||||
// BindingElement[?Yield,?Await]
|
||||
node.name = parseIdentifierOrPattern();
|
||||
node.name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
|
||||
if (getFullWidth(node.name) === 0 && !node.modifiers && isModifierKind(token())) {
|
||||
// in cases like
|
||||
// 'use strict'
|
||||
@@ -3436,6 +3455,7 @@ namespace ts {
|
||||
case SyntaxKind.LessThanToken:
|
||||
case SyntaxKind.AwaitKeyword:
|
||||
case SyntaxKind.YieldKeyword:
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
// Yield/await always starts an expression. Either it is an identifier (in which case
|
||||
// it is definitely an expression). Or it's a keyword (either because we're in
|
||||
// a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
|
||||
@@ -4763,8 +4783,8 @@ namespace ts {
|
||||
tagExpression.questionDotToken = questionDotToken;
|
||||
tagExpression.typeArguments = typeArguments;
|
||||
tagExpression.template = token() === SyntaxKind.NoSubstitutionTemplateLiteral
|
||||
? <NoSubstitutionTemplateLiteral>parseLiteralNode()
|
||||
: parseTemplateExpression();
|
||||
? (reScanTemplateHeadOrNoSubstitutionTemplate(), <NoSubstitutionTemplateLiteral>parseLiteralNode())
|
||||
: parseTemplateExpression(/*isTaggedTemplate*/ true);
|
||||
if (questionDotToken || tag.flags & NodeFlags.OptionalChain) {
|
||||
tagExpression.flags |= NodeFlags.OptionalChain;
|
||||
}
|
||||
@@ -4936,7 +4956,7 @@ namespace ts {
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.TemplateHead:
|
||||
return parseTemplateExpression();
|
||||
return parseTemplateExpression(/* isTaggedTemplate */ false);
|
||||
}
|
||||
|
||||
return parseIdentifier(Diagnostics.Expression_expected);
|
||||
@@ -5801,18 +5821,21 @@ namespace ts {
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
function isIdentifierOrPattern() {
|
||||
return token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.OpenBracketToken || isIdentifier();
|
||||
function isIdentifierOrPrivateIdentifierOrPattern() {
|
||||
return token() === SyntaxKind.OpenBraceToken
|
||||
|| token() === SyntaxKind.OpenBracketToken
|
||||
|| token() === SyntaxKind.PrivateIdentifier
|
||||
|| isIdentifier();
|
||||
}
|
||||
|
||||
function parseIdentifierOrPattern(): Identifier | BindingPattern {
|
||||
function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier | BindingPattern {
|
||||
if (token() === SyntaxKind.OpenBracketToken) {
|
||||
return parseArrayBindingPattern();
|
||||
}
|
||||
if (token() === SyntaxKind.OpenBraceToken) {
|
||||
return parseObjectBindingPattern();
|
||||
}
|
||||
return parseIdentifier();
|
||||
return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
|
||||
}
|
||||
|
||||
function parseVariableDeclarationAllowExclamation() {
|
||||
@@ -5821,7 +5844,7 @@ namespace ts {
|
||||
|
||||
function parseVariableDeclaration(allowExclamation?: boolean): VariableDeclaration {
|
||||
const node = <VariableDeclaration>createNode(SyntaxKind.VariableDeclaration);
|
||||
node.name = parseIdentifierOrPattern();
|
||||
node.name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
|
||||
if (allowExclamation && node.name.kind === SyntaxKind.Identifier &&
|
||||
token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
|
||||
node.exclamationToken = parseTokenNode<Token<SyntaxKind.ExclamationToken>>();
|
||||
@@ -6211,7 +6234,7 @@ namespace ts {
|
||||
const tok = token();
|
||||
Debug.assert(tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword); // isListElement() should ensure this.
|
||||
const node = <HeritageClause>createNode(SyntaxKind.HeritageClause);
|
||||
node.token = tok as SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
|
||||
node.token = tok;
|
||||
nextToken();
|
||||
node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments);
|
||||
return finishNode(node);
|
||||
@@ -6553,8 +6576,8 @@ namespace ts {
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
function parseNamespaceExport(): NamespaceExport {
|
||||
const node = <NamespaceExport>createNode(SyntaxKind.NamespaceExport);
|
||||
function parseNamespaceExport(pos: number): NamespaceExport {
|
||||
const node = <NamespaceExport>createNode(SyntaxKind.NamespaceExport, pos);
|
||||
node.name = parseIdentifier();
|
||||
return finishNode(node);
|
||||
}
|
||||
@@ -6562,9 +6585,10 @@ namespace ts {
|
||||
function parseExportDeclaration(node: ExportDeclaration): ExportDeclaration {
|
||||
node.kind = SyntaxKind.ExportDeclaration;
|
||||
node.isTypeOnly = parseOptional(SyntaxKind.TypeKeyword);
|
||||
const namespaceExportPos = scanner.getStartPos();
|
||||
if (parseOptional(SyntaxKind.AsteriskToken)) {
|
||||
if (parseOptional(SyntaxKind.AsKeyword)) {
|
||||
node.exportClause = parseNamespaceExport();
|
||||
node.exportClause = parseNamespaceExport(namespaceExportPos);
|
||||
}
|
||||
parseExpected(SyntaxKind.FromKeyword);
|
||||
node.moduleSpecifier = parseModuleSpecifier();
|
||||
@@ -6994,10 +7018,12 @@ namespace ts {
|
||||
comments.push(text);
|
||||
indent += text.length;
|
||||
}
|
||||
if (initialMargin) {
|
||||
if (initialMargin !== undefined) {
|
||||
// jump straight to saving comments if there is some initial indentation
|
||||
pushComment(initialMargin);
|
||||
state = JSDocState.SavingComments;
|
||||
if (initialMargin !== "") {
|
||||
pushComment(initialMargin);
|
||||
}
|
||||
state = JSDocState.SawAsterisk;
|
||||
}
|
||||
let tok = token() as JSDocSyntaxKind;
|
||||
loop: while (true) {
|
||||
@@ -7133,7 +7159,7 @@ namespace ts {
|
||||
case SyntaxKind.ArrayType:
|
||||
return isObjectOrObjectArrayTypeReference((node as ArrayTypeNode).elementType);
|
||||
default:
|
||||
return isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object";
|
||||
return isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7535,7 +7561,7 @@ namespace ts {
|
||||
const typeParameter = <TypeParameterDeclaration>createNode(SyntaxKind.TypeParameter);
|
||||
typeParameter.name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
|
||||
finishNode(typeParameter);
|
||||
skipWhitespace();
|
||||
skipWhitespaceOrAsterisk();
|
||||
typeParameters.push(typeParameter);
|
||||
} while (parseOptionalJsdoc(SyntaxKind.CommaToken));
|
||||
|
||||
|
||||
+25
-28
@@ -383,13 +383,6 @@ namespace ts {
|
||||
return formatStyle + text + resetEscapeSequence;
|
||||
}
|
||||
|
||||
function padLeft(s: string, length: number) {
|
||||
while (s.length < length) {
|
||||
s = " " + s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function formatCodeSpan(file: SourceFile, start: number, length: number, indent: string, squiggleColor: ForegroundColorEscapeSequences, host: FormatDiagnosticsHost) {
|
||||
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start);
|
||||
const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length);
|
||||
@@ -571,14 +564,14 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If number of files in the program do not match, it is not up-to-date
|
||||
if (program.getRootFileNames().length !== rootFileNames.length) {
|
||||
// If root file names don't match
|
||||
if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let seenResolvedRefs: ResolvedProjectReference[] | undefined;
|
||||
|
||||
// If project references dont match
|
||||
// If project references don't match
|
||||
if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
|
||||
return false;
|
||||
}
|
||||
@@ -764,7 +757,7 @@ namespace ts {
|
||||
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[];
|
||||
const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse;
|
||||
if (host.resolveModuleNames) {
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(resolved => {
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(resolved => {
|
||||
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
|
||||
if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) {
|
||||
return resolved as ResolvedModuleFull;
|
||||
@@ -777,16 +770,16 @@ namespace ts {
|
||||
else {
|
||||
moduleResolutionCache = createModuleResolutionCache(currentDirectory, x => host.getCanonicalFileName(x), options);
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache<ResolvedModuleFull>(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
resolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => (ResolvedTypeReferenceDirective | undefined)[];
|
||||
if (host.resolveTypeReferenceDirectives) {
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference, options);
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options);
|
||||
}
|
||||
else {
|
||||
const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective!; // TODO: GH#18217
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
// Map from a stringified PackageId to the source file with that id.
|
||||
@@ -1397,7 +1390,7 @@ namespace ts {
|
||||
}
|
||||
if (resolveTypeReferenceDirectiveNamesWorker) {
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase());
|
||||
const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName));
|
||||
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
|
||||
// ensure that types resolutions are still correct
|
||||
const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo);
|
||||
@@ -1850,19 +1843,19 @@ namespace ts {
|
||||
break;
|
||||
case SyntaxKind.InterfaceDeclaration:
|
||||
const interfaceKeyword = tokenToString(SyntaxKind.InterfaceKeyword);
|
||||
Debug.assertDefined(interfaceKeyword);
|
||||
Debug.assertIsDefined(interfaceKeyword);
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
|
||||
return;
|
||||
case SyntaxKind.ModuleDeclaration:
|
||||
const moduleKeyword = node.flags & NodeFlags.Namespace ? tokenToString(SyntaxKind.NamespaceKeyword) : tokenToString(SyntaxKind.ModuleKeyword);
|
||||
Debug.assertDefined(moduleKeyword);
|
||||
Debug.assertIsDefined(moduleKeyword);
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
|
||||
return;
|
||||
case SyntaxKind.TypeAliasDeclaration:
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
|
||||
return;
|
||||
case SyntaxKind.EnumDeclaration:
|
||||
const enumKeyword = Debug.assertDefined(tokenToString(SyntaxKind.EnumKeyword));
|
||||
const enumKeyword = Debug.checkDefined(tokenToString(SyntaxKind.EnumKeyword));
|
||||
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
|
||||
return;
|
||||
case SyntaxKind.NonNullExpression:
|
||||
@@ -2190,7 +2183,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getLibFileFromReference(ref: FileReference) {
|
||||
const libName = ref.fileName.toLocaleLowerCase();
|
||||
const libName = toFileNameLowerCase(ref.fileName);
|
||||
const libFileName = libMap.get(libName);
|
||||
if (libFileName) {
|
||||
return getSourceFile(combinePaths(defaultLibraryPath, libFileName));
|
||||
@@ -2438,7 +2431,7 @@ namespace ts {
|
||||
addFileToRefFileMap(fileName, file, refFile);
|
||||
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
const pathLowerCase = path.toLowerCase();
|
||||
const pathLowerCase = toFileNameLowerCase(path);
|
||||
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
|
||||
const existingFile = filesByNameIgnoreCase!.get(pathLowerCase);
|
||||
if (existingFile) {
|
||||
@@ -2650,7 +2643,7 @@ namespace ts {
|
||||
|
||||
function processTypeReferenceDirectives(file: SourceFile) {
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const typeDirectives = map(file.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase());
|
||||
const typeDirectives = map(file.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName));
|
||||
if (!typeDirectives) {
|
||||
return;
|
||||
}
|
||||
@@ -2661,7 +2654,7 @@ namespace ts {
|
||||
const ref = file.typeReferenceDirectives[i];
|
||||
const resolvedTypeReferenceDirective = resolutions[i];
|
||||
// store resolved type directive on the file
|
||||
const fileName = ref.fileName.toLocaleLowerCase();
|
||||
const fileName = toFileNameLowerCase(ref.fileName);
|
||||
setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
|
||||
processTypeReferenceDirective(
|
||||
fileName,
|
||||
@@ -2753,7 +2746,7 @@ namespace ts {
|
||||
|
||||
function processLibReferenceDirectives(file: SourceFile) {
|
||||
forEach(file.libReferenceDirectives, libReference => {
|
||||
const libName = libReference.fileName.toLocaleLowerCase();
|
||||
const libName = toFileNameLowerCase(libReference.fileName);
|
||||
const libFileName = libMap.get(libName);
|
||||
if (libFileName) {
|
||||
// we ignore any 'no-default-lib' reference set on this file.
|
||||
@@ -2913,7 +2906,7 @@ namespace ts {
|
||||
projectReferenceRedirects.set(sourceFilePath, false);
|
||||
return undefined;
|
||||
}
|
||||
sourceFile = Debug.assertDefined(commandLine.options.configFile);
|
||||
sourceFile = Debug.checkDefined(commandLine.options.configFile);
|
||||
Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
|
||||
addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
|
||||
}
|
||||
@@ -2987,6 +2980,10 @@ namespace ts {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
|
||||
}
|
||||
|
||||
if (!options.listFilesOnly && options.noEmit && isIncrementalCompilation(options)) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
|
||||
}
|
||||
|
||||
verifyProjectReferences();
|
||||
|
||||
// List of collected files is complete; validate exhautiveness if this is a project with a file list
|
||||
@@ -3196,7 +3193,7 @@ namespace ts {
|
||||
blockEmittingOfFile(emitFileName, createCompilerDiagnosticFromMessageChain(chain));
|
||||
}
|
||||
|
||||
const emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath;
|
||||
const emitFileKey = !host.useCaseSensitiveFileNames() ? toFileNameLowerCase(emitFilePath) : emitFilePath;
|
||||
// Report error if multiple files write into same file
|
||||
if (emitFilesSeen.has(emitFileKey)) {
|
||||
// Already seen the same emit file - report error
|
||||
@@ -3210,7 +3207,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function createFileDiagnosticAtReference(refPathToReportErrorOn: ts.RefFile, message: DiagnosticMessage, ...args: (string | number | undefined)[]) {
|
||||
const refFile = Debug.assertDefined(getSourceFileByPath(refPathToReportErrorOn.file));
|
||||
const refFile = Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
|
||||
const { kind, index } = refPathToReportErrorOn;
|
||||
let pos: number, end: number;
|
||||
switch (kind) {
|
||||
@@ -3476,8 +3473,8 @@ namespace ts {
|
||||
return {
|
||||
fileExists: f => directoryStructureHost.fileExists(f),
|
||||
readDirectory(root, extensions, excludes, includes, depth) {
|
||||
Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return directoryStructureHost.readDirectory!(root, extensions, excludes, includes, depth);
|
||||
Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
|
||||
},
|
||||
readFile: f => directoryStructureHost.readFile(f),
|
||||
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
|
||||
|
||||
@@ -73,8 +73,15 @@ namespace ts {
|
||||
nonRecursive?: boolean;
|
||||
}
|
||||
|
||||
export function isPathIgnored(path: Path) {
|
||||
return some(ignoredPaths, searchPath => stringContains(path, searchPath));
|
||||
export function removeIgnoredPath(path: Path): Path | undefined {
|
||||
// Consider whole staging folder as if node_modules changed.
|
||||
if (endsWith(path, "/node_modules/.staging")) {
|
||||
return removeSuffix(path, "/.staging") as Path;
|
||||
}
|
||||
|
||||
return some(ignoredPaths, searchPath => stringContains(path, searchPath)) ?
|
||||
undefined :
|
||||
path;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,6 +176,7 @@ namespace ts {
|
||||
const directoryWatchesOfFailedLookups = createMap<DirectoryWatchesOfFailedLookup>();
|
||||
const rootDir = rootDirForResolution && removeTrailingDirectorySeparator(getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
|
||||
const rootPath = (rootDir && resolutionHost.toPath(rootDir)) as Path; // TODO: GH#18217
|
||||
const rootSplitLength = rootPath !== undefined ? rootPath.split(directorySeparator).length : 0;
|
||||
|
||||
// TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
|
||||
const typeRootsWatches = createMap<FileWatcher>();
|
||||
@@ -286,7 +294,7 @@ namespace ts {
|
||||
// create different collection of failed lookup locations for second pass
|
||||
// if it will fail and we've already found something during the first pass - we don't want to pollute its results
|
||||
const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(
|
||||
Debug.assertDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName),
|
||||
Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName),
|
||||
resolutionHost.projectName,
|
||||
compilerOptions,
|
||||
host,
|
||||
@@ -432,15 +440,23 @@ namespace ts {
|
||||
if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
|
||||
// Ensure failed look up is normalized path
|
||||
failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
|
||||
Debug.assert(failedLookupLocation.length === failedLookupLocationPath.length, `FailedLookup: ${failedLookupLocation} failedLookupLocationPath: ${failedLookupLocationPath}`);
|
||||
const subDirectoryInRoot = failedLookupLocationPath.indexOf(directorySeparator, rootPath.length + 1);
|
||||
if (subDirectoryInRoot !== -1) {
|
||||
const failedLookupPathSplit = failedLookupLocationPath.split(directorySeparator);
|
||||
const failedLookupSplit = failedLookupLocation.split(directorySeparator);
|
||||
Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, `FailedLookup: ${failedLookupLocation} failedLookupLocationPath: ${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 { dir: failedLookupLocation.substr(0, subDirectoryInRoot), dirPath: failedLookupLocationPath.substr(0, subDirectoryInRoot) as Path };
|
||||
return {
|
||||
dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(directorySeparator),
|
||||
dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(directorySeparator) as Path
|
||||
};
|
||||
}
|
||||
else {
|
||||
// Always watch root directory non recursively
|
||||
return { dir: rootDir!, dirPath: rootPath, nonRecursive: false }; // TODO: GH#18217
|
||||
return {
|
||||
dir: rootDir!,
|
||||
dirPath: rootPath,
|
||||
nonRecursive: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -671,7 +687,7 @@ namespace ts {
|
||||
(filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = createMap<true>())).set(containingFilePath, true);
|
||||
|
||||
// When its a file with inferred types resolution, invalidate type reference directive resolution
|
||||
if (containingFilePath.endsWith(inferredTypesContainingFile)) {
|
||||
if (endsWith(containingFilePath, inferredTypesContainingFile)) {
|
||||
resolutionHost.onChangedAutomaticTypeDirectiveNames();
|
||||
}
|
||||
}
|
||||
@@ -722,7 +738,9 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
// If something to do with folder/file starting with "." in node_modules folder, skip it
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return false;
|
||||
const updatedPath = removeIgnoredPath(fileOrDirectoryPath);
|
||||
if (!updatedPath) return false;
|
||||
fileOrDirectoryPath = updatedPath;
|
||||
|
||||
// prevent saving an open file from over-eagerly triggering invalidation
|
||||
if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
|
||||
|
||||
+99
-14
@@ -28,7 +28,8 @@ namespace ts {
|
||||
getTokenFlags(): TokenFlags;
|
||||
reScanGreaterToken(): SyntaxKind;
|
||||
reScanSlashToken(): SyntaxKind;
|
||||
reScanTemplateToken(): SyntaxKind;
|
||||
reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind;
|
||||
reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind;
|
||||
scanJsxIdentifier(): SyntaxKind;
|
||||
scanJsxAttributeValue(): SyntaxKind;
|
||||
reScanJsxAttributeValue(): SyntaxKind;
|
||||
@@ -468,6 +469,14 @@ namespace ts {
|
||||
return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
|
||||
}
|
||||
|
||||
function isHexDigit(ch: number): boolean {
|
||||
return isDigit(ch) || ch >= CharacterCodes.A && ch <= CharacterCodes.F || ch >= CharacterCodes.a && ch <= CharacterCodes.f;
|
||||
}
|
||||
|
||||
function isCodePoint(code: number): boolean {
|
||||
return code <= 0x10FFFF;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function isOctalDigit(ch: number): boolean {
|
||||
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
|
||||
@@ -901,6 +910,7 @@ namespace ts {
|
||||
reScanGreaterToken,
|
||||
reScanSlashToken,
|
||||
reScanTemplateToken,
|
||||
reScanTemplateHeadOrNoSubstitutionTemplate,
|
||||
scanJsxIdentifier,
|
||||
scanJsxAttributeValue,
|
||||
reScanJsxAttributeValue,
|
||||
@@ -1164,7 +1174,7 @@ namespace ts {
|
||||
* Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
|
||||
* a literal component of a TemplateExpression.
|
||||
*/
|
||||
function scanTemplateAndSetTokenValue(): SyntaxKind {
|
||||
function scanTemplateAndSetTokenValue(isTaggedTemplate: boolean): SyntaxKind {
|
||||
const startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick;
|
||||
|
||||
pos++;
|
||||
@@ -1202,7 +1212,7 @@ namespace ts {
|
||||
// Escape character
|
||||
if (currChar === CharacterCodes.backslash) {
|
||||
contents += text.substring(start, pos);
|
||||
contents += scanEscapeSequence();
|
||||
contents += scanEscapeSequence(isTaggedTemplate);
|
||||
start = pos;
|
||||
continue;
|
||||
}
|
||||
@@ -1231,7 +1241,8 @@ namespace ts {
|
||||
return resultingToken;
|
||||
}
|
||||
|
||||
function scanEscapeSequence(): string {
|
||||
function scanEscapeSequence(isTaggedTemplate?: boolean): string {
|
||||
const start = pos;
|
||||
pos++;
|
||||
if (pos >= end) {
|
||||
error(Diagnostics.Unexpected_end_of_text);
|
||||
@@ -1241,6 +1252,12 @@ namespace ts {
|
||||
pos++;
|
||||
switch (ch) {
|
||||
case CharacterCodes._0:
|
||||
// '\01'
|
||||
if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
|
||||
pos++;
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
return "\0";
|
||||
case CharacterCodes.b:
|
||||
return "\b";
|
||||
@@ -1259,10 +1276,41 @@ namespace ts {
|
||||
case CharacterCodes.doubleQuote:
|
||||
return "\"";
|
||||
case CharacterCodes.u:
|
||||
if (isTaggedTemplate) {
|
||||
// '\u' or '\u0' or '\u00' or '\u000'
|
||||
for (let escapePos = pos; escapePos < pos + 4; escapePos++) {
|
||||
if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== CharacterCodes.openBrace) {
|
||||
pos = escapePos;
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
// '\u{DDDDDDDD}'
|
||||
if (pos < end && text.charCodeAt(pos) === CharacterCodes.openBrace) {
|
||||
tokenFlags |= TokenFlags.ExtendedUnicodeEscape;
|
||||
pos++;
|
||||
|
||||
// '\u{'
|
||||
if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
|
||||
if (isTaggedTemplate) {
|
||||
const savePos = pos;
|
||||
const escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
|
||||
const escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
|
||||
|
||||
// '\u{Not Code Point' or '\u{CodePoint'
|
||||
if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== CharacterCodes.closeBrace) {
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
else {
|
||||
pos = savePos;
|
||||
}
|
||||
}
|
||||
tokenFlags |= TokenFlags.ExtendedUnicodeEscape;
|
||||
return scanExtendedUnicodeEscape();
|
||||
}
|
||||
|
||||
@@ -1271,6 +1319,17 @@ namespace ts {
|
||||
return scanHexadecimalEscape(/*numDigits*/ 4);
|
||||
|
||||
case CharacterCodes.x:
|
||||
if (isTaggedTemplate) {
|
||||
if (!isHexDigit(text.charCodeAt(pos))) {
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
else if (!isHexDigit(text.charCodeAt(pos + 1))) {
|
||||
pos++;
|
||||
tokenFlags |= TokenFlags.ContainsInvalidEscape;
|
||||
return text.substring(start, pos);
|
||||
}
|
||||
}
|
||||
// '\xDD'
|
||||
return scanHexadecimalEscape(/*numDigits*/ 2);
|
||||
|
||||
@@ -1561,7 +1620,7 @@ namespace ts {
|
||||
tokenValue = scanString();
|
||||
return token = SyntaxKind.StringLiteral;
|
||||
case CharacterCodes.backtick:
|
||||
return token = scanTemplateAndSetTokenValue();
|
||||
return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
|
||||
case CharacterCodes.percent:
|
||||
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
|
||||
return pos += 2, token = SyntaxKind.PercentEqualsToken;
|
||||
@@ -1907,11 +1966,12 @@ namespace ts {
|
||||
if (ch === CharacterCodes.backslash) {
|
||||
tokenValue += scanIdentifierParts();
|
||||
}
|
||||
return token = SyntaxKind.PrivateIdentifier;
|
||||
}
|
||||
error(Diagnostics.Invalid_character);
|
||||
// no `pos++` because already advanced past the '#'
|
||||
return token = SyntaxKind.Unknown;
|
||||
else {
|
||||
tokenValue = "#";
|
||||
error(Diagnostics.Invalid_character);
|
||||
}
|
||||
return token = SyntaxKind.PrivateIdentifier;
|
||||
default:
|
||||
if (isIdentifierStart(ch, languageVersion)) {
|
||||
pos += charSize(ch);
|
||||
@@ -2018,10 +2078,15 @@ namespace ts {
|
||||
/**
|
||||
* Unconditionally back up and scan a template expression portion.
|
||||
*/
|
||||
function reScanTemplateToken(): SyntaxKind {
|
||||
function reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind {
|
||||
Debug.assert(token === SyntaxKind.CloseBraceToken, "'reScanTemplateToken' should only be called on a '}'");
|
||||
pos = tokenPos;
|
||||
return token = scanTemplateAndSetTokenValue();
|
||||
return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
|
||||
}
|
||||
|
||||
function reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind {
|
||||
pos = tokenPos;
|
||||
return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
|
||||
}
|
||||
|
||||
function reScanJsxToken(): JsxTokenSyntaxKind {
|
||||
@@ -2067,10 +2132,19 @@ namespace ts {
|
||||
|
||||
// First non-whitespace character on this line.
|
||||
let firstNonWhitespace = 0;
|
||||
let lastNonWhitespace = -1;
|
||||
|
||||
// These initial values are special because the first line is:
|
||||
// firstNonWhitespace = 0 to indicate that we want leading whitespace,
|
||||
|
||||
while (pos < end) {
|
||||
|
||||
// We want to keep track of the last non-whitespace (but including
|
||||
// newlines character for hitting the end of the JSX Text region)
|
||||
if (!isWhiteSpaceSingleLine(char)) {
|
||||
lastNonWhitespace = pos;
|
||||
}
|
||||
|
||||
char = text.charCodeAt(pos);
|
||||
if (char === CharacterCodes.openBrace) {
|
||||
break;
|
||||
@@ -2082,6 +2156,14 @@ namespace ts {
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (char === CharacterCodes.greaterThan) {
|
||||
error(Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
|
||||
}
|
||||
if (char === CharacterCodes.closeBrace) {
|
||||
error(Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
|
||||
}
|
||||
|
||||
if (lastNonWhitespace > 0) lastNonWhitespace++;
|
||||
|
||||
// FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
|
||||
// i.e (- : whitespace)
|
||||
@@ -2095,10 +2177,13 @@ namespace ts {
|
||||
else if (!isWhiteSpaceLike(char)) {
|
||||
firstNonWhitespace = pos;
|
||||
}
|
||||
|
||||
pos++;
|
||||
}
|
||||
|
||||
tokenValue = text.substring(startPos, pos);
|
||||
const endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
|
||||
tokenValue = text.substring(startPos, endPosition);
|
||||
|
||||
return firstNonWhitespace === -1 ? SyntaxKind.JsxTextAllWhiteSpaces : SyntaxKind.JsxText;
|
||||
}
|
||||
|
||||
@@ -2359,7 +2444,7 @@ namespace ts {
|
||||
return String.fromCharCode(codeUnit1, codeUnit2);
|
||||
}
|
||||
|
||||
const utf16EncodeAsStringWorker: (codePoint: number) => string = (String as any).fromCodePoint ? codePoint => String.fromCodePoint(codePoint) : utf16EncodeAsStringFallback;
|
||||
const utf16EncodeAsStringWorker: (codePoint: number) => string = (String as any).fromCodePoint ? codePoint => (String as any).fromCodePoint(codePoint) : utf16EncodeAsStringFallback;
|
||||
|
||||
/* @internal */
|
||||
export function utf16EncodeAsString(codePoint: number) {
|
||||
|
||||
@@ -42,7 +42,7 @@ namespace ts {
|
||||
constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string);
|
||||
constructor(major: number | string, minor = 0, patch = 0, prerelease = "", build = "") {
|
||||
if (typeof major === "string") {
|
||||
const result = Debug.assertDefined(tryParseComponents(major), "Invalid version");
|
||||
const result = Debug.checkDefined(tryParseComponents(major), "Invalid version");
|
||||
({ major, minor, patch, prerelease, build } = result);
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ namespace ts {
|
||||
private _alternatives: readonly (readonly Comparator[])[];
|
||||
|
||||
constructor(spec: string) {
|
||||
this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray;
|
||||
this._alternatives = spec ? Debug.checkDefined(parseRange(spec), "Invalid range spec.") : emptyArray;
|
||||
}
|
||||
|
||||
static tryParse(text: string) {
|
||||
|
||||
+39
-93
@@ -398,7 +398,7 @@ namespace ts {
|
||||
|
||||
return {
|
||||
close: () => {
|
||||
const watcher = Debug.assertDefined(cache.get(path));
|
||||
const watcher = Debug.checkDefined(cache.get(path));
|
||||
callbacksCache.remove(path, callback);
|
||||
watcher.refCount--;
|
||||
if (watcher.refCount) return;
|
||||
@@ -525,7 +525,7 @@ namespace ts {
|
||||
return {
|
||||
dirName,
|
||||
close: () => {
|
||||
const directoryWatcher = Debug.assertDefined(cache.get(dirPath));
|
||||
const directoryWatcher = Debug.checkDefined(cache.get(dirPath));
|
||||
if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd);
|
||||
directoryWatcher.refCount--;
|
||||
|
||||
@@ -772,7 +772,7 @@ namespace ts {
|
||||
|
||||
function watchFile(fileName: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, options: WatchOptions | undefined): FileWatcher {
|
||||
options = updateOptionsForWatchFile(options, useNonPollingWatchers);
|
||||
const watchFileKind = Debug.assertDefined(options.watchFile);
|
||||
const watchFileKind = Debug.checkDefined(options.watchFile);
|
||||
switch (watchFileKind) {
|
||||
case WatchFileKind.FixedPollingInterval:
|
||||
return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
|
||||
@@ -874,7 +874,7 @@ namespace ts {
|
||||
function nonRecursiveWatchDirectory(directoryName: string, callback: DirectoryWatcherCallback, recursive: boolean, options: WatchOptions | undefined): FileWatcher {
|
||||
Debug.assert(!recursive);
|
||||
options = updateOptionsForWatchDirectory(options);
|
||||
const watchDirectoryKind = Debug.assertDefined(options.watchDirectory);
|
||||
const watchDirectoryKind = Debug.checkDefined(options.watchDirectory);
|
||||
switch (watchDirectoryKind) {
|
||||
case WatchDirectoryKind.FixedPollingInterval:
|
||||
return pollingWatchFile(
|
||||
@@ -1004,14 +1004,14 @@ namespace ts {
|
||||
writeFloatBE(value: number, offset: number): number;
|
||||
writeDoubleLE(value: number, offset: number): number;
|
||||
writeDoubleBE(value: number, offset: number): number;
|
||||
readBigUInt64BE(offset?: number): bigint;
|
||||
readBigUInt64LE(offset?: number): bigint;
|
||||
readBigInt64BE(offset?: number): bigint;
|
||||
readBigInt64LE(offset?: number): bigint;
|
||||
writeBigInt64BE(value: bigint, offset?: number): number;
|
||||
writeBigInt64LE(value: bigint, offset?: number): number;
|
||||
writeBigUInt64BE(value: bigint, offset?: number): number;
|
||||
writeBigUInt64LE(value: bigint, offset?: number): number;
|
||||
readBigUInt64BE?(offset?: number): bigint;
|
||||
readBigUInt64LE?(offset?: number): bigint;
|
||||
readBigInt64BE?(offset?: number): bigint;
|
||||
readBigInt64LE?(offset?: number): bigint;
|
||||
writeBigInt64BE?(value: bigint, offset?: number): number;
|
||||
writeBigInt64LE?(value: bigint, offset?: number): number;
|
||||
writeBigUInt64BE?(value: bigint, offset?: number): number;
|
||||
writeBigUInt64LE?(value: bigint, offset?: number): number;
|
||||
fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this;
|
||||
indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
|
||||
lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
|
||||
@@ -1107,31 +1107,6 @@ namespace ts {
|
||||
return parseInt(version.substring(1, dot));
|
||||
}
|
||||
|
||||
declare const ChakraHost: {
|
||||
args: string[];
|
||||
currentDirectory: string;
|
||||
executingFile: string;
|
||||
newLine?: string;
|
||||
useCaseSensitiveFileNames?: boolean;
|
||||
echo(s: string): void;
|
||||
quit(exitCode?: number): void;
|
||||
fileExists(path: string): boolean;
|
||||
deleteFile(path: string): boolean;
|
||||
getModifiedTime(path: string): Date;
|
||||
setModifiedTime(path: string, time: Date): void;
|
||||
directoryExists(path: string): boolean;
|
||||
createDirectory(path: string): void;
|
||||
resolvePath(path: string): string;
|
||||
readFile(path: string): string | undefined;
|
||||
writeFile(path: string, contents: string): void;
|
||||
getDirectories(path: string): string[];
|
||||
readDirectory(path: string, extensions?: readonly string[], basePaths?: readonly string[], excludeEx?: string, includeFileEx?: string, includeDirEx?: string): string[];
|
||||
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
|
||||
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
|
||||
realpath(path: string): string;
|
||||
getEnvironmentVariable?(name: string): string;
|
||||
};
|
||||
|
||||
// TODO: GH#18217 this is used as if it's certainly defined in many places.
|
||||
// eslint-disable-next-line prefer-const
|
||||
export let sys: System = (() => {
|
||||
@@ -1559,10 +1534,13 @@ namespace ts {
|
||||
}
|
||||
|
||||
function readFileWorker(fileName: string, _encoding?: string): string | undefined {
|
||||
if (!fileExists(fileName)) {
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
buffer = _fs.readFileSync(fileName);
|
||||
}
|
||||
catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
const buffer = _fs.readFileSync(fileName);
|
||||
let len = buffer.length;
|
||||
if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
|
||||
// Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
|
||||
@@ -1617,23 +1595,32 @@ namespace ts {
|
||||
function getAccessibleFileSystemEntries(path: string): FileSystemEntries {
|
||||
perfLogger.logEvent("ReadDir: " + (path || "."));
|
||||
try {
|
||||
const entries = _fs.readdirSync(path || ".").sort();
|
||||
const entries = _fs.readdirSync(path || ".", { withFileTypes: true });
|
||||
const files: string[] = [];
|
||||
const directories: string[] = [];
|
||||
for (const entry of entries) {
|
||||
for (const dirent of entries) {
|
||||
// withFileTypes is not supported before Node 10.10.
|
||||
const entry = typeof dirent === "string" ? dirent : dirent.name;
|
||||
|
||||
// This is necessary because on some file system node fails to exclude
|
||||
// "." and "..". See https://github.com/nodejs/node/issues/4002
|
||||
if (entry === "." || entry === "..") {
|
||||
continue;
|
||||
}
|
||||
const name = combinePaths(path, entry);
|
||||
|
||||
let stat: any;
|
||||
try {
|
||||
stat = _fs.statSync(name);
|
||||
if (typeof dirent === "string" || dirent.isSymbolicLink()) {
|
||||
const name = combinePaths(path, entry);
|
||||
|
||||
try {
|
||||
stat = _fs.statSync(name);
|
||||
}
|
||||
catch (e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
continue;
|
||||
else {
|
||||
stat = dirent;
|
||||
}
|
||||
|
||||
if (stat.isFile()) {
|
||||
@@ -1643,6 +1630,8 @@ namespace ts {
|
||||
directories.push(entry);
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
directories.sort();
|
||||
return { files, directories };
|
||||
}
|
||||
catch (e) {
|
||||
@@ -1677,8 +1666,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getDirectories(path: string): string[] {
|
||||
perfLogger.logEvent("ReadDir: " + path);
|
||||
return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
|
||||
return getAccessibleFileSystemEntries(path).directories.slice();
|
||||
}
|
||||
|
||||
function realpath(path: string): string {
|
||||
@@ -1724,50 +1712,8 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getChakraSystem(): System {
|
||||
const realpath = ChakraHost.realpath && ((path: string) => ChakraHost.realpath(path));
|
||||
return {
|
||||
newLine: ChakraHost.newLine || "\r\n",
|
||||
args: ChakraHost.args,
|
||||
useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames,
|
||||
write: ChakraHost.echo,
|
||||
readFile(path: string, _encoding?: string) {
|
||||
// encoding is automatically handled by the implementation in ChakraHost
|
||||
return ChakraHost.readFile(path);
|
||||
},
|
||||
writeFile(path: string, data: string, writeByteOrderMark?: boolean) {
|
||||
// If a BOM is required, emit one
|
||||
if (writeByteOrderMark) {
|
||||
data = byteOrderMarkIndicator + data;
|
||||
}
|
||||
|
||||
ChakraHost.writeFile(path, data);
|
||||
},
|
||||
resolvePath: ChakraHost.resolvePath,
|
||||
fileExists: ChakraHost.fileExists,
|
||||
deleteFile: ChakraHost.deleteFile,
|
||||
getModifiedTime: ChakraHost.getModifiedTime,
|
||||
setModifiedTime: ChakraHost.setModifiedTime,
|
||||
directoryExists: ChakraHost.directoryExists,
|
||||
createDirectory: ChakraHost.createDirectory,
|
||||
getExecutingFilePath: () => ChakraHost.executingFile,
|
||||
getCurrentDirectory: () => ChakraHost.currentDirectory,
|
||||
getDirectories: ChakraHost.getDirectories,
|
||||
getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (() => ""),
|
||||
readDirectory(path, extensions, excludes, includes, _depth) {
|
||||
const pattern = getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory);
|
||||
return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern);
|
||||
},
|
||||
exit: ChakraHost.quit,
|
||||
realpath
|
||||
};
|
||||
}
|
||||
|
||||
let sys: System | undefined;
|
||||
if (typeof ChakraHost !== "undefined") {
|
||||
sys = getChakraSystem();
|
||||
}
|
||||
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
|
||||
if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
|
||||
// process and process.nextTick checks if current environment is node-like
|
||||
// process.browser check excludes webpack and browserify
|
||||
sys = getNodeSystem();
|
||||
@@ -1781,9 +1727,9 @@ namespace ts {
|
||||
|
||||
if (sys && sys.getEnvironmentVariable) {
|
||||
setCustomPollingValues(sys);
|
||||
Debug.currentAssertionLevel = /^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
|
||||
Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
|
||||
? AssertionLevel.Normal
|
||||
: AssertionLevel.None;
|
||||
: AssertionLevel.None);
|
||||
}
|
||||
if (sys && sys.debugMode) {
|
||||
Debug.isDebugging = true;
|
||||
|
||||
@@ -225,6 +225,7 @@ namespace ts {
|
||||
transformed,
|
||||
substituteNode,
|
||||
emitNodeWithNotification,
|
||||
isEmitNotificationEnabled,
|
||||
dispose,
|
||||
diagnostics
|
||||
};
|
||||
@@ -288,6 +289,8 @@ namespace ts {
|
||||
function emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) {
|
||||
Debug.assert(state < TransformationState.Disposed, "Cannot invoke TransformationResult callbacks after the result is disposed.");
|
||||
if (node) {
|
||||
// TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
|
||||
// (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
|
||||
if (isEmitNotificationEnabled(node)) {
|
||||
onEmitNode(hint, node, emitCallback);
|
||||
}
|
||||
@@ -409,6 +412,11 @@ namespace ts {
|
||||
Debug.assert(state > TransformationState.Uninitialized, "Cannot modify the transformation context during initialization.");
|
||||
Debug.assert(state < TransformationState.Completed, "Cannot modify the transformation context after transformation has completed.");
|
||||
Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
|
||||
if (helper.dependencies) {
|
||||
for (const h of helper.dependencies) {
|
||||
requestEmitHelper(h);
|
||||
}
|
||||
}
|
||||
emitHelpers = append(emitHelpers, helper);
|
||||
}
|
||||
|
||||
|
||||
@@ -518,7 +518,7 @@ namespace ts {
|
||||
|
||||
if (some(staticProperties) || some(pendingExpressions)) {
|
||||
if (isDecoratedClassDeclaration) {
|
||||
Debug.assertDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
|
||||
Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
|
||||
|
||||
// Write any pending expressions from elided or moved computed property names
|
||||
if (pendingStatements && pendingExpressions && some(pendingExpressions)) {
|
||||
|
||||
@@ -401,7 +401,7 @@ namespace ts {
|
||||
forEach(sourceFile.libReferenceDirectives, ref => {
|
||||
const lib = host.getLibFileFromReference(ref);
|
||||
if (lib) {
|
||||
ret.set(ref.fileName.toLocaleLowerCase(), true);
|
||||
ret.set(toFileNameLowerCase(ref.fileName), true);
|
||||
}
|
||||
});
|
||||
return ret;
|
||||
|
||||
@@ -252,7 +252,7 @@ namespace ts {
|
||||
value = inlineExpressions(append(pendingExpressions, value));
|
||||
pendingExpressions = undefined;
|
||||
}
|
||||
pendingDeclarations.push({ pendingExpressions, name: <BindingName>target, value, location, original });
|
||||
pendingDeclarations.push({ pendingExpressions, name: target, value, location, original });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,7 +325,7 @@ namespace ts {
|
||||
&& !(element.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread))
|
||||
&& !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread))
|
||||
&& !isComputedPropertyName(propertyName)) {
|
||||
bindingElements = append(bindingElements, element);
|
||||
bindingElements = append(bindingElements, visitNode(element, flattenContext.visitor));
|
||||
}
|
||||
else {
|
||||
if (bindingElements) {
|
||||
|
||||
@@ -1879,7 +1879,7 @@ namespace ts {
|
||||
// being emitted for the end position only.
|
||||
statementsLocation = moveRangeEnd(body, -1);
|
||||
|
||||
const equalsGreaterThanToken = (<ArrowFunction>node).equalsGreaterThanToken;
|
||||
const equalsGreaterThanToken = node.equalsGreaterThanToken;
|
||||
if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
|
||||
if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
|
||||
singleLine = true;
|
||||
@@ -2002,10 +2002,16 @@ namespace ts {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
function isVariableStatementOfTypeScriptClassWrapper(node: VariableStatement) {
|
||||
return node.declarationList.declarations.length === 1
|
||||
&& !!node.declarationList.declarations[0].initializer
|
||||
&& !!(getEmitFlags(node.declarationList.declarations[0].initializer) & EmitFlags.TypeScriptClassWrapper);
|
||||
}
|
||||
|
||||
function visitVariableStatement(node: VariableStatement): Statement | undefined {
|
||||
const ancestorFacts = enterSubtree(HierarchyFacts.None, hasModifier(node, ModifierFlags.Export) ? HierarchyFacts.ExportedVariableStatement : HierarchyFacts.None);
|
||||
let updated: Statement | undefined;
|
||||
if (convertedLoopState && (node.declarationList.flags & NodeFlags.BlockScoped) === 0) {
|
||||
if (convertedLoopState && (node.declarationList.flags & NodeFlags.BlockScoped) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
|
||||
// we are inside a converted loop - hoist variable declarations
|
||||
let assignments: Expression[] | undefined;
|
||||
for (const decl of node.declarationList.declarations) {
|
||||
@@ -3425,12 +3431,12 @@ namespace ts {
|
||||
const ancestorFacts = enterSubtree(HierarchyFacts.BlockScopeExcludes, HierarchyFacts.BlockScopeIncludes);
|
||||
let updated: CatchClause;
|
||||
Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
|
||||
if (isBindingPattern(node.variableDeclaration!.name)) {
|
||||
if (isBindingPattern(node.variableDeclaration.name)) {
|
||||
const temp = createTempVariable(/*recordTempVariable*/ undefined);
|
||||
const newVariableDeclaration = createVariableDeclaration(temp);
|
||||
setTextRange(newVariableDeclaration, node.variableDeclaration);
|
||||
const vars = flattenDestructuringBinding(
|
||||
node.variableDeclaration!,
|
||||
node.variableDeclaration,
|
||||
visitor,
|
||||
context,
|
||||
FlattenLevel.All,
|
||||
@@ -3606,7 +3612,13 @@ namespace ts {
|
||||
// The class statements are the statements generated by visiting the first statement with initializer of the
|
||||
// body (1), while all other statements are added to remainingStatements (2)
|
||||
const isVariableStatementWithInitializer = (stmt: Statement) => isVariableStatement(stmt) && !!first(stmt.declarationList.declarations).initializer;
|
||||
|
||||
// visit the class body statements outside of any converted loop body.
|
||||
const savedConvertedLoopState = convertedLoopState;
|
||||
convertedLoopState = undefined;
|
||||
const bodyStatements = visitNodes(body.statements, visitor, isStatement);
|
||||
convertedLoopState = savedConvertedLoopState;
|
||||
|
||||
const classStatements = filter(bodyStatements, isVariableStatementWithInitializer);
|
||||
const remainingStatements = filter(bodyStatements, stmt => !isVariableStatementWithInitializer(stmt));
|
||||
const varStatement = cast(first(classStatements), isVariableStatement);
|
||||
@@ -3951,78 +3963,14 @@ namespace ts {
|
||||
* @param node A TaggedTemplateExpression node.
|
||||
*/
|
||||
function visitTaggedTemplateExpression(node: TaggedTemplateExpression) {
|
||||
// Visit the tag expression
|
||||
const tag = visitNode(node.tag, visitor, isExpression);
|
||||
|
||||
// Build up the template arguments and the raw and cooked strings for the template.
|
||||
// We start out with 'undefined' for the first argument and revisit later
|
||||
// to avoid walking over the template string twice and shifting all our arguments over after the fact.
|
||||
const templateArguments: Expression[] = [undefined!];
|
||||
const cookedStrings: Expression[] = [];
|
||||
const rawStrings: Expression[] = [];
|
||||
const template = node.template;
|
||||
if (isNoSubstitutionTemplateLiteral(template)) {
|
||||
cookedStrings.push(createLiteral(template.text));
|
||||
rawStrings.push(getRawLiteral(template));
|
||||
}
|
||||
else {
|
||||
cookedStrings.push(createLiteral(template.head.text));
|
||||
rawStrings.push(getRawLiteral(template.head));
|
||||
for (const templateSpan of template.templateSpans) {
|
||||
cookedStrings.push(createLiteral(templateSpan.literal.text));
|
||||
rawStrings.push(getRawLiteral(templateSpan.literal));
|
||||
templateArguments.push(visitNode(templateSpan.expression, visitor, isExpression));
|
||||
}
|
||||
}
|
||||
|
||||
const helperCall = createTemplateObjectHelper(context, createArrayLiteral(cookedStrings), createArrayLiteral(rawStrings));
|
||||
|
||||
// Create a variable to cache the template object if we're in a module.
|
||||
// Do not do this in the global scope, as any variable we currently generate could conflict with
|
||||
// variables from outside of the current compilation. In the future, we can revisit this behavior.
|
||||
if (isExternalModule(currentSourceFile)) {
|
||||
const tempVar = createUniqueName("templateObject");
|
||||
recordTaggedTemplateString(tempVar);
|
||||
templateArguments[0] = createLogicalOr(
|
||||
tempVar,
|
||||
createAssignment(
|
||||
tempVar,
|
||||
helperCall)
|
||||
);
|
||||
}
|
||||
else {
|
||||
templateArguments[0] = helperCall;
|
||||
}
|
||||
|
||||
return createCall(tag, /*typeArguments*/ undefined, templateArguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ES5 compatible literal from an ES6 template literal.
|
||||
*
|
||||
* @param node The ES6 template literal.
|
||||
*/
|
||||
function getRawLiteral(node: TemplateLiteralLikeNode) {
|
||||
// Find original source text, since we need to emit the raw strings of the tagged template.
|
||||
// The raw strings contain the (escaped) strings of what the user wrote.
|
||||
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
|
||||
let text = node.rawText;
|
||||
if (text === undefined) {
|
||||
text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
|
||||
|
||||
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
|
||||
// thus we need to remove those characters.
|
||||
// First template piece starts with "`", others with "}"
|
||||
// Last template piece ends with "`", others with "${"
|
||||
const isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail;
|
||||
text = text.substring(1, text.length - (isLast ? 1 : 2));
|
||||
}
|
||||
|
||||
// Newline normalization:
|
||||
// ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
|
||||
// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
|
||||
text = text.replace(/\r\n?/g, "\n");
|
||||
return setTextRange(createLiteral(text), node);
|
||||
return processTaggedTemplateExpression(
|
||||
context,
|
||||
node,
|
||||
visitor,
|
||||
currentSourceFile,
|
||||
recordTaggedTemplateString,
|
||||
ProcessLevel.All
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4358,18 +4306,6 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
function createTemplateObjectHelper(context: TransformationContext, cooked: ArrayLiteralExpression, raw: ArrayLiteralExpression) {
|
||||
context.requestEmitHelper(templateObjectHelper);
|
||||
return createCall(
|
||||
getUnscopedHelperName("__makeTemplateObject"),
|
||||
/*typeArguments*/ undefined,
|
||||
[
|
||||
cooked,
|
||||
raw
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
export const extendsHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:extends",
|
||||
importName: "__extends",
|
||||
@@ -4391,17 +4327,4 @@ namespace ts {
|
||||
};
|
||||
})();`
|
||||
};
|
||||
|
||||
export const templateObjectHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:makeTemplateObject",
|
||||
importName: "__makeTemplateObject",
|
||||
scoped: false,
|
||||
priority: 0,
|
||||
text: `
|
||||
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
|
||||
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
|
||||
return cooked;
|
||||
};`
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ namespace ts {
|
||||
let enclosingSuperContainerFlags: NodeCheckFlags = 0;
|
||||
let hasLexicalThis: boolean;
|
||||
|
||||
let currentSourceFile: SourceFile;
|
||||
let taggedTemplateStringDeclarations: VariableDeclaration[];
|
||||
|
||||
/** Keeps track of property names accessed on super (`super.x`) within async functions. */
|
||||
let capturedSuperProperties: UnderscoreEscapedMap<true>;
|
||||
/** Whether the async function contains an element access on super (`super[x]`). */
|
||||
@@ -37,15 +40,23 @@ namespace ts {
|
||||
|
||||
return chainBundle(transformSourceFile);
|
||||
|
||||
function recordTaggedTemplateString(temp: Identifier) {
|
||||
taggedTemplateStringDeclarations = append(
|
||||
taggedTemplateStringDeclarations,
|
||||
createVariableDeclaration(temp));
|
||||
}
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
if (node.isDeclarationFile) {
|
||||
return node;
|
||||
}
|
||||
|
||||
exportedVariableStatement = false;
|
||||
hasLexicalThis = !isEffectiveStrictModeSourceFile(node, compilerOptions);
|
||||
const visited = visitEachChild(node, visitor, context);
|
||||
currentSourceFile = node;
|
||||
const visited = visitSourceFile(node);
|
||||
addEmitHelpers(visited, context.readEmitHelpers());
|
||||
|
||||
currentSourceFile = undefined!;
|
||||
taggedTemplateStringDeclarations = undefined!;
|
||||
return visited;
|
||||
}
|
||||
|
||||
@@ -127,6 +138,8 @@ namespace ts {
|
||||
return visitExpressionStatement(node as ExpressionStatement);
|
||||
case SyntaxKind.ParenthesizedExpression:
|
||||
return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue);
|
||||
case SyntaxKind.TaggedTemplateExpression:
|
||||
return visitTaggedTemplateExpression(node as TaggedTemplateExpression);
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) {
|
||||
capturedSuperProperties.set(node.name.escapedText, true);
|
||||
@@ -297,6 +310,28 @@ namespace ts {
|
||||
return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
|
||||
}
|
||||
|
||||
function visitSourceFile(node: SourceFile): SourceFile {
|
||||
exportedVariableStatement = false;
|
||||
hasLexicalThis = !isEffectiveStrictModeSourceFile(node, compilerOptions);
|
||||
const visited = visitEachChild(node, visitor, context);
|
||||
const statement = concatenate(visited.statements, taggedTemplateStringDeclarations && [
|
||||
createVariableStatement(/*modifiers*/ undefined,
|
||||
createVariableDeclarationList(taggedTemplateStringDeclarations))
|
||||
]);
|
||||
return updateSourceFileNode(visited, setTextRange(createNodeArray(statement), node.statements));
|
||||
}
|
||||
|
||||
function visitTaggedTemplateExpression(node: TaggedTemplateExpression) {
|
||||
return processTaggedTemplateExpression(
|
||||
context,
|
||||
node,
|
||||
visitor,
|
||||
currentSourceFile,
|
||||
recordTaggedTemplateString,
|
||||
ProcessLevel.LiftRestriction
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a BinaryExpression that contains a destructuring assignment.
|
||||
*
|
||||
|
||||
@@ -1989,7 +1989,7 @@ namespace ts {
|
||||
*/
|
||||
function markLabel(label: Label): void {
|
||||
Debug.assert(labelOffsets !== undefined, "No labels were defined.");
|
||||
labelOffsets![label] = operations ? operations.length : 0;
|
||||
labelOffsets[label] = operations ? operations.length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -105,7 +105,9 @@ namespace ts {
|
||||
*/
|
||||
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
|
||||
if (isSourceFile(node)) {
|
||||
helperNameSubstitutions = createMap<Identifier>();
|
||||
if ((isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
|
||||
helperNameSubstitutions = createMap<Identifier>();
|
||||
}
|
||||
previousOnEmitNode(hint, node, emitCallback);
|
||||
helperNameSubstitutions = undefined;
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ namespace ts {
|
||||
|
||||
const statements: Statement[] = [];
|
||||
const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
|
||||
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
|
||||
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict && !isJsonSourceFile(node), sourceElementVisitor);
|
||||
|
||||
if (shouldEmitUnderscoreUnderscoreESModule()) {
|
||||
append(statements, createUnderscoreUnderscoreESModule());
|
||||
@@ -103,11 +103,6 @@ namespace ts {
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
const updated = updateSourceFileNode(node, setTextRange(createNodeArray(statements), node.statements));
|
||||
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
|
||||
// If we have any `export * from ...` declarations
|
||||
// we need to inform the emitter to add the __export helper.
|
||||
addEmitHelper(updated, exportStarHelper);
|
||||
}
|
||||
addEmitHelpers(updated, context.readEmitHelpers());
|
||||
return updated;
|
||||
}
|
||||
@@ -435,11 +430,6 @@ namespace ts {
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
const body = createBlock(statements, /*multiLine*/ true);
|
||||
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
|
||||
// If we have any `export * from ...` declarations
|
||||
// we need to inform the emitter to add the __export helper.
|
||||
addEmitHelper(body, exportStarHelper);
|
||||
}
|
||||
if (needUMDDynamicImportHelper) {
|
||||
addEmitHelper(body, dynamicImportUMDHelper);
|
||||
}
|
||||
@@ -1001,20 +991,34 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
for (const specifier of node.exportClause.elements) {
|
||||
const exportedValue = createPropertyAccess(
|
||||
generatedName,
|
||||
specifier.propertyName || specifier.name
|
||||
);
|
||||
statements.push(
|
||||
setOriginalNode(
|
||||
setTextRange(
|
||||
createExpressionStatement(
|
||||
createExportExpression(getExportName(specifier), exportedValue)
|
||||
),
|
||||
specifier),
|
||||
specifier
|
||||
)
|
||||
);
|
||||
if (languageVersion === ScriptTarget.ES3) {
|
||||
statements.push(
|
||||
setOriginalNode(
|
||||
setTextRange(
|
||||
createExpressionStatement(
|
||||
createCreateBindingHelper(context, generatedName, createLiteral(specifier.propertyName || specifier.name), specifier.propertyName ? createLiteral(specifier.name) : undefined)
|
||||
),
|
||||
specifier),
|
||||
specifier
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
const exportedValue = createPropertyAccess(
|
||||
generatedName,
|
||||
specifier.propertyName || specifier.name
|
||||
);
|
||||
statements.push(
|
||||
setOriginalNode(
|
||||
setTextRange(
|
||||
createExpressionStatement(
|
||||
createExportExpression(getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)
|
||||
),
|
||||
specifier),
|
||||
specifier
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return singleOrMany(statements);
|
||||
@@ -1343,7 +1347,7 @@ namespace ts {
|
||||
|
||||
case SyntaxKind.NamedImports:
|
||||
for (const importBinding of namedBindings.elements) {
|
||||
statements = appendExportsOfDeclaration(statements, importBinding);
|
||||
statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -1453,12 +1457,12 @@ namespace ts {
|
||||
* appended.
|
||||
* @param decl The declaration to export.
|
||||
*/
|
||||
function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration): Statement[] | undefined {
|
||||
function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, liveBinding?: boolean): Statement[] | undefined {
|
||||
const name = getDeclarationName(decl);
|
||||
const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(idText(name));
|
||||
if (exportSpecifiers) {
|
||||
for (const exportSpecifier of exportSpecifiers) {
|
||||
statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name);
|
||||
statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
|
||||
}
|
||||
}
|
||||
return statements;
|
||||
@@ -1476,8 +1480,8 @@ namespace ts {
|
||||
* @param location The location to use for source maps and comments for the export.
|
||||
* @param allowComments Whether to allow comments on the export.
|
||||
*/
|
||||
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean): Statement[] | undefined {
|
||||
statements = append(statements, createExportStatement(exportName, expression, location, allowComments));
|
||||
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined {
|
||||
statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
|
||||
return statements;
|
||||
}
|
||||
|
||||
@@ -1518,8 +1522,8 @@ namespace ts {
|
||||
* @param location The location to use for source maps and comments for the export.
|
||||
* @param allowComments An optional value indicating whether to emit comments for the statement.
|
||||
*/
|
||||
function createExportStatement(name: Identifier, value: Expression, location?: TextRange, allowComments?: boolean) {
|
||||
const statement = setTextRange(createExpressionStatement(createExportExpression(name, value)), location);
|
||||
function createExportStatement(name: Identifier, value: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean) {
|
||||
const statement = setTextRange(createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
|
||||
startOnNewLine(statement);
|
||||
if (!allowComments) {
|
||||
setEmitFlags(statement, EmitFlags.NoComments);
|
||||
@@ -1535,9 +1539,31 @@ namespace ts {
|
||||
* @param value The exported value.
|
||||
* @param location The location to use for source maps and comments for the export.
|
||||
*/
|
||||
function createExportExpression(name: Identifier, value: Expression, location?: TextRange) {
|
||||
function createExportExpression(name: Identifier, value: Expression, location?: TextRange, liveBinding?: boolean) {
|
||||
return setTextRange(
|
||||
createAssignment(
|
||||
liveBinding && languageVersion !== ScriptTarget.ES3 ? createCall(
|
||||
createPropertyAccess(
|
||||
createIdentifier("Object"),
|
||||
"defineProperty"
|
||||
),
|
||||
/*typeArguments*/ undefined,
|
||||
[
|
||||
createIdentifier("exports"),
|
||||
createLiteral(name),
|
||||
createObjectLiteral([
|
||||
createPropertyAssignment("enumerable", createLiteral(/*value*/ true)),
|
||||
createPropertyAssignment("get", createFunctionExpression(
|
||||
/*modifiers*/ undefined,
|
||||
/*asteriskToken*/ undefined,
|
||||
/*name*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
/*parameters*/ [],
|
||||
/*type*/ undefined,
|
||||
createBlock([createReturn(value)])
|
||||
))
|
||||
])
|
||||
]
|
||||
) : createAssignment(
|
||||
createPropertyAccess(
|
||||
createIdentifier("exports"),
|
||||
getSynthesizedClone(name)
|
||||
@@ -1813,21 +1839,55 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
// emit output for the __export helper function
|
||||
const exportStarHelper: EmitHelper = {
|
||||
name: "typescript:export-star",
|
||||
scoped: true,
|
||||
export const createBindingHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:commonjscreatebinding",
|
||||
importName: "__createBinding",
|
||||
scoped: false,
|
||||
priority: 1,
|
||||
text: `
|
||||
function __export(m) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));`
|
||||
};
|
||||
|
||||
function createCreateBindingHelper(context: TransformationContext, module: Expression, inputName: Expression, outputName: Expression | undefined) {
|
||||
context.requestEmitHelper(createBindingHelper);
|
||||
return createCall(getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, [createIdentifier("exports"), module, inputName, ...(outputName ? [outputName] : [])]);
|
||||
}
|
||||
|
||||
export const setModuleDefaultHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:commonjscreatevalue",
|
||||
importName: "__setModuleDefault",
|
||||
scoped: false,
|
||||
priority: 1,
|
||||
text: `
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});`
|
||||
};
|
||||
|
||||
// emit output for the __export helper function
|
||||
const exportStarHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:export-star",
|
||||
importName: "__exportStar",
|
||||
scoped: false,
|
||||
dependencies: [createBindingHelper],
|
||||
priority: 2,
|
||||
text: `
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) __createBinding(exports, m, p);
|
||||
}`
|
||||
};
|
||||
|
||||
function createExportStarHelper(context: TransformationContext, module: Expression) {
|
||||
const compilerOptions = context.getCompilerOptions();
|
||||
return compilerOptions.importHelpers
|
||||
? createCall(getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, createIdentifier("exports")])
|
||||
: createCall(createIdentifier("__export"), /*typeArguments*/ undefined, [module]);
|
||||
context.requestEmitHelper(exportStarHelper);
|
||||
return createCall(getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, createIdentifier("exports")]);
|
||||
}
|
||||
|
||||
// emit helper for dynamic import
|
||||
@@ -1843,12 +1903,14 @@ namespace ts {
|
||||
name: "typescript:commonjsimportstar",
|
||||
importName: "__importStar",
|
||||
scoped: false,
|
||||
dependencies: [createBindingHelper, setModuleDefaultHelper],
|
||||
priority: 2,
|
||||
text: `
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};`
|
||||
};
|
||||
|
||||
@@ -637,7 +637,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function visitExportDeclaration(node: ExportDeclaration): VisitResult<Statement> {
|
||||
Debug.assertDefined(node);
|
||||
Debug.assertIsDefined(node);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export enum ProcessLevel {
|
||||
LiftRestriction,
|
||||
All
|
||||
}
|
||||
|
||||
export function processTaggedTemplateExpression(
|
||||
context: TransformationContext,
|
||||
node: TaggedTemplateExpression,
|
||||
visitor: ((node: Node) => VisitResult<Node>) | undefined,
|
||||
currentSourceFile: SourceFile,
|
||||
recordTaggedTemplateString: (temp: Identifier) => void,
|
||||
level: ProcessLevel) {
|
||||
|
||||
// Visit the tag expression
|
||||
const tag = visitNode(node.tag, visitor, isExpression);
|
||||
|
||||
// Build up the template arguments and the raw and cooked strings for the template.
|
||||
// We start out with 'undefined' for the first argument and revisit later
|
||||
// to avoid walking over the template string twice and shifting all our arguments over after the fact.
|
||||
const templateArguments: Expression[] = [undefined!];
|
||||
const cookedStrings: Expression[] = [];
|
||||
const rawStrings: Expression[] = [];
|
||||
const template = node.template;
|
||||
|
||||
if (level === ProcessLevel.LiftRestriction && !hasInvalidEscape(template)) return node;
|
||||
|
||||
if (isNoSubstitutionTemplateLiteral(template)) {
|
||||
cookedStrings.push(createTemplateCooked(template));
|
||||
rawStrings.push(getRawLiteral(template, currentSourceFile));
|
||||
}
|
||||
else {
|
||||
cookedStrings.push(createTemplateCooked(template.head));
|
||||
rawStrings.push(getRawLiteral(template.head, currentSourceFile));
|
||||
for (const templateSpan of template.templateSpans) {
|
||||
cookedStrings.push(createTemplateCooked(templateSpan.literal));
|
||||
rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
|
||||
templateArguments.push(visitNode(templateSpan.expression, visitor, isExpression));
|
||||
}
|
||||
}
|
||||
|
||||
const helperCall = createTemplateObjectHelper(context, createArrayLiteral(cookedStrings), createArrayLiteral(rawStrings));
|
||||
|
||||
// Create a variable to cache the template object if we're in a module.
|
||||
// Do not do this in the global scope, as any variable we currently generate could conflict with
|
||||
// variables from outside of the current compilation. In the future, we can revisit this behavior.
|
||||
if (isExternalModule(currentSourceFile)) {
|
||||
const tempVar = createUniqueName("templateObject");
|
||||
recordTaggedTemplateString(tempVar);
|
||||
templateArguments[0] = createLogicalOr(
|
||||
tempVar,
|
||||
createAssignment(
|
||||
tempVar,
|
||||
helperCall)
|
||||
);
|
||||
}
|
||||
else {
|
||||
templateArguments[0] = helperCall;
|
||||
}
|
||||
|
||||
return createCall(tag, /*typeArguments*/ undefined, templateArguments);
|
||||
}
|
||||
|
||||
function createTemplateCooked(template: TemplateHead | TemplateMiddle | TemplateTail | NoSubstitutionTemplateLiteral) {
|
||||
return template.templateFlags ? createIdentifier("undefined") : createLiteral(template.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ES5 compatible literal from an ES6 template literal.
|
||||
*
|
||||
* @param node The ES6 template literal.
|
||||
*/
|
||||
function getRawLiteral(node: LiteralLikeNode, currentSourceFile: SourceFile) {
|
||||
// Find original source text, since we need to emit the raw strings of the tagged template.
|
||||
// The raw strings contain the (escaped) strings of what the user wrote.
|
||||
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
|
||||
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
|
||||
|
||||
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
|
||||
// thus we need to remove those characters.
|
||||
// First template piece starts with "`", others with "}"
|
||||
// Last template piece ends with "`", others with "${"
|
||||
const isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail;
|
||||
text = text.substring(1, text.length - (isLast ? 1 : 2));
|
||||
|
||||
// Newline normalization:
|
||||
// ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
|
||||
// <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
|
||||
text = text.replace(/\r\n?/g, "\n");
|
||||
return setTextRange(createLiteral(text), node);
|
||||
}
|
||||
|
||||
function createTemplateObjectHelper(context: TransformationContext, cooked: ArrayLiteralExpression, raw: ArrayLiteralExpression) {
|
||||
context.requestEmitHelper(templateObjectHelper);
|
||||
return createCall(
|
||||
getUnscopedHelperName("__makeTemplateObject"),
|
||||
/*typeArguments*/ undefined,
|
||||
[
|
||||
cooked,
|
||||
raw
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
export const templateObjectHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:makeTemplateObject",
|
||||
importName: "__makeTemplateObject",
|
||||
scoped: false,
|
||||
priority: 0,
|
||||
text: `
|
||||
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
|
||||
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
|
||||
return cooked;
|
||||
};`
|
||||
};
|
||||
}
|
||||
@@ -23,11 +23,10 @@ namespace ts {
|
||||
IsNamedExternalExport = 1 << 4,
|
||||
IsDefaultExternalExport = 1 << 5,
|
||||
IsDerivedClass = 1 << 6,
|
||||
UseImmediatelyInvokedFunctionExpression = 1 << 7,
|
||||
|
||||
HasAnyDecorators = HasConstructorDecorators | HasMemberDecorators,
|
||||
NeedsName = HasStaticInitializedProperties | HasMemberDecorators,
|
||||
MayNeedImmediatelyInvokedFunctionExpression = HasAnyDecorators | HasStaticInitializedProperties,
|
||||
UseImmediatelyInvokedFunctionExpression = HasAnyDecorators | HasStaticInitializedProperties,
|
||||
IsExported = IsExportOfNamespace | IsDefaultExternalExport | IsNamedExternalExport,
|
||||
}
|
||||
|
||||
@@ -590,7 +589,6 @@ namespace ts {
|
||||
if (isExportOfNamespace(node)) facts |= ClassFacts.IsExportOfNamespace;
|
||||
else if (isDefaultExternalModuleExport(node)) facts |= ClassFacts.IsDefaultExternalExport;
|
||||
else if (isNamedExternalModuleExport(node)) facts |= ClassFacts.IsNamedExternalExport;
|
||||
if (languageVersion <= ScriptTarget.ES5 && (facts & ClassFacts.MayNeedImmediatelyInvokedFunctionExpression)) facts |= ClassFacts.UseImmediatelyInvokedFunctionExpression;
|
||||
return facts;
|
||||
}
|
||||
|
||||
@@ -661,6 +659,12 @@ namespace ts {
|
||||
const iife = createImmediatelyInvokedArrowFunction(statements);
|
||||
setEmitFlags(iife, EmitFlags.TypeScriptClassWrapper);
|
||||
|
||||
// Class comment is already added by the ES2015 transform when targeting ES5 or below.
|
||||
// Only add if targetting ES2015+ to prevent duplicates
|
||||
if (languageVersion > ScriptTarget.ES5) {
|
||||
addSyntheticLeadingComment(iife, SyntaxKind.MultiLineCommentTrivia, "* @class ");
|
||||
}
|
||||
|
||||
const varStatement = createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
@@ -669,7 +673,7 @@ namespace ts {
|
||||
/*type*/ undefined,
|
||||
iife
|
||||
)
|
||||
])
|
||||
], languageVersion > ScriptTarget.ES5 ? NodeFlags.Const : undefined)
|
||||
);
|
||||
|
||||
setOriginalNode(varStatement, node);
|
||||
@@ -2510,7 +2514,7 @@ namespace ts {
|
||||
|
||||
function declaredNameInScope(node: FunctionDeclaration | ClassDeclaration | ModuleDeclaration | EnumDeclaration): __String {
|
||||
Debug.assertNode(node.name, isIdentifier);
|
||||
return (node.name as Identifier).escapedText;
|
||||
return node.name.escapedText;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2778,8 +2782,8 @@ namespace ts {
|
||||
// Elide the declaration if the import clause was elided.
|
||||
const importClause = visitNode(node.importClause, visitImportClause, isImportClause);
|
||||
return importClause ||
|
||||
compilerOptions.importsNotUsedAsValues === importsNotUsedAsValues.Preserve ||
|
||||
compilerOptions.importsNotUsedAsValues === importsNotUsedAsValues.Error
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve ||
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error
|
||||
? updateImportDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
@@ -2866,7 +2870,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Elide the export declaration if all of its named exports are elided.
|
||||
const exportClause = visitNode(node.exportClause, visitNamedExportBindings, isNamedImportBindings);
|
||||
const exportClause = visitNode(node.exportClause, visitNamedExportBindings, isNamedExportBindings);
|
||||
return exportClause
|
||||
? updateExportDeclaration(
|
||||
node,
|
||||
@@ -2931,7 +2935,7 @@ namespace ts {
|
||||
if (isExternalModuleImportEqualsDeclaration(node)) {
|
||||
const isReferenced = resolver.isReferencedAliasDeclaration(node);
|
||||
// If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
|
||||
if (!isReferenced && compilerOptions.importsNotUsedAsValues === importsNotUsedAsValues.Preserve) {
|
||||
if (!isReferenced && compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve) {
|
||||
return setOriginalNode(
|
||||
setTextRange(
|
||||
createImportDeclaration(
|
||||
|
||||
@@ -294,10 +294,12 @@ namespace ts {
|
||||
return index;
|
||||
}
|
||||
|
||||
const statement = statements[index];
|
||||
if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCall((<ExpressionStatement>statement).expression)) {
|
||||
result.push(visitNode(statement, visitor, isStatement));
|
||||
return index + 1;
|
||||
const superIndex = findIndex(statements, s => isExpressionStatement(s) && isSuperCall(s.expression), index);
|
||||
if (superIndex > -1) {
|
||||
for (let i = index; i <= superIndex; i++) {
|
||||
result.push(visitNode(statements[i], visitor, isStatement));
|
||||
}
|
||||
return superIndex + 1;
|
||||
}
|
||||
|
||||
return index;
|
||||
|
||||
@@ -294,7 +294,7 @@ namespace ts {
|
||||
if (!compilerHost.resolveModuleNames) {
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule!;
|
||||
compilerHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference) =>
|
||||
loadWithLocalCache<ResolvedModuleFull>(Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
}
|
||||
|
||||
const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory<ResolvedConfigFileName>(hostWithWatch, options);
|
||||
@@ -828,7 +828,7 @@ namespace ts {
|
||||
if (state.options.verbose) reportStatus(state, Diagnostics.Building_project_0, project);
|
||||
|
||||
if (config.fileNames.length === 0) {
|
||||
reportAndStoreErrors(state, projectPath, config.errors);
|
||||
reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
|
||||
// Nothing to build - must be a solution file, basically
|
||||
buildResult = BuildResultFlags.None;
|
||||
step = Step.QueueReferencingProjects;
|
||||
@@ -846,7 +846,7 @@ namespace ts {
|
||||
config.options,
|
||||
compilerHost,
|
||||
getOldProgram(state, projectPath, config),
|
||||
config.errors,
|
||||
getConfigFileParsingDiagnostics(config),
|
||||
config.projectReferences
|
||||
);
|
||||
step++;
|
||||
@@ -871,13 +871,13 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getSyntaxDiagnostics(cancellationToken?: CancellationToken) {
|
||||
Debug.assertDefined(program);
|
||||
Debug.assertIsDefined(program);
|
||||
handleDiagnostics(
|
||||
[
|
||||
...program!.getConfigFileParsingDiagnostics(),
|
||||
...program!.getOptionsDiagnostics(cancellationToken),
|
||||
...program!.getGlobalDiagnostics(cancellationToken),
|
||||
...program!.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)
|
||||
...program.getConfigFileParsingDiagnostics(),
|
||||
...program.getOptionsDiagnostics(cancellationToken),
|
||||
...program.getGlobalDiagnostics(cancellationToken),
|
||||
...program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)
|
||||
],
|
||||
BuildResultFlags.SyntaxErrors,
|
||||
"Syntactic"
|
||||
@@ -886,22 +886,22 @@ namespace ts {
|
||||
|
||||
function getSemanticDiagnostics(cancellationToken?: CancellationToken) {
|
||||
handleDiagnostics(
|
||||
Debug.assertDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken),
|
||||
Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken),
|
||||
BuildResultFlags.TypeErrors,
|
||||
"Semantic"
|
||||
);
|
||||
}
|
||||
|
||||
function emit(writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken, customTransformers?: CustomTransformers): EmitResult {
|
||||
Debug.assertDefined(program);
|
||||
Debug.assertIsDefined(program);
|
||||
Debug.assert(step === Step.Emit);
|
||||
// Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
|
||||
program!.backupState();
|
||||
program.backupState();
|
||||
let declDiagnostics: Diagnostic[] | undefined;
|
||||
const reportDeclarationDiagnostics = (d: Diagnostic) => (declDiagnostics || (declDiagnostics = [])).push(d);
|
||||
const outputFiles: OutputFile[] = [];
|
||||
const { emitResult } = emitFilesAndReportErrors(
|
||||
program!,
|
||||
program,
|
||||
reportDeclarationDiagnostics,
|
||||
/*writeFileName*/ undefined,
|
||||
/*reportSummary*/ undefined,
|
||||
@@ -912,7 +912,7 @@ namespace ts {
|
||||
);
|
||||
// Don't emit .d.ts if there are decl file errors
|
||||
if (declDiagnostics) {
|
||||
program!.restoreState();
|
||||
program.restoreState();
|
||||
buildResult = buildErrors(
|
||||
state,
|
||||
projectPath,
|
||||
@@ -1095,12 +1095,12 @@ namespace ts {
|
||||
break;
|
||||
|
||||
case Step.BuildInvalidatedProjectOfBundle:
|
||||
Debug.assertDefined(invalidatedProjectOfBundle).done(cancellationToken);
|
||||
Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
|
||||
step = Step.Done;
|
||||
break;
|
||||
|
||||
case Step.QueueReferencingProjects:
|
||||
queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.assertDefined(buildResult));
|
||||
queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult));
|
||||
step++;
|
||||
break;
|
||||
|
||||
@@ -1118,7 +1118,7 @@ namespace ts {
|
||||
function needsBuild({ options }: SolutionBuilderState, status: UpToDateStatus, config: ParsedCommandLine) {
|
||||
if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force) return true;
|
||||
return config.fileNames.length === 0 ||
|
||||
!!config.errors.length ||
|
||||
!!getConfigFileParsingDiagnostics(config).length ||
|
||||
!isIncrementalCompilation(config.options);
|
||||
}
|
||||
|
||||
@@ -1172,7 +1172,7 @@ namespace ts {
|
||||
verboseReportProjectStatus(state, project, status);
|
||||
if (!options.force) {
|
||||
if (status.type === UpToDateStatusType.UpToDate) {
|
||||
reportAndStoreErrors(state, projectPath, config.errors);
|
||||
reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
|
||||
projectPendingBuild.delete(projectPath);
|
||||
// Up to date, skip
|
||||
if (options.dry) {
|
||||
@@ -1183,7 +1183,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) {
|
||||
reportAndStoreErrors(state, projectPath, config.errors);
|
||||
reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
|
||||
return createUpdateOutputFileStampsProject(
|
||||
state,
|
||||
project,
|
||||
@@ -1195,7 +1195,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (status.type === UpToDateStatusType.UpstreamBlocked) {
|
||||
reportAndStoreErrors(state, projectPath, config.errors);
|
||||
reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
|
||||
projectPendingBuild.delete(projectPath);
|
||||
if (options.verbose) {
|
||||
reportStatus(
|
||||
@@ -1211,7 +1211,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (status.type === UpToDateStatusType.ContainerOnly) {
|
||||
reportAndStoreErrors(state, projectPath, config.errors);
|
||||
reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config));
|
||||
projectPendingBuild.delete(projectPath);
|
||||
// Do nothing
|
||||
continue;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
},
|
||||
|
||||
"references": [
|
||||
{ "path": "../shims" },
|
||||
{ "path": "../shims" }
|
||||
],
|
||||
|
||||
"files": [
|
||||
@@ -38,6 +38,7 @@
|
||||
"sourcemap.ts",
|
||||
"transformers/utilities.ts",
|
||||
"transformers/destructuring.ts",
|
||||
"transformers/taggedTemplate.ts",
|
||||
"transformers/ts.ts",
|
||||
"transformers/classFields.ts",
|
||||
"transformers/es2017.ts",
|
||||
@@ -68,6 +69,6 @@
|
||||
"watch.ts",
|
||||
"watchPublic.ts",
|
||||
"tsbuild.ts",
|
||||
"tsbuildPublic.ts",
|
||||
"tsbuildPublic.ts"
|
||||
]
|
||||
}
|
||||
|
||||
+66
-16
@@ -3,6 +3,9 @@ namespace ts {
|
||||
// arbitrary file name can be converted to Path via toPath function
|
||||
export type Path = string & { __pathBrand: any };
|
||||
|
||||
/* @internal */
|
||||
export type MatchingKeys<TRecord, TMatch, K extends keyof TRecord = keyof TRecord> = K extends (TRecord[K] extends TMatch ? K : never) ? K : never;
|
||||
|
||||
export interface TextRange {
|
||||
pos: number;
|
||||
end: number;
|
||||
@@ -1732,6 +1735,8 @@ namespace ts {
|
||||
|
||||
export interface NoSubstitutionTemplateLiteral extends LiteralExpression, TemplateLiteralLikeNode, Declaration {
|
||||
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
|
||||
/* @internal */
|
||||
templateFlags?: TokenFlags;
|
||||
}
|
||||
|
||||
export const enum TokenFlags {
|
||||
@@ -1754,6 +1759,8 @@ namespace ts {
|
||||
/* @internal */
|
||||
UnicodeEscape = 1 << 10,
|
||||
/* @internal */
|
||||
ContainsInvalidEscape = 1 << 11, // e.g. `\uhello`
|
||||
/* @internal */
|
||||
BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier,
|
||||
/* @internal */
|
||||
NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator
|
||||
@@ -1772,16 +1779,22 @@ namespace ts {
|
||||
export interface TemplateHead extends TemplateLiteralLikeNode {
|
||||
kind: SyntaxKind.TemplateHead;
|
||||
parent: TemplateExpression;
|
||||
/* @internal */
|
||||
templateFlags?: TokenFlags;
|
||||
}
|
||||
|
||||
export interface TemplateMiddle extends TemplateLiteralLikeNode {
|
||||
kind: SyntaxKind.TemplateMiddle;
|
||||
parent: TemplateSpan;
|
||||
/* @internal */
|
||||
templateFlags?: TokenFlags;
|
||||
}
|
||||
|
||||
export interface TemplateTail extends TemplateLiteralLikeNode {
|
||||
kind: SyntaxKind.TemplateTail;
|
||||
parent: TemplateSpan;
|
||||
/* @internal */
|
||||
templateFlags?: TokenFlags;
|
||||
}
|
||||
|
||||
export type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral;
|
||||
@@ -2538,6 +2551,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier;
|
||||
export type TypeOnlyCompatibleAliasDeclaration = ImportClause | NamespaceImport | ImportOrExportSpecifier;
|
||||
|
||||
/**
|
||||
* This is either an `export =` or an `export default` declaration.
|
||||
@@ -3484,8 +3498,11 @@ namespace ts {
|
||||
*/
|
||||
/* @internal */ tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
|
||||
getApparentType(type: Type): Type;
|
||||
/* @internal */ getSuggestionForNonexistentProperty(name: Identifier | string, containingType: Type): string | undefined;
|
||||
/* @internal */ getSuggestedSymbolForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): Symbol | undefined;
|
||||
/* @internal */ getSuggestionForNonexistentProperty(name: Identifier | PrivateIdentifier | string, containingType: Type): string | undefined;
|
||||
/* @internal */ getSuggestedSymbolForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): Symbol | undefined;
|
||||
/* @internal */ getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
|
||||
/* @internal */ getSuggestedSymbolForNonexistentModule(node: Identifier, target: Symbol): Symbol | undefined;
|
||||
/* @internal */ getSuggestionForNonexistentExport(node: Identifier, target: Symbol): string | undefined;
|
||||
getBaseConstraintOfType(type: Type): Type | undefined;
|
||||
getDefaultFromTypeParameter(type: Type): Type | undefined;
|
||||
@@ -3508,7 +3525,7 @@ namespace ts {
|
||||
/* @internal */ createPromiseType(type: Type): Type;
|
||||
|
||||
/* @internal */ isTypeAssignableTo(source: Type, target: Type): boolean;
|
||||
/* @internal */ createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type;
|
||||
/* @internal */ createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type;
|
||||
/* @internal */ createSignature(
|
||||
declaration: SignatureDeclaration,
|
||||
typeParameters: TypeParameter[] | undefined,
|
||||
@@ -3604,7 +3621,8 @@ namespace ts {
|
||||
None = 0,
|
||||
Signature = 1 << 0, // Obtaining contextual signature
|
||||
NoConstraints = 1 << 1, // Don't obtain type variable constraints
|
||||
BaseConstraint = 1 << 2, // Use base constraint type for completions
|
||||
Completions = 1 << 2, // Ignore inference to current node and parent nodes out to the containing call for completions
|
||||
|
||||
}
|
||||
|
||||
// NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
|
||||
@@ -3626,6 +3644,7 @@ namespace ts {
|
||||
UseTypeOfFunction = 1 << 12, // Build using typeof instead of function type literal
|
||||
OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters
|
||||
UseAliasDefinedOutsideCurrentScope = 1 << 14, // Allow non-visible aliases
|
||||
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
|
||||
|
||||
// Error handling
|
||||
AllowThisInObjectLiteral = 1 << 15,
|
||||
@@ -3668,6 +3687,7 @@ namespace ts {
|
||||
OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters
|
||||
|
||||
UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope.
|
||||
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
|
||||
|
||||
// Error Handling
|
||||
AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags`
|
||||
@@ -3686,7 +3706,8 @@ namespace ts {
|
||||
|
||||
NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature |
|
||||
UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral |
|
||||
UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias,
|
||||
UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias |
|
||||
UseSingleQuotesForStringLiteralType,
|
||||
}
|
||||
|
||||
export const enum SymbolFormatFlags {
|
||||
@@ -4038,7 +4059,6 @@ namespace ts {
|
||||
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
|
||||
/* @internal */ parent?: Symbol; // Parent symbol
|
||||
/* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
|
||||
/* @internal */ nameType?: Type; // Type associated with a late-bound symbol
|
||||
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
|
||||
/* @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter.
|
||||
/* @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
|
||||
@@ -4051,15 +4071,16 @@ namespace ts {
|
||||
immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead.
|
||||
target?: Symbol; // Resolved (non-alias) target of an alias
|
||||
type?: Type; // Type of value symbol
|
||||
nameType?: Type; // Type associated with a late-bound symbol
|
||||
uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol
|
||||
declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter
|
||||
resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference
|
||||
typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic)
|
||||
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
|
||||
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
|
||||
inferredClassSymbol?: Map<TransientSymbol>; // Symbol of an inferred ES5 constructor function
|
||||
mapper?: TypeMapper; // Type mapper for instantiation alias
|
||||
referenced?: boolean; // True if alias symbol has been referenced as a value
|
||||
referenced?: boolean; // True if alias symbol has been referenced as a value that can be emitted
|
||||
constEnumReferenced?: boolean; // True if alias symbol resolves to a const enum and is referenced as a value ('referenced' will be false)
|
||||
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
|
||||
leftSpread?: Symbol; // Left source for synthetic spread property
|
||||
rightSpread?: Symbol; // Right source for synthetic spread property
|
||||
@@ -4082,6 +4103,7 @@ namespace ts {
|
||||
deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type
|
||||
deferralParent?: Type; // Source union/intersection of a deferred type
|
||||
cjsExportMerged?: Symbol; // Version of the symbol with all non export= exports merged with the export= target
|
||||
typeOnlyDeclaration?: TypeOnlyCompatibleAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4227,6 +4249,7 @@ namespace ts {
|
||||
jsxFlags: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
|
||||
resolvedJsxElementAttributesType?: Type; // resolved element attributes type of a JSX openinglike element
|
||||
resolvedJsxElementAllAttributesType?: Type; // resolved all element attributes type of a JSX openinglike element
|
||||
resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference
|
||||
hasSuperCall?: boolean; // recorded result when we try to find super-call. We only try to find one if this flag is undefined, indicating that we haven't made an attempt.
|
||||
superCall?: SuperCall; // Cached first super-call found in the constructor. Used in checking whether super is called before this-accessing
|
||||
switchTypes?: Type[]; // Cached array of switch case expression types
|
||||
@@ -4237,6 +4260,7 @@ namespace ts {
|
||||
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
|
||||
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
|
||||
isExhaustive?: boolean; // Is node an exhaustive switch statement
|
||||
skipDirectInference?: true; // Flag set by the API `getContextualType` call on a node when `Completions` is passed to force the checker to skip making inferences to a node's type
|
||||
}
|
||||
|
||||
export const enum TypeFlags {
|
||||
@@ -4304,6 +4328,8 @@ namespace ts {
|
||||
ObjectFlagsType = Any | Nullable | Never | Object | Union | Intersection,
|
||||
/* @internal */
|
||||
Simplifiable = IndexedAccess | Conditional,
|
||||
/* @internal */
|
||||
Substructure = Object | Union | Intersection | Index | IndexedAccess | Conditional | Substitution,
|
||||
// 'Narrowable' types are types where narrowing actually narrows.
|
||||
// This *should* be every type other than null, undefined, void, and never
|
||||
Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive,
|
||||
@@ -4322,9 +4348,6 @@ namespace ts {
|
||||
IncludesWildcard = Index,
|
||||
/* @internal */
|
||||
IncludesEmptyObject = IndexedAccess,
|
||||
// The following flag is used for different purposes by maybeTypeOfKind
|
||||
/* @internal */
|
||||
GenericMappedType = Never,
|
||||
}
|
||||
|
||||
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
|
||||
@@ -4428,6 +4451,18 @@ namespace ts {
|
||||
ContainsObjectOrArrayLiteral = 1 << 20, // Type is or contains object literal type
|
||||
/* @internal */
|
||||
NonInferrableType = 1 << 21, // Type is or contains anyFunctionType or silentNeverType
|
||||
/* @internal */
|
||||
IsGenericObjectTypeComputed = 1 << 22, // IsGenericObjectType flag has been computed
|
||||
/* @internal */
|
||||
IsGenericObjectType = 1 << 23, // Union or intersection contains generic object type
|
||||
/* @internal */
|
||||
IsGenericIndexTypeComputed = 1 << 24, // IsGenericIndexType flag has been computed
|
||||
/* @internal */
|
||||
IsGenericIndexType = 1 << 25, // Union or intersection contains generic index type
|
||||
/* @internal */
|
||||
CouldContainTypeVariablesComputed = 1 << 26, // CouldContainTypeVariables flag has been computed
|
||||
/* @internal */
|
||||
CouldContainTypeVariables = 1 << 27, // Type could contain a type variable
|
||||
ClassOrInterface = Class | Interface,
|
||||
/* @internal */
|
||||
RequiresWidening = ContainsWideningType | ContainsObjectOrArrayLiteral,
|
||||
@@ -4546,8 +4581,6 @@ namespace ts {
|
||||
resolvedStringIndexType: IndexType;
|
||||
/* @internal */
|
||||
resolvedBaseConstraint: Type;
|
||||
/* @internal */
|
||||
couldContainTypeVariables: boolean;
|
||||
}
|
||||
|
||||
export interface UnionType extends UnionOrIntersectionType {
|
||||
@@ -5043,7 +5076,7 @@ namespace ts {
|
||||
/*@internal*/generateCpuProfile?: string;
|
||||
/*@internal*/help?: boolean;
|
||||
importHelpers?: boolean;
|
||||
importsNotUsedAsValues?: importsNotUsedAsValues;
|
||||
importsNotUsedAsValues?: ImportsNotUsedAsValues;
|
||||
/*@internal*/init?: boolean;
|
||||
inlineSourceMap?: boolean;
|
||||
inlineSources?: boolean;
|
||||
@@ -5165,7 +5198,7 @@ namespace ts {
|
||||
ReactNative = 3
|
||||
}
|
||||
|
||||
export const enum importsNotUsedAsValues {
|
||||
export const enum ImportsNotUsedAsValues {
|
||||
Remove,
|
||||
Preserve,
|
||||
Error
|
||||
@@ -5763,6 +5796,7 @@ namespace ts {
|
||||
readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope.
|
||||
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); // ES3-compatible raw script text, or a function yielding such a string
|
||||
readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node.
|
||||
readonly dependencies?: EmitHelper[]
|
||||
}
|
||||
|
||||
export interface UnscopedEmitHelper extends EmitHelper {
|
||||
@@ -5803,8 +5837,10 @@ namespace ts {
|
||||
MakeTemplateObject = 1 << 17, // __makeTemplateObject (used for constructing template string array objects)
|
||||
ClassPrivateFieldGet = 1 << 18, // __classPrivateFieldGet (used by the class private field transformation)
|
||||
ClassPrivateFieldSet = 1 << 19, // __classPrivateFieldSet (used by the class private field transformation)
|
||||
CreateBinding = 1 << 20, // __createBinding (use by the module transform for exports and namespace imports)
|
||||
SetModuleDefault = 1 << 21, // __setModuleDefault (use by the module transform for default exports)
|
||||
FirstEmitHelper = Extends,
|
||||
LastEmitHelper = ClassPrivateFieldSet,
|
||||
LastEmitHelper = SetModuleDefault,
|
||||
|
||||
// Helpers included by ES2015 for..of
|
||||
ForOfIncludes = Values,
|
||||
@@ -5830,6 +5866,7 @@ namespace ts {
|
||||
MappedTypeParameter, // Emitting a TypeParameterDeclaration inside of a MappedTypeNode
|
||||
Unspecified, // Emitting an otherwise unspecified node
|
||||
EmbeddedStatement, // Emitting an embedded statement
|
||||
JsxAttributeValue, // Emitting a JSX attribute value
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -5966,6 +6003,13 @@ namespace ts {
|
||||
*/
|
||||
emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
|
||||
|
||||
/**
|
||||
* Indicates if a given node needs an emit notification
|
||||
*
|
||||
* @param node The node to emit.
|
||||
*/
|
||||
isEmitNotificationEnabled?(node: Node): boolean;
|
||||
|
||||
/**
|
||||
* Clean up EmitNode entries on any parse-tree nodes.
|
||||
*/
|
||||
@@ -6161,6 +6205,12 @@ namespace ts {
|
||||
* ```
|
||||
*/
|
||||
onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void;
|
||||
|
||||
/**
|
||||
* A hook used to check if an emit notification is required for a node.
|
||||
* @param node The node to emit.
|
||||
*/
|
||||
isEmitNotificationEnabled?(node: Node | undefined): boolean;
|
||||
/**
|
||||
* A hook used by the Printer to perform just-in-time substitution of a node. This is
|
||||
* primarily used by node transformations that need to substitute one node for another,
|
||||
@@ -6584,7 +6634,7 @@ namespace ts {
|
||||
readonly includeCompletionsWithInsertText?: boolean;
|
||||
readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative";
|
||||
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
|
||||
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
|
||||
readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js";
|
||||
readonly allowTextChangesInNewFiles?: boolean;
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
}
|
||||
|
||||
+187
-53
@@ -44,14 +44,6 @@ namespace ts {
|
||||
return (symbol.flags & SymbolFlags.Transient) !== 0;
|
||||
}
|
||||
|
||||
export function isTypeOnlyAlias(symbol: Symbol): symbol is TransientSymbol & { immediateTarget: Symbol } {
|
||||
return isTransientSymbol(symbol) && !!symbol.immediateTarget;
|
||||
}
|
||||
|
||||
export function isTypeOnlyEnumAlias(symbol: Symbol): ReturnType<typeof isTypeOnlyAlias> {
|
||||
return isTypeOnlyAlias(symbol) && !!(symbol.immediateTarget.flags & SymbolFlags.Enum);
|
||||
}
|
||||
|
||||
const stringWriter = createSingleLineStringWriter();
|
||||
|
||||
function createSingleLineStringWriter(): EmitTextWriter {
|
||||
@@ -517,7 +509,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function isJSDocTypeExpressionOrChild(node: Node): boolean {
|
||||
return node.kind === SyntaxKind.JSDocTypeExpression || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
|
||||
return !!findAncestor(node, isJSDocTypeExpression);
|
||||
}
|
||||
|
||||
export function getTextOfNodeFromSourceText(sourceText: string, node: Node, includeTrivia = false): string {
|
||||
@@ -559,7 +551,7 @@ namespace ts {
|
||||
return emitNode && emitNode.flags || 0;
|
||||
}
|
||||
|
||||
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, neverAsciiEscape: boolean | undefined) {
|
||||
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean) {
|
||||
// If we don't need to downlevel and we can reach the original source text using
|
||||
// the node's parent reference, then simply get the text as it was originally written.
|
||||
if (!nodeIsSynthesized(node) && node.parent && !(
|
||||
@@ -569,24 +561,29 @@ namespace ts {
|
||||
return getSourceTextOfNodeFromSourceFile(sourceFile, node);
|
||||
}
|
||||
|
||||
// If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
|
||||
// had to include a backslash: `not \${a} substitution`.
|
||||
const escapeText = neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString : escapeNonAsciiString;
|
||||
|
||||
// If we can't reach the original source text, use the canonical form if it's a number,
|
||||
// or a (possibly escaped) quoted form of the original text if it's string-like.
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.StringLiteral:
|
||||
case SyntaxKind.StringLiteral: {
|
||||
const escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
|
||||
neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString :
|
||||
escapeNonAsciiString;
|
||||
if ((<StringLiteral>node).singleQuote) {
|
||||
return "'" + escapeText(node.text, CharacterCodes.singleQuote) + "'";
|
||||
}
|
||||
else {
|
||||
return '"' + escapeText(node.text, CharacterCodes.doubleQuote) + '"';
|
||||
}
|
||||
}
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
case SyntaxKind.TemplateHead:
|
||||
case SyntaxKind.TemplateMiddle:
|
||||
case SyntaxKind.TemplateTail:
|
||||
case SyntaxKind.TemplateTail: {
|
||||
// If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
|
||||
// had to include a backslash: `not \${a} substitution`.
|
||||
const escapeText = neverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString :
|
||||
escapeNonAsciiString;
|
||||
|
||||
const rawText = (<TemplateLiteralLikeNode>node).rawText || escapeTemplateSubstitution(escapeText(node.text, CharacterCodes.backtick));
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
@@ -599,6 +596,7 @@ namespace ts {
|
||||
return "}" + rawText + "`";
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyntaxKind.NumericLiteral:
|
||||
case SyntaxKind.BigIntLiteral:
|
||||
case SyntaxKind.RegularExpressionLiteral:
|
||||
@@ -1779,6 +1777,13 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
export function isPartOfTypeQuery(node: Node) {
|
||||
while (node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.Identifier) {
|
||||
node = node.parent;
|
||||
}
|
||||
return node.kind === SyntaxKind.TypeQuery;
|
||||
}
|
||||
|
||||
export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference } {
|
||||
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference;
|
||||
}
|
||||
@@ -2285,6 +2290,19 @@ namespace ts {
|
||||
return node.kind === SyntaxKind.ImportDeclaration && !!node.importClause && !!node.importClause.name;
|
||||
}
|
||||
|
||||
export function forEachImportClauseDeclaration<T>(node: ImportClause, action: (declaration: ImportClause | NamespaceImport | ImportSpecifier) => T | undefined): T | undefined {
|
||||
if (node.name) {
|
||||
const result = action(node);
|
||||
if (result) return result;
|
||||
}
|
||||
if (node.namedBindings) {
|
||||
const result = isNamespaceImport(node.namedBindings)
|
||||
? action(node.namedBindings)
|
||||
: forEach(node.namedBindings.elements, action);
|
||||
if (result) return result;
|
||||
}
|
||||
}
|
||||
|
||||
export function hasQuestionToken(node: Node) {
|
||||
if (node) {
|
||||
switch (node.kind) {
|
||||
@@ -2318,9 +2336,9 @@ namespace ts {
|
||||
|
||||
function getSourceOfAssignment(node: Node): Node | undefined {
|
||||
return isExpressionStatement(node) &&
|
||||
node.expression && isBinaryExpression(node.expression) &&
|
||||
isBinaryExpression(node.expression) &&
|
||||
node.expression.operatorToken.kind === SyntaxKind.EqualsToken
|
||||
? node.expression.right
|
||||
? getRightMostAssignedExpression(node.expression)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -2445,7 +2463,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getJSDocHost(node: Node): HasJSDoc {
|
||||
return Debug.assertDefined(findAncestor(node.parent, isJSDoc)).parent;
|
||||
return Debug.checkDefined(findAncestor(node.parent, isJSDoc)).parent;
|
||||
}
|
||||
|
||||
export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined {
|
||||
@@ -2734,7 +2752,24 @@ namespace ts {
|
||||
node.kind === SyntaxKind.PropertyAssignment && isAliasableExpression((node as PropertyAssignment).initializer);
|
||||
}
|
||||
|
||||
function isAliasableExpression(e: Expression) {
|
||||
export function getAliasDeclarationFromName(node: EntityName): Declaration | undefined {
|
||||
switch (node.parent.kind) {
|
||||
case SyntaxKind.ImportClause:
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
case SyntaxKind.NamespaceImport:
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
case SyntaxKind.ExportAssignment:
|
||||
case SyntaxKind.ImportEqualsDeclaration:
|
||||
return node.parent as Declaration;
|
||||
case SyntaxKind.QualifiedName:
|
||||
do {
|
||||
node = node.parent as QualifiedName;
|
||||
} while (node.parent.kind === SyntaxKind.QualifiedName);
|
||||
return getAliasDeclarationFromName(node);
|
||||
}
|
||||
}
|
||||
|
||||
export function isAliasableExpression(e: Expression) {
|
||||
return isEntityNameExpression(e) || isClassExpression(e);
|
||||
}
|
||||
|
||||
@@ -3330,6 +3365,13 @@ namespace ts {
|
||||
return str.replace(templateSubstitutionRegExp, "\\${");
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function hasInvalidEscape(template: TemplateLiteral): boolean {
|
||||
return template && !!(isNoSubstitutionTemplateLiteral(template)
|
||||
? template.templateFlags
|
||||
: (template.head.templateFlags || some(template.templateSpans, span => !!span.literal.templateFlags)));
|
||||
}
|
||||
|
||||
// This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
|
||||
// paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
|
||||
// the language service. These characters should be escaped when printing, and if any characters are added,
|
||||
@@ -3355,6 +3397,25 @@ namespace ts {
|
||||
"\u0085": "\\u0085" // nextLine
|
||||
});
|
||||
|
||||
function encodeUtf16EscapeSequence(charCode: number): string {
|
||||
const hexCharCode = charCode.toString(16).toUpperCase();
|
||||
const paddedHexCode = ("0000" + hexCharCode).slice(-4);
|
||||
return "\\u" + paddedHexCode;
|
||||
}
|
||||
|
||||
function getReplacement(c: string, offset: number, input: string) {
|
||||
if (c.charCodeAt(0) === CharacterCodes.nullCharacter) {
|
||||
const lookAhead = input.charCodeAt(offset + c.length);
|
||||
if (lookAhead >= CharacterCodes._0 && lookAhead <= CharacterCodes._9) {
|
||||
// If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
|
||||
return "\\x00";
|
||||
}
|
||||
// Otherwise, keep printing a literal \0 for the null character
|
||||
return "\\0";
|
||||
}
|
||||
return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
|
||||
* but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
|
||||
@@ -3368,6 +3429,46 @@ namespace ts {
|
||||
return s.replace(escapedCharsRegExp, getReplacement);
|
||||
}
|
||||
|
||||
const nonAsciiCharacters = /[^\u0000-\u007F]/g;
|
||||
export function escapeNonAsciiString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string {
|
||||
s = escapeString(s, quoteChar);
|
||||
// Replace non-ASCII characters with '\uNNNN' escapes if any exist.
|
||||
// Otherwise just return the original string.
|
||||
return nonAsciiCharacters.test(s) ?
|
||||
s.replace(nonAsciiCharacters, c => encodeUtf16EscapeSequence(c.charCodeAt(0))) :
|
||||
s;
|
||||
}
|
||||
|
||||
// This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
|
||||
// paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
|
||||
// the language service. These characters should be escaped when printing, and if any characters are added,
|
||||
// the map below must be updated.
|
||||
const jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
|
||||
const jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
|
||||
const jsxEscapedCharsMap = createMapFromTemplate({
|
||||
"\"": """,
|
||||
"\'": "'"
|
||||
});
|
||||
|
||||
function encodeJsxCharacterEntity(charCode: number): string {
|
||||
const hexCharCode = charCode.toString(16).toUpperCase();
|
||||
return "&#x" + hexCharCode + ";";
|
||||
}
|
||||
|
||||
function getJsxAttributeStringReplacement(c: string) {
|
||||
if (c.charCodeAt(0) === CharacterCodes.nullCharacter) {
|
||||
return "�";
|
||||
}
|
||||
return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
|
||||
}
|
||||
|
||||
export function escapeJsxAttributeString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote) {
|
||||
const escapedCharsRegExp =
|
||||
quoteChar === CharacterCodes.singleQuote ? jsxSingleQuoteEscapedCharsRegExp :
|
||||
jsxDoubleQuoteEscapedCharsRegExp;
|
||||
return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip off existed surrounding single quotes, double quotes, or backticks from a given string
|
||||
*
|
||||
@@ -3387,40 +3488,11 @@ namespace ts {
|
||||
charCode === CharacterCodes.backtick;
|
||||
}
|
||||
|
||||
function getReplacement(c: string, offset: number, input: string) {
|
||||
if (c.charCodeAt(0) === CharacterCodes.nullCharacter) {
|
||||
const lookAhead = input.charCodeAt(offset + c.length);
|
||||
if (lookAhead >= CharacterCodes._0 && lookAhead <= CharacterCodes._9) {
|
||||
// If the null character is followed by digits, print as a hex escape to prevent the result from parsing as an octal (which is forbidden in strict mode)
|
||||
return "\\x00";
|
||||
}
|
||||
// Otherwise, keep printing a literal \0 for the null character
|
||||
return "\\0";
|
||||
}
|
||||
return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0));
|
||||
}
|
||||
|
||||
export function isIntrinsicJsxName(name: __String | string) {
|
||||
const ch = (name as string).charCodeAt(0);
|
||||
return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains((name as string), "-");
|
||||
}
|
||||
|
||||
function get16BitUnicodeEscapeSequence(charCode: number): string {
|
||||
const hexCharCode = charCode.toString(16).toUpperCase();
|
||||
const paddedHexCode = ("0000" + hexCharCode).slice(-4);
|
||||
return "\\u" + paddedHexCode;
|
||||
}
|
||||
|
||||
const nonAsciiCharacters = /[^\u0000-\u007F]/g;
|
||||
export function escapeNonAsciiString(s: string, quoteChar?: CharacterCodes.doubleQuote | CharacterCodes.singleQuote | CharacterCodes.backtick): string {
|
||||
s = escapeString(s, quoteChar);
|
||||
// Replace non-ASCII characters with '\uNNNN' escapes if any exist.
|
||||
// Otherwise just return the original string.
|
||||
return nonAsciiCharacters.test(s) ?
|
||||
s.replace(nonAsciiCharacters, c => get16BitUnicodeEscapeSequence(c.charCodeAt(0))) :
|
||||
s;
|
||||
}
|
||||
|
||||
const indentStrings: string[] = ["", " "];
|
||||
export function getIndentString(level: number) {
|
||||
if (indentStrings[level] === undefined) {
|
||||
@@ -4153,6 +4225,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getModifierFlags(node: Node): ModifierFlags {
|
||||
if (node.kind >= SyntaxKind.FirstToken && node.kind <= SyntaxKind.LastToken) {
|
||||
return ModifierFlags.None;
|
||||
}
|
||||
if (node.modifierFlagsCache & ModifierFlags.HasComputedFlags) {
|
||||
return node.modifierFlagsCache & ~ModifierFlags.HasComputedFlags;
|
||||
}
|
||||
@@ -4278,7 +4353,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function isDottedName(node: Expression): boolean {
|
||||
return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword ||
|
||||
return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.SuperKeyword ||
|
||||
node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((<PropertyAccessExpression>node).expression) ||
|
||||
node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((<ParenthesizedExpression>node).expression);
|
||||
}
|
||||
@@ -4934,6 +5009,14 @@ namespace ts {
|
||||
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression;
|
||||
}
|
||||
|
||||
export function getNameOfAccessExpression(node: AccessExpression) {
|
||||
if (node.kind === SyntaxKind.PropertyAccessExpression) {
|
||||
return node.name;
|
||||
}
|
||||
Debug.assert(node.kind === SyntaxKind.ElementAccessExpression);
|
||||
return node.argumentExpression;
|
||||
}
|
||||
|
||||
export function isBundleFileTextLike(section: BundleFileSection): section is BundleFileTextLike {
|
||||
switch (section.kind) {
|
||||
case BundleFileSectionKind.Text:
|
||||
@@ -5000,6 +5083,28 @@ namespace ts {
|
||||
this.original = undefined;
|
||||
}
|
||||
|
||||
function Token(this: Node, kind: SyntaxKind, pos: number, end: number) {
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.kind = kind;
|
||||
this.id = 0;
|
||||
this.flags = NodeFlags.None;
|
||||
this.transformFlags = TransformFlags.None;
|
||||
this.parent = undefined!;
|
||||
}
|
||||
|
||||
function Identifier(this: Node, kind: SyntaxKind, pos: number, end: number) {
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.kind = kind;
|
||||
this.id = 0;
|
||||
this.flags = NodeFlags.None;
|
||||
this.transformFlags = TransformFlags.None;
|
||||
this.parent = undefined!;
|
||||
this.original = undefined;
|
||||
this.flowNode = undefined;
|
||||
}
|
||||
|
||||
function SourceMapSource(this: SourceMapSource, fileName: string, text: string, skipTrivia?: (pos: number) => number) {
|
||||
this.fileName = fileName;
|
||||
this.text = text;
|
||||
@@ -5009,8 +5114,8 @@ namespace ts {
|
||||
// eslint-disable-next-line prefer-const
|
||||
export let objectAllocator: ObjectAllocator = {
|
||||
getNodeConstructor: () => <any>Node,
|
||||
getTokenConstructor: () => <any>Node,
|
||||
getIdentifierConstructor: () => <any>Node,
|
||||
getTokenConstructor: () => <any>Token,
|
||||
getIdentifierConstructor: () => <any>Identifier,
|
||||
getPrivateIdentifierConstructor: () => <any>Node,
|
||||
getSourceFileConstructor: () => <any>Node,
|
||||
getSymbolConstructor: () => <any>Symbol,
|
||||
@@ -5024,7 +5129,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function formatStringFromArgs(text: string, args: ArrayLike<string | number>, baseIndex = 0): string {
|
||||
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.assertDefined(args[+index + baseIndex]));
|
||||
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.checkDefined(args[+index + baseIndex]));
|
||||
}
|
||||
|
||||
export let localizedDiagnosticMessages: MapLike<string> | undefined;
|
||||
@@ -6098,4 +6203,33 @@ namespace ts {
|
||||
export function pseudoBigIntToString({negative, base10Value}: PseudoBigInt): string {
|
||||
return (negative && base10Value !== "0" ? "-" : "") + base10Value;
|
||||
}
|
||||
|
||||
export function isValidTypeOnlyAliasUseSite(useSite: Node): boolean {
|
||||
return !!(useSite.flags & NodeFlags.Ambient)
|
||||
|| isPartOfTypeQuery(useSite)
|
||||
|| isFirstIdentifierOfNonEmittingHeritageClause(useSite)
|
||||
|| isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
|
||||
|| !isExpressionNode(useSite);
|
||||
}
|
||||
|
||||
function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node: Node) {
|
||||
while (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.PropertyAccessExpression) {
|
||||
node = node.parent;
|
||||
}
|
||||
if (node.kind !== SyntaxKind.ComputedPropertyName) {
|
||||
return false;
|
||||
}
|
||||
if (hasModifier(node.parent, ModifierFlags.Abstract)) {
|
||||
return true;
|
||||
}
|
||||
const containerKind = node.parent.parent.kind;
|
||||
return containerKind === SyntaxKind.InterfaceDeclaration || containerKind === SyntaxKind.TypeLiteral;
|
||||
}
|
||||
|
||||
/** Returns true for the first identifier of 1) an `implements` clause, and 2) an `extends` clause of an interface. */
|
||||
function isFirstIdentifierOfNonEmittingHeritageClause(node: Node): boolean {
|
||||
// Number of parents to climb from identifier is 2 for `implements I`, 3 for `implements x.I`
|
||||
const heritageClause = tryCast(node.parent.parent, isHeritageClause) ?? tryCast(node.parent.parent?.parent, isHeritageClause);
|
||||
return heritageClause?.token === SyntaxKind.ImplementsKeyword || heritageClause?.parent.kind === SyntaxKind.InterfaceDeclaration;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1721,16 +1721,15 @@ namespace ts {
|
||||
return isImportSpecifier(node) || isExportSpecifier(node);
|
||||
}
|
||||
|
||||
export function isTypeOnlyImportOrExportName(node: Node): boolean {
|
||||
if (node.kind !== SyntaxKind.Identifier) {
|
||||
return false;
|
||||
}
|
||||
switch (node.parent.kind) {
|
||||
export function isTypeOnlyImportOrExportDeclaration(node: Node): node is TypeOnlyCompatibleAliasDeclaration {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
return (node.parent as ImportSpecifier | ExportSpecifier).parent.parent.isTypeOnly;
|
||||
return (node as ImportOrExportSpecifier).parent.parent.isTypeOnly;
|
||||
case SyntaxKind.NamespaceImport:
|
||||
return (node as NamespaceImport).parent.isTypeOnly;
|
||||
case SyntaxKind.ImportClause:
|
||||
return (node.parent as ImportClause).isTypeOnly;
|
||||
return (node as ImportClause).isTypeOnly;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -2470,7 +2469,7 @@ namespace ts {
|
||||
|
||||
/** True if node is of a kind that may contain comment text. */
|
||||
export function isJSDocCommentContainingNode(node: Node): boolean {
|
||||
return node.kind === SyntaxKind.JSDocComment || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
|
||||
return node.kind === SyntaxKind.JSDocComment || node.kind === SyntaxKind.JSDocNamepathType || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
|
||||
}
|
||||
|
||||
// TODO: determine what this does before making it public.
|
||||
@@ -2508,9 +2507,19 @@ namespace ts {
|
||||
}
|
||||
|
||||
/** True if has initializer node attached to it. */
|
||||
/* @internal */
|
||||
export function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer {
|
||||
return hasInitializer(node) && !isForStatement(node) && !isForInStatement(node) && !isForOfStatement(node) && !isJsxAttribute(node);
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.VariableDeclaration:
|
||||
case SyntaxKind.Parameter:
|
||||
case SyntaxKind.BindingElement:
|
||||
case SyntaxKind.PropertySignature:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
case SyntaxKind.PropertyAssignment:
|
||||
case SyntaxKind.EnumMember:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isObjectLiteralElement(node: Node): node is ObjectLiteralElement {
|
||||
|
||||
@@ -105,7 +105,7 @@ namespace ts {
|
||||
|
||||
// Visit each original node.
|
||||
for (let i = 0; i < count; i++) {
|
||||
const node = nodes[i + start];
|
||||
const node: T = nodes[i + start];
|
||||
aggregateTransformFlags(node);
|
||||
const visited = node !== undefined ? visitor(node) : undefined;
|
||||
if (updated !== undefined || visited === undefined || visited !== node) {
|
||||
|
||||
@@ -360,7 +360,7 @@ namespace ts {
|
||||
const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath())));
|
||||
let host: DirectoryStructureHost = system;
|
||||
// TODO: `host` is unused!
|
||||
// eslint-disable-next-line no-unused-expressions
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||
host;
|
||||
return {
|
||||
useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames,
|
||||
|
||||
@@ -687,15 +687,16 @@ namespace ts {
|
||||
fileOrDirectory => {
|
||||
Debug.assert(!!configFileName);
|
||||
|
||||
const fileOrDirectoryPath = toPath(fileOrDirectory);
|
||||
let fileOrDirectoryPath: Path | undefined = toPath(fileOrDirectory);
|
||||
|
||||
// Since the file existance changed, update the sourceFiles cache
|
||||
// Since the file existence changed, update the sourceFiles cache
|
||||
if (cachedDirectoryStructureHost) {
|
||||
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
|
||||
}
|
||||
nextSourceFileVersion(fileOrDirectoryPath);
|
||||
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return;
|
||||
fileOrDirectoryPath = removeIgnoredPath(fileOrDirectoryPath);
|
||||
if (!fileOrDirectoryPath) return;
|
||||
|
||||
// If the the added or created file or directory is not supported file name, ignore the file
|
||||
// But when watched directory is added/removed, we need to reload the file list
|
||||
|
||||
@@ -33,21 +33,6 @@ namespace ts {
|
||||
return options.pretty;
|
||||
}
|
||||
|
||||
function padLeft(s: string, length: number) {
|
||||
while (s.length < length) {
|
||||
s = " " + s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function padRight(s: string, length: number) {
|
||||
while (s.length < length) {
|
||||
s = s + " ";
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
function getOptionsForHelp(commandLine: ParsedCommandLine) {
|
||||
// Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch")
|
||||
return !!commandLine.options.all ?
|
||||
@@ -243,13 +228,12 @@ namespace ts {
|
||||
if (commandLine.fileNames.length === 0 && !configFileName) {
|
||||
if (commandLine.options.showConfig) {
|
||||
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0, normalizePath(sys.getCurrentDirectory())));
|
||||
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
|
||||
}
|
||||
else {
|
||||
printVersion(sys);
|
||||
printHelp(sys, getOptionsForHelp(commandLine));
|
||||
return sys.exit(ExitStatus.Success);
|
||||
}
|
||||
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
|
||||
}
|
||||
|
||||
const currentDirectory = sys.getCurrentDirectory();
|
||||
@@ -739,4 +723,4 @@ namespace ts {
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +291,7 @@ namespace ts.server {
|
||||
|
||||
const request = this.processRequest<protocol.DefinitionRequest>(CommandNames.DefinitionAndBoundSpan, args);
|
||||
const response = this.processResponse<protocol.DefinitionInfoAndBoundSpanResponse>(request);
|
||||
const body = Debug.assertDefined(response.body); // TODO: GH#18217
|
||||
const body = Debug.checkDefined(response.body); // TODO: GH#18217
|
||||
|
||||
return {
|
||||
definitions: body.definitions.map(entry => ({
|
||||
@@ -385,7 +385,7 @@ namespace ts.server {
|
||||
start: entry.start,
|
||||
length: entry.length,
|
||||
messageText: entry.message,
|
||||
category: Debug.assertDefined(category, "convertDiagnostic: category should not be undefined"),
|
||||
category: Debug.checkDefined(category, "convertDiagnostic: category should not be undefined"),
|
||||
code: entry.code,
|
||||
reportsUnnecessary: entry.reportsUnnecessary,
|
||||
};
|
||||
|
||||
@@ -534,6 +534,8 @@ ${indentText}${text}`;
|
||||
buildInfo.version = ts.version;
|
||||
return ts.getBuildInfoText(buildInfo);
|
||||
};
|
||||
const originalWrite = sys.write;
|
||||
sys.write = msg => originalWrite.call(sys, msg.replace(ts.version, version));
|
||||
|
||||
if (sys.writeFile) {
|
||||
const originalWriteFile = sys.writeFile;
|
||||
|
||||
+167
-32
@@ -254,7 +254,7 @@ namespace FourSlash {
|
||||
const tsConfig = ts.convertCompilerOptionsFromJson(configJson.config.compilerOptions, baseDirectory, file.fileName);
|
||||
|
||||
if (!tsConfig.errors || !tsConfig.errors.length) {
|
||||
compilationOptions = ts.extend(compilationOptions, tsConfig.options);
|
||||
compilationOptions = ts.extend(tsConfig.options, compilationOptions);
|
||||
}
|
||||
}
|
||||
configFileName = file.fileName;
|
||||
@@ -381,7 +381,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
private getFileContent(fileName: string): string {
|
||||
return ts.Debug.assertDefined(this.tryGetFileContent(fileName));
|
||||
return ts.Debug.checkDefined(this.tryGetFileContent(fileName));
|
||||
}
|
||||
private tryGetFileContent(fileName: string): string | undefined {
|
||||
const script = this.languageServiceAdapterHost.getScriptInfo(fileName);
|
||||
@@ -843,8 +843,8 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) {
|
||||
const { insertText, replacementSpan, hasAction, isRecommended, kind, kindModifiers, text, documentation, tags, source, sourceDisplay, sortText } = typeof expected === "string"
|
||||
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined, sortText: undefined }
|
||||
const { insertText, replacementSpan, hasAction, isRecommended, isFromUncheckedFile, kind, kindModifiers, text, documentation, tags, source, sourceDisplay, sortText } = typeof expected === "string"
|
||||
? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, isFromUncheckedFile: undefined, kind: undefined, kindModifiers: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined, sortText: undefined }
|
||||
: expected;
|
||||
|
||||
if (actual.insertText !== insertText) {
|
||||
@@ -860,15 +860,21 @@ namespace FourSlash {
|
||||
|
||||
if (kind !== undefined || kindModifiers !== undefined) {
|
||||
if (actual.kind !== kind) {
|
||||
this.raiseError(`Unexpected kind for ${actual.name}: Expected ${kind}, actual ${actual.kind}`);
|
||||
this.raiseError(`Unexpected kind for ${actual.name}: Expected '${kind}', actual '${actual.kind}'`);
|
||||
}
|
||||
if (actual.kindModifiers !== (kindModifiers || "")) {
|
||||
this.raiseError(`Bad kind modifiers for ${actual.name}: Expected ${kindModifiers || ""}, actual ${actual.kindModifiers}`);
|
||||
this.raiseError(`Bad kindModifiers for ${actual.name}: Expected ${kindModifiers || ""}, actual ${actual.kindModifiers}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (isFromUncheckedFile !== undefined) {
|
||||
if (actual.isFromUncheckedFile !== isFromUncheckedFile) {
|
||||
this.raiseError(`Expected 'isFromUncheckedFile' value '${actual.isFromUncheckedFile}' to equal '${isFromUncheckedFile}'`);
|
||||
}
|
||||
}
|
||||
|
||||
assert.equal(actual.hasAction, hasAction, `Expected 'hasAction' value '${actual.hasAction}' to equal '${hasAction}'`);
|
||||
assert.equal(actual.isRecommended, isRecommended, `Expected 'isRecommended' value '${actual.source}' to equal '${isRecommended}'`);
|
||||
assert.equal(actual.isRecommended, isRecommended, `Expected 'isRecommended' value '${actual.isRecommended}' to equal '${isRecommended}'`);
|
||||
assert.equal(actual.source, source, `Expected 'source' value '${actual.source}' to equal '${source}'`);
|
||||
assert.equal(actual.sortText, sortText || ts.Completions.SortText.LocationPriority, this.messageAtLastKnownMarker(`Actual entry: ${JSON.stringify(actual)}`));
|
||||
|
||||
@@ -997,18 +1003,43 @@ namespace FourSlash {
|
||||
definition: string | { text: string, range: ts.TextSpan };
|
||||
references: ts.ReferenceEntry[];
|
||||
}
|
||||
interface RangeMarkerData {
|
||||
id?: string;
|
||||
isWriteAccess?: boolean,
|
||||
isDefinition?: boolean,
|
||||
isInString?: true,
|
||||
contextRangeIndex?: number,
|
||||
contextRangeDelta?: number,
|
||||
contextRangeId?: string
|
||||
}
|
||||
const fullExpected = ts.map<FourSlashInterface.ReferenceGroup, ReferenceGroupJson>(parts, ({ definition, ranges }) => ({
|
||||
definition: typeof definition === "string" ? definition : { ...definition, range: ts.createTextSpanFromRange(definition.range) },
|
||||
references: ranges.map<ts.ReferenceEntry>(r => {
|
||||
const { isWriteAccess = false, isDefinition = false, isInString, contextRangeIndex } = (r.marker && r.marker.data || {}) as { isWriteAccess?: boolean, isDefinition?: boolean, isInString?: true, contextRangeIndex?: number };
|
||||
const { isWriteAccess = false, isDefinition = false, isInString, contextRangeIndex, contextRangeDelta, contextRangeId } = (r.marker && r.marker.data || {}) as RangeMarkerData;
|
||||
let contextSpan: ts.TextSpan | undefined;
|
||||
if (contextRangeDelta !== undefined) {
|
||||
const allRanges = this.getRanges();
|
||||
const index = allRanges.indexOf(r);
|
||||
if (index !== -1) {
|
||||
contextSpan = ts.createTextSpanFromRange(allRanges[index + contextRangeDelta]);
|
||||
}
|
||||
}
|
||||
else if (contextRangeId !== undefined) {
|
||||
const allRanges = this.getRanges();
|
||||
const contextRange = ts.find(allRanges, range => (range.marker?.data as RangeMarkerData)?.id === contextRangeId);
|
||||
if (contextRange) {
|
||||
contextSpan = ts.createTextSpanFromRange(contextRange);
|
||||
}
|
||||
}
|
||||
else if (contextRangeIndex !== undefined) {
|
||||
contextSpan = ts.createTextSpanFromRange(this.getRanges()[contextRangeIndex]);
|
||||
}
|
||||
return {
|
||||
fileName: r.fileName,
|
||||
textSpan: ts.createTextSpanFromRange(r),
|
||||
fileName: r.fileName,
|
||||
...(contextSpan ? { contextSpan } : undefined),
|
||||
isWriteAccess,
|
||||
isDefinition,
|
||||
...(contextRangeIndex !== undefined ?
|
||||
{ contextSpan: ts.createTextSpanFromRange(this.getRanges()[contextRangeIndex]) } :
|
||||
undefined),
|
||||
...(isInString ? { isInString: true } : undefined),
|
||||
};
|
||||
}),
|
||||
@@ -1032,7 +1063,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
public verifyNoReferences(markerNameOrRange?: string | Range) {
|
||||
if (markerNameOrRange) this.goToMarkerOrRange(markerNameOrRange);
|
||||
if (markerNameOrRange !== undefined) this.goToMarkerOrRange(markerNameOrRange);
|
||||
const refs = this.getReferencesAtCaret();
|
||||
if (refs && refs.length) {
|
||||
this.raiseError(`Expected getReferences to fail, but saw references: ${stringify(refs)}`);
|
||||
@@ -1233,6 +1264,12 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
public verifyRenameLocations(startRanges: ArrayOrSingle<Range>, options: FourSlashInterface.RenameLocationsOptions) {
|
||||
interface RangeMarkerData {
|
||||
id?: string;
|
||||
contextRangeIndex?: number,
|
||||
contextRangeDelta?: number
|
||||
contextRangeId?: string;
|
||||
}
|
||||
const { findInStrings = false, findInComments = false, ranges = this.getRanges(), providePrefixAndSuffixTextForRename = true } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options, providePrefixAndSuffixTextForRename: true } : options;
|
||||
|
||||
const _startRanges = toArray(startRanges);
|
||||
@@ -1253,19 +1290,66 @@ namespace FourSlash {
|
||||
locations && ts.sort(locations, (r1, r2) => ts.compareStringsCaseSensitive(r1.fileName, r2.fileName) || r1.textSpan.start - r2.textSpan.start);
|
||||
assert.deepEqual(sort(references), sort(ranges.map((rangeOrOptions): ts.RenameLocation => {
|
||||
const { range, ...prefixSuffixText } = "range" in rangeOrOptions ? rangeOrOptions : { range: rangeOrOptions }; // eslint-disable-line no-in-operator
|
||||
const { contextRangeIndex } = (range.marker && range.marker.data || {}) as { contextRangeIndex?: number; };
|
||||
const { contextRangeIndex, contextRangeDelta, contextRangeId } = (range.marker && range.marker.data || {}) as RangeMarkerData;
|
||||
let contextSpan: ts.TextSpan | undefined;
|
||||
if (contextRangeDelta !== undefined) {
|
||||
const allRanges = this.getRanges();
|
||||
const index = allRanges.indexOf(range);
|
||||
if (index !== -1) {
|
||||
contextSpan = ts.createTextSpanFromRange(allRanges[index + contextRangeDelta]);
|
||||
}
|
||||
}
|
||||
else if (contextRangeId !== undefined) {
|
||||
const allRanges = this.getRanges();
|
||||
const contextRange = ts.find(allRanges, range => (range.marker?.data as RangeMarkerData)?.id === contextRangeId);
|
||||
if (contextRange) {
|
||||
contextSpan = ts.createTextSpanFromRange(contextRange);
|
||||
}
|
||||
}
|
||||
else if (contextRangeIndex !== undefined) {
|
||||
contextSpan = ts.createTextSpanFromRange(this.getRanges()[contextRangeIndex]);
|
||||
}
|
||||
return {
|
||||
fileName: range.fileName,
|
||||
textSpan: ts.createTextSpanFromRange(range),
|
||||
...(contextRangeIndex !== undefined ?
|
||||
{ contextSpan: ts.createTextSpanFromRange(this.getRanges()[contextRangeIndex]) } :
|
||||
undefined),
|
||||
...(contextSpan ? { contextSpan } : undefined),
|
||||
...prefixSuffixText
|
||||
};
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
public baselineRename(marker: string, options: FourSlashInterface.RenameOptions) {
|
||||
const position = this.getMarkerByName(marker).position;
|
||||
const locations = this.languageService.findRenameLocations(
|
||||
this.activeFile.fileName,
|
||||
position,
|
||||
options.findInStrings ?? false,
|
||||
options.findInComments ?? false,
|
||||
options.providePrefixAndSuffixTextForRename);
|
||||
|
||||
if (!locations) {
|
||||
this.raiseError(`baselineRename failed. Could not rename at the provided position.`);
|
||||
}
|
||||
|
||||
const renamesByFile = ts.group(locations, l => l.fileName);
|
||||
const baselineContent = renamesByFile.map(renames => {
|
||||
const { fileName } = renames[0];
|
||||
const sortedRenames = ts.sort(renames, (a, b) => b.textSpan.start - a.textSpan.start);
|
||||
let baselineFileContent = this.getFileContent(fileName);
|
||||
for (const { textSpan } of sortedRenames) {
|
||||
const isOriginalSpan = fileName === this.activeFile.fileName && ts.textSpanIntersectsWithPosition(textSpan, position);
|
||||
baselineFileContent =
|
||||
baselineFileContent.slice(0, textSpan.start) +
|
||||
(isOriginalSpan ? "[|RENAME|]" : "RENAME") +
|
||||
baselineFileContent.slice(textSpan.start + textSpan.length);
|
||||
}
|
||||
return `/*====== ${fileName} ======*/\n\n${baselineFileContent}`;
|
||||
}).join("\n\n") + "\n";
|
||||
|
||||
Harness.Baseline.runBaseline(this.getBaselineFileNameForContainingTestFile(), baselineContent);
|
||||
}
|
||||
|
||||
public verifyQuickInfoExists(negative: boolean) {
|
||||
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
if (negative) {
|
||||
@@ -1479,7 +1563,7 @@ namespace FourSlash {
|
||||
const output: string[] = [];
|
||||
for (let lineNumber = contextStart.line; lineNumber <= contextEnd.line; lineNumber++) {
|
||||
const spanLine = contextString.substring(contextLineMap[lineNumber], contextLineMap[lineNumber + 1]);
|
||||
output.push(lineNumbers ? `${`${lineNumber + 1}: `.padStart(lineNumberPrefixLength, " ")}${spanLine}` : spanLine);
|
||||
output.push(lineNumbers ? `${ts.padLeft(`${lineNumber + 1}: `, lineNumberPrefixLength)}${spanLine}` : spanLine);
|
||||
if (selection) {
|
||||
if (lineNumber < selectionStart.line || lineNumber > selectionEnd.line) {
|
||||
continue;
|
||||
@@ -1632,7 +1716,7 @@ namespace FourSlash {
|
||||
resultString += Harness.IO.newLine();
|
||||
}
|
||||
|
||||
Harness.Baseline.runBaseline(ts.Debug.assertDefined(this.testData.globalOptions[MetadataOptionNames.baselineFile]), resultString);
|
||||
Harness.Baseline.runBaseline(ts.Debug.checkDefined(this.testData.globalOptions[MetadataOptionNames.baselineFile]), resultString);
|
||||
}
|
||||
|
||||
private flattenChainedMessage(diag: ts.DiagnosticMessageChain, indent = " ") {
|
||||
@@ -2544,9 +2628,9 @@ namespace FourSlash {
|
||||
|
||||
public verifyCodeFixAll({ fixId, fixAllDescription, newFileContent, commands: expectedCommands }: FourSlashInterface.VerifyCodeFixAllOptions): void {
|
||||
const fixWithId = ts.find(this.getCodeFixes(this.activeFile.fileName), a => a.fixId === fixId);
|
||||
ts.Debug.assert(fixWithId !== undefined, "No available code fix has that group id.", () =>
|
||||
`Expected '${fixId}'. Available action ids: ${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => a.fixId)}`);
|
||||
ts.Debug.assertEqual(fixWithId!.fixAllDescription, fixAllDescription);
|
||||
ts.Debug.assert(fixWithId !== undefined, "No available code fix has the expected id. Fix All is not available if there is only one potentially fixable diagnostic present.", () =>
|
||||
`Expected '${fixId}'. Available actions:\n${ts.mapDefined(this.getCodeFixes(this.activeFile.fileName), a => `${a.fixName} (${a.fixId || "no fix id"})`).join("\n")}`);
|
||||
ts.Debug.assertEqual(fixWithId.fixAllDescription, fixAllDescription);
|
||||
|
||||
const { changes, commands } = this.languageService.getCombinedCodeFix({ type: "file", fileName: this.activeFile.fileName }, fixId, this.formatCodeSettings, ts.emptyOptions);
|
||||
assert.deepEqual<readonly {}[] | undefined>(commands, expectedCommands);
|
||||
@@ -2574,6 +2658,10 @@ namespace FourSlash {
|
||||
if (typeof options.description === "string") {
|
||||
assert.equal(action.description, options.description);
|
||||
}
|
||||
else if (Array.isArray(options.description)) {
|
||||
const description = ts.formatStringFromArgs(options.description[0], options.description, 1);
|
||||
assert.equal(action.description, description);
|
||||
}
|
||||
else {
|
||||
assert.match(action.description, templateToRegExp(options.description.template));
|
||||
}
|
||||
@@ -2681,7 +2769,7 @@ namespace FourSlash {
|
||||
}
|
||||
const range = ts.firstOrUndefined(ranges);
|
||||
|
||||
const codeFixes = this.getCodeFixes(fileName, errorCode, preferences).filter(f => f.fixId === ts.codefix.importFixId);
|
||||
const codeFixes = this.getCodeFixes(fileName, errorCode, preferences).filter(f => f.fixName === ts.codefix.importFixName);
|
||||
|
||||
if (codeFixes.length === 0) {
|
||||
if (expectedTextArray.length !== 0) {
|
||||
@@ -2717,7 +2805,7 @@ namespace FourSlash {
|
||||
const codeFixes = this.getCodeFixes(marker.fileName, ts.Diagnostics.Cannot_find_name_0.code, {
|
||||
includeCompletionsForModuleExports: true,
|
||||
includeCompletionsWithInsertText: true
|
||||
}, marker.position).filter(f => f.fixId === ts.codefix.importFixId);
|
||||
}, marker.position).filter(f => f.fixName === ts.codefix.importFixName);
|
||||
|
||||
const actualModuleSpecifiers = ts.mapDefined(codeFixes, fix => {
|
||||
return ts.forEach(ts.flatMap(fix.changes, c => c.textChanges), c => {
|
||||
@@ -2869,7 +2957,7 @@ namespace FourSlash {
|
||||
|
||||
private verifyNavigationTreeOrBar(json: any, tree: any, name: "Tree" | "Bar", options: { checkSpans?: boolean } | undefined) {
|
||||
if (JSON.stringify(tree, replacer) !== JSON.stringify(json)) {
|
||||
this.raiseError(`verifyNavigation${name} failed - expected: ${stringify(json)}, got: ${stringify(tree, replacer)}`);
|
||||
this.raiseError(`verifyNavigation${name} failed - \n${showTextDiff(stringify(json), stringify(tree, replacer))}`);
|
||||
}
|
||||
|
||||
function replacer(key: string, value: any) {
|
||||
@@ -3044,6 +3132,26 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
public verifyCodeFixAllAvailable(negative: boolean, fixName: string) {
|
||||
const availableFixes = this.getCodeFixes(this.activeFile.fileName);
|
||||
const hasFix = availableFixes.some(fix => fix.fixName === fixName && fix.fixId);
|
||||
if (negative && hasFix) {
|
||||
this.raiseError(`Expected not to find a fix with the name '${fixName}', but one exists.`);
|
||||
}
|
||||
else if (!negative && !hasFix) {
|
||||
if (availableFixes.some(fix => fix.fixName === fixName)) {
|
||||
this.raiseError(`Found a fix with the name '${fixName}', but fix-all is not available.`);
|
||||
}
|
||||
|
||||
this.raiseError(
|
||||
`Expected to find a fix with the name '${fixName}', but none exists.` +
|
||||
availableFixes.length
|
||||
? ` Available fixes: ${availableFixes.map(fix => `${fix.fixName} (${fix.fixId ? "with" : "without"} fix-all)`).join(", ")}`
|
||||
: ""
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public verifyApplicableRefactorAvailableAtMarker(negative: boolean, markerName: string) {
|
||||
const isAvailable = this.getApplicableRefactors(this.getMarkerByName(markerName)).length > 0;
|
||||
if (negative && isAvailable) {
|
||||
@@ -3565,19 +3673,41 @@ namespace FourSlash {
|
||||
// Parse out the files and their metadata
|
||||
const testData = parseTestData(absoluteBasePath, content, absoluteFileName);
|
||||
const state = new TestState(absoluteFileName, absoluteBasePath, testType, testData);
|
||||
const output = ts.transpileModule(content, { reportDiagnostics: true, compilerOptions: { target: ts.ScriptTarget.ES2015 } });
|
||||
const actualFileName = Harness.IO.resolvePath(fileName) || absoluteFileName;
|
||||
const output = ts.transpileModule(content, { reportDiagnostics: true, fileName: actualFileName, compilerOptions: { target: ts.ScriptTarget.ES2015, inlineSourceMap: true } });
|
||||
if (output.diagnostics!.length > 0) {
|
||||
throw new Error(`Syntax error in ${absoluteBasePath}: ${output.diagnostics![0].messageText}`);
|
||||
}
|
||||
runCode(output.outputText, state);
|
||||
runCode(output.outputText, state, actualFileName);
|
||||
}
|
||||
|
||||
function runCode(code: string, state: TestState): void {
|
||||
function runCode(code: string, state: TestState, fileName: string): void {
|
||||
// Compile and execute the test
|
||||
const wrappedCode =
|
||||
`(function(test, goTo, plugins, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) {
|
||||
${code}
|
||||
})`;
|
||||
const generatedFile = ts.changeExtension(fileName, ".js");
|
||||
const wrappedCode = `(function(test, goTo, plugins, verify, edit, debug, format, cancellation, classification, completion, verifyOperationIsCancelled) {${code}\n//# sourceURL=${generatedFile}\n})`;
|
||||
|
||||
type SourceMapSupportModule = typeof import("source-map-support") & {
|
||||
// TODO(rbuckton): This is missing from the DT definitions and needs to be added.
|
||||
resetRetrieveHandlers(): void
|
||||
};
|
||||
|
||||
// Provide the content of the current test to 'source-map-support' so that it can give us the correct source positions
|
||||
// for test failures.
|
||||
let sourceMapSupportModule: SourceMapSupportModule | undefined;
|
||||
try {
|
||||
sourceMapSupportModule = require("source-map-support");
|
||||
}
|
||||
catch {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
sourceMapSupportModule?.install({
|
||||
retrieveFile: path => {
|
||||
return path === generatedFile ? wrappedCode :
|
||||
undefined!;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const test = new FourSlashInterface.Test(state);
|
||||
const goTo = new FourSlashInterface.GoTo(state);
|
||||
@@ -3592,8 +3722,13 @@ ${code}
|
||||
f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled);
|
||||
}
|
||||
catch (err) {
|
||||
// ensure 'source-map-support' is triggered while we still have the handler attached by accessing `error.stack`.
|
||||
err.stack?.toString();
|
||||
throw err;
|
||||
}
|
||||
finally {
|
||||
sourceMapSupportModule?.resetRetrieveHandlers();
|
||||
}
|
||||
}
|
||||
|
||||
function chompLeadingSpace(content: string) {
|
||||
|
||||
@@ -191,6 +191,10 @@ namespace FourSlashInterface {
|
||||
this.state.verifyCodeFixAvailable(this.negative, options);
|
||||
}
|
||||
|
||||
public codeFixAllAvailable(fixName: string) {
|
||||
this.state.verifyCodeFixAllAvailable(this.negative, fixName);
|
||||
}
|
||||
|
||||
public applicableRefactorAvailableAtMarker(markerName: string) {
|
||||
this.state.verifyApplicableRefactorAvailableAtMarker(this.negative, markerName);
|
||||
}
|
||||
@@ -512,6 +516,10 @@ namespace FourSlashInterface {
|
||||
this.state.verifyRenameLocations(startRanges, options);
|
||||
}
|
||||
|
||||
public baselineRename(marker: string, options: RenameOptions) {
|
||||
this.state.baselineRename(marker, options);
|
||||
}
|
||||
|
||||
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: FourSlash.TextSpan,
|
||||
displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]) {
|
||||
this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation, tags);
|
||||
@@ -889,7 +897,7 @@ namespace FourSlashInterface {
|
||||
const res: ExpectedCompletionEntryObject[] = [];
|
||||
for (let i = ts.SyntaxKind.FirstKeyword; i <= ts.SyntaxKind.LastKeyword; i++) {
|
||||
res.push({
|
||||
name: ts.Debug.assertDefined(ts.tokenToString(i)),
|
||||
name: ts.Debug.checkDefined(ts.tokenToString(i)),
|
||||
kind: "keyword",
|
||||
sortText: SortText.GlobalsOrKeywords
|
||||
});
|
||||
@@ -898,7 +906,7 @@ namespace FourSlashInterface {
|
||||
export const keywords: readonly ExpectedCompletionEntryObject[] = keywordsWithUndefined.filter(k => k.name !== "undefined");
|
||||
|
||||
export const typeKeywords: readonly ExpectedCompletionEntryObject[] =
|
||||
["false", "null", "true", "void", "any", "boolean", "keyof", "never", "readonly", "number", "object", "string", "symbol", "undefined", "unique", "unknown", "bigint"].map(keywordEntry);
|
||||
["false", "null", "true", "void", "asserts", "any", "boolean", "keyof", "never", "readonly", "number", "object", "string", "symbol", "undefined", "unique", "unknown", "bigint"].map(keywordEntry);
|
||||
|
||||
const globalTypeDecls: readonly ExpectedCompletionEntryObject[] = [
|
||||
interfaceEntry("Symbol"),
|
||||
@@ -1054,7 +1062,7 @@ namespace FourSlashInterface {
|
||||
}
|
||||
|
||||
export const classElementKeywords: readonly ExpectedCompletionEntryObject[] =
|
||||
["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"].map(keywordEntry);
|
||||
["private", "protected", "public", "static", "abstract", "async", "constructor", "declare", "get", "readonly", "set"].map(keywordEntry);
|
||||
|
||||
export const classElementInJsKeywords = getInJsKeywords(classElementKeywords);
|
||||
|
||||
@@ -1148,6 +1156,8 @@ namespace FourSlashInterface {
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"as",
|
||||
"asserts",
|
||||
"any",
|
||||
"async",
|
||||
"await",
|
||||
@@ -1347,6 +1357,8 @@ namespace FourSlashInterface {
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"as",
|
||||
"asserts",
|
||||
"any",
|
||||
"async",
|
||||
"await",
|
||||
@@ -1472,6 +1484,7 @@ namespace FourSlashInterface {
|
||||
readonly replacementSpan?: FourSlash.Range;
|
||||
readonly hasAction?: boolean; // If not specified, will assert that this is false.
|
||||
readonly isRecommended?: boolean; // If not specified, will assert that this is false.
|
||||
readonly isFromUncheckedFile?: boolean; // If not specified, won't assert about this
|
||||
readonly kind?: string; // If not specified, won't assert about this
|
||||
readonly kindModifiers?: string; // Must be paired with 'kind'
|
||||
readonly text?: string;
|
||||
@@ -1552,7 +1565,7 @@ namespace FourSlashInterface {
|
||||
}
|
||||
|
||||
export interface VerifyCodeFixOptions extends NewContentOptions {
|
||||
readonly description: string | DiagnosticIgnoredInterpolations;
|
||||
readonly description: string | [string, ...(string | number)[]] | DiagnosticIgnoredInterpolations;
|
||||
readonly errorCode?: number;
|
||||
readonly index?: number;
|
||||
readonly preferences?: ts.UserPreferences;
|
||||
@@ -1614,4 +1627,9 @@ namespace FourSlashInterface {
|
||||
template: string
|
||||
};
|
||||
export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string };
|
||||
export interface RenameOptions {
|
||||
readonly findInStrings?: boolean;
|
||||
readonly findInComments?: boolean;
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
+53
-46
@@ -54,7 +54,7 @@ namespace Utils {
|
||||
export function memoize<T extends ts.AnyFunction>(f: T, memoKey: (...anything: any[]) => string): T {
|
||||
const cache = ts.createMap<any>();
|
||||
|
||||
return <any>(function(this: any, ...args: any[]) {
|
||||
return <any>(function (this: any, ...args: any[]) {
|
||||
const key = memoKey(...args);
|
||||
if (cache.has(key)) {
|
||||
return cache.get(key);
|
||||
@@ -69,56 +69,63 @@ namespace Utils {
|
||||
|
||||
export const canonicalizeForHarness = ts.createGetCanonicalFileName(/*caseSensitive*/ false); // This is done so tests work on windows _and_ linux
|
||||
|
||||
export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | undefined): void {
|
||||
if (node) {
|
||||
assert.isFalse(node.pos < 0, "node.pos < 0");
|
||||
assert.isFalse(node.end < 0, "node.end < 0");
|
||||
assert.isFalse(node.end < node.pos, "node.end < node.pos");
|
||||
assert.equal(node.parent, parent, "node.parent !== parent");
|
||||
export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | undefined) {
|
||||
const queue: [ts.Node | undefined, ts.Node | undefined][] = [[node, parent]];
|
||||
for (const [node, parent] of queue) {
|
||||
assertInvariantsWorker(node, parent);
|
||||
}
|
||||
|
||||
if (parent) {
|
||||
// Make sure each child is contained within the parent.
|
||||
assert.isFalse(node.pos < parent.pos, "node.pos < parent.pos");
|
||||
assert.isFalse(node.end > parent.end, "node.end > parent.end");
|
||||
}
|
||||
function assertInvariantsWorker(node: ts.Node | undefined, parent: ts.Node | undefined): void {
|
||||
if (node) {
|
||||
assert.isFalse(node.pos < 0, "node.pos < 0");
|
||||
assert.isFalse(node.end < 0, "node.end < 0");
|
||||
assert.isFalse(node.end < node.pos, "node.end < node.pos");
|
||||
assert.equal(node.parent, parent, "node.parent !== parent");
|
||||
|
||||
ts.forEachChild(node, child => {
|
||||
assertInvariants(child, node);
|
||||
});
|
||||
if (parent) {
|
||||
// Make sure each child is contained within the parent.
|
||||
assert.isFalse(node.pos < parent.pos, "node.pos < parent.pos");
|
||||
assert.isFalse(node.end > parent.end, "node.end > parent.end");
|
||||
}
|
||||
|
||||
// Make sure each of the children is in order.
|
||||
let currentPos = 0;
|
||||
ts.forEachChild(node,
|
||||
child => {
|
||||
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
|
||||
currentPos = child.end;
|
||||
},
|
||||
array => {
|
||||
assert.isFalse(array.pos < node.pos, "array.pos < node.pos");
|
||||
assert.isFalse(array.end > node.end, "array.end > node.end");
|
||||
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
|
||||
|
||||
for (const item of array) {
|
||||
assert.isFalse(item.pos < currentPos, "array[i].pos < currentPos");
|
||||
currentPos = item.end;
|
||||
}
|
||||
|
||||
currentPos = array.end;
|
||||
ts.forEachChild(node, child => {
|
||||
queue.push([child, node]);
|
||||
});
|
||||
|
||||
const childNodesAndArrays: any[] = [];
|
||||
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
|
||||
// Make sure each of the children is in order.
|
||||
let currentPos = 0;
|
||||
ts.forEachChild(node,
|
||||
child => {
|
||||
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
|
||||
currentPos = child.end;
|
||||
},
|
||||
array => {
|
||||
assert.isFalse(array.pos < node.pos, "array.pos < node.pos");
|
||||
assert.isFalse(array.end > node.end, "array.end > node.end");
|
||||
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
|
||||
|
||||
for (const childName in node) {
|
||||
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
|
||||
// for now ignore jsdoc comments
|
||||
childName === "jsDocComment" || childName === "checkJsDirective" || childName === "commonJsModuleIndicator") {
|
||||
continue;
|
||||
}
|
||||
const child = (<any>node)[childName];
|
||||
if (isNodeOrArray(child)) {
|
||||
assert.isFalse(childNodesAndArrays.indexOf(child) < 0,
|
||||
"Missing child when forEach'ing over node: " + (<any>ts).SyntaxKind[node.kind] + "-" + childName);
|
||||
for (const item of array) {
|
||||
assert.isFalse(item.pos < currentPos, "array[i].pos < currentPos");
|
||||
currentPos = item.end;
|
||||
}
|
||||
|
||||
currentPos = array.end;
|
||||
});
|
||||
|
||||
const childNodesAndArrays: any[] = [];
|
||||
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
|
||||
|
||||
for (const childName in node) {
|
||||
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
|
||||
// for now ignore jsdoc comments
|
||||
childName === "jsDocComment" || childName === "checkJsDirective" || childName === "commonJsModuleIndicator") {
|
||||
continue;
|
||||
}
|
||||
const child = (<any>node)[childName];
|
||||
if (isNodeOrArray(child)) {
|
||||
assert.isFalse(childNodesAndArrays.indexOf(child) < 0,
|
||||
"Missing child when forEach'ing over node: " + (<any>ts).SyntaxKind[node.kind] + "-" + childName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,4 +395,4 @@ namespace Utils {
|
||||
function isHarness(line: string) {
|
||||
return /[\\/]src[\\/]harness[\\/]|[\\/]run\.js/.test(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+22
-13
@@ -21,6 +21,19 @@ namespace Harness {
|
||||
type?: string;
|
||||
}
|
||||
|
||||
function* forEachASTNode(node: ts.Node) {
|
||||
const work = [node];
|
||||
while (work.length) {
|
||||
const elem = work.pop()!;
|
||||
yield elem;
|
||||
|
||||
const resChildren: ts.Node[] = [];
|
||||
// push onto work queue in reverse order to maintain preorder traversal
|
||||
ts.forEachChild(elem, c => { resChildren.unshift(c); });
|
||||
work.push(...resChildren);
|
||||
}
|
||||
}
|
||||
|
||||
export class TypeWriterWalker {
|
||||
currentSourceFile!: ts.SourceFile;
|
||||
|
||||
@@ -53,19 +66,15 @@ namespace Harness {
|
||||
}
|
||||
|
||||
private *visitNode(node: ts.Node, isSymbolWalk: boolean): IterableIterator<TypeWriterResult> {
|
||||
if (ts.isExpressionNode(node) || node.kind === ts.SyntaxKind.Identifier || ts.isDeclarationName(node)) {
|
||||
const result = this.writeTypeOrSymbol(node, isSymbolWalk);
|
||||
if (result) {
|
||||
yield result;
|
||||
}
|
||||
}
|
||||
|
||||
const children: ts.Node[] = [];
|
||||
ts.forEachChild(node, child => void children.push(child));
|
||||
for (const child of children) {
|
||||
const gen = this.visitNode(child, isSymbolWalk);
|
||||
for (let {done, value} = gen.next(); !done; { done, value } = gen.next()) {
|
||||
yield value;
|
||||
const gen = forEachASTNode(node);
|
||||
let res = gen.next();
|
||||
for (; !res.done; res = gen.next()) {
|
||||
const {value: node} = res;
|
||||
if (ts.isExpressionNode(node) || node.kind === ts.SyntaxKind.Identifier || ts.isDeclarationName(node)) {
|
||||
const result = this.writeTypeOrSymbol(node, isSymbolWalk);
|
||||
if (result) {
|
||||
yield result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,17 +199,21 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
checkMap(`watchedFiles:: ${additionalInfo || ""}::`, host.watchedFiles, expectedFiles, /*eachKeyCount*/ undefined);
|
||||
}
|
||||
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap<number>, expectedPollingIntervals?: Map<PollingInterval[]>): void;
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: readonly string[], eachFileWatchCount: number, expectedPollingIntervals?: Map<PollingInterval[]>): void;
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap<number> | readonly string[], eachFileWatchCount?: number | Map<PollingInterval[]>, expectedPollingIntervals?: Map<PollingInterval[]>) {
|
||||
if (!isNumber(eachFileWatchCount)) expectedPollingIntervals = eachFileWatchCount;
|
||||
export interface WatchFileDetails {
|
||||
fileName: string;
|
||||
pollingInterval: PollingInterval;
|
||||
}
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap<number>, expectedDetails?: Map<WatchFileDetails[]>): void;
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: readonly string[], eachFileWatchCount: number, expectedDetails?: Map<WatchFileDetails[]>): void;
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap<number> | readonly string[], eachFileWatchCountOrExpectedDetails?: number | Map<WatchFileDetails[]>, expectedDetails?: Map<WatchFileDetails[]>) {
|
||||
if (!isNumber(eachFileWatchCountOrExpectedDetails)) expectedDetails = eachFileWatchCountOrExpectedDetails;
|
||||
if (isArray(expectedFiles)) {
|
||||
checkMap(
|
||||
"watchedFiles",
|
||||
host.watchedFiles,
|
||||
expectedFiles,
|
||||
eachFileWatchCount as number,
|
||||
[expectedPollingIntervals, ({ pollingInterval }) => pollingInterval]
|
||||
eachFileWatchCountOrExpectedDetails as number,
|
||||
[expectedDetails, ({ fileName, pollingInterval }) => ({ fileName, pollingInterval })]
|
||||
);
|
||||
}
|
||||
else {
|
||||
@@ -217,7 +221,7 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
"watchedFiles",
|
||||
host.watchedFiles,
|
||||
expectedFiles,
|
||||
[expectedPollingIntervals, ({ pollingInterval }) => pollingInterval]
|
||||
[expectedDetails, ({ fileName, pollingInterval }) => ({ fileName, pollingInterval })]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -226,30 +230,31 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
checkMap(`watchedDirectories${recursive ? " recursive" : ""}`, recursive ? host.fsWatchesRecursive : host.fsWatches, expectedDirectories, /*eachKeyCount*/ undefined);
|
||||
}
|
||||
|
||||
export interface FallbackPollingOptions {
|
||||
export interface WatchDirectoryDetails {
|
||||
directoryName: string;
|
||||
fallbackPollingInterval: PollingInterval;
|
||||
fallbackOptions: WatchOptions | undefined;
|
||||
}
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap<number>, recursive: boolean, expectedFallbacks?: Map<FallbackPollingOptions[]>): void;
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: readonly string[], eachDirectoryWatchCount: number, recursive: boolean, expectedFallbacks?: Map<FallbackPollingOptions[]>): void;
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap<number> | readonly string[], recursiveOrEachDirectoryWatchCount: boolean | number, recursiveOrExpectedFallbacks?: boolean | Map<FallbackPollingOptions[]>, expectedFallbacks?: Map<FallbackPollingOptions[]>) {
|
||||
if (typeof recursiveOrExpectedFallbacks !== "boolean") expectedFallbacks = recursiveOrExpectedFallbacks;
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap<number>, recursive: boolean, expectedDetails?: Map<WatchDirectoryDetails[]>): void;
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: readonly string[], eachDirectoryWatchCount: number, recursive: boolean, expectedDetails?: Map<WatchDirectoryDetails[]>): void;
|
||||
export function checkWatchedDirectoriesDetailed(host: TestServerHost, expectedDirectories: ReadonlyMap<number> | readonly string[], recursiveOrEachDirectoryWatchCount: boolean | number, recursiveOrExpectedDetails?: boolean | Map<WatchDirectoryDetails[]>, expectedDetails?: Map<WatchDirectoryDetails[]>) {
|
||||
if (typeof recursiveOrExpectedDetails !== "boolean") expectedDetails = recursiveOrExpectedDetails;
|
||||
if (isArray(expectedDirectories)) {
|
||||
checkMap(
|
||||
`fsWatches${recursiveOrExpectedFallbacks ? " recursive" : ""}`,
|
||||
recursiveOrExpectedFallbacks as boolean ? host.fsWatchesRecursive : host.fsWatches,
|
||||
`fsWatches${recursiveOrExpectedDetails ? " recursive" : ""}`,
|
||||
recursiveOrExpectedDetails as boolean ? host.fsWatchesRecursive : host.fsWatches,
|
||||
expectedDirectories,
|
||||
recursiveOrEachDirectoryWatchCount as number,
|
||||
[expectedFallbacks, ({ fallbackPollingInterval, fallbackOptions }) => ({ fallbackPollingInterval, fallbackOptions })]
|
||||
[expectedDetails, ({ directoryName, fallbackPollingInterval, fallbackOptions }) => ({ directoryName, fallbackPollingInterval, fallbackOptions })]
|
||||
);
|
||||
}
|
||||
else {
|
||||
recursiveOrExpectedFallbacks = recursiveOrEachDirectoryWatchCount as boolean;
|
||||
recursiveOrExpectedDetails = recursiveOrEachDirectoryWatchCount as boolean;
|
||||
checkMap(
|
||||
`fsWatches{recursive ? " recursive" : ""}`,
|
||||
recursiveOrExpectedFallbacks ? host.fsWatchesRecursive : host.fsWatches,
|
||||
recursiveOrExpectedDetails ? host.fsWatchesRecursive : host.fsWatches,
|
||||
expectedDirectories,
|
||||
[expectedFallbacks, ({ fallbackPollingInterval, fallbackOptions }) => ({ fallbackPollingInterval, fallbackOptions })]
|
||||
[expectedDetails, ({ directoryName, fallbackPollingInterval, fallbackOptions }) => ({ directoryName, fallbackPollingInterval, fallbackOptions })]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -330,6 +335,7 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
|
||||
export interface TestFsWatcher {
|
||||
cb: FsWatchCallback;
|
||||
directoryName: string;
|
||||
fallbackPollingInterval: PollingInterval;
|
||||
fallbackOptions: WatchOptions | undefined;
|
||||
}
|
||||
@@ -611,28 +617,29 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
}
|
||||
|
||||
ensureFileOrFolder(fileOrDirectoryOrSymLink: FileOrFolderOrSymLink, ignoreWatchInvokedWithTriggerAsFileCreate?: boolean) {
|
||||
ensureFileOrFolder(fileOrDirectoryOrSymLink: FileOrFolderOrSymLink, ignoreWatchInvokedWithTriggerAsFileCreate?: boolean, ignoreParentWatch?: boolean) {
|
||||
if (isFile(fileOrDirectoryOrSymLink)) {
|
||||
const file = this.toFsFile(fileOrDirectoryOrSymLink);
|
||||
// file may already exist when updating existing type declaration file
|
||||
if (!this.fs.get(file.path)) {
|
||||
const baseFolder = this.ensureFolder(getDirectoryPath(file.fullPath));
|
||||
const baseFolder = this.ensureFolder(getDirectoryPath(file.fullPath), ignoreParentWatch);
|
||||
this.addFileOrFolderInFolder(baseFolder, file, ignoreWatchInvokedWithTriggerAsFileCreate);
|
||||
}
|
||||
}
|
||||
else if (isSymLink(fileOrDirectoryOrSymLink)) {
|
||||
const symLink = this.toFsSymLink(fileOrDirectoryOrSymLink);
|
||||
Debug.assert(!this.fs.get(symLink.path));
|
||||
const baseFolder = this.ensureFolder(getDirectoryPath(symLink.fullPath));
|
||||
const baseFolder = this.ensureFolder(getDirectoryPath(symLink.fullPath), ignoreParentWatch);
|
||||
this.addFileOrFolderInFolder(baseFolder, symLink, ignoreWatchInvokedWithTriggerAsFileCreate);
|
||||
}
|
||||
else {
|
||||
const fullPath = getNormalizedAbsolutePath(fileOrDirectoryOrSymLink.path, this.currentDirectory);
|
||||
this.ensureFolder(fullPath);
|
||||
this.ensureFolder(getDirectoryPath(fullPath), ignoreParentWatch);
|
||||
this.ensureFolder(fullPath, ignoreWatchInvokedWithTriggerAsFileCreate);
|
||||
}
|
||||
}
|
||||
|
||||
private ensureFolder(fullPath: string): FsFolder {
|
||||
private ensureFolder(fullPath: string, ignoreWatch: boolean | undefined): FsFolder {
|
||||
const path = this.toPath(fullPath);
|
||||
let folder = this.fs.get(path) as FsFolder;
|
||||
if (!folder) {
|
||||
@@ -640,8 +647,8 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
const baseFullPath = getDirectoryPath(fullPath);
|
||||
if (fullPath !== baseFullPath) {
|
||||
// Add folder in the base folder
|
||||
const baseFolder = this.ensureFolder(baseFullPath);
|
||||
this.addFileOrFolderInFolder(baseFolder, folder);
|
||||
const baseFolder = this.ensureFolder(baseFullPath, ignoreWatch);
|
||||
this.addFileOrFolderInFolder(baseFolder, folder, ignoreWatch);
|
||||
}
|
||||
else {
|
||||
// root folder
|
||||
@@ -739,7 +746,12 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
createWatcher(
|
||||
recursive ? this.fsWatchesRecursive : this.fsWatches,
|
||||
this.toFullPath(fileOrDirectory),
|
||||
{ cb, fallbackPollingInterval, fallbackOptions }
|
||||
{
|
||||
directoryName: fileOrDirectory,
|
||||
cb,
|
||||
fallbackPollingInterval,
|
||||
fallbackOptions
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1067,7 +1079,7 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
|
||||
serializeWatches(baseline: string[]) {
|
||||
serializeMultiMap(baseline, "WatchedFiles", this.watchedFiles, ({ pollingInterval }) => ({ pollingInterval }));
|
||||
serializeMultiMap(baseline, "WatchedFiles", this.watchedFiles, ({ fileName, pollingInterval }) => ({ fileName, pollingInterval }));
|
||||
baseline.push("");
|
||||
serializeMultiMap(baseline, "FsWatches", this.fsWatches, serializeTestFsWatcher);
|
||||
baseline.push("");
|
||||
@@ -1170,8 +1182,9 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
}
|
||||
|
||||
function serializeTestFsWatcher({ fallbackPollingInterval, fallbackOptions }: TestFsWatcher) {
|
||||
function serializeTestFsWatcher({ directoryName, fallbackPollingInterval, fallbackOptions }: TestFsWatcher) {
|
||||
return {
|
||||
directoryName,
|
||||
fallbackPollingInterval,
|
||||
fallbackOptions: serializeWatchOptions(fallbackOptions)
|
||||
};
|
||||
|
||||
Vendored
+2
-2
@@ -1,6 +1,6 @@
|
||||
interface Symbol {
|
||||
/**
|
||||
* expose the [[Description]] internal slot of a symbol directly
|
||||
* Expose the [[Description]] internal slot of a symbol directly.
|
||||
*/
|
||||
readonly description: string;
|
||||
readonly description: string | undefined;
|
||||
}
|
||||
|
||||
Vendored
+6
-6
@@ -966,7 +966,7 @@ declare var Error: ErrorConstructor;
|
||||
interface EvalError extends Error {
|
||||
}
|
||||
|
||||
interface EvalErrorConstructor {
|
||||
interface EvalErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): EvalError;
|
||||
(message?: string): EvalError;
|
||||
readonly prototype: EvalError;
|
||||
@@ -977,7 +977,7 @@ declare var EvalError: EvalErrorConstructor;
|
||||
interface RangeError extends Error {
|
||||
}
|
||||
|
||||
interface RangeErrorConstructor {
|
||||
interface RangeErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): RangeError;
|
||||
(message?: string): RangeError;
|
||||
readonly prototype: RangeError;
|
||||
@@ -988,7 +988,7 @@ declare var RangeError: RangeErrorConstructor;
|
||||
interface ReferenceError extends Error {
|
||||
}
|
||||
|
||||
interface ReferenceErrorConstructor {
|
||||
interface ReferenceErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): ReferenceError;
|
||||
(message?: string): ReferenceError;
|
||||
readonly prototype: ReferenceError;
|
||||
@@ -999,7 +999,7 @@ declare var ReferenceError: ReferenceErrorConstructor;
|
||||
interface SyntaxError extends Error {
|
||||
}
|
||||
|
||||
interface SyntaxErrorConstructor {
|
||||
interface SyntaxErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): SyntaxError;
|
||||
(message?: string): SyntaxError;
|
||||
readonly prototype: SyntaxError;
|
||||
@@ -1010,7 +1010,7 @@ declare var SyntaxError: SyntaxErrorConstructor;
|
||||
interface TypeError extends Error {
|
||||
}
|
||||
|
||||
interface TypeErrorConstructor {
|
||||
interface TypeErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): TypeError;
|
||||
(message?: string): TypeError;
|
||||
readonly prototype: TypeError;
|
||||
@@ -1021,7 +1021,7 @@ declare var TypeError: TypeErrorConstructor;
|
||||
interface URIError extends Error {
|
||||
}
|
||||
|
||||
interface URIErrorConstructor {
|
||||
interface URIErrorConstructor extends ErrorConstructor {
|
||||
new(message?: string): URIError;
|
||||
(message?: string): URIError;
|
||||
readonly prototype: URIError;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user