Merge branch 'master' into separate-nodetypes

This commit is contained in:
Ron Buckton authored and GitHub committed 2020-02-12 11:23:51 -08:00
commit cf6b641709
4243 files changed
+420800 -179570

No files matched your search

+2 -1
View File
@@ -29,6 +29,7 @@ scripts/processDiagnosticMessages.js
scripts/produceLKG.js
scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.js
scripts/generateLocalizedDiagnosticMessages.js
scripts/configureLanguageServiceBuild.js
scripts/*.js.map
scripts/typings/
coverage/
@@ -45,4 +46,4 @@ TEST-results.xml
package-lock.json
tests
.vscode
.git
.git
+12 -1
View File
@@ -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",
@@ -54,6 +65,7 @@
"simple-indent": "error",
"debug-assert": "error",
"no-keywords": "error",
"one-namespace-per-file": "error",
// eslint-plugin-import
"import/no-extraneous-dependencies": ["error", { "optionalDependencies": false }],
@@ -96,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",
+44 -37
View File
@@ -1,37 +1,44 @@
---
name: Bug report
about: Create a report to help us improve
---
<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨
Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker. Even if you think you've found a *bug*, please read the FAQ first, especially the Common "Bugs" That Aren't Bugs section!
Please help us by doing the following steps before logging an issue:
* Search: https://github.com/Microsoft/TypeScript/search?type=Issues
* Read the FAQ: https://github.com/Microsoft/TypeScript/wiki/FAQ
Please fill in the *entire* template below.
-->
<!-- Please try to reproduce the issue with `typescript@next`. It may have already been fixed. -->
**TypeScript Version:** 3.4.0-dev.201xxxxx
<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**
**Code**
```ts
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
```
**Expected behavior:**
**Actual behavior:**
**Playground Link:** <!-- A link to a TypeScript Playground "Share" link which demonstrates this behavior -->
**Related Issues:** <!-- Did you find other bugs that looked similar? -->
---
name: Bug
about: Create a report to help us improve TypeScript
title: ''
labels: ''
assignees: ''
---
<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨
Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker. Even if you think you've found a *bug*, please read the FAQ first, especially the Common "Bugs" That Aren't Bugs section!
Please help us by doing the following steps before logging an issue:
* Search: https://github.com/Microsoft/TypeScript/search?type=Issues
* Read the FAQ: https://github.com/Microsoft/TypeScript/wiki/FAQ
Please fill in the *entire* template below.
-->
<!--
Please try to reproduce the issue with the latest published version. It may have already been fixed.
For npm: `typescript@next`
This is also the 'Nightly' version in the playground: http://www.typescriptlang.org/play/?ts=Nightly
-->
**TypeScript Version:** 3.7.x-dev.201xxxxx
<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**
**Code**
```ts
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
```
**Expected behavior:**
**Actual behavior:**
**Playground Link:** <!-- A link to a TypeScript Playground "Share" link which demonstrates this behavior -->
**Related Issues:** <!-- Did you find other bugs that looked similar? -->
+47 -45
View File
@@ -1,45 +1,47 @@
---
name: Feature request
about: Suggest an idea for this project
---
<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨
Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker.
Please help us by doing the following steps before logging an issue:
* Search: https://github.com/Microsoft/TypeScript/search?type=Issues
* Read the FAQ, especially the "Common Feature Requests" section: https://github.com/Microsoft/TypeScript/wiki/FAQ
-->
## Search Terms
<!-- List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily -->
## Suggestion
<!-- A summary of what you'd like to see added or changed -->
## Use Cases
<!--
What do you want to use this for?
What shortcomings exist with current approaches?
-->
## Examples
<!-- Show how this would be used and what the behavior would be -->
## Checklist
My suggestion meets these guidelines:
* [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
* [ ] This wouldn't change the runtime behavior of existing JavaScript code
* [ ] This could be implemented without emitting different JS based on the types of the expressions
* [ ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
* [ ] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).
---
name: Feature Request
about: Suggest an idea
title: ''
labels: ''
assignees: ''
---
<!-- 🚨 STOP 🚨 𝗦𝗧𝗢𝗣 🚨 𝑺𝑻𝑶𝑷 🚨
Half of all issues filed here are duplicates, answered in the FAQ, or not appropriate for the bug tracker.
Please help us by doing the following steps before logging an issue:
* Search: https://github.com/Microsoft/TypeScript/search?type=Issues
* Read the FAQ, especially the "Common Feature Requests" section: https://github.com/Microsoft/TypeScript/wiki/FAQ
-->
## Search Terms
<!-- List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily -->
## Suggestion
<!-- A summary of what you'd like to see added or changed -->
## Use Cases
<!--
What do you want to use this for?
What shortcomings exist with current approaches?
-->
## Examples
<!-- Show how this would be used and what the behavior would be -->
## Checklist
My suggestion meets these guidelines:
* [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
* [ ] This wouldn't change the runtime behavior of existing JavaScript code
* [ ] This could be implemented without emitting different JS based on the types of the expressions
* [ ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
* [ ] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).
-15
View File
@@ -1,15 +0,0 @@
---
name: Question
about: The issue tracker is not for questions. Please use Stack Overflow or other resources for help writing TypeScript code.
---
THE ISSUE TRACKER IS NOT FOR QUESTIONS.
DO NOT CREATE A NEW ISSUE TO ASK A QUESTION.
IF YOU ARE HAVING PROBLEMS WITH YOUR TYPESCRIPT CODE, DO NOT ASK A QUESTION HERE.
Tens of thousands of TypeScript questions have been asked and answered on StackOverflow; see https://stackoverflow.com/questions/tagged/typescript . You can ask questions there or on other websites.
The only exception is if you have a question about *the TypeScript compiler API itself*. Please post a complete example of what you're trying to do and precisely describe what your question is.
+19
View File
@@ -0,0 +1,19 @@
---
blank_issues_enabled: false
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"
+8
View File
@@ -0,0 +1,8 @@
sandersn
elibarzilay
weswigham
andrewbranch
RyanCavanaugh
sheetalkamat
orta
rbuckton
+37
View File
@@ -0,0 +1,37 @@
name: CI
on:
push:
branches:
- master
- release-*
pull_request:
branches:
- master
- release-*
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [8.x, 10.x, 12.x]
steps:
- uses: actions/checkout@v1
with:
fetch-depth: 5
- name: Use node version ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- 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
+17 -3
View File
@@ -45,6 +45,7 @@ scripts/buildProtocol.js
scripts/ior.js
scripts/authors.js
scripts/configurePrerelease.js
scripts/configureLanguageServiceBuild.js
scripts/open-user-pr.js
scripts/open-cherry-pick-pr.js
scripts/processDiagnosticMessages.d.ts
@@ -59,9 +60,10 @@ internal/
**/.DS_Store
.settings
**/.vs
**/.vscode
**/.vscode/*
!**/.vscode/tasks.json
!**/.vscode/settings.json
!**/.vscode/settings.template.json
!**/.vscode/launch.template.json
!**/.vscode/extensions.json
!tests/cases/projects/projectOption/**/node_modules
!tests/cases/projects/NodeModulesSearch/**/*
@@ -81,4 +83,16 @@ tests/cases/user/*/**/*.d.ts
tests/baselines/reference/dt
.failed-tests
TEST-results.xml
package-lock.json
package-lock.json
tests/cases/user/TypeScript-React-Starter/TypeScript-React-Starter
tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter
tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter
tests/cases/user/TypeScript-Vue-Starter/TypeScript-Vue-Starter
tests/cases/user/TypeScript-WeChat-Starter/TypeScript-WeChat-Starter
tests/cases/user/create-react-app/create-react-app
tests/cases/user/fp-ts/fp-ts
tests/cases/user/webpack/webpack
tests/cases/user/puppeteer/puppeteer
tests/cases/user/axios-src/axios-src
tests/cases/user/prettier/prettier
.eslintcache
-40
View File
@@ -1,40 +0,0 @@
[submodule "tests/cases/user/TypeScript-React-Starter/TypeScript-React-Starter"]
path = tests/cases/user/TypeScript-React-Starter/TypeScript-React-Starter
url = https://github.com/Microsoft/TypeScript-React-Starter
ignore = all
[submodule "tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter"]
path = tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter
url = https://github.com/Microsoft/TypeScript-Node-Starter.git
ignore = all
[submodule "tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter"]
path = tests/cases/user/TypeScript-React-Native-Starter/TypeScript-React-Native-Starter
url = https://github.com/Microsoft/TypeScript-React-Native-Starter.git
ignore = all
[submodule "tests/cases/user/TypeScript-Vue-Starter/TypeScript-Vue-Starter"]
path = tests/cases/user/TypeScript-Vue-Starter/TypeScript-Vue-Starter
url = https://github.com/Microsoft/TypeScript-Vue-Starter.git
ignore = all
[submodule "tests/cases/user/TypeScript-WeChat-Starter/TypeScript-WeChat-Starter"]
path = tests/cases/user/TypeScript-WeChat-Starter/TypeScript-WeChat-Starter
url = https://github.com/Microsoft/TypeScript-WeChat-Starter.git
ignore = all
[submodule "tests/cases/user/create-react-app/create-react-app"]
path = tests/cases/user/create-react-app/create-react-app
url = https://github.com/facebook/create-react-app.git
ignore = all
[submodule "tests/cases/user/webpack/webpack"]
path = tests/cases/user/webpack/webpack
url = https://github.com/webpack/webpack.git
ignore = all
[submodule "tests/cases/user/puppeteer/puppeteer"]
path = tests/cases/user/puppeteer/puppeteer
url = https://github.com/GoogleChrome/puppeteer.git
ignore = all
[submodule "tests/cases/user/axios-src/axios-src"]
path = tests/cases/user/axios-src/axios-src
url = https://github.com/axios/axios.git
ignore = all
[submodule "tests/cases/user/prettier/prettier"]
path = tests/cases/user/prettier/prettier
url = https://github.com/prettier/prettier.git
ignore = all
+5 -1
View File
@@ -31,4 +31,8 @@ yarn.lock
CONTRIBUTING.md
TEST-results.xml
.dockerignore
Dockerfile
Dockerfile
.DS_Store
.eslintrc.json
.yarnrc
tmp
+2 -1
View File
@@ -1,6 +1,7 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
"dbaeumer.vscode-eslint",
"rbuckton.tsserver-live-reload"
],
"unwantedRecommendations": [
+60
View File
@@ -0,0 +1,60 @@
/*
Copy this file into '.vscode/launch.json' or merge its
contents into your existing configurations.
If you want to remove the errors in comments for all JSON
files, add this to your settings in ~/.vscode/User/settings.json
"files.associations": {
"*.json": "jsonc"
},
*/
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"protocol": "inspector",
"request": "launch",
"name": "Mocha Tests (currently opened test)",
"runtimeArgs": ["--nolazy"],
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",
"--no-timeouts",
"--colors",
"built/local/run.js",
"-f",
// You can change this to be the name of a specific test file (without the file extension)
// to consistently launch the same test
"${fileBasenameNoExtension}",
"--skip-percent",
"0"
],
"env": {
"NODE_ENV": "testing"
},
"sourceMaps": true,
"smartStep": true,
"preLaunchTask": "tests",
"console": "integratedTerminal",
"outFiles": [
"${workspaceRoot}/built/local/run.js"
]
},
{
// See: https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code
"type": "node",
"request": "attach",
"name": "Attach to VS Code TS Server via Port",
"processId": "${command:PickProcess}"
}
]
}
-13
View File
@@ -1,13 +0,0 @@
{
"eslint.validate": [
{
"language": "typescript",
"autoFix": true
}
],
"eslint.options": {
"rulePaths": ["../scripts/eslint/built/rules/"],
"ext": [".ts"]
},
"eslint.workingDirectories": ["./src", "./scripts"]
}
+19
View File
@@ -0,0 +1,19 @@
// Rename this file 'settings.json' or merge its
// contents into your existing settings.
{
"eslint.validate": [
{
"language": "typescript",
"autoFix": true
}
],
"eslint.options": {
"rulePaths": ["./scripts/eslint/built/rules/"],
"ext": [".ts"]
},
// To use the last-known-good (LKG) compiler version:
// "typescript.tsdk": "lib"
// To use the locally built compiler, after 'npm run build':
// "typescript.tsdk": "built/local"
}
+11 -9
View File
@@ -59,11 +59,11 @@ Run `gulp` to build a version of the compiler/language service that reflects cha
## Contributing bug fixes
TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)) by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort.
TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) or in the "Backlog milestone") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort.
## Contributing features
Features (things that add new or improved functionality to TypeScript) may be accepted, but will need to first be approved ([labelled "help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) by a TypeScript project maintainer) in the suggestion issue. Features with language design impact, or that are adequately satisfied with external tools, will not be accepted.
Features (things that add new or improved functionality to TypeScript) may be accepted, but will need to first be approved (labelled ["help wanted"](https://github.com/Microsoft/TypeScript/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) or in the "Backlog" milestone) by a TypeScript project maintainer) in the suggestion issue. Features with language design impact, or that are adequately satisfied with external tools, will not be accepted.
Design changes will not be accepted at this time. If you have a design change proposal, please log a suggestion issue.
@@ -71,19 +71,19 @@ Design changes will not be accepted at this time. If you have a design change pr
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.
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.
## Housekeeping
Your pull request should:
Your pull request should:
* Include a description of what your change intends to do
* Be a child commit of a reasonably recent commit in the **master** branch
* Be a child commit of a reasonably recent commit in the **master** branch
* Requests need not be a single commit, but should be a linear sequence of commits (i.e. no merge commits in your PR)
* It is desirable, but not necessary, for the tests to pass at each commit
* Have clear commit messages
* Have clear commit messages
* e.g. "Minor refactor in goToTypeDefinition", "Fix iterated type in for-await-of", "Add test for preserveWatchOutput on command line"
* Include adequate tests
* Include adequate tests
* At least one test should fail in the absence of your non-test code changes. If your PR does not match this criteria, please specify why
* Tests should include reasonable permutations of the target fix/change
* Include baseline changes with your change
@@ -133,7 +133,7 @@ e.g. to run all compiler baseline tests:
gulp runtests --tests=compiler
```
or to run a specific test: `tests\cases\compiler\2dArrays.ts`
or to run a specific test: `tests\cases\compiler\2dArrays.ts`
```Shell
gulp runtests --tests=2dArrays
@@ -148,7 +148,7 @@ You will probably only want to debug one test at a time:
gulp runtests-browser --tests=2dArrays
```
You can specify which browser to use for debugging. Currently Chrome and IE are supported:
You can specify which browser to use for debugging. Currently, Chrome and IE are supported:
```Shell
gulp runtests-browser --tests=2dArrays --browser=chrome
@@ -160,6 +160,8 @@ You can debug with VS Code or Node instead with `gulp runtests --inspect=true`:
gulp runtests --tests=2dArrays --inspect=true
```
You can also use the [provided VS Code launch configuration](./.vscode/launch.template.json) to launch a debug session for an open test file. Rename the file 'launch.json', open the test file of interest, and launch the debugger from the debug panel (or press F5).
## Adding a Test
To add a new test case, simply place a `.ts` file in `tests\cases\compiler` containing code that exemplifies the bugfix or change you are making.
+23 -15
View File
@@ -90,8 +90,18 @@ const localize = async () => {
}
};
const buildShims = () => buildProject("src/shims");
const cleanShims = () => cleanProject("src/shims");
cleanTasks.push(cleanShims);
const buildDebugTools = () => buildProject("src/debug");
const cleanDebugTools = () => cleanProject("src/debug");
cleanTasks.push(cleanDebugTools);
const buildShimsAndTools = parallel(buildShims, buildDebugTools);
// Pre-build steps when targeting the LKG compiler
const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics));
const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools));
const buildTsc = () => buildProject("src/tsc");
task("tsc", series(lkgPreBuild, buildTsc));
@@ -107,7 +117,7 @@ task("watch-tsc", series(lkgPreBuild, parallel(watchLib, watchDiagnostics, watch
task("watch-tsc").description = "Watch for changes and rebuild the command-line compiler only.";
// Pre-build steps when targeting the built/local compiler.
const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildTsc));
const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools, buildTsc));
// Pre-build steps to use based on supplied options.
const preBuild = cmdLineOptions.lkg ? lkgPreBuild : localPreBuild;
@@ -333,24 +343,19 @@ task("run-eslint-rules-tests").description = "Runs the eslint rule tests";
const lintFoldStart = async () => { if (fold.isTravis()) console.log(fold.start("lint")); };
const lintFoldEnd = async () => { if (fold.isTravis()) console.log(fold.end("lint")); };
/** @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",
"--cache",
"--cache-location", `${folder}/.eslintcache`,
"--format", "autolinkable-stylish",
"--rulesdir", "scripts/eslint/built/rules",
"--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");
}
@@ -463,7 +468,6 @@ task("runtests-parallel").flags = {
" --workers=<number>": "The number of parallel workers to use.",
" --timeout=<ms>": "Overrides the default test timeout.",
" --built": "Compile using the built version of the compiler.",
" --skipPercent=<number>": "Skip expensive tests with <percent> chance to miss an edit. Default 5%.",
" --shards": "Total number of shards running tests (default: 1)",
" --shardId": "1-based ID of this shard (default: 1)",
};
@@ -574,18 +578,22 @@ task("generate-spec").description = "Generates a Markdown version of the Languag
task("clean", series(parallel(cleanTasks), cleanBuilt));
task("clean").description = "Cleans build outputs";
const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.js", "dev", "package.json", "src/compiler/core.ts"]);
const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.js", "dev", "package.json", "src/compiler/corePublic.ts"]);
task("configure-nightly", series(buildScripts, configureNightly));
task("configure-nightly").description = "Runs scripts/configurePrerelease.ts to prepare a build for nightly publishing";
const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/core.ts"]);
const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/corePublic.ts"]);
task("configure-insiders", series(buildScripts, configureInsiders));
task("configure-insiders").description = "Runs scripts/configurePrerelease.ts to prepare a build for insiders publishing";
const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/core.ts"]);
const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/corePublic.ts"]);
task("configure-experimental", series(buildScripts, configureExperimental));
task("configure-experimental").description = "Runs scripts/configurePrerelease.ts to prepare a build for experimental publishing";
const createLanguageServicesBuild = () => exec(process.execPath, ["scripts/createLanguageServicesBuild.js"]);
task("create-language-services-build", series(buildScripts, createLanguageServicesBuild));
task("create-language-services-build").description = "Runs scripts/createLanguageServicesBuild.ts to prepare a build which only has the require('typescript') JS.";
const publishNightly = () => exec("npm", ["publish", "--tag", "next"]);
task("publish-nightly", series(task("clean"), task("LKG"), task("clean"), task("runtests-parallel"), publishNightly));
task("publish-nightly").description = "Runs `npm publish --tag next` to create a new nightly build on npm";
+4 -4
View File
@@ -1,16 +1,15 @@
# TypeScript
[![Join the chat at https://gitter.im/microsoft/TypeScript](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/microsoft/TypeScript?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/microsoft/TypeScript)
[![VSTS Build Status](https://dev.azure.com/typescript/TypeScript/_apis/build/status/Typescript/node10)](https://dev.azure.com/typescript/TypeScript/_build/latest?definitionId=4&view=logs)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
@@ -31,6 +30,7 @@ There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/master/CONTRIBUTING.md).
* Read the language specification ([docx](https://github.com/microsoft/TypeScript/blob/master/doc/TypeScript%20Language%20Specification.docx?raw=true),
@@ -42,7 +42,7 @@ with any additional questions or comments.
## Documentation
* [Quick tutorial](https://www.typescriptlang.org/docs/tutorial.html)
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html)
* [Language specification](https://github.com/microsoft/TypeScript/blob/master/doc/spec.md)
* [Homepage](https://www.typescriptlang.org/)
+1 -7
View File
@@ -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;
+1 -1
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.",
"Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.",
"Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.",
"Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.",
"Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set",
+1 -1
View File
@@ -1032,7 +1032,7 @@
"await_expression_is_only_allowed_within_an_async_function_1308": "Der Ausdruck \"await\" ist nur in einer asynchronen Funktion zulässig.",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungsauftrags verwendet werden.",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungszuweisung verwendet werden.",
"case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.",
"class_expressions_are_not_currently_supported_9003": "class-Ausdrücke werden zurzeit nicht unterstützt.",
"const_declarations_can_only_be_declared_inside_a_block_1156": "const-Deklarationen können nur innerhalb eines Blocks deklariert werden.",
+2 -2
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.",
"Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción return final en la función y el tipo de valor devuelto no incluye 'undefined'.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción \"return\" final en la función y el tipo de valor devuelto no incluye 'undefined'.",
"Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.",
"Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.",
"Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"",
@@ -453,7 +453,7 @@
"Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Los generadores solo están disponibles cuando el destino es ECMAScript 2015 o una versión posterior.",
"Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.",
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de instancias de tipo genérico es excesivamente profunda y posiblemente infinita.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de una instancia de tipo genérico es excesivamente profunda y posiblemente infinita.",
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Los descriptores de acceso de captador y establecedor no se corresponden respecto a la visibilidad.",
"Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.",
"Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.",
+3 -3
View File
@@ -142,7 +142,7 @@
"An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.",
"An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.",
"An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Une attribution d'exportation peut uniquement être utilisée dans un module.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Une affectation d'exportation peut uniquement être utilisée dans un module.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.",
"An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite '{0}' n'implémente pas le membre abstrait '{1}' hérité de la classe '{2}'.",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.",
"Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.",
"Not_all_code_paths_return_a_value_7030": "Les chemins du code ne retournent pas tous une valeur.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.",
"Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.",
"Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Supprimer l'étiquette inutilisée",
"Remove_variable_statement_90010": "Supprimer l'instruction de variable",
"Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins du code de la fonction ne retournent pas tous une valeur.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.",
"Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.",
"Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.",
+16 -16
View File
@@ -130,7 +130,7 @@
"Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。",
"Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。",
"Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を割り当てることはできません。",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を代入することはできません。",
"An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。",
"An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。",
"An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。",
@@ -142,10 +142,10 @@
"An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。",
"An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。",
"An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。",
"An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。",
"An_export_assignment_cannot_have_modifiers_1120": "エクスポートの割り当てに修飾子を指定することはできません。",
"An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの代入はモジュールでのみ使用可能です。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの代入は、名前空間では使用できません。",
"An_export_assignment_cannot_have_modifiers_1120": "エクスポートの代入に修飾子を指定することはできません。",
"An_export_declaration_can_only_be_used_in_a_module_1233": "エクスポート宣言はモジュールでのみ使用可能です。",
"An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。",
@@ -389,8 +389,8 @@
"Experimental_Options_6177": "試験的なオプション",
"Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'experimentalDecorators' オプションを設定してこの警告を削除します。",
"Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。",
"Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。",
"Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。",
"Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。",
@@ -399,7 +399,7 @@
"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。",
"Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。",
"Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。",
"Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。",
"Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。",
"Expression_expected_1109": "式が必要です。",
"Expression_or_comma_expected_1137": "式またはコンマが必要です。",
"Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。",
@@ -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": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。",
@@ -473,7 +473,7 @@
"Implement_interface_0_90006": "インターフェイス '{0}' を実装する",
"Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。",
"Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする",
"Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。",
"Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。",
"Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。",
"Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。",
"Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。",
@@ -536,7 +536,7 @@
"JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。",
"JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。",
"JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ pragma の使用時にサポートされていません",
"JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません",
"JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。",
"Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。",
@@ -714,7 +714,7 @@
"Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。",
"Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。",
"Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。",
"Property_assignment_expected_1136": "プロパティの割り当てが必要です。",
"Property_assignment_expected_1136": "プロパティの代入が必要です。",
"Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。",
"Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。",
"Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。",
@@ -850,7 +850,7 @@
"The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。",
"The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。",
"The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。",
"The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。",
@@ -882,7 +882,7 @@
"The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "instanceof' 式の右辺には、'any' 型、または 'Function' インターフェイス型に割り当てることができる型を指定してください。",
"The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。",
"The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "代入式のターゲットは、変数またはプロパティ アクセスである必要があります。",
"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。",
"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。",
"The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。",
"The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。",
"The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "型パラメーター '{0}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。",
@@ -1032,14 +1032,14 @@
"await_expression_is_only_allowed_within_an_async_function_1308": "'await' 式は、非同期関数内でのみ使用できます。",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化代入内のオブジェクト リテラル プロパティでのみ使用できます。",
"case_or_default_expected_1130": "'case' または 'default' が必要です。",
"class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。",
"const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。",
"const_declarations_must_be_initialized_1155": "'const' 宣言は初期化する必要があります。",
"const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。",
"const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。",
"const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。",
"const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの代入の右辺、型のクエリにのみ使用できます。",
"delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。",
"delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "これを削除します - プロジェクト '{0}' は、以前にビルドされているため、最新の状態です",
"enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。",
+2 -2
View File
@@ -885,7 +885,7 @@
"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "개체 rest 할당의 대상은 변수 또는 속성 액세스여야 합니다.",
"The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "'{0}' 형식의 'this' 컨텍스트를 메서드의 '{1}' 형식 'this'에 할당할 수 없습니다.",
"The_this_types_of_each_signature_are_incompatible_2685": "각 시그니처의 'this' 형식이 호환되지 않습니다.",
"The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "형식 매개 변수 '{0}'의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하세요.",
"The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "사용량에서 형식 매개 변수 '{0}'의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하세요.",
"The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547": "비동기 반복기의 'next()' 메서드에서 반환하는 형식은 'value' 속성이 있는 형식에 대한 프라미스여야 합니다.",
"The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490": "반복기의 'next()' 메서드에 의해 반환되는 형식에는 'value' 속성이 있어야 합니다.",
"The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189": "'for...in' 문의 변수 선언에 이니셜라이저가 포함될 수 없습니다.",
@@ -1067,7 +1067,7 @@
"or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.",
"package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.",
"package_json_has_0_field_1_that_references_2_6101": "'package.json'에 '{2}'을(를) 참조하는 '{0}' 필드 '{1}'이(가) 있습니다.",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'매개 변수 한정자'는 .ts 파일에서만 사용할 수 있습니다.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.",
"require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.",
+520 -415
View File
File diff suppressed because it is too large. Load diff
+16 -16
View File
@@ -293,37 +293,37 @@ interface WebAuthentication {
}
interface WebGL2RenderingContextBase {
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: GLuint): void;
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: GLuint): void;
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: GLuint): void;
drawBuffers(buffers: Iterable<GLenum>): void;
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): Iterable<GLuint> | null;
invalidateFramebuffer(target: GLenum, attachments: Iterable<GLenum>): void;
invalidateSubFramebuffer(target: GLenum, attachments: Iterable<GLenum>, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void;
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
uniform1uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
vertexAttribI4iv(index: GLuint, values: Iterable<GLint>): void;
vertexAttribI4uiv(index: GLuint, values: Iterable<GLuint>): void;
drawBuffers(buffers: Iterable<GLenum>): void;
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: GLuint): void;
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: GLuint): void;
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: GLuint): void;
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): Iterable<GLuint> | null;
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
}
interface WebGL2RenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform1iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
@@ -339,12 +339,12 @@ interface WebGLRenderingContextBase {
interface WebGLRenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform1iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform2iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform3iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform4iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
+4 -4
View File
@@ -30,7 +30,7 @@ interface Map<K, V> {
interface MapConstructor {
new(): Map<any, any>;
new<K, V>(entries?: ReadonlyArray<readonly [K, V]> | null): Map<K, V>;
new<K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
@@ -50,7 +50,7 @@ interface WeakMap<K extends object, V> {
}
interface WeakMapConstructor {
new <K extends object = object, V = any>(entries?: ReadonlyArray<[K, V]> | null): WeakMap<K, V>;
new <K extends object = object, V = any>(entries?: readonly [K, V][] | null): WeakMap<K, V>;
readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;
@@ -65,7 +65,7 @@ interface Set<T> {
}
interface SetConstructor {
new <T = any>(values?: ReadonlyArray<T> | null): Set<T>;
new <T = any>(values?: readonly T[] | null): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
@@ -83,7 +83,7 @@ interface WeakSet<T extends object> {
}
interface WeakSetConstructor {
new <T extends object = object>(values?: ReadonlyArray<T> | null): WeakSet<T>;
new <T extends object = object>(values?: readonly T[] | null): WeakSet<T>;
readonly prototype: WeakSet<object>;
}
declare var WeakSet: WeakSetConstructor;
+7 -7
View File
@@ -319,9 +319,9 @@ interface ObjectConstructor {
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
keys(o: {}): string[];
/**
@@ -332,7 +332,7 @@ interface ObjectConstructor {
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
@@ -349,8 +349,8 @@ interface ReadonlyArray<T> {
* @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<S extends T>(predicate: (this: void, value: T, index: number, obj: ReadonlyArray<T>) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: ReadonlyArray<T>) => unknown, thisArg?: any): T | undefined;
find<S extends T>(predicate: (this: void, value: T, index: number, obj: readonly T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
@@ -361,7 +361,7 @@ interface ReadonlyArray<T> {
* @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: T, index: number, obj: ReadonlyArray<T>) => unknown, thisArg?: any): number;
findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number;
}
interface RegExp {
+11 -11
View File
@@ -38,7 +38,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -46,7 +46,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -54,7 +54,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -62,7 +62,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -70,7 +70,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5, T6>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -78,7 +78,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4, T5>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -86,7 +86,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3, T4>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -94,7 +94,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2, T3>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -102,7 +102,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
all<T1, T2>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
@@ -110,7 +110,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>;
all<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
@@ -118,7 +118,7 @@ interface PromiseConstructor {
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: T[]): Promise<T extends PromiseLike<infer U> ? U : T>;
race<T>(values: readonly T[]): Promise<T extends PromiseLike<infer U> ? U : T>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
+7 -7
View File
@@ -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;
+1 -1
View File
@@ -23,7 +23,7 @@ interface ObjectConstructor {
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];
values<T>(o: { [s: string]: T } | ArrayLike<T>): T[];
/**
* Returns an array of values of the enumerable properties of an object
+1 -1
View File
@@ -22,7 +22,7 @@ and limitations under the License.
interface AsyncGenerator<T = unknown, TReturn = any, TNext = unknown> extends AsyncIterator<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext | PromiseLike<TNext>]): Promise<IteratorResult<T, TReturn>>;
next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return(value: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw(e: any): Promise<IteratorResult<T, TReturn>>;
[Symbol.asyncIterator](): AsyncGenerator<T, TReturn, TNext>;
+1 -1
View File
@@ -31,7 +31,7 @@ interface SymbolConstructor {
interface AsyncIterator<T, TReturn = any, TNext = undefined> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext | PromiseLike<TNext>]): Promise<IteratorResult<T, TReturn>>;
next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return?(value?: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw?(e?: any): Promise<IteratorResult<T, TReturn>>;
}
+3 -3
View File
@@ -20,14 +20,14 @@ and limitations under the License.
declare namespace Intl {
interface PluralRulesOptions {
localeMatcher?: 'lookup' | 'best fit';
type?: 'cardinal' | 'ordinal';
localeMatcher?: "lookup" | "best fit";
type?: "cardinal" | "ordinal";
}
interface ResolvedPluralRulesOptions {
locale: string;
pluralCategories: string[];
type: 'cardinal' | 'ordinal';
type: "cardinal" | "ordinal";
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
+3 -3
View File
@@ -31,7 +31,7 @@ interface ReadonlyArray<T> {
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined> (
callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray<U>,
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This
): U[]
@@ -130,7 +130,7 @@ interface ReadonlyArray<T> {
* @param depth The maximum recursion depth
*/
flat<U>(depth?: number): any[];
}
}
interface Array<T> {
@@ -145,7 +145,7 @@ interface Array<T> {
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined> (
callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray<U>,
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This
): U[]
+8 -8
View File
@@ -19,15 +19,15 @@ and limitations under the License.
interface String {
/** Removes the trailing white space and line terminator characters from a string. */
trimEnd(): string;
/** Removes the trailing white space and line terminator characters from a string. */
trimEnd(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimStart(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimStart(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimLeft(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimLeft(): string;
/** Removes the trailing white space and line terminator characters from a string. */
trimRight(): string;
/** Removes the trailing white space and line terminator characters from a string. */
trimRight(): string;
}
+629
View File
@@ -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;
}
+2
View File
@@ -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" />
+50
View File
@@ -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>[]>;
}
+6 -6
View File
@@ -21,10 +21,10 @@ and limitations under the License.
/// <reference lib="es2015.iterable" />
interface String {
/**
* Matches a string with a regular expression, and returns an iterable of matches
* containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>;
/**
* Matches a string with a regular expression, and returns an iterable of matches
* containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>;
}
+11 -11
View File
@@ -22,18 +22,18 @@ and limitations under the License.
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.matchAll method.
*/
readonly matchAll: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.matchAll method.
*/
readonly matchAll: symbol;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an iterable of matches
* containing the results of that search.
* @param string A string to search within.
*/
[Symbol.matchAll](str: string): IterableIterator<RegExpMatchArray>;
/**
* Matches a string with this regular expression, and returns an iterable of matches
* containing the results of that search.
* @param string A string to search within.
*/
[Symbol.matchAll](str: string): IterableIterator<RegExpMatchArray>;
}
+2201 -2157
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -18,6 +18,5 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
/// <reference lib="es2019" />
/// <reference lib="esnext.bigint" />
/// <reference lib="es2020" />
/// <reference lib="esnext.intl" />
+1 -1
View File
@@ -29,4 +29,4 @@ declare namespace Intl {
interface NumberFormat {
formatToParts(number?: number): NumberFormatPart[];
}
}
}
+126 -59
View File
@@ -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.
*
@@ -2222,7 +2242,7 @@ interface ImageData {
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height?: number): ImageData;
};
/** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */
@@ -2472,7 +2492,7 @@ declare var OffscreenCanvas: {
new(width: number, height: number): OffscreenCanvas;
};
interface OffscreenCanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath {
interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform {
readonly canvas: OffscreenCanvas;
commit(): void;
}
@@ -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;
@@ -3102,7 +3118,9 @@ interface TextDecoderCommon {
readonly ignoreBOM: boolean;
}
interface TextDecoderStream extends TextDecoderCommon, GenericTransformStream {
interface TextDecoderStream extends GenericTransformStream, TextDecoderCommon {
readonly readable: ReadableStream<string>;
readonly writable: WritableStream<BufferSource>;
}
declare var TextDecoderStream: {
@@ -3134,7 +3152,9 @@ interface TextEncoderCommon {
readonly encoding: string;
}
interface TextEncoderStream extends TextEncoderCommon, GenericTransformStream {
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 {
@@ -3385,7 +3411,7 @@ interface WEBGL_lose_context {
restoreContext(): void;
}
interface WebGL2RenderingContext extends WebGLRenderingContextBase, WebGL2RenderingContextBase, WebGL2RenderingContextOverloads {
interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase {
}
declare var WebGL2RenderingContext: {
@@ -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;
}
@@ -5375,7 +5429,7 @@ interface WorkerGlobalScopeEventMap {
}
/** This Web Workers API interface is an interface representing the scope of any worker. Workers have no browsing context; this scope contains the information usually conveyed by Window objects — in this case event handlers, the console or the associated WorkerNavigator object. Each WorkerGlobalScope has its own event loop. */
interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, WindowOrWorkerGlobalScope {
interface WorkerGlobalScope extends EventTarget, WindowConsole, WindowOrWorkerGlobalScope, WorkerUtils {
readonly caches: CacheStorage;
readonly isSecureContext: boolean;
readonly location: WorkerLocation;
@@ -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: {
@@ -5414,7 +5468,7 @@ declare var WorkerLocation: {
};
/** A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */
interface WorkerNavigator extends NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorStorage {
interface WorkerNavigator extends NavigatorBeacon, NavigatorConcurrentHardware, NavigatorID, NavigatorOnLine, NavigatorStorage {
readonly permissions: Permissions;
readonly serviceWorker: ServiceWorkerContainer;
}
@@ -5620,16 +5674,16 @@ declare namespace WebAssembly {
var Global: {
prototype: Global;
new(descriptor: GlobalDescriptor, value?: any): Global;
new(descriptor: GlobalDescriptor, v?: any): Global;
};
interface Instance {
readonly exports: any;
readonly exports: Exports;
}
var Instance: {
prototype: Instance;
new(module: Module, importObject?: any): Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface Memory {
@@ -5648,9 +5702,9 @@ declare namespace WebAssembly {
var Module: {
prototype: Module;
new(bytes: BufferSource): Module;
customSections(module: Module, sectionName: string): ArrayBuffer[];
exports(module: Module): ModuleExportDescriptor[];
imports(module: Module): ModuleImportDescriptor[];
customSections(moduleObject: Module, sectionName: string): ArrayBuffer[];
exports(moduleObject: Module): ModuleExportDescriptor[];
imports(moduleObject: Module): ModuleImportDescriptor[];
};
interface Table {
@@ -5667,7 +5721,7 @@ declare namespace WebAssembly {
interface GlobalDescriptor {
mutable?: boolean;
value: string;
value: ValueType;
}
interface MemoryDescriptor {
@@ -5697,11 +5751,19 @@ declare namespace WebAssembly {
module: Module;
}
type ImportExportKind = "function" | "table" | "memory" | "global";
type ImportExportKind = "function" | "global" | "memory" | "table";
type TableKind = "anyfunc";
type ValueType = "f32" | "f64" | "i32" | "i64";
type ExportValue = Function | Global | Memory | Table;
type Exports = Record<string, ExportValue>;
type ImportValue = ExportValue | number;
type ModuleImports = Record<string, ImportValue>;
type Imports = Record<string, ModuleImports>;
function compile(bytes: BufferSource): Promise<Module>;
function instantiate(bytes: BufferSource, importObject?: any): Promise<WebAssemblyInstantiatedSource>;
function instantiate(moduleObject: Module, importObject?: any): Promise<Instance>;
function compileStreaming(source: Response | Promise<Response>): Promise<Module>;
function instantiate(bytes: BufferSource, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>;
function instantiate(moduleObject: Module, importObject?: Imports): Promise<Instance>;
function instantiateStreaming(response: Response | PromiseLike<Response>, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>;
function validate(bytes: BufferSource): boolean;
}
@@ -5741,6 +5803,10 @@ interface TransformStreamDefaultControllerTransformCallback<I, O> {
(chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
}
interface VoidFunction {
(): void;
}
interface WritableStreamDefaultControllerCloseCallback {
(): void | PromiseLike<void>;
}
@@ -5795,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;
@@ -5816,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;
@@ -5841,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 VisibilityState = "hidden" | "visible" | "prerender";
type WebGLPowerPreference = "default" | "low-power" | "high-performance";
type ServiceWorkerState = "activated" | "activating" | "installed" | "installing" | "parsed" | "redundant";
type ServiceWorkerUpdateViaCache = "all" | "imports" | "none";
type VisibilityState = "hidden" | "visible";
type WebGLPowerPreference = "default" | "high-performance" | "low-power";
type WorkerType = "classic" | "module";
type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
+5 -5
View File
@@ -30,7 +30,7 @@
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorator może dekorować jedynie implementację metody, a nie przeciążenie.",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzula „default” nie może występować więcej niż raz w instrukcji „switch”.",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Eksport domyślny może być używany tylko w module w stylu języka ECMAScript.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przypisania „!” nie jest dozwolona w tym kontekście.",
"A_destructuring_declaration_must_have_an_initializer_1182": "Deklaracja usuwająca strukturę musi mieć inicjator.",
"A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Wywołanie dynamicznego importowania w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.",
"A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Wywołanie dynamicznego importowania zwraca element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.",
@@ -278,7 +278,7 @@
"Computed_property_names_are_not_allowed_in_enums_1164": "Obliczone nazwy właściwości nie są dozwolone w wyliczeniach.",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "Obliczone wartości nie są dozwolone w wyliczeniu ze składowymi o wartości ciągu.",
"Concatenate_and_emit_output_to_single_file_6001": "Połącz i wyemituj dane wyjściowe do pojedynczego pliku.",
"Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Znaleziono sprzeczne definicje dla „{0}” w „{1}” i „{2}”. Rozważ zainstalowanie konkretnej wersji tej biblioteki, aby rozwiązać problem.",
"Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090": "Znaleziono definicje będące w konflikcie dla „{0}” w „{1}” i „{2}”. Rozważ zainstalowanie konkretnej wersji tej biblioteki, aby rozwiązać problem.",
"Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013": "Dla sygnatury konstrukcji bez adnotacji zwracanego typu niejawnie określono zwracany typ „any”.",
"Constructor_implementation_is_missing_2390": "Brak implementacji konstruktora.",
"Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673": "Konstruktor klasy „{0}” jest prywatny i dostępny tylko w ramach deklaracji klasy.",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Brak implementacji funkcji lub nie występuje ona bezpośrednio po deklaracji.",
"Function_implementation_name_must_be_0_2389": "Implementacja funkcji musi mieć nazwę „{0}”.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dla funkcji niejawnie określono zwracany typ „any”, ponieważ nie zawiera ona adnotacji zwracanego typu i jest przywoływana bezpośrednio lub pośrednio w jednym z jej zwracanych wyrażeń.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji „return”, a zwracany typ nie obejmuje wartości „undefined”.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.",
"Function_overload_must_be_static_2387": "Przeciążenie funkcji musi być statyczne.",
"Function_overload_must_not_be_static_2388": "Przeciążenie funkcji nie może być statyczne.",
"Generate_get_and_set_accessors_95046": "Generuj metody dostępu „get” i „set”.",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nie można znaleźć danych wejściowych w pliku konfiguracji „{0}”. Określone ścieżki „include” to „{1}”, a „exclude” to „{2}”.",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Klasa nieabstrakcyjna „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” z klasy „{2}”.",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.",
"Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.",
"Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki w kodzie zwracają wartość.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.",
"Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.",
"Object_is_of_type_unknown_2571": "Obiekt jest typu „nieznany”.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Usuń nieużywaną etykietę",
"Remove_variable_statement_90010": "Usuń instrukcję zmiennej",
"Replace_import_with_0_95015": "Zamień import na element „{0}”.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki w kodzie zwracają wartość.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.",
"Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.",
"Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.",
+103 -20
View File
@@ -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
@@ -467,7 +470,7 @@ declare namespace ts.server.protocol {
scope: OrganizeImportsScope;
}
interface OrganizeImportsResponse extends Response {
body: ReadonlyArray<FileCodeEdits>;
body: readonly FileCodeEdits[];
}
interface GetEditsForFileRenameRequest extends Request {
command: CommandTypes.GetEditsForFileRename;
@@ -479,7 +482,7 @@ declare namespace ts.server.protocol {
readonly newFilePath: string;
}
interface GetEditsForFileRenameResponse extends Response {
body: ReadonlyArray<FileCodeEdits>;
body: readonly FileCodeEdits[];
}
/**
* Request for the available codefixes at a specific position.
@@ -526,7 +529,7 @@ declare namespace ts.server.protocol {
/**
* Errorcodes we want to get the fixes for.
*/
errorCodes: ReadonlyArray<number>;
errorCodes: readonly number[];
}
interface GetCombinedCodeFixRequestArgs {
scope: GetCombinedCodeFixScope;
@@ -643,7 +646,7 @@ declare namespace ts.server.protocol {
interface FileSpanWithContext extends FileSpan, TextSpanWithContext {
}
interface DefinitionInfoAndBoundSpan {
definitions: ReadonlyArray<FileSpanWithContext>;
definitions: readonly FileSpanWithContext[];
textSpan: TextSpan;
}
/**
@@ -652,9 +655,11 @@ declare namespace ts.server.protocol {
interface DefinitionResponse extends Response {
body?: FileSpanWithContext[];
}
interface DefinitionInfoAndBoundSpanReponse extends Response {
interface DefinitionInfoAndBoundSpanResponse extends Response {
body?: DefinitionInfoAndBoundSpan;
}
/** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */
type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse;
/**
* Definition response message. Gives text range for definition.
*/
@@ -781,7 +786,7 @@ declare namespace ts.server.protocol {
/**
* The file locations referencing the symbol.
*/
refs: ReadonlyArray<ReferencesResponseItem>;
refs: readonly ReferencesResponseItem[];
/**
* The name of the symbol.
*/
@@ -885,7 +890,7 @@ declare namespace ts.server.protocol {
/**
* An array of span groups (one per file) that refer to the item to be renamed.
*/
locs: ReadonlyArray<SpanGroup>;
locs: readonly SpanGroup[];
}
/**
* Rename response message.
@@ -955,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
*/
@@ -995,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
@@ -1364,8 +1394,8 @@ declare namespace ts.server.protocol {
commands?: {}[];
}
interface CombinedCodeActions {
changes: ReadonlyArray<FileCodeEdits>;
commands?: ReadonlyArray<{}>;
changes: readonly FileCodeEdits[];
commands?: readonly {}[];
}
interface CodeFixAction extends CodeAction {
/** Short name to identify the fix, for use by telemetry. */
@@ -1572,7 +1602,7 @@ declare namespace ts.server.protocol {
readonly isGlobalCompletion: boolean;
readonly isMemberCompletion: boolean;
readonly isNewIdentifierLocation: boolean;
readonly entries: ReadonlyArray<CompletionEntry>;
readonly entries: readonly CompletionEntry[];
}
interface CompletionDetailsResponse extends Response {
body?: CompletionEntryDetails[];
@@ -2251,7 +2281,7 @@ declare namespace ts.server.protocol {
/**
* list of packages to install
*/
packages: ReadonlyArray<string>;
packages: readonly string[];
}
interface BeginInstallTypesEventBody extends InstallTypesEventBody {
}
@@ -2267,11 +2297,49 @@ 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",
Smart = "Smart"
}
enum SemicolonPreference {
Ignore = "ignore",
Insert = "insert",
Remove = "remove"
}
interface EditorSettings {
baseIndentSize?: number;
indentSize?: number;
@@ -2297,6 +2365,7 @@ declare namespace ts.server.protocol {
placeOpenBraceOnNewLineForFunctions?: boolean;
placeOpenBraceOnNewLineForControlBlocks?: boolean;
insertSpaceBeforeTypeAnnotation?: boolean;
semicolons?: SemicolonPreference;
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
@@ -2311,7 +2380,13 @@ declare namespace ts.server.protocol {
* For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`.
*/
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/**
* Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled,
* member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined
* values, with insertion text to replace preceding `.` tokens with `?.`.
*/
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
@@ -2380,6 +2455,7 @@ declare namespace ts.server.protocol {
strictNullChecks?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
useDefineForClassFields?: boolean;
target?: ScriptTarget | ts.ScriptTarget;
traceResolution?: boolean;
resolveJsonModule?: boolean;
@@ -2532,7 +2608,11 @@ declare namespace ts.server.protocol {
string = "string"
}
interface TypeAcquisition {
export interface TypeAcquisition {
/**
* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
enableAutoDiscovery?: boolean;
enable?: boolean;
include?: string[];
@@ -2540,12 +2620,14 @@ declare namespace ts.server.protocol {
[option: string]: string[] | boolean | undefined;
}
interface FileExtensionInfo {
export interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
}
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
interface JSDocTagInfo {
name: string;
text?: string;
@@ -2560,11 +2642,11 @@ declare namespace ts.server.protocol {
[index: string]: T;
}
interface PluginImport {
export interface PluginImport {
name: string;
}
interface ProjectReference {
export interface ProjectReference {
/** A normalized path on disk */
path: string;
/** The path as the user originally wrote it */
@@ -2574,12 +2656,13 @@ declare namespace ts.server.protocol {
/** True if it is intended that this reference form a circularity */
circular?: boolean;
}
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;
+1 -1
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "A implementação da função está ausente ou não está imediatamente depois da declaração.",
"Function_implementation_name_must_be_0_2389": "O nome da implementação de função deve ser '{0}'.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "A função tem o tipo de retorno 'any', de forma implícita, porque ela não tem uma anotação de tipo de retorno e é referenciada direta ou indiretamente em uma das suas expressões de retorno.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução de retorno final e o tipo de retorno não inclui 'undefined'.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução return final e o tipo de retorno não inclui 'undefined'.",
"Function_overload_must_be_static_2387": "A sobrecarga de função deve ser estática.",
"Function_overload_must_not_be_static_2388": "A sobrecarga de função não deve ser estática.",
"Generate_get_and_set_accessors_95046": "Gerar acessadores 'get' e 'set'",
+15 -15
View File
@@ -30,7 +30,7 @@
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Декоратор может только декорировать реализацию метода, а не перегрузку.",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Предложение default не может повторяться в операторе switch.",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Экспорт по умолчанию можно использовать только в модуле в стиле ECMAScript.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного присваивания \"!\" запрещено в этом контексте.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного назначения \"!\" запрещено в этом контексте.",
"A_destructuring_declaration_must_have_an_initializer_1182": "Объявление деструктурирования должно включать инициализатор.",
"A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Для вызова динамического импорта в ES5/ES3 требуется конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".",
"A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Вызов динамического импорта возвращает конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".",
@@ -103,8 +103,8 @@
"Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super",
"Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию",
"Add_braces_to_arrow_function_95059": "Добавить скобки в стрелочную функцию",
"Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного присваивания ко всем неинициализированным свойствам",
"Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам",
"Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"",
"Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"",
"Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам",
@@ -130,7 +130,7 @@
"Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".",
"Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Объявление окружающего модуля не может содержать относительное имя модуля.",
"Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Внешний модуль не может быть вложен в другие модули или пространства имен.",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько присваиваний имен.",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько назначений имен.",
"An_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.",
"An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.",
"An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.",
@@ -142,10 +142,10 @@
"An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().",
"An_element_access_expression_should_take_an_argument_1011": "Выражение доступа к элементу должно принимать аргумент.",
"An_enum_member_cannot_have_a_numeric_name_2452": "Имя элемента перечисления не может быть числовым.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Присваивание экспорта может быть использовано только в модуле.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Присваивание экспорта нельзя использовать в пространстве имен.",
"An_export_assignment_cannot_have_modifiers_1120": "Присваивание экспорта не может иметь модификаторы.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Назначение экспорта может быть использовано только в модуле.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Назначение экспорта нельзя использовать в модуле с другими экспортированными элементами.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Назначение экспорта нельзя использовать в пространстве имен.",
"An_export_assignment_cannot_have_modifiers_1120": "Назначение экспорта не может иметь модификаторы.",
"An_export_declaration_can_only_be_used_in_a_module_1233": "Объявление экспорта может быть использовано только в модуле.",
"An_export_declaration_cannot_have_modifiers_1193": "Объявление экспорта не может иметь модификаторы.",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Расширенное escape-значение в Юникоде должно быть в пределах от 0x0 до 0x10FFFF включительно.",
@@ -390,7 +390,7 @@
"Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр experimentalDecorators, чтобы удалить это предупреждение.",
"Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Присваивание экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Назначение экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".",
"Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".",
"Export_declarations_are_not_permitted_in_a_namespace_1194": "Объявления экспорта не разрешены в пространстве имен.",
"Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Файл экспортированных внешних типизаций пакета \"{0}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Реализация функции отсутствует либо не идет сразу после объявления.",
"Function_implementation_name_must_be_0_2389": "Имя реализации функции должно иметь значение \"{0}\".",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Функция неявно имеет тип возвращаемого значения any, так как у нее нет заметки с типом возвращаемого значения, а также на нее прямо или косвенно указывает ссылка в одном из ее выражений \"return\".",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор return, а тип возвращаемого значения не включает \"undefined\".",
"Function_overload_must_be_static_2387": "Перегрузка функции должна быть статической.",
"Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.",
"Generate_get_and_set_accessors_95046": "Создать методы доступа get и set",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Не удалось найти входные данные в файле конфигурации \"{0}\". Указанные пути \"include\": \"{1}\", пути \"exclude\": \"{2}\".",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Класс \"{0}\", не являющийся абстрактным, не реализует наследуемый абстрактный элемент \"{1}\" класса \"{2}\".",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".",
"Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.",
"Not_all_code_paths_return_a_value_7030": "Не все пути к коду возвращают значение.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".",
"Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.",
"Object_is_of_type_unknown_2571": "Объект имеет тип \"Неизвестный\".",
@@ -714,7 +714,7 @@
"Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Свойство \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".",
"Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу числового индекса \"{2}\".",
"Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу строкового индекса \"{2}\".",
"Property_assignment_expected_1136": "Ожидалось присваивание свойства.",
"Property_assignment_expected_1136": "Ожидалось назначение свойства.",
"Property_destructuring_pattern_expected_1180": "Ожидался шаблон деструктурирования свойства.",
"Property_or_signature_expected_1131": "Ожидалось свойство или сигнатура.",
"Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Значение свойства может быть только строковым или числовым литералом, True, False, Null, объектным литералом либо литералом массива.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Удалить неиспользуемую метку",
"Remove_variable_statement_90010": "Удалить оператор с переменной",
"Replace_import_with_0_95015": "Замена импорта на \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути к коду в функции возвращают значение.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.",
"Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.",
"Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.",
@@ -850,7 +850,7 @@
"The_character_set_of_the_input_files_6163": "Кодировка входных файлов.",
"The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Содержащая функция или текст модуля слишком велики для анализа потока управления.",
"The_current_host_does_not_support_the_0_option_5001": "Текущий узел не поддерживает параметр \"{0}\".",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение назначения экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.",
"The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.",
@@ -1039,7 +1039,7 @@
"const_declarations_must_be_initialized_1155": "Объявления \"const\" должны быть инициализированы.",
"const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Инициализатор элементов перечисления const был вычислен в неконечное значение.",
"const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Инициализатор элементов перечисления const был вычислен в запрещенное значение NaN.",
"const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.",
"const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, назначения экспорта или запроса типа.",
"delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.",
"delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "удалить это — проект \"{0}\" не требует обновления, так как был собран ранее",
"enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений можно использовать только в TS-файле.",
+1 -1
View File
@@ -453,7 +453,7 @@
"Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Oluşturucular yalnızca ECMEAScript 2015 veya üstü hedeflenirken kullanılabilir.",
"Generic_type_0_requires_1_type_argument_s_2314": "'{0}' genel türü, {1} tür bağımsız değişkenini gerektiriyor.",
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "'{0}' genel türü {1} ile {2} arasında bağımsız değişken gerektirir.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür örneği oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.",
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Alıcı ve ayarlayıcı erişimcileri görünürlükte anlaşamıyor.",
"Global_module_exports_may_only_appear_at_top_level_1316": "Genel modül dışarı aktarmaları yalnızca en üst düzeyde görünebilir.",
"Global_module_exports_may_only_appear_in_declaration_files_1315": "Genel modül dışarı aktarmaları yalnızca bildirim dosyalarında görünebilir.",
+18060 -12123
View File
File diff suppressed because it is too large. Load diff
+27558 -17021
View File
File diff suppressed because it is too large. Load diff
+1576 -1233
View File
File diff suppressed because it is too large. Load diff
+27561 -16907
View File
File diff suppressed because it is too large. Load diff
+1386 -1156
View File
File diff suppressed because it is too large. Load diff
+26455 -16636
View File
File diff suppressed because it is too large. Load diff
+1386 -1156
View File
File diff suppressed because it is too large. Load diff
+26455 -16636
View File
File diff suppressed because it is too large. Load diff
+20080 -13380
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "函数实现缺失或未立即出现在声明之后。",
"Function_implementation_name_must_be_0_2389": "函数实现名称必须为“{0}”。",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "由于函数不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束返回语句,返回类型不包括 \"undefined\"。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束 return 语句,返回类型不包括 \"undefined\"。",
"Function_overload_must_be_static_2387": "函数重载必须为静态。",
"Function_overload_must_not_be_static_2388": "函数重载不能为静态。",
"Generate_get_and_set_accessors_95046": "生成 \"get\" 和 \"set\" 访问器",
@@ -536,7 +536,7 @@
"JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。",
"JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。",
"JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂 pragma 时,不支持 JSX 片段",
"JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段",
"JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。",
"Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。",
+33 -33
View File
@@ -1,12 +1,12 @@
{
"A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾詞無法與匯入宣告並用。",
"A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾詞無法與介面宣告並用。",
"A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾元無法與匯入宣告並用。",
"A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾元無法與介面宣告並用。",
"A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 參數必須為第一個參數。",
"A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "實作簽章中不得省略繫結模式參數。",
"A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 陳述式只可在封入的反覆項目或 switch 陳述式內使用。",
"A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 陳述式只可跳至封入之陳述式的標籤。",
"A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "類別只能實作具有選擇性型別引數的識別碼/限定名稱。",
"A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾詞的類別宣告必須要有名稱。",
"A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾元的類別宣告必須要有名稱。",
"A_class_may_only_extend_another_class_2311": "每個類別只可擴充另一個類別。",
"A_class_may_only_implement_another_class_or_interface_2422": "每個類別只可實作另一個類別或介面。",
"A_class_member_cannot_have_the_0_keyword_1248": "類別成員不能含有 '{0}' 關鍵字。",
@@ -25,8 +25,8 @@
"A_constructor_cannot_have_a_this_parameter_2681": "建構函式不能含有 'this' 參數。",
"A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 陳述式只可在封入的反覆項目陳述式內使用。",
"A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 陳述式只可跳至封入之反覆項目陳述式的標籤。",
"A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不得在現有環境內容中使用 'declare' 修飾詞。",
"A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾詞。",
"A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不得在現有環境內容中使用 'declare' 修飾元。",
"A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾元。",
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "一個裝飾項目只能裝飾一項方法實作,而不能多載。",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 子句在 'switch' 陳述式中不得出現一次以上。",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "預設匯出只能在 ECMAScript 樣式的模組中使用。",
@@ -93,15 +93,15 @@
"Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "無法透過 super 運算式存取類別 '{1}' 中的抽象方法 '{0}'。",
"Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只可出現在抽象類別中。",
"Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "無法從建構函式存取類別 '{1}' 中的抽象屬性 '{0}'。",
"Accessibility_modifier_already_seen_1028": "已有存取範圍修飾詞。",
"Accessibility_modifier_already_seen_1028": "已有存取範圍修飾元。",
"Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "只有當目標為 ECMAScript 5 及更高版本時,才可使用存取子。",
"Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。",
"Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告",
"Add_0_to_unresolved_variable_90008": "對未解析的變數新增 '{0}.'",
"Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾詞",
"Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾元",
"Add_all_missing_members_95022": "新增遺漏的所有成員",
"Add_all_missing_super_calls_95039": "新增缺少的所有 super 呼叫",
"Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式",
"Add_async_modifier_to_containing_function_90029": "將 async 修飾元新增至包含的函式",
"Add_braces_to_arrow_function_95059": "將大括號新增至箭號函式",
"Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示",
@@ -119,7 +119,7 @@
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。",
"Additional_Checks_6176": "其他檢查",
"Advanced_Options_6178": "進階選項",
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。",
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾元。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。",
"All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。",
@@ -145,20 +145,20 @@
"An_export_assignment_can_only_be_used_in_a_module_1231": "匯出指派只可用於模組中。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "匯出指派不得用於具有其他匯出項目的模組中。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "命名空間中不可使用匯出指派。",
"An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾詞。",
"An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾元。",
"An_export_declaration_can_only_be_used_in_a_module_1233": "匯出宣告只可用於模組中。",
"An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾詞。",
"An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾元。",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "擴充的 Unicode 逸出值必須介於 0x0 與 0x10FFFF (不含) 之間。",
"An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不得在環境內容中宣告實作。",
"An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "匯入宣告只可用於命名空間或模組中。",
"An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾詞。",
"An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾元。",
"An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。",
"An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引運算式引數必須是 'string'、'number'、'symbol' 或 'any' 類型。",
"An_index_signature_cannot_have_a_rest_parameter_1017": "索引簽章不得有剩餘參數。",
"An_index_signature_must_have_a_type_annotation_1021": "索引簽章必須有類型註釋。",
"An_index_signature_must_have_exactly_one_parameter_1096": "索引簽章只可有一個參數。",
"An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引簽章參數不得有問號。",
"An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾詞。",
"An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾元。",
"An_index_signature_parameter_cannot_have_an_initializer_1020": "索引簽章參數不得有初始設定式。",
"An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。",
"An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引簽章參數類型不能是類型別名。請考慮改為撰寫 '[{0}: {1}]: {2}'。",
@@ -183,7 +183,7 @@
"Array_element_destructuring_pattern_expected_1181": "必須是陣列項目解構模式。",
"Asterisk_Slash_expected_1010": "必須是 '*/'。",
"Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "全域範圍的增強指定只能在外部模組宣告或環境模組宣告直接巢狀。",
"Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾詞。",
"Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾元。",
"Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "專案 '{0}' 中已啟用鍵入的自動探索。正在使用快取位置 '{2}' 執行模組 '{1}' 的額外解析傳遞。",
"Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底類別運算式無法參考類別型別參數。",
"Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "基底建構函式傳回型別 '{0}' 不是類別或介面類型。",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "遺漏函式實作,或函式實作未緊接在宣告之後。",
"Function_implementation_name_must_be_0_2389": "函式實作名稱必須是 '{0}'。",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "函式因為沒有傳回型別註解,並在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束傳回陳述式,且傳回類型不包括 'undefined'。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束 return 陳述式,且傳回類型不包括 'undefined'。",
"Function_overload_must_be_static_2387": "函式多載必須為靜態。",
"Function_overload_must_not_be_static_2388": "函式多載不可為靜態。",
"Generate_get_and_set_accessors_95046": "產生 'get' 與 'set' 存取子",
@@ -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": "全域模組匯出只能顯示在模組檔案中。",
@@ -565,7 +565,7 @@
"Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "因為方法 '{0}' 已標記為抽象,所以不可具有實作。",
"Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "匯出介面的方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。",
"Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "匯出介面的方法 '{0}' 具有或使用私用名稱 '{1}'。",
"Modifiers_cannot_appear_here_1184": "此處不得出現修飾詞。",
"Modifiers_cannot_appear_here_1184": "此處不得出現修飾元。",
"Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "模組 '{0}' 未參考任何類型,但在此用為類型。",
"Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "模組 '{0}' 未參考任何值,但在此用為值。",
"Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模組 {0} 已匯出名為 '{1}' 的成員。請考慮明確重新匯出項目以解決模稜兩可的情形。",
@@ -1009,26 +1009,26 @@
"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。",
"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。",
"_0_list_cannot_be_empty_1097": "'{0}' 清單不得為空白。",
"_0_modifier_already_seen_1030": "已有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾詞。",
"_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾詞。",
"_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾詞。",
"_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾詞。",
"_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾詞無法與 '{1}' 修飾詞並用。",
"_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾詞無法與類別宣告並用。",
"_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾詞必須在 '{1}' 修飾詞之前。",
"_0_modifier_already_seen_1030": "已有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾元。",
"_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾元。",
"_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾元。",
"_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾元。",
"_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾元無法與 '{1}' 修飾元並用。",
"_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾元無法與類別宣告並用。",
"_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾元必須在 '{1}' 修飾元之前。",
"_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' 只參考類型,但在這裡用作命名空間。",
"_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' 只會參考類型,但此處將其用為值。",
"_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' 指的是全域的 UMD,但目前的檔案為模組。請考慮改為新增匯入。",
"_0_tag_already_specified_1223": "已指定 '{0}' 標記。",
"_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' 標記不得獨立用作頂層 JSDoc 標記。",
"_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "缺少傳回型別註解的 '{0}' 隱含了 '{1}' 傳回型別。",
"abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾詞只能出現在類別宣告、方法宣告或屬性宣告。",
"abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾元只能出現在類別宣告、方法宣告或屬性宣告。",
"await_expression_is_only_allowed_within_an_async_function_1308": "只有非同步函式才允許 'await' 運算式。",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 運算式不得用於參數初始設定式。",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 選項已設為 '{0}'。此值將用於解析非相對的模組名稱 '{1}'。",
@@ -1044,7 +1044,7 @@
"delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "刪除此項目 - 因為先前已建置專案 '{0}',所以其為最新狀態",
"enum_declarations_can_only_be_used_in_a_ts_file_8015": "「列舉宣告」只可用於 .ts 檔案中。",
"export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。",
"export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾詞無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。",
"export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾元無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。",
"extends_clause_already_seen_1172": "已經有 'extends' 子句。",
"extends_clause_must_precede_implements_clause_1173": "'extends' 子句必須在 'implements' 子句之前。",
"extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "匯出類別 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。",
@@ -1069,7 +1069,7 @@
"package_json_has_0_field_1_that_references_2_6101": "'package.json' 有參考 '{2}' 的 '{0}' 欄位 '{1}'。",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾元只能出現在屬性宣告或索引簽章。",
"require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。",
+12 -12
View File
@@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "https://www.typescriptlang.org/",
"version": "3.7.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.2.0",
"@typescript-eslint/experimental-utils": "2.2.0",
"@typescript-eslint/parser": "2.2.0",
"@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.3.0",
"eslint-formatter-autolinkable-stylish": "1.0.3",
"eslint-plugin-import": "2.18.2",
"eslint-plugin-jsdoc": "15.9.1",
"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",
@@ -92,7 +92,6 @@
"prex": "^0.4.3",
"q": "latest",
"remove-internal": "^2.9.2",
"simple-git": "^1.113.0",
"source-map-support": "latest",
"through2": "latest",
"travis-fold": "latest",
@@ -102,6 +101,7 @@
"xml2js": "^0.4.19"
},
"scripts": {
"prepare": "gulp build-eslint-rules",
"pretest": "gulp tests",
"test": "gulp runtests-parallel --light=false",
"test:eslint-rules": "gulp run-eslint-rules-tests",
@@ -116,8 +116,7 @@
"lint:ci": "gulp lint --ci",
"lint:compiler": "gulp lint-compiler",
"lint:scripts": "gulp lint-scripts",
"setup-hooks": "node scripts/link-hooks.js",
"update-costly-tests": "node scripts/costly-tests.js"
"setup-hooks": "node scripts/link-hooks.js"
},
"browser": {
"fs": false,
@@ -126,7 +125,8 @@
"crypto": false,
"buffer": false,
"@microsoft/typescript-etw": false,
"source-map-support": false
"source-map-support": false,
"inspector": false
},
"dependencies": {}
}
+8 -9
View File
@@ -4,17 +4,16 @@ const os = require("os");
/** @type {CommandLineOptions} */
module.exports = minimist(process.argv.slice(2), {
boolean: ["debug", "dirty", "inspect", "light", "colors", "lint", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built"],
string: ["browser", "tests", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"],
boolean: ["debug", "dirty", "light", "colors", "lint", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built"],
string: ["browser", "tests", "inspect", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"],
alias: {
"b": "browser",
"d": "debug", "debug-brk": "debug",
"i": "inspect", "inspect-brk": "inspect",
"t": "tests", "test": "tests",
"ru": "runners", "runner": "runners",
"d": ["debug", "debug-brk"],
"i": ["inspect", "inspect-brk"],
"t": ["tests", "test"],
"ru": ["runners", "runner"],
"r": "reporter",
"c": "colors", "color": "colors",
"skip-percent": "skipPercent",
"c": ["colors", "color"],
"skippercent": "skipPercent",
"w": "workers",
"f": "fix"
@@ -50,7 +49,6 @@ if (module.exports.built) {
* @typedef TypedOptions
* @property {boolean} debug
* @property {boolean} dirty
* @property {boolean} inspect
* @property {boolean} light
* @property {boolean} colors
* @property {boolean} lint
@@ -60,6 +58,7 @@ if (module.exports.built) {
* @property {boolean} fix
* @property {string} browser
* @property {string} tests
* @property {string} inspect
* @property {string} runners
* @property {string|number} workers
* @property {string} host
+7 -8
View File
@@ -31,7 +31,6 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode,
const inspect = cmdLineOptions.inspect;
const runners = cmdLineOptions.runners;
const light = cmdLineOptions.light;
const skipPercent = process.env.CI === "true" ? 0 : cmdLineOptions.skipPercent;
const stackTraceLimit = cmdLineOptions.stackTraceLimit;
const testConfigFile = "test.config";
const failed = cmdLineOptions.failed;
@@ -65,8 +64,8 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode,
testTimeout = 400000;
}
if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed || skipPercent !== undefined || shards || shardId) {
writeTestConfigFile(tests, runners, light, skipPercent, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout, keepFailed, shards, shardId);
if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed || shards || shardId) {
writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, testTimeout, keepFailed, shards, shardId);
}
const colors = cmdLineOptions.colors;
@@ -90,11 +89,13 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode,
else {
args.push("--no-colors");
}
if (inspect) {
args.unshift("--inspect-brk");
if (inspect !== undefined) {
args.unshift(inspect == "" ? "--inspect-brk" : "--inspect-brk="+inspect);
args.push("-t", "0");
}
else if (debug) {
args.unshift("--debug-brk");
args.push("-t", "0");
}
else {
args.push("-t", "" + testTimeout);
@@ -161,7 +162,6 @@ exports.cleanTestDirs = cleanTestDirs;
* @param {string} tests
* @param {string} runners
* @param {boolean} light
* @param {string} skipPercent
* @param {string} [taskConfigsFolder]
* @param {string | number} [workerCount]
* @param {string} [stackTraceLimit]
@@ -170,12 +170,11 @@ exports.cleanTestDirs = cleanTestDirs;
* @param {number | undefined} [shards]
* @param {number | undefined} [shardId]
*/
function writeTestConfigFile(tests, runners, light, skipPercent, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
const testConfigContents = JSON.stringify({
test: tests ? [tests] : undefined,
runners: runners ? runners.split(",") : undefined,
light,
skipPercent,
workerCount,
stackTraceLimit,
taskConfigsFolder,
+1 -1
View File
@@ -8,7 +8,7 @@ const mkdirp = require("mkdirp");
const del = require("del");
const File = require("vinyl");
const ts = require("../../lib/typescript");
const { default: chalk } = require("chalk");
const chalk = require("chalk");
const { spawn } = require("child_process");
const { CancellationToken, CancelError, Deferred } = require("prex");
const { Readable, Duplex } = require("stream");
+87
View File
@@ -0,0 +1,87 @@
/// <reference types="node"/>
import { normalize, dirname, join } from "path";
import { readFileSync, writeFileSync, unlinkSync, existsSync } from "fs";
import assert = require("assert");
import { execSync } from "child_process";
const args = process.argv.slice(2);
/**
* A minimal description for a parsed package.json object.
*/
interface PackageJson {
name: string;
bin: {};
main: string;
scripts: {
prepare: string
postpublish: string
}
}
function main(): void {
if (args.length < 1) {
console.log("Usage:");
console.log("\tnode configureTSCBuild.js <package.json location>");
return;
}
// Acquire the version from the package.json file and modify it appropriately.
const packageJsonFilePath = normalize(args[0]);
const packageJsonValue: PackageJson = JSON.parse(readFileSync(packageJsonFilePath).toString());
// Remove the bin section from the current package
delete packageJsonValue.bin;
// We won't be running eslint which would run before publishing
delete packageJsonValue.scripts.prepare;
// No infinite loops
delete packageJsonValue.scripts.postpublish;
// Set the new name
packageJsonValue.name = "@typescript/language-services";
writeFileSync(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4));
// Remove the files which aren't use when just using the API
const toRemove = [
// JS Files
"tsserver.js",
"tsserverlibrary.js",
"typescriptServices.js",
"typingsInstaller.js",
"tsc.js",
// DTS files
"typescriptServices.d.ts",
"tsserverlibrary.d.ts"
];
// Get a link to the main dependency JS file
const lib = join(dirname(packageJsonFilePath), packageJsonValue.main);
const libPath = dirname(lib);
// Remove the sibling JS large files referenced above
toRemove.forEach(file => {
const path = join(libPath, file);
if (existsSync(path)) unlinkSync(path);
});
// Remove VS-specific localization keys
execSync("rm -rf loc", { cwd: dirname(packageJsonFilePath) });
// Remove runnable file reference
execSync("rm -rf bin", { cwd: dirname(packageJsonFilePath) });
///////////////////////////////////
// This section verifies that the build of TypeScript compiles and emits
const ts = require(lib);
const source = "let x: string = 'string'";
const results = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS }
});
assert(results.outputText.trim() === "var x = 'string';", `Running typescript with ${packageJsonValue.name} did not return the expected results, got: ${results.outputText}`);
}
main();
+5 -5
View File
@@ -1,9 +1,7 @@
/// <reference types="node"/>
import { normalize } from "path";
import { normalize, relative } from "path";
import assert = require("assert");
import { readFileSync, writeFileSync } from "fs";
const args = process.argv.slice(2);
/**
* A minimal description for a parsed package.json object.
@@ -15,9 +13,11 @@ interface PackageJson {
}
function main(): void {
const args = process.argv.slice(2);
if (args.length < 3) {
const thisProgramName = relative(process.cwd(), __filename);
console.log("Usage:");
console.log("\tnode configureNightly.js <dev|insiders> <package.json location> <file containing version>");
console.log(`\tnode ${thisProgramName} <dev|insiders> <package.json location> <file containing version>`);
return;
}
@@ -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];
-103
View File
@@ -1,103 +0,0 @@
// @ts-check
const fs = require("fs");
const git = require('simple-git/promise')('.')
const readline = require('readline')
/** @typedef {{ [s: string]: number}} Histogram */
async function main() {
/** @type {Histogram} */
const edits = Object.create(null)
/** @type {Histogram} */
const perf = JSON.parse(fs.readFileSync('.parallelperf.json', 'utf8'))
await collectCommits(git, "release-2.3", "master", /*author*/ undefined, files => fillMap(files, edits))
const totalTime = Object.values(perf).reduce((n,m) => n + m, 0)
const untouched = Object.values(perf).length - Object.values(edits).length
const totalEdits = Object.values(edits).reduce((n,m) => n + m, 0) + untouched + Object.values(edits).length
let i = 0
/** @type {{ name: string, time: number, edits: number, cost: number }[]} */
let data = []
for (const k in perf) {
const otherk = k.replace(/tsrunner-[a-z-]+?:\/\//, '')
const percentTime = perf[k] / totalTime
const percentHits = (1 + (edits[otherk] || 0)) / totalEdits
const cost = 5 + Math.log(percentTime / percentHits)
data.push({ name: otherk, time: perf[k], edits: 1 + (edits[otherk] || 0), cost})
if (edits[otherk])
i++
}
const output = {
totalTime,
totalEdits,
data: data.sort((x,y) => y.cost - x.cost).map(x => ({ ...x, cost: x.cost.toFixed(2) }))
}
fs.writeFileSync('tests/.test-cost.json', JSON.stringify(output), 'utf8')
}
main().catch(e => {
console.log(e);
process.exit(1);
})
/**
* @param {string[]} files
* @param {Histogram} histogram
*/
function fillMap(files, histogram) {
// keep edits to test cases (but not /users), and not file moves
const tests = files.filter(f => f.startsWith('tests/cases/') && !f.startsWith('tests/cases/user') && !/=>/.test(f))
for (const test of tests) {
histogram[test] = (histogram[test] || 0) + 1
}
}
/**
* @param {string} s
*/
function isSquashMergeMessage(s) {
return /\(#[0-9]+\)$/.test(s)
}
/**
* @param {string} s
*/
function isMergeCommit(s) {
return /Merge pull request #[0-9]+/.test(s)
}
/**
* @param {string} s
*/
function parseFiles(s) {
const lines = s.split('\n')
// Note that slice(2) only works for merge commits, which have an empty newline after the title
return lines.slice(2, lines.length - 2).map(line => line.split("|")[0].trim())
}
/**
* @param {import('simple-git/promise').SimpleGit} git
* @param {string} from
* @param {string} to
* @param {string | undefined} author - only include commits from this author
* @param {(files: string[]) => void} update
*/
async function collectCommits(git, from, to, author, update) {
let i = 0
for (const commit of (await git.log({ from, to })).all) {
i++
if ((!author || commit.author_name === author) && isMergeCommit(commit.message) || isSquashMergeMessage(commit.message)) {
readline.clearLine(process.stdout, /*left*/ -1)
readline.cursorTo(process.stdout, 0)
process.stdout.write(i + ": " + commit.date)
const files = parseFiles(await git.show([commit.hash, "--stat=1000,960,40", "--pretty=oneline"]))
update(files)
}
}
}
@@ -0,0 +1,44 @@
import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/experimental-utils";
import { createRule } from "./utils";
export = createRule({
name: "one-namespace-per-file",
meta: {
docs: {
description: `Limits each file to having at most one top-level namespace declaration`,
category: "Possible Errors",
recommended: "error",
},
messages: {
excessNamespaceError: `All but one of these namespaces should be moved into separate files.`,
},
schema: [],
type: "problem",
},
defaultOptions: [],
create(context) {
const isNamespaceDeclaration = (node: TSESTree.Node): node is TSESTree.TSModuleDeclaration => node.type === AST_NODE_TYPES.TSModuleDeclaration;
const checkSourceFile = (node: TSESTree.Program) => {
if (context.getFilename().endsWith(".d.ts")) {
return;
}
const members = node.body;
const namespaces = members.filter(isNamespaceDeclaration);
if (namespaces.length <= 1) {
return;
}
namespaces.forEach(n => {
context.report({
messageId: "excessNamespaceError", node: n
});
});
};
return {
Program: checkSourceFile,
};
},
});
Regular → Executable
+2 -2
View File
@@ -1,2 +1,2 @@
#!/bin/sh
npm run gulp -- generate-diagnostics
#!/bin/sh
npm run gulp -- generate-diagnostics
+20 -9
View File
@@ -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,34 @@ async function main() {
const currentAuthor = runSequence([
["git", ["log", "-1", `--pretty="%aN <%aE>"`]]
]);
const gh = new Octokit();
gh.authenticate({
type: "token",
token: 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 +83,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",
+10 -2
View File
@@ -28,8 +28,12 @@ async function main() {
type: "token",
token: process.argv[2]
});
// Please keep the strings "an installable tgz" and "packed" in this message, as well as the devDependencies section,
// so that the playgrounds deployment process can find these comments.
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 packed this into [an installable tgz](${link}). You can install it for testing by referencing it in your \`package.json\` like so:
@@ -43,6 +47,10 @@ async function main() {
and then running \`npm install\`.
`
});
// Temporarily disable until we get access controls set up right
// Send a ping to https://github.com/orta/make-monaco-builds#pull-request-builds
await gh.request("POST /repos/orta/make-monaco-builds/dispatches", { event_type: process.env.SOURCE_ISSUE, headers: { Accept: "application/vnd.github.everest-preview+json" }});
}
main().catch(async e => {
@@ -61,4 +69,4 @@ main().catch(async e => {
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)).`
});
}
});
});
+6 -4
View File
@@ -6,6 +6,7 @@ interface DiagnosticDetails {
code: number;
reportsUnnecessary?: {};
isEarly?: boolean;
elidedInCompatabilityPyramid?: boolean;
}
type InputDiagnosticMessageTable = Map<string, DiagnosticDetails>;
@@ -63,14 +64,15 @@ function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, inputFil
"// generated from '" + inputFilePathRel + "' by '" + thisFilePathRel.replace(/\\/g, "/") + "'\r\n" +
"/* @internal */\r\n" +
"namespace ts {\r\n" +
" function diag(code: number, category: DiagnosticCategory, key: string, message: string, reportsUnnecessary?: {}): DiagnosticMessage {\r\n" +
" return { code, category, key, message, reportsUnnecessary };\r\n" +
" function diag(code: number, category: DiagnosticCategory, key: string, message: string, reportsUnnecessary?: {}, elidedInCompatabilityPyramid?: boolean): DiagnosticMessage {\r\n" +
" return { code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid };\r\n" +
" }\r\n" +
" export const Diagnostics = {\r\n";
messageTable.forEach(({ code, category, reportsUnnecessary }, name) => {
messageTable.forEach(({ code, category, reportsUnnecessary, elidedInCompatabilityPyramid }, name) => {
const propName = convertPropertyName(name);
const argReportsUnnecessary = reportsUnnecessary ? `, /*reportsUnnecessary*/ ${reportsUnnecessary}` : "";
result += ` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}${argReportsUnnecessary}),\r\n`;
const argElidedInCompatabilityPyramid = elidedInCompatabilityPyramid ? `${!reportsUnnecessary ? ", /*reportsUnnecessary*/ undefined" : ""}, /*elidedInCompatabilityPyramid*/ ${elidedInCompatabilityPyramid}` : "";
result += ` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}${argReportsUnnecessary}${argElidedInCompatabilityPyramid}),\r\n`;
});
result += " };\r\n}";
+6 -1
View File
@@ -76,10 +76,15 @@ declare module "undertaker" {
interface TaskFunctionParams {
flags?: Record<string, string>;
}
interface TaskFunctionWrapped {
description: string
flags: { [name: string]: string }
}
}
declare module "gulp-sourcemaps" {
interface WriteOptions {
destPath?: string;
}
}
}
-11
View File
@@ -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"
}
}
+8
View File
@@ -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"],
+8 -7
View File
@@ -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 {
+693 -283
View File
File diff suppressed because it is too large. Load diff
+86 -241
View File
@@ -20,7 +20,7 @@ namespace ts {
export interface ReusableBuilderProgramState extends ReusableBuilderState {
/**
* Cache of semantic diagnostics for files with their Path being the key
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile?: ReadonlyMap<readonly ReusableDiagnostic[] | readonly Diagnostic[]> | undefined;
/**
@@ -85,7 +85,7 @@ namespace ts {
// TODO: GH#18217 Properties of this interface are frequently asserted to be defined.
export interface BuilderProgramState extends BuilderState {
/**
* Cache of semantic diagnostics for files with their Path being the key
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile: Map<readonly Diagnostic[]> | undefined;
/**
@@ -173,8 +173,7 @@ namespace ts {
const compilerOptions = newProgram.getCompilerOptions();
state.compilerOptions = compilerOptions;
// With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
// With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors
if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) {
if (!compilerOptions.outFile && !compilerOptions.out) {
state.semanticDiagnosticsPerFile = createMap<readonly Diagnostic[]>();
}
state.changedFilesSet = createMap<true>();
@@ -247,17 +246,18 @@ namespace ts {
if (oldCompilerOptions && compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
// Add all files to affectedFilesPendingEmit since emit changed
newProgram.getSourceFiles().forEach(f => addToAffectedFilesPendingEmit(state, f.path, BuilderFileEmit.Full));
newProgram.getSourceFiles().forEach(f => addToAffectedFilesPendingEmit(state, f.resolvedPath, BuilderFileEmit.Full));
Debug.assert(state.seenAffectedFiles === undefined);
state.seenAffectedFiles = createMap<true>();
}
state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
return state;
}
function convertToDiagnostics(diagnostics: readonly ReusableDiagnostic[], newProgram: Program, getCanonicalFileName: GetCanonicalFileName): readonly Diagnostic[] {
if (!diagnostics.length) return emptyArray;
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getOutputPathForBuildInfo(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
return diagnostics.map(diagnostic => {
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
@@ -321,7 +321,7 @@ namespace ts {
* Verifies that source file is ok to be used in calls that arent handled by next
*/
function assertSourceFileOkWithoutNextAffectedCall(state: BuilderProgramState, sourceFile: SourceFile | undefined) {
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex! - 1] !== sourceFile || !state.semanticDiagnosticsPerFile!.has(sourceFile.path));
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex! - 1] !== sourceFile || !state.semanticDiagnosticsPerFile!.has(sourceFile.resolvedPath));
}
/**
@@ -338,7 +338,7 @@ namespace ts {
let affectedFilesIndex = state.affectedFilesIndex!; // TODO: GH#18217
while (affectedFilesIndex < affectedFiles.length) {
const affectedFile = affectedFiles[affectedFilesIndex];
if (!seenAffectedFiles.has(affectedFile.path)) {
if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
// Set the next affected file as seen and remove the cached semantic diagnostics
state.affectedFilesIndex = affectedFilesIndex;
handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
@@ -395,8 +395,8 @@ namespace ts {
for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) {
const affectedFile = Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
if (affectedFile) {
const seenKind = seenEmittedFiles.get(affectedFile.path);
const emitKind = Debug.assertDefined(Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.path));
const seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
const emitKind = Debug.assertDefined(Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
if (seenKind === undefined || seenKind < emitKind) {
// emit this file
state.affectedFilesPendingEmitIndex = i;
@@ -416,7 +416,7 @@ namespace ts {
* This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
*/
function handleDtsMayChangeOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash) {
removeSemanticDiagnosticsOf(state, affectedFile.path);
removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
// If affected files is everything except default library, then nothing more to do
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
@@ -426,14 +426,16 @@ namespace ts {
const options = program.getCompilerOptions();
forEach(program.getSourceFiles(), f =>
program.isSourceFileDefaultLibrary(f) &&
!skipTypeChecking(f, options) &&
removeSemanticDiagnosticsOf(state, f.path)
!skipTypeChecking(f, options, program) &&
removeSemanticDiagnosticsOf(state, f.resolvedPath)
);
}
return;
}
forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, (state, path) => handleDtsMayChangeOf(state, path, cancellationToken, computeHash));
if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, (state, path) => handleDtsMayChangeOf(state, path, cancellationToken, computeHash));
}
}
/**
@@ -483,23 +485,50 @@ namespace ts {
return !state.semanticDiagnosticsFromOldState.size;
}
function isChangedSignagure(state: BuilderProgramState, path: Path) {
const newSignature = Debug.assertDefined(state.currentAffectedFilesSignatures).get(path);
const oldSignagure = Debug.assertDefined(state.fileInfos.get(path)).signature;
return newSignature !== oldSignagure;
}
/**
* Iterate on referencing modules that export entities from affected file
*/
function forEachReferencingModulesOfExportOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, fn: (state: BuilderProgramState, filePath: Path) => boolean) {
// If there was change in signature (dts output) for the changed file,
// then only we need to handle pending file emit
if (!state.exportedModulesMap || state.affectedFiles!.length === 1 || !state.changedFilesSet.has(affectedFile.path)) {
if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
return;
}
if (!isChangedSignagure(state, affectedFile.resolvedPath)) return;
// Since isolated modules dont change js files, files affected by change in signature is itself
// But we need to cleanup semantic diagnostics and queue dts emit for affected files
if (state.compilerOptions.isolatedModules) {
const seenFileNamesMap = createMap<true>();
seenFileNamesMap.set(affectedFile.resolvedPath, true);
const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
while (queue.length > 0) {
const currentPath = queue.pop()!;
if (!seenFileNamesMap.has(currentPath)) {
seenFileNamesMap.set(currentPath, true);
const result = fn(state, currentPath);
if (result && isChangedSignagure(state, currentPath)) {
const currentSourceFile = Debug.assertDefined(state.program).getSourceFileByPath(currentPath)!;
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
}
}
}
}
Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
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) =>
exportedModules &&
exportedModules.has(affectedFile.path) &&
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
)) {
return;
@@ -508,7 +537,7 @@ namespace ts {
// If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
forEachEntry(state.exportedModulesMap, (exportedModules, exportedFromPath) =>
!state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it
exportedModules.has(affectedFile.path) &&
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
);
}
@@ -583,9 +612,9 @@ namespace ts {
state.programEmitComplete = true;
}
else {
state.seenAffectedFiles!.set((affected as SourceFile).path, true);
state.seenAffectedFiles!.set((affected as SourceFile).resolvedPath, true);
if (emitKind !== undefined) {
(state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).path, emitKind);
(state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).resolvedPath, emitKind);
}
if (isPendingEmit) {
state.affectedFilesPendingEmitIndex!++;
@@ -620,21 +649,32 @@ namespace ts {
}
/**
* Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it
* Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set
* Gets semantic diagnostics for the file which are
* bindAndCheckDiagnostics (from cache) and program diagnostics
*/
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
const path = sourceFile.path;
return concatenate(
getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken),
Debug.assertDefined(state.program).getProgramDiagnostics(sourceFile)
);
}
/**
* Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
* Note that it is assumed that when asked about binder and checker diagnostics, the file has been taken out of affected files/changed file set
*/
function getBinderAndCheckerDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
const path = sourceFile.resolvedPath;
if (state.semanticDiagnosticsPerFile) {
const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
// Report the semantic diagnostics from the cache if we already have those diagnostics present
// Report the bind and check diagnostics from the cache if we already have those diagnostics present
if (cachedDiagnostics) {
return cachedDiagnostics;
}
}
// Diagnostics werent cached, get them from program, and cache the result
const diagnostics = Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
const diagnostics = Debug.assertDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
if (state.semanticDiagnosticsPerFile) {
state.semanticDiagnosticsPerFile.set(path, diagnostics);
}
@@ -656,7 +696,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 buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getOutputPathForBuildInfo(state.compilerOptions)!, currentDirectory));
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory));
const fileInfos: MapLike<BuilderState.FileInfo> = {};
state.fileInfos.forEach((value, key) => {
const signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
@@ -716,7 +756,7 @@ namespace ts {
function convertToReusableCompilerOptions(options: CompilerOptions, relativeToBuildInfo: (path: string) => string) {
const result: CompilerOptions = {};
const optionsNameMap = getOptionNameMap().optionNameMap;
const { optionsNameMap } = getOptionsNameMap();
for (const name in options) {
if (hasProperty(options, name)) {
@@ -768,7 +808,7 @@ namespace ts {
const { file } = diagnostic;
return {
...diagnostic,
file: file ? relativeToBuildInfo(file.path) : undefined
file: file ? relativeToBuildInfo(file.resolvedPath) : undefined
};
}
@@ -844,36 +884,36 @@ namespace ts {
oldProgram = undefined;
oldState = undefined;
const result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
result.getState = () => state;
result.backupState = () => {
const builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
builderProgram.getState = () => state;
builderProgram.backupState = () => {
Debug.assert(backupState === undefined);
backupState = cloneBuilderProgramState(state);
};
result.restoreState = () => {
builderProgram.restoreState = () => {
state = Debug.assertDefined(backupState);
backupState = undefined;
};
result.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile);
result.getSemanticDiagnostics = getSemanticDiagnostics;
result.emit = emit;
result.releaseProgram = () => {
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile);
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
builderProgram.emit = emit;
builderProgram.releaseProgram = () => {
releaseCache(state);
backupState = undefined;
};
if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
(result as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
(builderProgram as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
}
else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
(result as EmitAndSemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
(result as EmitAndSemanticDiagnosticsBuilderProgram).emitNextAffectedFile = emitNextAffectedFile;
(builderProgram as EmitAndSemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
(builderProgram as EmitAndSemanticDiagnosticsBuilderProgram).emitNextAffectedFile = emitNextAffectedFile;
}
else {
notImplemented();
}
return result;
return builderProgram;
/**
* Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
@@ -909,11 +949,7 @@ namespace ts {
}
else {
const program = Debug.assertDefined(state.program);
// Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes
if (state.programEmitComplete || !some(program.getProjectReferences(), ref => !!ref.prepend)) {
state.programEmitComplete = true;
return undefined;
}
if (state.programEmitComplete) return undefined;
affected = program;
}
}
@@ -949,6 +985,8 @@ namespace ts {
function emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult {
if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
const result = handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
if (result) return result;
if (!targetSourceFile) {
// Emit and report any errors we ran into.
let sourceMaps: SourceMapEmitResult[] = [];
@@ -996,7 +1034,7 @@ namespace ts {
// Add file to affected file pending emit to handle for later emit time
if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
addToAffectedFilesPendingEmit(state, (affected as SourceFile).path, BuilderFileEmit.Full);
addToAffectedFilesPendingEmit(state, (affected as SourceFile).resolvedPath, BuilderFileEmit.Full);
}
// Get diagnostics for the affected file if its not ignored
@@ -1092,7 +1130,7 @@ namespace ts {
const state: ReusableBuilderProgramState = {
fileInfos,
compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath),
compilerOptions: convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toPath(isString(value) ? value : value[0]), value => isString(value) ? emptyArray : value[1]),
@@ -1119,6 +1157,7 @@ namespace ts {
getCurrentDirectory: notImplemented,
emitNextAffectedFile: notImplemented,
getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
close: noop,
};
function toPath(path: string) {
@@ -1130,40 +1169,6 @@ namespace ts {
}
}
function convertFromReusableCompilerOptions(options: CompilerOptions, toAbsolutePath: (path: string) => string) {
const result: CompilerOptions = {};
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
if (hasProperty(options, name)) {
result[name] = convertFromReusableCompilerOptionValue(
optionsNameMap.get(name.toLowerCase()),
options[name] as CompilerOptionsValue,
toAbsolutePath
);
}
}
if (result.configFilePath) {
result.configFilePath = toAbsolutePath(result.configFilePath);
}
return result;
}
function convertFromReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) {
if (option) {
if (option.type === "list") {
const values = value as readonly (string | number)[];
if (option.element.isFilePath && values.length) {
return values.map(toAbsolutePath);
}
}
else if (option.isFilePath) {
return toAbsolutePath(value as string);
}
}
return value;
}
export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram {
return {
getState: notImplemented,
@@ -1184,6 +1189,7 @@ namespace ts {
emit: (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers),
getAllDependencies: notImplemented,
getCurrentDirectory: () => getProgram().getCurrentDirectory(),
close: noop,
};
function getProgram() {
@@ -1191,164 +1197,3 @@ namespace ts {
}
}
}
namespace ts {
export type AffectedFileResult<T> = { result: T; affected: SourceFile | Program; } | undefined;
export interface BuilderProgramHost {
/**
* return true if file names are treated with case sensitivity
*/
useCaseSensitiveFileNames(): boolean;
/**
* If provided this would be used this hash instead of actual file shape text for detecting changes
*/
createHash?: (data: string) => string;
/**
* When emit or emitNextAffectedFile are called without writeFile,
* this callback if present would be used to write files
*/
writeFile?: WriteFileCallback;
}
/**
* Builder to manage the program state changes
*/
export interface BuilderProgram {
/*@internal*/
getState(): ReusableBuilderProgramState;
/*@internal*/
backupState(): void;
/*@internal*/
restoreState(): void;
/**
* Returns current program
*/
getProgram(): Program;
/**
* Returns current program that could be undefined if the program was released
*/
/*@internal*/
getProgramOrUndefined(): Program | undefined;
/**
* Releases reference to the program, making all the other operations that need program to fail.
*/
/*@internal*/
releaseProgram(): void;
/**
* Get compiler options of the program
*/
getCompilerOptions(): CompilerOptions;
/**
* Get the source file in the program with file name
*/
getSourceFile(fileName: string): SourceFile | undefined;
/**
* Get a list of files in the program
*/
getSourceFiles(): readonly SourceFile[];
/**
* Get the diagnostics for compiler options
*/
getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the diagnostics that dont belong to any file
*/
getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the diagnostics from config file parsing
*/
getConfigFileParsingDiagnostics(): readonly Diagnostic[];
/**
* Get the syntax diagnostics, for all source files if source file is not supplied
*/
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the declaration diagnostics, for all source files if source file is not supplied
*/
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
/**
* Get all the dependencies of the file
*/
getAllDependencies(sourceFile: SourceFile): readonly string[];
/**
* Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
* The semantic diagnostics are cached and managed here
* Note that it is assumed that when asked about semantic diagnostics through this API,
* the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
* In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
* it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
*/
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Emits the JavaScript and declaration files.
* When targetSource file is specified, emits the files corresponding to that source file,
* otherwise for the whole program.
* In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
* it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
* it will only emit all the affected files instead of whole program
*
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
/**
* Get the current directory of the program
*/
getCurrentDirectory(): string;
}
/**
* The builder that caches the semantic diagnostics for the program and handles the changed files and affected files
*/
export interface SemanticDiagnosticsBuilderProgram extends BuilderProgram {
/**
* Gets the semantic diagnostics from the program for the next affected file and caches it
* Returns undefined if the iteration is complete
*/
getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult<readonly Diagnostic[]>;
}
/**
* The builder that can handle the changes in program and iterate through changed file to emit the files
* The semantic diagnostics are cached per file and managed by clearing for the changed/affected files
*/
export interface EmitAndSemanticDiagnosticsBuilderProgram extends SemanticDiagnosticsBuilderProgram {
/**
* Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult<EmitResult>;
}
/**
* Create the builder to manage semantic diagnostics and cache them
*/
export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): SemanticDiagnosticsBuilderProgram;
export function createSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): SemanticDiagnosticsBuilderProgram;
export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) {
return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
/**
* Create the builder that can handle the changes in program and iterate through changed files
* to emit the those files and manage semantic diagnostics cache as well
*/
export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): EmitAndSemanticDiagnosticsBuilderProgram;
export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): EmitAndSemanticDiagnosticsBuilderProgram;
export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) {
return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
/**
* Creates a builder thats just abstraction over program and can be used with watch
*/
export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): BuilderProgram;
export function createAbstractBuilder(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram;
export function createAbstractBuilder(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram {
const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences);
return createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
}
}
+162
View File
@@ -0,0 +1,162 @@
namespace ts {
export type AffectedFileResult<T> = { result: T; affected: SourceFile | Program; } | undefined;
export interface BuilderProgramHost {
/**
* return true if file names are treated with case sensitivity
*/
useCaseSensitiveFileNames(): boolean;
/**
* If provided this would be used this hash instead of actual file shape text for detecting changes
*/
createHash?: (data: string) => string;
/**
* When emit or emitNextAffectedFile are called without writeFile,
* this callback if present would be used to write files
*/
writeFile?: WriteFileCallback;
}
/**
* Builder to manage the program state changes
*/
export interface BuilderProgram {
/*@internal*/
getState(): ReusableBuilderProgramState;
/*@internal*/
backupState(): void;
/*@internal*/
restoreState(): void;
/**
* Returns current program
*/
getProgram(): Program;
/**
* Returns current program that could be undefined if the program was released
*/
/*@internal*/
getProgramOrUndefined(): Program | undefined;
/**
* Releases reference to the program, making all the other operations that need program to fail.
*/
/*@internal*/
releaseProgram(): void;
/**
* Get compiler options of the program
*/
getCompilerOptions(): CompilerOptions;
/**
* Get the source file in the program with file name
*/
getSourceFile(fileName: string): SourceFile | undefined;
/**
* Get a list of files in the program
*/
getSourceFiles(): readonly SourceFile[];
/**
* Get the diagnostics for compiler options
*/
getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the diagnostics that dont belong to any file
*/
getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the diagnostics from config file parsing
*/
getConfigFileParsingDiagnostics(): readonly Diagnostic[];
/**
* Get the syntax diagnostics, for all source files if source file is not supplied
*/
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Get the declaration diagnostics, for all source files if source file is not supplied
*/
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
/**
* Get all the dependencies of the file
*/
getAllDependencies(sourceFile: SourceFile): readonly string[];
/**
* Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
* The semantic diagnostics are cached and managed here
* Note that it is assumed that when asked about semantic diagnostics through this API,
* the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
* In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
* it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
*/
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Emits the JavaScript and declaration files.
* When targetSource file is specified, emits the files corresponding to that source file,
* otherwise for the whole program.
* In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
* it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
* it will only emit all the affected files instead of whole program
*
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
/**
* Get the current directory of the program
*/
getCurrentDirectory(): string;
/*@internal*/
close(): void;
}
/**
* The builder that caches the semantic diagnostics for the program and handles the changed files and affected files
*/
export interface SemanticDiagnosticsBuilderProgram extends BuilderProgram {
/**
* Gets the semantic diagnostics from the program for the next affected file and caches it
* Returns undefined if the iteration is complete
*/
getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult<readonly Diagnostic[]>;
}
/**
* The builder that can handle the changes in program and iterate through changed file to emit the files
* The semantic diagnostics are cached per file and managed by clearing for the changed/affected files
*/
export interface EmitAndSemanticDiagnosticsBuilderProgram extends SemanticDiagnosticsBuilderProgram {
/**
* Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult<EmitResult>;
}
/**
* Create the builder to manage semantic diagnostics and cache them
*/
export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): SemanticDiagnosticsBuilderProgram;
export function createSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): SemanticDiagnosticsBuilderProgram;
export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) {
return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
/**
* Create the builder that can handle the changes in program and iterate through changed files
* to emit the those files and manage semantic diagnostics cache as well
*/
export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): EmitAndSemanticDiagnosticsBuilderProgram;
export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): EmitAndSemanticDiagnosticsBuilderProgram;
export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]) {
return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
}
/**
* Creates a builder thats just abstraction over program and can be used with watch
*/
export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[]): BuilderProgram;
export function createAbstractBuilder(rootNames: readonly string[] | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram;
export function createAbstractBuilder(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderProgram {
const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences);
return createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
}
}
File diff suppressed because it is too large. Load diff
+13
View File
@@ -0,0 +1,13 @@
namespace ts {
export interface EmitOutput {
outputFiles: OutputFile[];
emitSkipped: boolean;
/* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit;
}
export interface OutputFile {
name: string;
writeByteOrderMark: boolean;
text: string;
}
}
+5053 -1634
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+121 -303
View File
@@ -1,93 +1,15 @@
namespace ts {
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
// If changing the text in this section, be sure to test `configureNightly` too.
export const versionMajorMinor = "3.7";
/** The version of the TypeScript compiler release */
export const version = `${versionMajorMinor}.0-dev`;
}
namespace ts {
/**
* Type of objects whose values are all of the same type.
* The `in` and `for-in` operators can *not* be safely used,
* since `Object.prototype` may be modified by outside code.
*/
export interface MapLike<T> {
[index: string]: T;
}
export interface SortedReadonlyArray<T> extends ReadonlyArray<T> {
" __sortedArrayBrand": any;
}
export interface SortedArray<T> extends Array<T> {
" __sortedArrayBrand": any;
}
/** ES6 Map interface, only read methods included. */
export interface ReadonlyMap<T> {
get(key: string): T | undefined;
has(key: string): boolean;
forEach(action: (value: T, key: string) => void): void;
readonly size: number;
keys(): Iterator<string>;
values(): Iterator<T>;
entries(): Iterator<[string, T]>;
}
/** ES6 Map interface. */
export interface Map<T> extends ReadonlyMap<T> {
set(key: string, value: T): this;
delete(key: string): boolean;
clear(): void;
}
/** ES6 Iterator type. */
export interface Iterator<T> {
next(): { value: T, done?: false } | { value: never, done: true };
}
/** Array that is only intended to be pushed to, never read. */
export interface Push<T> {
push(...values: T[]): void;
}
/* @internal */
export type EqualityComparer<T> = (a: T, b: T) => boolean;
/* @internal */
export type Comparer<T> = (a: T, b: T) => Comparison;
/* @internal */
export const enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1
}
}
/* @internal */
namespace ts {
export const emptyArray: never[] = [] as never[];
/** Create a MapLike with good performance. */
function createDictionaryObject<T>(): MapLike<T> {
const map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map.__ = undefined;
delete map.__;
return map;
}
/** Create a new map. If a template object is provided, the map will copy entries from it. */
/** Create a new map. */
export function createMap<T>(): Map<T> {
return new MapCtr<T>();
return new Map<T>();
}
/** Create a new map from an array of entries. */
export function createMapFromEntries<T>(entries: [string, T][]): Map<T> {
const map = createMap<T>();
for (const [key, value] of entries) {
@@ -96,8 +18,9 @@ namespace ts {
return map;
}
/** Create a new map from a template object is provided, the map will copy entries from it. */
export function createMapFromTemplate<T>(template: MapLike<T>): Map<T> {
const map: Map<T> = new MapCtr<T>();
const map: Map<T> = new Map<T>();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
@@ -110,204 +33,6 @@ namespace ts {
return map;
}
// The global Map object. This may not be available, so we must test for it.
declare const Map: (new <T>() => Map<T>) | undefined;
// Internet Explorer's Map doesn't support iteration, so don't use it.
// eslint-disable-next-line no-in-operator
export const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
// Keep the class inside a function so it doesn't get compiled if it's not used.
export function shimMap(): new <T>() => Map<T> {
interface MapEntry<T> {
readonly key?: string;
value?: T;
// Linked list references for iterators.
nextEntry?: MapEntry<T>;
previousEntry?: MapEntry<T>;
/**
* Specifies if iterators should skip the next entry.
* This will be set when an entry is deleted.
* See https://github.com/Microsoft/TypeScript/pull/27292 for more information.
*/
skipNext?: boolean;
}
class MapIterator<T, U extends (string | T | [string, T])> {
private currentEntry?: MapEntry<T>;
private selector: (key: string, value: T) => U;
constructor(currentEntry: MapEntry<T>, selector: (key: string, value: T) => U) {
this.currentEntry = currentEntry;
this.selector = selector;
}
public next(): { value: U, done: false } | { value: never, done: true } {
// Navigate to the next entry.
while (this.currentEntry) {
const skipNext = !!this.currentEntry.skipNext;
this.currentEntry = this.currentEntry.nextEntry;
if (!skipNext) {
break;
}
}
if (this.currentEntry) {
return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false };
}
else {
return { value: undefined as never, done: true };
}
}
}
return class <T> implements Map<T> {
private data = createDictionaryObject<MapEntry<T>>();
public size = 0;
// Linked list references for iterators.
// See https://github.com/Microsoft/TypeScript/pull/27292
// for more information.
/**
* The first entry in the linked list.
* Note that this is only a stub that serves as starting point
* for iterators and doesn't contain a key and a value.
*/
private readonly firstEntry: MapEntry<T>;
private lastEntry: MapEntry<T>;
constructor() {
// Create a first (stub) map entry that will not contain a key
// and value but serves as starting point for iterators.
this.firstEntry = {};
// When the map is empty, the last entry is the same as the
// first one.
this.lastEntry = this.firstEntry;
}
get(key: string): T | undefined {
const entry = this.data[key] as MapEntry<T> | undefined;
return entry && entry.value!;
}
set(key: string, value: T): this {
if (!this.has(key)) {
this.size++;
// Create a new entry that will be appended at the
// end of the linked list.
const newEntry: MapEntry<T> = {
key,
value
};
this.data[key] = newEntry;
// Adjust the references.
const previousLastEntry = this.lastEntry;
previousLastEntry.nextEntry = newEntry;
newEntry.previousEntry = previousLastEntry;
this.lastEntry = newEntry;
}
else {
this.data[key].value = value;
}
return this;
}
has(key: string): boolean {
// eslint-disable-next-line no-in-operator
return key in this.data;
}
delete(key: string): boolean {
if (this.has(key)) {
this.size--;
const entry = this.data[key];
delete this.data[key];
// Adjust the linked list references of the neighbor entries.
const previousEntry = entry.previousEntry!;
previousEntry.nextEntry = entry.nextEntry;
if (entry.nextEntry) {
entry.nextEntry.previousEntry = previousEntry;
}
// When the deleted entry was the last one, we need to
// adjust the lastEntry reference.
if (this.lastEntry === entry) {
this.lastEntry = previousEntry;
}
// Adjust the forward reference of the deleted entry
// in case an iterator still references it. This allows us
// to throw away the entry, but when an active iterator
// (which points to the current entry) continues, it will
// navigate to the entry that originally came before the
// current one and skip it.
entry.previousEntry = undefined;
entry.nextEntry = previousEntry;
entry.skipNext = true;
return true;
}
return false;
}
clear(): void {
this.data = createDictionaryObject<MapEntry<T>>();
this.size = 0;
// Reset the linked list. Note that we must adjust the forward
// references of the deleted entries to ensure iterators stuck
// in the middle of the list don't continue with deleted entries,
// but can continue with new entries added after the clear()
// operation.
const firstEntry = this.firstEntry;
let currentEntry = firstEntry.nextEntry;
while (currentEntry) {
const nextEntry = currentEntry.nextEntry;
currentEntry.previousEntry = undefined;
currentEntry.nextEntry = firstEntry;
currentEntry.skipNext = true;
currentEntry = nextEntry;
}
firstEntry.nextEntry = undefined;
this.lastEntry = firstEntry;
}
keys(): Iterator<string> {
return new MapIterator(this.firstEntry, key => key);
}
values(): Iterator<T> {
return new MapIterator(this.firstEntry, (_key, value) => value);
}
entries(): Iterator<[string, T]> {
return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]);
}
forEach(action: (value: T, key: string) => void): void {
const iterator = this.entries();
while (true) {
const iterResult = iterator.next();
if (iterResult.done) {
break;
}
const [key, value] = iterResult.value;
action(value, key);
}
}
};
}
export function length(array: readonly any[] | undefined): number {
return array ? array.length : 0;
}
@@ -329,6 +54,21 @@ namespace ts {
return undefined;
}
/**
* Like `forEach`, but iterates in reverse order.
*/
export function forEachRight<T, U>(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined {
if (array) {
for (let i = array.length - 1; i >= 0; i--) {
const result = callback(array[i], i);
if (result) {
return result;
}
}
}
return undefined;
}
/** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
export function firstDefined<T, U>(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined {
if (array === undefined) {
@@ -758,6 +498,17 @@ namespace ts {
};
}
export function mapDefinedMap<T, U>(map: ReadonlyMap<T>, mapValue: (value: T, key: string) => U | undefined, mapKey: (key: string) => string = identity): Map<U> {
const result = createMap<U>();
map.forEach((value, key) => {
const mapped = mapValue(value, key);
if (mapped !== undefined) {
result.set(mapKey(key), mapped);
}
});
return result;
}
export const emptyIterator: Iterator<never> = { next: () => ({ value: undefined as never, done: true }) };
export function singleIterator<T>(value: T): Iterator<T> {
@@ -879,10 +630,18 @@ namespace ts {
return [...array1, ...array2];
}
function selectIndex(_: unknown, i: number) {
return i;
}
export function indicesOf(array: readonly unknown[]): number[] {
return array.map(selectIndex);
}
function deduplicateRelational<T>(array: readonly T[], equalityComparer: EqualityComparer<T>, comparer: Comparer<T>) {
// Perform a stable sort of the array. This ensures the first entry in a list of
// duplicates remains the first entry in the result.
const indices = array.map((_, i) => i);
const indices = indicesOf(array);
stableSortIndices(array, indices, comparer);
let last = array[indices[0]];
@@ -1188,7 +947,7 @@ namespace ts {
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
export function stableSort<T>(array: readonly T[], comparer: Comparer<T>): SortedReadonlyArray<T> {
const indices = array.map((_, i) => i);
const indices = indicesOf(array);
stableSortIndices(array, indices, comparer);
return indices.map(i => array[i]) as SortedArray<T> as SortedReadonlyArray<T>;
}
@@ -1494,8 +1253,10 @@ namespace ts {
return result;
}
export function group<T>(values: readonly T[], getGroupId: (value: T) => string): readonly (readonly T[])[] {
return arrayFrom(arrayToMultiMap(values, getGroupId).values());
export function group<T>(values: readonly T[], getGroupId: (value: T) => string): readonly (readonly T[])[];
export function group<T, R>(values: readonly T[], getGroupId: (value: T) => string, resultSelector: (values: readonly T[]) => R): R[];
export function group<T>(values: readonly T[], getGroupId: (value: T) => string, resultSelector: (values: readonly T[]) => readonly T[] = identity): readonly (readonly T[])[] {
return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
}
export function clone<T>(object: T): T {
@@ -1508,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) {
@@ -1537,6 +1303,14 @@ namespace ts {
return fn ? fn.bind(obj) : undefined;
}
export function mapMap<T, U>(map: Map<T>, f: (t: T, key: string) => [string, U]): Map<U>;
export function mapMap<T, U>(map: UnderscoreEscapedMap<T>, f: (t: T, key: __String) => [string, U]): Map<U>;
export function mapMap<T, U>(map: Map<T> | UnderscoreEscapedMap<T>, f: ((t: T, key: string) => [string, U]) | ((t: T, key: __String) => [string, U])): Map<U> {
const result = createMap<U>();
map.forEach((t: T, key: string & __String) => result.set(...(f(t, key))));
return result;
}
export interface MultiMap<T> extends Map<T[]> {
/**
* Adds the value to an array of values associated with the key, and returns the array.
@@ -1630,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");
@@ -1654,7 +1468,7 @@ namespace ts {
*/
export function compose<T>(...args: ((t: T) => T)[]): (t: T) => T;
export function compose<T>(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t: T) => T, e: (t: T) => T): (t: T) => T {
if (e) {
if (!!e) {
const args: ((t: T) => T)[] = [];
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
@@ -1740,6 +1554,13 @@ namespace ts {
return compareComparableValues(a, b);
}
/**
* Compare two TextSpans, first by `start`, then by `length`.
*/
export function compareTextSpans(a: Partial<TextSpan> | undefined, b: Partial<TextSpan> | undefined): Comparison {
return compareValues(a?.start, b?.start) || compareValues(a?.length, b?.length);
}
export function min<T>(a: T, b: T, compare: Comparer<T>): T {
return compare(a, b) === Comparison.LessThan ? a : b;
}
@@ -2029,20 +1850,6 @@ namespace ts {
return str.indexOf(substring) !== -1;
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
@@ -2098,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. */
@@ -2159,8 +1966,19 @@ namespace ts {
return (arg: T) => f(arg) && g(arg);
}
export function or<T>(f: (arg: T) => boolean, g: (arg: T) => boolean): (arg: T) => boolean {
return arg => f(arg) || g(arg);
export function or<T extends unknown[]>(...fs: ((...args: T) => boolean)[]): (...args: T) => boolean {
return (...args) => {
for (const f of fs) {
if (f(...args)) {
return true;
}
}
return false;
};
}
export function not<T extends unknown[]>(fn: (...args: T) => boolean): (...args: T) => boolean {
return (...args) => !fn(...args);
}
export function assertType<T>(_: T): void { }
+96
View File
@@ -0,0 +1,96 @@
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.9";
/** The version of the TypeScript compiler release */
export const version = `${versionMajorMinor}.0-dev`;
/**
* Type of objects whose values are all of the same type.
* The `in` and `for-in` operators can *not* be safely used,
* since `Object.prototype` may be modified by outside code.
*/
export interface MapLike<T> {
[index: string]: T;
}
export interface SortedReadonlyArray<T> extends ReadonlyArray<T> {
" __sortedArrayBrand": any;
}
export interface SortedArray<T> extends Array<T> {
" __sortedArrayBrand": any;
}
/** ES6 Map interface, only read methods included. */
export interface ReadonlyMap<T> {
get(key: string): T | undefined;
has(key: string): boolean;
forEach(action: (value: T, key: string) => void): void;
readonly size: number;
keys(): Iterator<string>;
values(): Iterator<T>;
entries(): Iterator<[string, T]>;
}
/** ES6 Map interface. */
export interface Map<T> extends ReadonlyMap<T> {
set(key: string, value: T): this;
delete(key: string): boolean;
clear(): void;
}
/* @internal */
export interface MapConstructor {
// eslint-disable-next-line @typescript-eslint/prefer-function-type
new <T>(): Map<T>;
}
/**
* Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
*/
/* @internal */
export function tryGetNativeMap(): MapConstructor | undefined {
// Internet Explorer's Map doesn't support iteration, so don't use it.
// Natives
// NOTE: TS doesn't strictly allow in-line declares, but if we suppress the error, the declaration
// is still used for typechecking _and_ correctly elided, which is out goal, as this prevents us from
// needing to pollute an outer scope with a declaration of `Map` just to satisfy the checks in this function
//@ts-ignore
declare const Map: (new <T>() => Map<T>) | undefined;
// eslint-disable-next-line no-in-operator
return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
}
/* @internal */
export const Map: MapConstructor = tryGetNativeMap() || (() => {
// NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
if (typeof createMapShim === "function") {
return createMapShim();
}
throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
})();
/** ES6 Iterator type. */
export interface Iterator<T> {
next(): { value: T, done?: false } | { value: never, done: true };
}
/** Array that is only intended to be pushed to, never read. */
export interface Push<T> {
push(...values: T[]): void;
}
/* @internal */
export type EqualityComparer<T> = (a: T, b: T) => boolean;
/* @internal */
export type Comparer<T> = (a: T, b: T) => Comparison;
/* @internal */
export const enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1
}
}
+64 -4
View File
@@ -100,11 +100,13 @@ namespace ts {
if (isFlags) {
let result = "";
let remainingFlags = value;
for (let i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) {
const [enumValue, enumName] = members[i];
if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) {
for (const [enumValue, enumName] of members) {
if (enumValue > value) {
break;
}
if (enumValue !== 0 && enumValue & value) {
result = `${result}${result ? "|" : ""}${enumName}`;
remainingFlags &= ~enumValue;
result = `${enumName}${result ? "|" : ""}${result}`;
}
}
if (remainingFlags === 0) {
@@ -187,6 +189,14 @@ namespace ts {
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),
@@ -213,6 +223,40 @@ namespace ts {
let isDebugInfoEnabled = false;
interface ExtendedDebugModule {
init(_ts: typeof ts): void;
formatControlFlowGraph(flowNode: FlowNode): string;
}
let extendedDebugModule: ExtendedDebugModule | undefined;
function extendedDebug() {
enableDebugInfo();
if (!extendedDebugModule) {
throw new Error("Debugging helpers could not be loaded.");
}
return extendedDebugModule;
}
export function printControlFlowGraph(flowNode: FlowNode) {
return console.log(formatControlFlowGraph(flowNode));
}
export function formatControlFlowGraph(flowNode: FlowNode) {
return extendedDebug().formatControlFlowGraph(flowNode);
}
export function attachFlowNodeDebugInfo(flowNode: FlowNode) {
if (isDebugInfoEnabled) {
if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
Object.defineProperties(flowNode, {
__debugFlowFlags: { get(this: FlowNode) { return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); } },
__debugToString: { value(this: FlowNode) { return formatControlFlowGraph(this); } }
});
}
}
}
/**
* Injects debug information into frequently used types.
*/
@@ -258,7 +302,23 @@ namespace ts {
}
}
// attempt to load extended debugging information
try {
if (sys && sys.require) {
const basePath = getDirectoryPath(resolvePath(sys.getExecutingFilePath()));
const result = sys.require(basePath, "./compiler-debug") as RequireResult<ExtendedDebugModule>;
if (!result.error) {
result.module.init(ts);
extendedDebugModule = result.module;
}
}
}
catch {
// do nothing
}
isDebugInfoEnabled = true;
}
}
}
+459 -46
View File
@@ -15,6 +15,10 @@
"category": "Error",
"code": 1006
},
"The parser expected to find a '}' to match the '{' token here.": {
"category": "Error",
"code": 1007
},
"Trailing comma not allowed.": {
"category": "Error",
"code": 1009
@@ -71,7 +75,7 @@
"category": "Error",
"code": 1022
},
"An index signature parameter type must be 'string' or 'number'.": {
"An index signature parameter type must be either 'string' or 'number'.": {
"category": "Error",
"code": 1023
},
@@ -635,7 +639,7 @@
"category": "Error",
"code": 1203
},
"Cannot re-export a type when the '--isolatedModules' flag is provided.": {
"Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.": {
"category": "Error",
"code": 1205
},
@@ -851,11 +855,15 @@
"category": "Error",
"code": 1260
},
"Already included file name '{0}' differs from file name '{1}' only in casing.": {
"category": "Error",
"code": 1261
},
"'with' statements are not allowed in an async function block.": {
"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
},
@@ -903,7 +911,7 @@
"category": "Error",
"code": 1322
},
"Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.": {
"Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'.": {
"category": "Error",
"code": 1323
},
@@ -1039,6 +1047,131 @@
"category": "Error",
"code": 1357
},
"Tagged template expressions are not permitted in an optional chain.": {
"category": "Error",
"code": 1358
},
"Identifier expected. '{0}' is a reserved word that cannot be used here.": {
"category": "Error",
"code": 1359
},
"Did you mean to parenthesize this function type?": {
"category": "Error",
"code": 1360
},
"'{0}' cannot be used as a value because it was imported using 'import type'.": {
"category": "Error",
"code": 1361
},
"'{0}' cannot be used as a value because it was exported using 'export type'.": {
"category": "Error",
"code": 1362
},
"A type-only import can specify a default import or named bindings, but not both.": {
"category": "Error",
"code": 1363
},
"Convert to type-only export": {
"category": "Message",
"code": 1364
},
"Convert all re-exported types to type-only exports": {
"category": "Message",
"code": 1365
},
"Split into two separate import declarations": {
"category": "Message",
"code": 1366
},
"Split all invalid type-only imports": {
"category": "Message",
"code": 1367
},
"Specify emit/checking behavior for imports that are only used for types": {
"category": "Message",
"code": 1368
},
"Did you mean '{0}'?": {
"category": "Message",
"code": 1369
},
"Only ECMAScript imports may use 'import type'.": {
"category": "Error",
"code": 1370
},
"This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'.": {
"category": "Error",
"code": 1371
},
"Convert to type-only import": {
"category": "Message",
"code": 1373
},
"Convert all imports not used as a value to type-only imports": {
"category": "Message",
"code": 1374
},
"'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 `&rbrace;`?": {
"category": "Error",
"code": 1381
},
"Unexpected token. Did you mean `{'>'}` or `&gt;`?": {
"category": "Error",
"code": 1382
},
"The types of '{0}' are incompatible between these types.": {
"category": "Error",
"code": 2200
},
"The types returned by '{0}' are incompatible between these types.": {
"category": "Error",
"code": 2201
},
"Call signature return types '{0}' and '{1}' are incompatible.": {
"category": "Error",
"code": 2202,
"elidedInCompatabilityPyramid": true
},
"Construct signature return types '{0}' and '{1}' are incompatible.": {
"category": "Error",
"code": 2203,
"elidedInCompatabilityPyramid": true
},
"Call signatures with no arguments have incompatible return types '{0}' and '{1}'.": {
"category": "Error",
"code": 2204,
"elidedInCompatabilityPyramid": true
},
"Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.": {
"category": "Error",
"code": 2205,
"elidedInCompatabilityPyramid": true
},
"Duplicate identifier '{0}'.": {
"category": "Error",
@@ -1212,7 +1345,7 @@
"category": "Error",
"code": 2342
},
"This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'.": {
"This syntax requires an imported helper named '{1}' which does not exist in '{0}'. Consider upgrading your version of '{0}'.": {
"category": "Error",
"code": 2343
},
@@ -1344,7 +1477,7 @@
"category": "Error",
"code": 2375
},
"A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.": {
"A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers.": {
"category": "Error",
"code": 2376
},
@@ -1524,10 +1657,6 @@
"category": "Error",
"code": 2423
},
"Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": {
"category": "Error",
"code": 2424
},
"Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": {
"category": "Error",
"code": 2425
@@ -1660,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
@@ -2204,6 +2341,27 @@
"category": "Error",
"code": 2609
},
"'{0}' is defined as an accessor in class '{1}', but is overridden here in '{2}' as an instance property.": {
"category": "Error",
"code": 2610
},
"'{0}' is defined as a property in class '{1}', but is overridden here in '{2}' as an accessor.": {
"category": "Error",
"code": 2611
},
"Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration.": {
"category": "Error",
"code": 2612
},
"Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?": {
"category": "Error",
"code": 2613
},
"Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?": {
"category": "Error",
"code": 2614
},
"Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": {
"category": "Error",
"code": 2649
@@ -2409,11 +2567,11 @@
"category": "Error",
"code": 2702
},
"The operand of a delete operator must be a property reference.": {
"The operand of a 'delete' operator must be a property reference.": {
"category": "Error",
"code": 2703
},
"The operand of a delete operator cannot be a read-only property.": {
"The operand of a 'delete' operator cannot be a read-only property.": {
"category": "Error",
"code": 2704
},
@@ -2533,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
},
@@ -2545,7 +2703,7 @@
"category": "Error",
"code": 2736
},
"BigInt literals are not available when targeting lower than ESNext.": {
"BigInt literals are not available when targeting lower than ES2020.": {
"category": "Error",
"code": 2737
},
@@ -2693,6 +2851,46 @@
"category": "Error",
"code": 2773
},
"This condition will always return true since the function is always defined. Did you mean to call it instead?": {
"category": "Error",
"code": 2774
},
"Assertions require every name in the call target to be declared with an explicit type annotation.": {
"category": "Error",
"code": 2775
},
"Assertions require the call target to be an identifier or qualified name.": {
"category": "Error",
"code": 2776
},
"The operand of an increment or decrement operator may not be an optional property access.": {
"category": "Error",
"code": 2777
},
"The target of an object rest assignment may not be an optional property access.": {
"category": "Error",
"code": 2778
},
"The left-hand side of an assignment expression may not be an optional property access.": {
"category": "Error",
"code": 2779
},
"The left-hand side of a 'for...in' statement may not be an optional property access.": {
"category": "Error",
"code": 2780
},
"The left-hand side of a 'for...of' statement may not be an optional property access.": {
"category": "Error",
"code": 2781
},
"'{0}' needs an explicit type annotation.": {
"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",
@@ -2994,7 +3192,6 @@
"category": "Error",
"code": 4094
},
"Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named.": {
"category": "Error",
"code": 4095
@@ -3039,6 +3236,26 @@
"category": "Error",
"code": 4105
},
"Parameter '{0}' of accessor has or is using private name '{1}'.": {
"category": "Error",
"code": 4106
},
"Parameter '{0}' of accessor has or is using name '{1}' from private module '{2}'.": {
"category": "Error",
"code": 4107
},
"Parameter '{0}' of accessor has or is using name '{1}' from external module '{2}' but cannot be named.": {
"category": "Error",
"code": 4108
},
"Type arguments for '{0}' circularly reference themselves.": {
"category": "Error",
"code": 4109
},
"Tuple type arguments circularly reference themselves.": {
"category": "Error",
"code": 4110
},
"The current host does not support the '{0}' option.": {
"category": "Error",
@@ -3068,6 +3285,10 @@
"category": "Error",
"code": 5024
},
"Unknown compiler option '{0}'. Did you mean '{1}'?": {
"category": "Error",
"code": 5025
},
"Could not write file '{0}': {1}.": {
"category": "Error",
"code": 5033
@@ -3080,6 +3301,10 @@
"category": "Error",
"code": 5047
},
"Option '{0}' cannot be specified when option 'target' is 'ES3'.": {
"category": "Error",
"code": 5048
},
"Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"category": "Error",
"code": 5051
@@ -3124,7 +3349,7 @@
"category": "Error",
"code": 5061
},
"Substitution '{0}' in pattern '{1}' in can have at most one '*' character.": {
"Substitution '{0}' in pattern '{1}' can have at most one '*' character.": {
"category": "Error",
"code": 5062
},
@@ -3180,6 +3405,30 @@
"category": "Error",
"code": 5075
},
"'{0}' and '{1}' operations cannot be mixed without parentheses.": {
"category": "Error",
"code": 5076
},
"Unknown build option '{0}'. Did you mean '{1}'?": {
"category": "Error",
"code": 5077
},
"Unknown watch option '{0}'.": {
"category": "Error",
"code": 5078
},
"Unknown watch option '{0}'. Did you mean '{1}'?": {
"category": "Error",
"code": 5079
},
"Watch option '{0}' requires a value of type {1}.": {
"category": "Error",
"code": 5080
},
"Cannot find a tsconfig.json file at the current directory: {0}.": {
"category": "Error",
"code": 5081
},
"Generates a sourcemap for each corresponding '.d.ts' file.": {
"category": "Message",
@@ -3241,11 +3490,11 @@
"category": "Message",
"code": 6014
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'.": {
"Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'.": {
"category": "Message",
"code": 6015
},
"Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.": {
"Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'.": {
"category": "Message",
"code": 6016
},
@@ -3365,7 +3614,7 @@
"category": "Error",
"code": 6053
},
"File '{0}' has unsupported extension. The only supported extensions are {1}.": {
"File '{0}' has an unsupported extension. The only supported extensions are {1}.": {
"category": "Error",
"code": 6054
},
@@ -3935,6 +4184,10 @@
"category": "Message",
"code": 6201
},
"Project references may not form a circular graph. Cycle detected: {0}": {
"category": "Error",
"code": 6202
},
"'{0}' was also declared here.": {
"category": "Message",
"code": 6203
@@ -4007,6 +4260,38 @@
"category": "Message",
"code": 6220
},
"Disable use of source files instead of declaration files from referenced projects.": {
"category": "Message",
"code": 6221
},
"Emit class fields with Define instead of Set.": {
"category": "Message",
"code": 6222
},
"Generates a CPU profile.": {
"category": "Message",
"code": 6223
},
"Disable solution searching for this project.": {
"category": "Message",
"code": 6224
},
"Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'.": {
"category": "Message",
"code": 6225
},
"Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'.": {
"category": "Message",
"code": 6226
},
"Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'.": {
"category": "Message",
"code": 6227
},
"Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively.": {
"category": "Message",
"code": 6228
},
"Projects to reference": {
"category": "Message",
@@ -4016,10 +4301,7 @@
"category": "Message",
"code": 6302
},
"Project references may not form a circular graph. Cycle detected: {0}": {
"category": "Error",
"code": 6202
},
"Composite projects may not disable declaration emit.": {
"category": "Error",
"code": 6304
@@ -4180,6 +4462,10 @@
"category": "Message",
"code": 6383
},
"Have recompiles in '--incremental' and '--watch' assume that changes within a file will only affect files directly depending on it.": {
"category": "Message",
"code": 6384
},
"The expected type comes from property '{0}' which is declared here on type '{1}'": {
"category": "Message",
@@ -4193,6 +4479,14 @@
"category": "Message",
"code": 6502
},
"Print names of files that are part of the compilation and then stop processing.": {
"category": "Message",
"code": 6503
},
"File '{0}' is a JavaScript file. Did you mean to enable the 'allowJs' option?": {
"category": "Error",
"code": 6504
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
@@ -4372,7 +4666,7 @@
"category": "Error",
"code": 7051
},
"Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}' ?": {
"Element implicitly has an 'any' type because type '{0}' has no index signature. Did you mean to call '{1}'?": {
"category": "Error",
"code": 7052
},
@@ -4397,59 +4691,51 @@
"category": "Error",
"code": 8001
},
"'import ... =' can only be used in a .ts file.": {
"'import ... =' can only be used in TypeScript files.": {
"category": "Error",
"code": 8002
},
"'export=' can only be used in a .ts file.": {
"'export =' can only be used in TypeScript files.": {
"category": "Error",
"code": 8003
},
"'type parameter declarations' can only be used in a .ts file.": {
"Type parameter declarations can only be used in TypeScript files.": {
"category": "Error",
"code": 8004
},
"'implements clauses' can only be used in a .ts file.": {
"'implements' clauses can only be used in TypeScript files.": {
"category": "Error",
"code": 8005
},
"'interface declarations' can only be used in a .ts file.": {
"'{0}' declarations can only be used in TypeScript files.": {
"category": "Error",
"code": 8006
},
"'module declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8007
},
"'type aliases' can only be used in a .ts file.": {
"Type aliases can only be used in TypeScript files.": {
"category": "Error",
"code": 8008
},
"'{0}' can only be used in a .ts file.": {
"The '{0}' modifier can only be used in TypeScript files.": {
"category": "Error",
"code": 8009
},
"'types' can only be used in a .ts file.": {
"Type annotations can only be used in TypeScript files.": {
"category": "Error",
"code": 8010
},
"'type arguments' can only be used in a .ts file.": {
"Type arguments can only be used in TypeScript files.": {
"category": "Error",
"code": 8011
},
"'parameter modifiers' can only be used in a .ts file.": {
"Parameter modifiers can only be used in TypeScript files.": {
"category": "Error",
"code": 8012
},
"'non-null assertions' can only be used in a .ts file.": {
"Non-null assertions can only be used in TypeScript files.": {
"category": "Error",
"code": 8013
},
"'enum declarations' can only be used in a .ts file.": {
"category": "Error",
"code": 8015
},
"'type assertion expressions' can only be used in a .ts file.": {
"Type assertion expressions can only be used in TypeScript files.": {
"category": "Error",
"code": 8016
},
@@ -4529,6 +4815,14 @@
"category": "Error",
"code": 9004
},
"Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit.": {
"category": "Error",
"code": 9005
},
"Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit.": {
"category": "Error",
"code": 9006
},
"JSX attributes must only be assigned a non-empty 'expression'.": {
"category": "Error",
"code": 17000
@@ -4601,7 +4895,10 @@
"category": "Error",
"code": 17017
},
"Unknown type acquisition option '{0}'. Did you mean '{1}'?": {
"category": "Error",
"code": 17018
},
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
"code": 18000
@@ -4664,7 +4961,7 @@
"category": "Message",
"code": 90003
},
"Remove declaration for: '{0}'": {
"Remove unused declaration for: '{0}'": {
"category": "Message",
"code": 90004
},
@@ -4788,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
@@ -5140,6 +5441,42 @@
"category": "Message",
"code": 95092
},
"Convert 'const' to 'let'": {
"category": "Message",
"code": 95093
},
"Prefix with 'declare'": {
"category": "Message",
"code": 95094
},
"Prefix all incorrect property declarations with 'declare'": {
"category": "Message",
"code": 95095
},
"Convert to template string": {
"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",
@@ -5152,5 +5489,81 @@
"JSX expressions may not use the comma operator. Did you mean to write an array?": {
"category": "Error",
"code": 18007
},
"Private identifiers cannot be used as parameters": {
"category": "Error",
"code": 18009
},
"An accessibility modifier cannot be used with a private identifier.": {
"category": "Error",
"code": 18010
},
"The operand of a 'delete' operator cannot be a private identifier.": {
"category": "Error",
"code": 18011
},
"'#constructor' is a reserved word.": {
"category": "Error",
"code": 18012
},
"Property '{0}' is not accessible outside class '{1}' because it has a private identifier.": {
"category": "Error",
"code": 18013
},
"The property '{0}' cannot be accessed on type '{1}' within this class because it is shadowed by another private identifier with the same spelling.": {
"category": "Error",
"code": 18014
},
"Property '{0}' in type '{1}' refers to a different member that cannot be accessed from within type '{2}'.": {
"category": "Error",
"code": 18015
},
"Private identifiers are not allowed outside class bodies.": {
"category": "Error",
"code": 18016
},
"The shadowing declaration of '{0}' is defined here": {
"category": "Error",
"code": 18017
},
"The declaration of '{0}' that you probably intended to use is defined here": {
"category": "Error",
"code": 18018
},
"'{0}' modifier cannot be used with a private identifier": {
"category": "Error",
"code": 18019
},
"A method cannot be named with a private identifier.": {
"category": "Error",
"code": 18022
},
"An accessor cannot be named with a private identifier.": {
"category": "Error",
"code": 18023
},
"An enum member cannot be named with a private identifier.": {
"category": "Error",
"code": 18024
},
"'#!' can only be used at the start of a file.": {
"category": "Error",
"code": 18026
},
"Compiler reserves name '{0}' when emitting private identifier downlevel.": {
"category": "Error",
"code": 18027
},
"Private identifiers are only available when targeting ECMAScript 2015 and higher.": {
"category": "Error",
"code": 18028
},
"Private identifiers are not allowed in variable declarations.": {
"category": "Error",
"code": 18029
},
"An optional chain cannot contain private identifiers.": {
"category": "Error",
"code": 18030
}
}
+300 -126
View File
@@ -23,7 +23,7 @@ namespace ts {
forceDtsEmit = false,
onlyBuildInfo?: boolean,
includeBuildInfo?: boolean) {
const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
const options = host.getCompilerOptions();
if (options.outFile || options.out) {
const prepends = host.getPrependNodes();
@@ -45,14 +45,13 @@ namespace ts {
}
}
if (includeBuildInfo) {
const buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
const buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
if (buildInfoPath) return action({ buildInfoPath }, /*sourceFileOrBundle*/ undefined);
}
}
}
/*@internal*/
export function getOutputPathForBuildInfo(options: CompilerOptions) {
export function getTsBuildInfoEmitOutputFilePath(options: CompilerOptions) {
const configFile = options.configFilePath;
if (!isIncrementalCompilation(options)) return undefined;
if (options.tsBuildInfoFile) return options.tsBuildInfoFile;
@@ -80,7 +79,7 @@ namespace ts {
const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
const buildInfoPath = getOutputPathForBuildInfo(options);
const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath };
}
@@ -92,14 +91,13 @@ namespace ts {
}
else {
const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
const isJsonFile = isJsonSourceFile(sourceFile);
// If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
const isJsonEmittedToSameLocation = isJsonSourceFile(sourceFile) &&
const isJsonEmittedToSameLocation = isJsonFile &&
comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === Comparison.EqualTo;
const jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
// For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error
const isJs = isSourceFileJS(sourceFile);
const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
const declarationFilePath = (forceDtsPaths || (getEmitDeclarations(options) && !isJsonFile)) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath: undefined };
}
@@ -147,7 +145,7 @@ namespace ts {
/* @internal */
export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean) {
Debug.assert(!fileExtensionIs(inputFileName, Extension.Dts) && hasTSFileExtension(inputFileName));
Debug.assert(!fileExtensionIs(inputFileName, Extension.Dts) && !fileExtensionIs(inputFileName, Extension.Json));
return changeExtension(
getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir),
Extension.Dts
@@ -170,38 +168,71 @@ namespace ts {
undefined;
}
function createAddOutput() {
let outputs: string[] | undefined;
return { addOutput, getOutputs };
function addOutput(path: string | undefined) {
if (path) {
(outputs || (outputs = [])).push(path);
}
}
function getOutputs(): readonly string[] {
return outputs || emptyArray;
}
}
function getSingleOutputFileNames(configFile: ParsedCommandLine, addOutput: ReturnType<typeof createAddOutput>["addOutput"]) {
const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false);
addOutput(jsFilePath);
addOutput(sourceMapFilePath);
addOutput(declarationFilePath);
addOutput(declarationMapPath);
addOutput(buildInfoPath);
}
function getOwnOutputFileNames(configFile: ParsedCommandLine, inputFileName: string, ignoreCase: boolean, addOutput: ReturnType<typeof createAddOutput>["addOutput"]) {
if (fileExtensionIs(inputFileName, Extension.Dts)) return;
const js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
addOutput(js);
if (fileExtensionIs(inputFileName, Extension.Json)) return;
if (js && configFile.options.sourceMap) {
addOutput(`${js}.map`);
}
if (getEmitDeclarations(configFile.options)) {
const dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
addOutput(dts);
if (configFile.options.declarationMap) {
addOutput(`${dts}.map`);
}
}
}
/*@internal*/
export function getAllProjectOutputs(configFile: ParsedCommandLine, ignoreCase: boolean): readonly string[] {
let outputs: string[] | undefined;
const addOutput = (path: string | undefined) => path && (outputs || (outputs = [])).push(path);
const { addOutput, getOutputs } = createAddOutput();
if (configFile.options.outFile || configFile.options.out) {
const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false);
addOutput(jsFilePath);
addOutput(sourceMapFilePath);
addOutput(declarationFilePath);
addOutput(declarationMapPath);
addOutput(buildInfoPath);
getSingleOutputFileNames(configFile, addOutput);
}
else {
for (const inputFileName of configFile.fileNames) {
if (fileExtensionIs(inputFileName, Extension.Dts)) continue;
const js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
addOutput(js);
if (fileExtensionIs(inputFileName, Extension.Json)) continue;
if (js && configFile.options.sourceMap) {
addOutput(`${js}.map`);
}
if (getEmitDeclarations(configFile.options) && hasTSFileExtension(inputFileName)) {
const dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
addOutput(dts);
if (configFile.options.declarationMap) {
addOutput(`${dts}.map`);
}
}
getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
}
addOutput(getOutputPathForBuildInfo(configFile.options));
addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
}
return outputs || emptyArray;
return getOutputs();
}
export function getOutputFileNames(commandLine: ParsedCommandLine, inputFileName: string, ignoreCase: boolean): readonly string[] {
inputFileName = normalizePath(inputFileName);
Debug.assert(contains(commandLine.fileNames, inputFileName), `Expected fileName to be present in command line`);
const { addOutput, getOutputs } = createAddOutput();
if (commandLine.options.outFile || commandLine.options.out) {
getSingleOutputFileNames(commandLine, addOutput);
}
else {
getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
}
return getOutputs();
}
/*@internal*/
@@ -216,11 +247,11 @@ namespace ts {
const jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
if (jsFilePath) return jsFilePath;
if (fileExtensionIs(inputFileName, Extension.Json)) continue;
if (getEmitDeclarations(configFile.options) && hasTSFileExtension(inputFileName)) {
if (getEmitDeclarations(configFile.options)) {
return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
}
}
const buildInfoPath = getOutputPathForBuildInfo(configFile.options);
const buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
if (buildInfoPath) return buildInfoPath;
return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`);
}
@@ -244,7 +275,7 @@ namespace ts {
forEachEmittedFile(
host,
emitSourceFileOrBundle,
getSourceFilesToEmit(host, targetSourceFile),
getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit),
forceDtsEmit,
onlyBuildInfo,
!targetSourceFile
@@ -306,6 +337,7 @@ namespace ts {
emitSkipped = true;
return;
}
const version = ts.version; // Extracted into a const so the form is stable between namespace and module
writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle, program, version }), /*writeByteOrderMark*/ false);
}
@@ -347,6 +379,7 @@ namespace ts {
// transform hooks
onEmitNode: transform.emitNodeWithNotification,
isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
substituteNode: transform.substituteNode,
});
@@ -363,17 +396,19 @@ namespace ts {
declarationFilePath: string | undefined,
declarationMapPath: string | undefined,
relativeToBuildInfo: (path: string) => string) {
if (!sourceFileOrBundle || !(declarationFilePath && !isInJSFile(sourceFileOrBundle))) {
if (!sourceFileOrBundle) return;
if (!declarationFilePath) {
if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) emitSkipped = true;
return;
}
const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson);
// Setup and perform the transformation to retrieve declarations from the input files
const nonJsFiles = filter(sourceFiles, isSourceFileNotJS);
const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(filesForEmit, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) {
// Checker wont collect the linked aliases since thats only done when declaration is enabled.
// Do that here when emitting only dts files
nonJsFiles.forEach(collectLinkedAliases);
filesForEmit.forEach(collectLinkedAliases);
}
const declarationTransform = transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
if (length(declarationTransform.diagnostics)) {
@@ -403,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;
@@ -627,6 +663,7 @@ namespace ts {
getAllAccessorDeclarations: notImplemented,
getSymbolOfExternalModuleSpecifier: notImplemented,
isBindingCapturedByNode: notImplemented,
getDeclarationStatementsForSourceFile: notImplemented,
};
/*@internal*/
@@ -722,6 +759,7 @@ namespace ts {
getLibFileFromReference: notImplemented,
isSourceFileFromExternalLibrary: returnFalse,
getResolvedProjectReferenceToRedirect: returnUndefined,
isSourceOfProjectReferenceRedirect: returnFalse,
writeFile: (name, text, writeByteOrderMark) => {
switch (name) {
case jsFilePath:
@@ -783,6 +821,7 @@ namespace ts {
const {
hasGlobalName,
onEmitNode = noEmitNotification,
isEmitNotificationEnabled,
substituteNode = noEmitSubstitution,
onBeforeEmitNodeArray,
onAfterEmitNodeArray,
@@ -828,6 +867,8 @@ namespace ts {
let detachedCommentsInfo: { nodePos: number, detachedCommentEndPos: number}[] | undefined;
let hasWrittenComment = false;
let commentsDisabled = !!printerOptions.removeComments;
let lastNode: Node | undefined;
let lastSubstitution: Node | undefined;
const { enter: enterComment, exit: exitComment } = performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment");
reset();
@@ -1050,8 +1091,7 @@ namespace ts {
setSourceFile(sourceFile);
}
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(hint, node);
pipelineEmit(hint, node);
}
function setSourceFile(sourceFile: SourceFile | undefined) {
@@ -1083,6 +1123,8 @@ namespace ts {
currentSourceFile = undefined!;
currentLineMap = undefined!;
detachedCommentsInfo = undefined;
lastNode = undefined;
lastSubstitution = undefined;
setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
}
@@ -1090,36 +1132,63 @@ namespace ts {
return currentLineMap || (currentLineMap = getLineStarts(currentSourceFile!));
}
function emit(node: Node): Node;
function emit(node: Node | undefined): Node | undefined;
function emit(node: Node | undefined) {
if (node === undefined) return;
const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(EmitHint.Unspecified, node);
const substitute = pipelineEmit(EmitHint.Unspecified, node);
recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
return substitute;
}
function emitIdentifierName(node: Identifier | undefined) {
function emitIdentifierName(node: Identifier): Node;
function emitIdentifierName(node: Identifier | undefined): Node | undefined;
function emitIdentifierName(node: Identifier | undefined): Node | undefined {
if (node === undefined) return;
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(EmitHint.IdentifierName, node);
return pipelineEmit(EmitHint.IdentifierName, node);
}
function emitExpression(node: Expression | undefined) {
function emitExpression(node: Expression): Node;
function emitExpression(node: Expression | undefined): Node | undefined;
function emitExpression(node: Expression | undefined): Node | undefined {
if (node === undefined) return;
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(EmitHint.Expression, node);
return pipelineEmit(EmitHint.Expression, node);
}
function getPipelinePhase(phase: PipelinePhase, node: 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, emitHint, node);
pipelinePhase(emitHint, node);
Debug.assert(lastNode === node);
const substitute = lastSubstitution;
lastNode = savedLastNode;
lastSubstitution = savedLastSubstitution;
return substitute || 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
@@ -1144,18 +1213,22 @@ 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) {
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, node);
Debug.assert(lastNode === node);
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Notification, hint, node);
onEmitNode(hint, node, pipelinePhase);
Debug.assert(lastNode === node);
}
function pipelineEmitWithHint(hint: EmitHint, node: Node): void {
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);
@@ -1169,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:
@@ -1190,6 +1263,10 @@ namespace ts {
case SyntaxKind.Identifier:
return emitIdentifier(<Identifier>node);
// PrivateIdentifiers
case SyntaxKind.PrivateIdentifier:
return emitPrivateIdentifier(node as PrivateIdentifier);
// Parse tree nodes
// Names
case SyntaxKind.QualifiedName:
@@ -1372,6 +1449,8 @@ namespace ts {
return emitImportClause(<ImportClause>node);
case SyntaxKind.NamespaceImport:
return emitNamespaceImport(<NamespaceImport>node);
case SyntaxKind.NamespaceExport:
return emitNamespaceExport(<NamespaceExport>node);
case SyntaxKind.NamedImports:
return emitNamedImports(<NamedImports>node);
case SyntaxKind.ImportSpecifier:
@@ -1465,7 +1544,7 @@ namespace ts {
if (isExpression(node)) {
hint = EmitHint.Expression;
if (substituteNode !== noEmitSubstitution) {
node = substituteNode(hint, node);
lastSubstitution = node = substituteNode(hint, node);
}
}
else if (isToken(node)) {
@@ -1482,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:
@@ -1581,8 +1660,10 @@ namespace ts {
}
function pipelineEmitWithSubstitution(hint: EmitHint, node: Node) {
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, node);
pipelinePhase(hint, substituteNode(hint, node));
Debug.assert(lastNode === node || lastSubstitution === node);
const pipelinePhase = getNextPipelinePhase(PipelinePhase.Substitution, hint, node);
pipelinePhase(hint, lastSubstitution!);
Debug.assert(lastNode === node || lastSubstitution === node);
}
function getHelpersFromBundledSourceFiles(bundle: Bundle): string[] | undefined {
@@ -1670,7 +1751,7 @@ namespace ts {
// SyntaxKind.NumericLiteral
// SyntaxKind.BigIntLiteral
function emitNumericOrBigIntLiteral(node: NumericLiteral | BigIntLiteral) {
emitLiteral(node);
emitLiteral(node, /*jsxAttributeEscape*/ false);
}
// SyntaxKind.StringLiteral
@@ -1679,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);
@@ -1750,6 +1831,12 @@ namespace ts {
// Names
//
function emitPrivateIdentifier(node: PrivateIdentifier) {
const writeText = node.symbol ? writeSymbol : write;
writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
}
function emitQualifiedName(node: QualifiedName) {
emitEntityName(node.left);
writePunctuation(".");
@@ -1914,11 +2001,17 @@ namespace ts {
//
function emitTypePredicate(node: TypePredicateNode) {
if (node.assertsModifier) {
emit(node.assertsModifier);
writeSpace();
}
emit(node.parameterName);
writeSpace();
writeKeyword("is");
writeSpace();
emit(node.type);
if (node.type) {
writeSpace();
writeKeyword("is");
writeSpace();
emit(node.type);
}
}
function emitTypeReference(node: TypeReferenceNode) {
@@ -2080,8 +2173,7 @@ namespace ts {
}
writePunctuation("[");
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node.typeParameter);
pipelinePhase(EmitHint.MappedTypeParameter, node.typeParameter);
pipelineEmit(EmitHint.MappedTypeParameter, node.typeParameter);
writePunctuation("]");
if (node.questionToken) {
@@ -2179,34 +2271,24 @@ namespace ts {
}
function emitPropertyAccessExpression(node: PropertyAccessExpression) {
let indentBeforeDot = false;
let indentAfterDot = false;
const dotRangeFirstCommentStart = skipTrivia(
currentSourceFile!.text,
node.expression.end,
/*stopAfterLineBreak*/ false,
/*stopAtComments*/ true
);
const dotRangeStart = skipTrivia(currentSourceFile!.text, dotRangeFirstCommentStart);
const dotRangeEnd = dotRangeStart + 1;
if (!(getEmitFlags(node) & EmitFlags.NoIndentation)) {
const dotToken = createToken(SyntaxKind.DotToken);
dotToken.pos = node.expression.end;
dotToken.end = dotRangeEnd;
indentBeforeDot = needsIndentation(node, node.expression, dotToken);
indentAfterDot = needsIndentation(node, dotToken, node.name);
}
const expression = cast(emitExpression(node.expression), isExpression);
const token = getDotOrQuestionDotToken(node);
const indentBeforeDot = needsIndentation(node, node.expression, token);
const indentAfterDot = needsIndentation(node, token, node.name);
emitExpression(node.expression);
increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false);
const dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart;
const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia);
const shouldEmitDotDot =
token.kind !== SyntaxKind.QuestionDotToken &&
mayNeedDotDotForPropertyAccess(expression) &&
!writer.hasTrailingComment() &&
!writer.hasTrailingWhitespace();
if (shouldEmitDotDot) {
writePunctuation(".");
}
emitTokenWithComment(SyntaxKind.DotToken, node.expression.end, writePunctuation, node);
emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false);
emit(node.name);
decreaseIndentIf(indentBeforeDot, indentAfterDot);
@@ -2214,28 +2296,27 @@ namespace ts {
// 1..toString is a valid property access, emit a dot after the literal
// Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
function needsDotDotForPropertyAccess(expression: Expression, dotHasTrivia: boolean) {
function mayNeedDotDotForPropertyAccess(expression: Expression) {
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)!) &&
(!dotHasTrivia || printerOptions.removeComments);
return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!);
}
else if (isPropertyAccessExpression(expression) || isElementAccessExpression(expression)) {
else if (isAccessExpression(expression)) {
// check if constant enum value is integer
const constantValue = getConstantValue(expression);
// isFinite handles cases when constantValue is undefined
return typeof constantValue === "number" && isFinite(constantValue)
&& Math.floor(constantValue) === constantValue
&& printerOptions.removeComments;
&& Math.floor(constantValue) === constantValue;
}
}
function emitElementAccessExpression(node: ElementAccessExpression) {
emitExpression(node.expression);
emit(node.questionDotToken);
emitTokenWithComment(SyntaxKind.OpenBracketToken, node.expression.end, writePunctuation, node);
emitExpression(node.argumentExpression);
emitTokenWithComment(SyntaxKind.CloseBracketToken, node.argumentExpression.end, writePunctuation, node);
@@ -2243,6 +2324,7 @@ namespace ts {
function emitCallExpression(node: CallExpression) {
emitExpression(node.expression);
emit(node.questionDotToken);
emitTypeArguments(node, node.typeArguments);
emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments);
}
@@ -2350,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) {
@@ -2597,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();
}
@@ -2682,6 +2829,7 @@ namespace ts {
function emitVariableDeclaration(node: VariableDeclaration) {
emit(node.name);
emit(node.exclamationToken);
emitTypeAnnotation(node.type);
emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
}
@@ -2974,6 +3122,10 @@ namespace ts {
}
function emitImportClause(node: ImportClause) {
if (node.isTypeOnly) {
emitTokenWithComment(SyntaxKind.TypeKeyword, node.pos, writeKeyword, node);
writeSpace();
}
emit(node.name);
if (node.name && node.namedBindings) {
emitTokenWithComment(SyntaxKind.CommaToken, node.name.end, writePunctuation, node);
@@ -3015,6 +3167,10 @@ namespace ts {
function emitExportDeclaration(node: ExportDeclaration) {
let nextPos = emitTokenWithComment(SyntaxKind.ExportKeyword, node.pos, writeKeyword, node);
writeSpace();
if (node.isTypeOnly) {
nextPos = emitTokenWithComment(SyntaxKind.TypeKeyword, nextPos, writeKeyword, node);
writeSpace();
}
if (node.exportClause) {
emit(node.exportClause);
}
@@ -3042,6 +3198,14 @@ namespace ts {
writeTrailingSemicolon();
}
function emitNamespaceExport(node: NamespaceExport) {
const asPos = emitTokenWithComment(SyntaxKind.AsteriskToken, node.pos, writePunctuation, node);
writeSpace();
emitTokenWithComment(SyntaxKind.AsKeyword, asPos, writeKeyword, node);
writeSpace();
emit(node.name);
}
function emitNamedExports(node: NamedExports) {
emitNamedImportsOrExports(node);
}
@@ -3136,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) {
@@ -3669,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);
@@ -3706,8 +3870,7 @@ namespace ts {
writeLine();
increaseIndent();
if (isEmptyStatement(node)) {
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(EmitHint.EmbeddedStatement, node);
pipelineEmit(EmitHint.EmbeddedStatement, node);
}
else {
emit(node);
@@ -4178,6 +4341,10 @@ namespace ts {
}
function needsIndentation(parent: Node, node1: Node, node2: Node): boolean {
if (getEmitFlags(parent) & EmitFlags.NoIndentation) {
return false;
}
parent = skipSynthesizedParentheses(parent);
node1 = skipSynthesizedParentheses(node1);
node2 = skipSynthesizedParentheses(node2);
@@ -4210,7 +4377,7 @@ namespace ts {
if (isGeneratedIdentifier(node)) {
return generateName(node);
}
else if (isIdentifier(node) && (nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && getSourceFileOfNode(node) !== getOriginalNode(currentSourceFile)))) {
else if ((isIdentifier(node) || isPrivateIdentifier(node)) && (nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && getSourceFileOfNode(node) !== getOriginalNode(currentSourceFile)))) {
return idText(node);
}
else if (node.kind === SyntaxKind.StringLiteral && (<StringLiteral>node).textSourceNode) {
@@ -4223,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);
}
/**
@@ -4343,6 +4510,9 @@ namespace ts {
case SyntaxKind.NamespaceImport:
generateNameIfNeeded((<NamespaceImport>node).name);
break;
case SyntaxKind.NamespaceExport:
generateNameIfNeeded((<NamespaceExport>node).name);
break;
case SyntaxKind.NamedImports:
forEach((<NamedImports>node).elements, generateNames);
break;
@@ -4633,6 +4803,7 @@ namespace ts {
// Comments
function pipelineEmitWithComments(hint: EmitHint, node: Node) {
Debug.assert(lastNode === node || lastSubstitution === node);
enterComment();
hasWrittenComment = false;
const emitFlags = getEmitFlags(node);
@@ -4674,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);
@@ -4699,6 +4870,7 @@ namespace ts {
}
}
exitComment();
Debug.assert(lastNode === node || lastSubstitution === node);
}
function emitLeadingSynthesizedComment(comment: SynthesizedComment) {
@@ -4945,7 +5117,8 @@ namespace ts {
}
function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) {
const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, node);
Debug.assert(lastNode === node || lastSubstitution === node);
const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, hint, node);
if (isUnparsedSource(node) || isUnparsedPrepend(node)) {
pipelinePhase(hint, node);
}
@@ -4987,6 +5160,7 @@ namespace ts {
emitSourcePos(source, end);
}
}
Debug.assert(lastNode === node || lastSubstitution === node);
}
/**
+26 -3508
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-8
View File
@@ -10,12 +10,6 @@ namespace ts {
return !!compilerOptions.traceResolution && host.trace !== undefined;
}
/** Array that is only intended to be pushed to, never read. */
/* @internal */
export interface Push<T> {
push(value: T): void;
}
function withPackageId(packageInfo: PackageJsonInfo | undefined, r: PathAndExtension | undefined): Resolved | undefined {
let packageId: PackageId | undefined;
if (r && packageInfo) {
@@ -118,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 {
+88 -55
View File
@@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers {
function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences {
return {
relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative,
ending: hasJSOrJsonFileExtension(oldImportSpecifier) ?
ending: hasJSFileExtension(oldImportSpecifier) ?
Ending.JsExtension :
getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal,
};
@@ -64,6 +64,20 @@ namespace ts.moduleSpecifiers {
return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile));
}
export function getNodeModulesPackageName(
compilerOptions: CompilerOptions,
importingSourceFileName: Path,
nodeModulesFileName: string,
host: ModuleSpecifierResolutionHost,
files: readonly SourceFile[],
redirectTargetsMap: RedirectTargetsMap,
): string | undefined {
const info = getInfo(importingSourceFileName, host);
const modulePaths = getAllModulePaths(files, importingSourceFileName, nodeModulesFileName, info.getCanonicalFileName, host, redirectTargetsMap);
return firstDefined(modulePaths,
moduleFileName => tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true));
}
function getModuleSpecifierWorker(
compilerOptions: CompilerOptions,
importingSourceFileName: Path,
@@ -79,7 +93,7 @@ namespace ts.moduleSpecifiers {
getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
}
// Returns an import for each symlink and for the realpath.
/** Returns an import for each symlink and for the realpath. */
export function getModuleSpecifiers(
moduleSymbol: Symbol,
compilerOptions: CompilerOptions,
@@ -149,41 +163,19 @@ namespace ts.moduleSpecifiers {
}
function usesJsExtensionOnImports({ imports }: SourceFile): boolean {
return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSOrJsonFileExtension(text) : undefined) || false;
return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSFileExtension(text) : undefined) || false;
}
function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean {
return getCanonicalFileName(a) === getCanonicalFileName(b);
function numberOfDirectorySeparators(str: string) {
const match = str.match(/\//g);
return match ? match.length : 0;
}
// KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
// ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
function isNodeModulesOrScopedPackageDirectory(s: string, getCanonicalFileName: GetCanonicalFileName): boolean {
return getCanonicalFileName(s) === "node_modules" || startsWith(s, "@");
}
function guessDirectorySymlink(a: string, b: string, cwd: string, getCanonicalFileName: GetCanonicalFileName): [string, string] {
const aParts = getPathComponents(toPath(a, cwd, getCanonicalFileName));
const bParts = getPathComponents(toPath(b, cwd, getCanonicalFileName));
while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
!isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
stringsEqual(aParts[aParts.length - 1], bParts[bParts.length - 1], getCanonicalFileName)) {
aParts.pop();
bParts.pop();
}
return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)];
}
function discoverProbableSymlinks(files: readonly SourceFile[], getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap<string> {
const result = createMap<string>();
const symlinks = flatten<readonly [string, string]>(mapDefined(files, sf =>
sf.resolvedModules && compact(arrayFrom(mapIterator(sf.resolvedModules.values(), res =>
res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] as const : undefined)))));
for (const [resolvedPath, originalPath] of symlinks) {
const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName);
result.set(commonOriginal, commonResolved);
}
return result;
function comparePathsByNumberOfDirectorySeparators(a: string, b: string) {
return compareValues(
numberOfDirectorySeparators(a),
numberOfDirectorySeparators(b)
);
}
/**
@@ -195,7 +187,9 @@ namespace ts.moduleSpecifiers {
const importedFileNames = redirects ? [...redirects, importedFileName] : [importedFileName];
const cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : "";
const targets = importedFileNames.map(f => getNormalizedAbsolutePath(f, cwd));
const links = discoverProbableSymlinks(files, getCanonicalFileName, cwd);
const links = host.getProbableSymlinks
? host.getProbableSymlinks(files)
: discoverProbableSymlinks(files, getCanonicalFileName, cwd);
const result: string[] = [];
const compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? compareStringsCaseSensitive : compareStringsCaseInsensitive;
@@ -214,7 +208,39 @@ namespace ts.moduleSpecifiers {
}
});
result.push(...targets);
return result;
if (result.length < 2) return result;
// Sort by paths closest to importing file Name directory
const allFileNames = arrayToMap(result, identity, getCanonicalFileName);
const sortedPaths: string[] = [];
for (
let directory = getDirectoryPath(toPath(importingFileName, cwd, getCanonicalFileName));
allFileNames.size !== 0;
) {
const directoryStart = ensureTrailingDirectorySeparator(directory);
let pathsInDirectory: string[] | undefined;
allFileNames.forEach((canonicalFileName, fileName) => {
if (startsWith(canonicalFileName, directoryStart)) {
(pathsInDirectory || (pathsInDirectory = [])).push(fileName);
allFileNames.delete(fileName);
}
});
if (pathsInDirectory) {
if (pathsInDirectory.length > 1) {
pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
}
sortedPaths.push(...pathsInDirectory);
}
const newDirectory = getDirectoryPath(directory);
if (newDirectory === directory) break;
directory = newDirectory;
}
if (allFileNames.size) {
const remainingPaths = arrayFrom(allFileNames.values());
if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
sortedPaths.push(...remainingPaths);
}
return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol): string | undefined {
@@ -262,7 +288,7 @@ namespace ts.moduleSpecifiers {
: removeFileExtension(relativePath);
}
function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions): string | undefined {
function tryGetModuleNameAsNodeModule(moduleFileName: string, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions, packageNameOnly?: boolean): string | undefined {
if (!host.fileExists || !host.readFile) {
return undefined;
}
@@ -271,33 +297,40 @@ namespace ts.moduleSpecifiers {
return undefined;
}
let packageJsonContent: any | undefined;
const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex);
const packageJsonPath = combinePaths(packageRootPath, "package.json");
const packageJsonContent = host.fileExists(packageJsonPath)
? JSON.parse(host.readFile(packageJsonPath)!)
: undefined;
const versionPaths = packageJsonContent && packageJsonContent.typesVersions
? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
: undefined;
if (versionPaths) {
const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
const fromPaths = tryGetModuleNameFromPaths(
removeFileExtension(subModuleName),
removeExtensionAndIndexPostFix(subModuleName, Ending.Minimal, options),
versionPaths.paths
);
if (fromPaths !== undefined) {
moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
if (!packageNameOnly) {
const packageJsonPath = combinePaths(packageRootPath, "package.json");
packageJsonContent = host.fileExists(packageJsonPath)
? JSON.parse(host.readFile(packageJsonPath)!)
: undefined;
const versionPaths = packageJsonContent && packageJsonContent.typesVersions
? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
: undefined;
if (versionPaths) {
const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1);
const fromPaths = tryGetModuleNameFromPaths(
removeFileExtension(subModuleName),
removeExtensionAndIndexPostFix(subModuleName, Ending.Minimal, options),
versionPaths.paths
);
if (fromPaths !== undefined) {
moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths);
}
}
}
// Simplify the full file path to something that can be resolved by Node.
// If the module could be imported by a directory name, use that directory's name
const moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName);
const moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName);
const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
// Get a path that's relative to node_modules or the importing file's path
// if node_modules folder is in this folder or any of its parent folders, no need to keep it.
if (!startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined;
const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
if (!(startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
return undefined;
}
// If the module was found in @types, get the actual Node package name
const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
@@ -309,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;
+375 -139
View File
File diff suppressed because it is too large. Load diff
+855
View File
@@ -0,0 +1,855 @@
/* @internal */
namespace ts {
/**
* Internally, we represent paths as strings with '/' as the directory separator.
* When we make system calls (eg: LanguageServiceHost.getDirectory()),
* we expect the host to correctly handle paths in our specified format.
*/
export const directorySeparator = "/";
const altDirectorySeparator = "\\";
const urlSchemeSeparator = "://";
const backslashRegExp = /\\/g;
//// Path Tests
/**
* Determines whether a charCode corresponds to `/` or `\`.
*/
export function isAnyDirectorySeparator(charCode: number): boolean {
return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash;
}
/**
* Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
*/
export function isUrl(path: string) {
return getEncodedRootLength(path) < 0;
}
/**
* Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
* like `c:`, `c:\` or `c:/`).
*/
export function isRootedDiskPath(path: string) {
return getEncodedRootLength(path) > 0;
}
/**
* Determines whether a path consists only of a path root.
*/
export function isDiskPathRoot(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength > 0 && rootLength === path.length;
}
/**
* Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
*
* ```ts
* // POSIX
* pathIsAbsolute("/path/to/file.ext") === true
* // DOS
* pathIsAbsolute("c:/path/to/file.ext") === true
* // URL
* pathIsAbsolute("file:///path/to/file.ext") === true
* // Non-absolute
* pathIsAbsolute("path/to/file.ext") === false
* pathIsAbsolute("./path/to/file.ext") === false
* ```
*/
export function pathIsAbsolute(path: string): boolean {
return getEncodedRootLength(path) !== 0;
}
/**
* Determines whether a path starts with a relative path component (i.e. `.` or `..`).
*/
export function pathIsRelative(path: string): boolean {
return /^\.\.?($|[\\/])/.test(path);
}
export function hasExtension(fileName: string): boolean {
return stringContains(getBaseFileName(fileName), ".");
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}
/**
* Determines whether a path has a trailing separator (`/` or `\\`).
*/
export function hasTrailingDirectorySeparator(path: string) {
return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
}
//// Path Parsing
function isVolumeCharacter(charCode: number) {
return (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) ||
(charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z);
}
function getFileUrlVolumeSeparatorEnd(url: string, start: number) {
const ch0 = url.charCodeAt(start);
if (ch0 === CharacterCodes.colon) return start + 1;
if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) {
const ch2 = url.charCodeAt(start + 2);
if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3;
}
return -1;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
* If the root is part of a URL, the twos-complement of the root length is returned.
*/
function getEncodedRootLength(path: string): number {
if (!path) return 0;
const ch0 = path.charCodeAt(0);
// POSIX or UNC
if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) {
if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\")
const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2);
if (p1 < 0) return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
}
// DOS
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) {
const ch2 = path.charCodeAt(2);
if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\"
if (path.length === 2) return 2; // DOS: "c:" (but not "c:d")
}
// URL
const schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
const authorityStart = schemeEnd + urlSchemeSeparator.length;
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
// For local "file" URLs, include the leading DOS volume (if present).
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
// special case interpreted as "the machine from which the URL is being interpreted".
const scheme = path.slice(0, schemeEnd);
const authority = path.slice(authorityStart, authorityEnd);
if (scheme === "file" && (authority === "" || authority === "localhost") &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) {
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
// but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
return ~path.length; // URL: "file://server", "http://server"
}
// relative
return 0;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
*
* For example:
* ```ts
* getRootLength("a") === 0 // ""
* getRootLength("/") === 1 // "/"
* getRootLength("c:") === 2 // "c:"
* getRootLength("c:d") === 0 // ""
* getRootLength("c:/") === 3 // "c:/"
* getRootLength("c:\\") === 3 // "c:\\"
* getRootLength("//server") === 7 // "//server"
* getRootLength("//server/share") === 8 // "//server/"
* getRootLength("\\\\server") === 7 // "\\\\server"
* getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
* getRootLength("file:///path") === 8 // "file:///"
* getRootLength("file:///c:") === 10 // "file:///c:"
* getRootLength("file:///c:d") === 8 // "file:///"
* getRootLength("file:///c:/path") === 11 // "file:///c:/"
* getRootLength("file://server") === 13 // "file://server"
* getRootLength("file://server/path") === 14 // "file://server/"
* getRootLength("http://server") === 13 // "http://server"
* getRootLength("http://server/path") === 14 // "http://server/"
* ```
*/
export function getRootLength(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* ```
*/
export function getDirectoryPath(path: Path): Path;
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* getDirectoryPath("file://server/path/to/file.ext") === "file://server/path/to"
* getDirectoryPath("file://server/path/to") === "file://server/path"
* getDirectoryPath("file://server/") === "file://server/"
* getDirectoryPath("file://server") === "file://server"
* getDirectoryPath("file:///path/to/file.ext") === "file:///path/to"
* getDirectoryPath("file:///path/to") === "file:///path"
* getDirectoryPath("file:///") === "file:///"
* getDirectoryPath("file://") === "file://"
* ```
*/
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): string {
path = normalizeSlashes(path);
// If the path provided is itself the root, then return it.
const rootLength = getRootLength(path);
if (rootLength === path.length) return path;
// return the leading portion of the path up to the last (non-terminal) directory separator
// but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
}
/**
* Returns the path except for its containing directory name.
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
*
* ```ts
* // POSIX
* getBaseFileName("/path/to/file.ext") === "file.ext"
* getBaseFileName("/path/to/") === "to"
* getBaseFileName("/") === ""
* // DOS
* getBaseFileName("c:/path/to/file.ext") === "file.ext"
* getBaseFileName("c:/path/to/") === "to"
* getBaseFileName("c:/") === ""
* getBaseFileName("c:") === ""
* // URL
* getBaseFileName("http://typescriptlang.org/path/to/file.ext") === "file.ext"
* getBaseFileName("http://typescriptlang.org/path/to/") === "to"
* getBaseFileName("http://typescriptlang.org/") === ""
* getBaseFileName("http://typescriptlang.org") === ""
* getBaseFileName("file://server/path/to/file.ext") === "file.ext"
* getBaseFileName("file://server/path/to/") === "to"
* getBaseFileName("file://server/") === ""
* getBaseFileName("file://server") === ""
* getBaseFileName("file:///path/to/file.ext") === "file.ext"
* getBaseFileName("file:///path/to/") === "to"
* getBaseFileName("file:///") === ""
* getBaseFileName("file://") === ""
* ```
*/
export function getBaseFileName(path: string): string;
/**
* Gets the portion of a path following the last (non-terminal) separator (`/`).
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
* If the base name has any one of the provided extensions, it is removed.
*
* ```ts
* getBaseFileName("/path/to/file.ext", ".ext", true) === "file"
* getBaseFileName("/path/to/file.js", ".ext", true) === "file.js"
* getBaseFileName("/path/to/file.js", [".ext", ".js"], true) === "file"
* getBaseFileName("/path/to/file.ext", ".EXT", false) === "file.ext"
* ```
*/
export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
path = normalizeSlashes(path);
// if the path provided is itself the root, then it has not file name.
const rootLength = getRootLength(path);
if (rootLength === path.length) return "";
// return the trailing portion of the path starting after the last (non-terminal) directory
// separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
function tryGetExtensionFromPath(path: string, extension: string, stringEqualityComparer: (a: string, b: string) => boolean) {
if (!startsWith(extension, ".")) extension = "." + extension;
if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === CharacterCodes.dot) {
const pathExtension = path.slice(path.length - extension.length);
if (stringEqualityComparer(pathExtension, extension)) {
return pathExtension;
}
}
}
function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) {
if (typeof extensions === "string") {
return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
}
for (const extension of extensions) {
const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
if (result) return result;
}
return "";
}
/**
* Gets the file extension for a path.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext") === ".ext"
* getAnyExtensionFromPath("/path/to/file.ext/") === ".ext"
* getAnyExtensionFromPath("/path/to/file") === ""
* getAnyExtensionFromPath("/path/to.ext/file") === ""
* ```
*/
export function getAnyExtensionFromPath(path: string): string;
/**
* Gets the file extension for a path, provided it is one of the provided extensions.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext", ".ext", true) === ".ext"
* getAnyExtensionFromPath("/path/to/file.js", ".ext", true) === ""
* getAnyExtensionFromPath("/path/to/file.js", [".ext", ".js"], true) === ".js"
* getAnyExtensionFromPath("/path/to/file.ext", ".EXT", false) === ""
*/
export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string {
// Retrieves any string from the final "." onwards from a base file name.
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
}
const baseFileName = getBaseFileName(path);
const extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
return "";
}
function pathComponents(path: string, rootLength: number) {
const root = path.substring(0, rootLength);
const rest = path.substring(rootLength).split(directorySeparator);
if (rest.length && !lastOrUndefined(rest)) rest.pop();
return [root, ...rest];
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is not normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* // POSIX
* getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
* getPathComponents("/path/to/") === ["/", "path", "to"]
* getPathComponents("/") === ["/"]
* // DOS
* getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
* getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
* getPathComponents("c:/") === ["c:/"]
* getPathComponents("c:") === ["c:"]
* // URL
* getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
* getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
* getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
* getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
* getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
* getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
* getPathComponents("file://server/") === ["file://server/"]
* getPathComponents("file://server") === ["file://server"]
* getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
* getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
* getPathComponents("file:///") === ["file:///"]
* getPathComponents("file://") === ["file://"]
*/
export function getPathComponents(path: string, currentDirectory = "") {
path = combinePaths(currentDirectory, path);
return pathComponents(path, getRootLength(path));
}
//// Path Formatting
/**
* Formats a parsed path consisting of a root component (at index 0) and zero or more path
* segments (at indices > 0).
*
* ```ts
* getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
* ```
*/
export function getPathFromPathComponents(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
return root + pathComponents.slice(1).join(directorySeparator);
}
//// Path Normalization
/**
* Normalize path separators, converting `\` into `/`.
*/
export function normalizeSlashes(path: string): string {
return path.replace(backslashRegExp, directorySeparator);
}
/**
* Reduce an array of path components to a more simplified path by navigating any
* `"."` or `".."` entries in the path.
*/
export function reducePathComponents(components: readonly string[]) {
if (!some(components)) return [];
const reduced = [components[0]];
for (let i = 1; i < components.length; i++) {
const component = components[i];
if (!component) continue;
if (component === ".") continue;
if (component === "..") {
if (reduced.length > 1) {
if (reduced[reduced.length - 1] !== "..") {
reduced.pop();
continue;
}
}
else if (reduced[0]) continue;
}
reduced.push(component);
}
return reduced;
}
/**
* Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
*
* ```ts
* // Non-rooted
* combinePaths("path", "to", "file.ext") === "path/to/file.ext"
* combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
* // POSIX
* combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
* combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
* // DOS
* combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
* combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
* // URL
* combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
* combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
* ```
*/
export function combinePaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
relativePath = normalizeSlashes(relativePath);
if (!path || getRootLength(relativePath) !== 0) {
path = relativePath;
}
else {
path = ensureTrailingDirectorySeparator(path) + relativePath;
}
}
return path;
}
/**
* Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
* `.` and `..` path components are resolved. Trailing directory separators are preserved.
*
* ```ts
* resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
* resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
* resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
* ```
*/
export function resolvePath(path: string, ...paths: (string | undefined)[]): string {
return normalizePath(some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path));
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
*/
export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) {
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
export function normalizePath(path: string): string {
path = normalizeSlashes(path);
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
}
function getPathWithoutRoot(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
return pathComponents.slice(1).join(directorySeparator);
}
export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) {
return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
}
export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path {
const nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return <Path>getCanonicalFileName(nonCanonicalizedPath);
}
export function normalizePathAndParts(path: string): { path: string, parts: string[] } {
path = normalizeSlashes(path);
const [root, ...parts] = reducePathComponents(getPathComponents(path));
if (parts.length) {
const joinedParts = root + parts.join(directorySeparator);
return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts };
}
else {
return { path: root, parts };
}
}
//// Path Mutation
/**
* Removes a trailing directory separator from a path, if it does not already have one.
*
* ```ts
* removeTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext"
* removeTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext"
* ```
*/
export function removeTrailingDirectorySeparator(path: Path): Path;
export function removeTrailingDirectorySeparator(path: string): string;
export function removeTrailingDirectorySeparator(path: string) {
if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
/**
* Adds a trailing directory separator to a path, if it does not already have one.
*
* ```ts
* ensureTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext/"
* ensureTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext/"
* ```
*/
export function ensureTrailingDirectorySeparator(path: Path): Path;
export function ensureTrailingDirectorySeparator(path: string): string;
export function ensureTrailingDirectorySeparator(path: string) {
if (!hasTrailingDirectorySeparator(path)) {
return path + directorySeparator;
}
return path;
}
/**
* Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
* with `./` or `../`) so as not to be confused with an unprefixed module name.
*
* ```ts
* ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
* ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
* ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
* ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
* ```
*/
export function ensurePathIsNonModuleName(path: string): string {
return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
}
/**
* Changes the extension of a path to the provided extension.
*
* ```ts
* changeAnyExtension("/path/to/file.ext", ".js") === "/path/to/file.js"
* ```
*/
export function changeAnyExtension(path: string, ext: string): string;
/**
* Changes the extension of a path to the provided extension if it has one of the provided extensions.
*
* ```ts
* changeAnyExtension("/path/to/file.ext", ".js", ".ext") === "/path/to/file.js"
* changeAnyExtension("/path/to/file.ext", ".js", ".ts") === "/path/to/file.ext"
* changeAnyExtension("/path/to/file.ext", ".js", [".ext", ".ts"]) === "/path/to/file.js"
* ```
*/
export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
}
//// Path Comparisons
// check path for these segments: '', '.'. '..'
const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) {
if (a === b) return Comparison.EqualTo;
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
// NOTE: Performance optimization - shortcut if the root segments differ as there would be no
// need to perform path reduction.
const aRoot = a.substring(0, getRootLength(a));
const bRoot = b.substring(0, getRootLength(b));
const result = compareStringsCaseInsensitive(aRoot, bRoot);
if (result !== Comparison.EqualTo) {
return result;
}
// NOTE: Performance optimization - shortcut if there are no relative path segments in
// the non-root portion of the path
const aRest = a.substring(aRoot.length);
const bRest = b.substring(bRoot.length);
if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
return componentComparer(aRest, bRest);
}
// The path contains a relative path segment. Normalize the paths and perform a slower component
// by component comparison.
const aComponents = reducePathComponents(getPathComponents(a));
const bComponents = reducePathComponents(getPathComponents(b));
const sharedLength = Math.min(aComponents.length, bComponents.length);
for (let i = 1; i < sharedLength; i++) {
const result = componentComparer(aComponents[i], bComponents[i]);
if (result !== Comparison.EqualTo) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
/**
* Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
*/
export function comparePathsCaseSensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseSensitive);
}
/**
* Performs a case-insensitive comparison of two paths.
*/
export function comparePathsCaseInsensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseInsensitive);
}
/**
* Compare two paths using the provided case sensitivity.
*/
export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
a = combinePaths(currentDirectory, a);
b = combinePaths(currentDirectory, b);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
return comparePathsWorker(a, b, getStringComparer(ignoreCase));
}
/**
* Determines whether a `parent` path contains a `child` path using the provide case sensitivity.
*/
export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
parent = combinePaths(currentDirectory, parent);
child = combinePaths(currentDirectory, child);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
if (parent === undefined || child === undefined) return false;
if (parent === child) return true;
const parentComponents = reducePathComponents(getPathComponents(parent));
const childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (let i = 0; i < parentComponents.length; i++) {
const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
}
return true;
}
/**
* Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
* Comparison is case-sensitive between the canonical paths.
*
* @deprecated Use `containsPath` if possible.
*/
export function startsWithDirectory(fileName: string, directoryName: string, getCanonicalFileName: GetCanonicalFileName): boolean {
const canonicalFileName = getCanonicalFileName(fileName);
const canonicalDirectoryName = getCanonicalFileName(directoryName);
return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\");
}
//// Relative Paths
export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName) {
const fromComponents = reducePathComponents(getPathComponents(from));
const toComponents = reducePathComponents(getPathComponents(to));
let start: number;
for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
const fromComponent = getCanonicalFileName(fromComponents[start]);
const toComponent = getCanonicalFileName(toComponents[start]);
const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
if (!comparer(fromComponent, toComponent)) break;
}
if (start === 0) {
return toComponents;
}
const components = toComponents.slice(start);
const relative: string[] = [];
for (; start < fromComponents.length; start++) {
relative.push("..");
}
return ["", ...relative, ...components];
}
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string;
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: GetCanonicalFileName | boolean) {
Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
return getPathFromPathComponents(pathComponents);
}
export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) {
return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) {
const pathComponents = getPathComponentsRelativeTo(
resolvePath(currentDirectory, directoryPathOrUrl),
resolvePath(currentDirectory, relativeOrAbsolutePath),
equateStringsCaseSensitive,
getCanonicalFileName
);
const firstComponent = pathComponents[0];
if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///";
pathComponents[0] = prefix + firstComponent;
}
return getPathFromPathComponents(pathComponents);
}
//// Path Traversal
/**
* Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result.
*/
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined {
while (true) {
const result = callback(directory);
if (result !== undefined) {
return result;
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
return undefined;
}
directory = parentPath;
}
}
}
-2
View File
@@ -38,6 +38,4 @@ namespace ts {
/** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
export const perfLogger: PerfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
const args = typeof process === "undefined" ? [] : process.argv;
perfLogger.logInfoEvent(`Starting TypeScript v${versionMajorMinor} with command line: ${JSON.stringify(args)}`);
}
-7
View File
@@ -1,10 +1,3 @@
/*@internal*/
namespace ts {
declare const performance: { now?(): number } | undefined;
/** Gets a timestamp with (at least) ms resolution */
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now!() : Date.now ? Date.now : () => +(new Date());
}
/*@internal*/
/** Performance measurements for the compiler. */
namespace ts.performance {
+6
View File
@@ -0,0 +1,6 @@
/*@internal*/
namespace ts {
declare const performance: { now?(): number } | undefined;
/** Gets a timestamp with (at least) ms resolution */
export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now!() : Date.now ? Date.now : () => +(new Date());
}
+399 -227
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 4243 files, more files were not shown because too many files have changed in this diff. Show more