Compare commits

...

71 commits

Author SHA1 Message Date
zhengbli 3375fed667 Reset the noEmitForJsFiles option when updating compiler options (#12570) 2016-11-29 22:34:49 -08:00
zhengbli 5108285df4 Port (#12474) 2016-11-23 12:35:16 -08:00
jramsay c43c37f64a Merge pull request #12454 from Microsoft/PortTypingOptionsRenameToRelease2.1
Port typingOptions rename from master to release-2.1
2016-11-22 17:47:42 -08:00
Jason Ramsay e5227b15f9 Addressing CR feedback 2016-11-22 17:36:05 -08:00
Jason Ramsay 19dcb45e4f Maintain support for deprecated API typingOptions.enableAutoDiscovery 2016-11-22 17:35:54 -08:00
Jason Ramsay ada48e548a Rename typingOptions.enableAutoDiscovery to typeAcquisition.enable 2016-11-22 17:35:21 -08:00
Vladimir Matveev 432f7a9a7d add typings installer user agent for npm requests (#12446) (#12449)
* add typings installer user agent for npm requests

* address PR feedback: change name of user agent
2016-11-22 15:22:50 -08:00
Ryan Cavanaugh fb23e6dba1 Merge pull request #12442 from RyanCavanaugh/portAugments
Port augments to 2.1
2016-11-22 11:52:18 -08:00
Ryan Cavanaugh daa9d59c4c Support JSDoc @augments tag
Fixes #12428
2016-11-22 11:27:16 -08:00
zhengbli 761895dee4 Port (#12372) 2016-11-22 11:11:00 -08:00
Mohamed Hegazy 77613eb325 Merge pull request #12440 from Microsoft/mergeMaster11222016
Merge master into release-2.1
2016-11-22 10:59:17 -08:00
Mohamed Hegazy 7e8af628ed Merge branch 'master' into release-2.1 2016-11-22 10:45:18 -08:00
Vladimir Matveev 6389a0debc wrap subexpressions of conditional expressions in parens if necessary (#12420) (#12422) 2016-11-21 13:41:12 -08:00
Vladimir Matveev 4c8cdb41e6 recompute character to column when comparing indentations (#12375) (#12418)
recompute character to column when comparing indentations
2016-11-21 12:06:43 -08:00
Zhengbo Li 0952e7d8d6 Port 12369 to release-2.1 (#12414) 2016-11-21 10:45:43 -08:00
Nathan Shively-Sanders b857439270 Check assignability: rest destructuring assignment 2016-11-18 16:02:03 -08:00
Nathan Shively-Sanders 6b0de7b5ae Test assignability checking of object rests 2016-11-18 16:01:54 -08:00
Nathan Shively-Sanders 0e1be3efa1 Always enable evolving types in Javascript files 2016-11-18 15:52:34 -08:00
Nathan Shively-Sanders 6fb9d9a811 Update baselines to have no evolving types 2016-11-18 15:52:29 -08:00
Nathan Shively-Sanders 90fa6335c8 Disable evolving types with implicit any
That is, without --noImplicitAny
2016-11-18 15:52:24 -08:00
Sheetal Nandi 707ed699bb Merge pull request #12366 from Microsoft/declarationsInFilesWithErrors
[Release 2.1] Fixes for #12291 and #12326: Declaration emit when there are errors in the source file
2016-11-18 15:46:58 -08:00
Mohamed Hegazy b8f6227aa8 Merge pull request #12368 from Microsoft/Port12351-3
Port #12351  to release-2.1
2016-11-18 15:42:32 -08:00
Anders Hejlsberg a41746bd6c Add tests 2016-11-18 15:24:52 -08:00
Anders Hejlsberg dad5736306 Support apparent types for T[K] indexed access types 2016-11-18 15:24:47 -08:00
Anders Hejlsberg c1d9b19bc7 Add new tests 2016-11-18 15:24:43 -08:00
Anders Hejlsberg 4b1ac518d3 Accept new baselines 2016-11-18 15:24:37 -08:00
Anders Hejlsberg 47cf1ff5fc Error on circular constraints in mapped types 2016-11-18 15:24:32 -08:00
Anders Hejlsberg 398244177d Type relations for generic mapped types 2016-11-18 15:24:26 -08:00
Sheetal Nandi 6f1c3b3b49 Handle when type alias's type parameter extends type that wont get emitted in .d.ts
Fixes #12326
2016-11-18 14:58:17 -08:00
Sheetal Nandi 9ce544e229 Handle the scenario when heritage clause of interface is not entity name expression
Fixes #12291
2016-11-18 14:58:14 -08:00
Vladimir Matveev 30fde91970 use location of config file as initial location for automatic type reference inclusion if possible (#12341) (#12361) 2016-11-18 14:25:26 -08:00
Vladimir Matveev 5f6ec46bf8 pass project name as a constructor parameter (#12333) (#12337) 2016-11-17 16:49:16 -08:00
Mohamed Hegazy 83994e151b Update LKG 2016-11-17 15:41:40 -08:00
Mohamed Hegazy efe2c56b5e Disable code fixes for now 2016-11-17 15:41:07 -08:00
Mohamed Hegazy 7da6391ca8 Revert versions after merge 2016-11-17 14:39:01 -08:00
Mohamed Hegazy 0309fd161f Merge branch 'master' into release-2.1 2016-11-17 14:33:49 -08:00
Mohamed Hegazy ee145ec9f6 Update LKG 2016-11-10 16:28:37 -08:00
Mohamed Hegazy 245a998de5 Merge master into release 2.1 (#12160)
* Use a single ShimMap class, and indicate that iteration always yields string keys (which it did before too)

* Remove emacs-added newline at end of baseline

* Remove space at end of line in baseline

* Add numeric indexer to strings and remove lint

* Update baselines with spread string's numeric indexers

* Reset baseline line number to the locally incorrect value

* Remove trailing newline from baseline again

* Respond to PR comments

* Refactor getTypeFromTypeLiteral, from PR comments

* Fix lint

* Use same literal comparison rules for switch/===

switch was missing the rule for converting literal types to the literal
base type if needed.

* Add switch comparability test and update baselines

* Push eitherIsNotLiteral check into isTypeEqualityComparableTo

Since all callers need this check -- it's how equality is supposed to
work everywhere.

* Update baselines

There are more literal types in error messages because error reporting
no longer has the advantage of calls to getBaseLiteralType

* Adds ES5 to ES3 transformer for reserved words

* Minor cleanup

* Cleaned up emit of enum declaration

* Return both ts and js results from module resolution, and don't have moduleNameResolver responsible for omitting files based on compiler options

* Instead of getResolutionOrDiagnostic, use getResolutionDiagnostic and avoid using resolution.resolvedFileName if the diagnostic is defined.

* Remove "ResolvedModuleFromHost" type and just make `resolvedTsFileName` and `resolvedJsFileName` optional properties

(but still automatically infer one of them to supply if the host supplied neither)

* Remove type inference for spread types

* Update inference test for spread types

* Make spread assignability and apparent type stricter

Assignability now does not allow properties to the left of a type
parameter.
Apparent type now only returns the apparent type of the right-most
spread member.

* Update tests w/spread assignability+apparent type

* Moved AMD/CJS/UMD transform to end

* Spread no longer distributes intersections

* Update spread w/intersection tests

* Move System module transform to end.

* Update baseline

* Revert baseline change due to stale output

* Resolve all-object intersections inside spreads

This means that getSpreadType will return an object type, even when
spreading two intersections, as long as those intersections contain
nothing but object types themselves.

* Update and improve spread intersection tests

* Simplify expression in resolveObjectIntersection

* Update baselines with new index signature rules

* Move n-ary spread handling into separate function.

To be moved to callers in the next step.

* Move multiple-spread handling out of getSpreadType

* Clean up and reorder getSpreadType body

* Respond to PR comments

* Error for call/construct signatures in spread type

1. Simplify the error reporting code to handle all kinds of signatures.
2. Remove index signature handling code when creating a spread type
since it's an error anyway.

* Update baselines with new spread type index errors

* Explain writeSpreadType a little better

* Add more commentary to getSpreadType

* Initial implementation of 'keyof T' type operator

* Introduce PropertyNameType

* Move most of resolveModuleNameForLsHost to lsHost

* Simplify isImplicitGlob test

* Initial implementation of 'T[K]' property access types

* add a fallback logic for older versions of node that don't support 'homedir' (#11845)

* add a fallback logic for older versions of node that don't support 'homedir'

* try os.homedir first

* For JavaScript files, we report semantic errors for using TypeScript-only constructs 
from within a JavaScript file as syntactic errors.

* Don't require `resolvedTsFileName` and `resolvedJsFileName`, just `resolvedFileName` and `extension`. Also, change search order to do all TS searching before searching for JS.

* Fix #10108 (Completion suggestion for object literal with getter) (#11808)

* Fix #10108 (Completion suggestion for object literal with getter)

* completions for setter

* Move helper functions to core (fix build)

* Support parametric property access expressions + some renaming

* rewrite void-returning statements in constructors that capture result of super call (#11868)

* rewrite void-returning statements in constructors that capture result of super call

* linter

* only emit /// types reference for a symbol in d.ts file if all declarations of a symbol come from type reference directives (#11872)

* only emit /// types reference for a symbol in d.ts file if all declarations of a symbol come from type reference directives

* pass proper value for current directory when compiling .d.ts files

* Fix bug: Return a resolution diagnostic for a `.jsx` import if `--allowJs` is turned off

* Remove a comment about a parameter that no longer exists

* Fix bug: We want to test for existence of the enum value, not whether it's non-zero

* Fix: test for presence, not absence

* Allow untyped imports

* Simplify for loops in fourslash.ts

* Rename to zipWith

* Change diagnostic message

* Make `extension` property of `ResolvedModule` optional; introduce `ResolvedModuleFull` interface for when the extension is provided.

* Consider index signatures in type produced by 'keyof T'

* Respond to PR comments

* Refactor getIndexedAccessType to be reusable from checkIndexedAccess

* Skip overloads with too-short function parameters

If the parameter of an overload is a function and the argument is also a
function, skip the overload if the parameter has fewer arguments than
the argument does. That overload cannot possibly apply, and should not
participate in, for example, contextual typing.

Example:

```ts
interface I {
  (a: number): void;
  (b: string, c): void;
}
declare function f(i: I): void;
f((x, y) => {});
```

This code now skips the first overload instead of considering.

This was a longstanding bug but was only uncovered now that more
functions expressions are context sensitive.

* Test skip overloads w/too-short function params

1. Update changed baseline.
2. Add a new test with baseline.

* Minor style improvements

* Ignore optionality when skipping overloads

* Revert "Merge pull request #11354 from Microsoft/map4"

This reverts commit adfdae0dc4, reversing
changes made to aad663cebf.

* Rename Experimental transform to ESNext

1. Spread/rest are no longer experimental.
2. We need a place to put stage 3 ES features.

* Changes from CR feedback

* disable CoS for inferred projects (#11909)

* Updating test due to CR changes.  The order of the diagnostic messages has changed due to concatenation changes

* Do not use contextual signatures with too few parameters

* isAritySmaller runs later: getNonGenericSignature

* Rename TransformFlags.Experimental -> ESNext

* enable non-ts extensions in inferred projects by default

* update CFG to properly handle do statements

* do not inline async IIFEs in control flow graph

* Minor fixes

* cache type for empty type literal (#11934)

cache type for empty type literal

* Improved error messages for invalid assignments to identifiers

* Accept new baselines

* Improved error messages for invalid assignments to properties

* Accept new baselines

* Improve more error messages

* Accept new baselines

* Fix realPathMap in test harness: Must be used in `directoryExists`

* Add helper function

* Update generated files (#11963)

* Move eitherIsNotLiteral check into switch and === checks

This improves error messages

* Forbid augmentation of untyped module (#11962)

* Forbid augmentation of untyped module

* Just use `undefined` for untyped modules

* Unify checking of indexed access expressions and indexed access types

* Accept new baselines

* Accept additional baselines

* Make `cachingInServerLSHost` tests work with `runtests-browser`

* Get literal type only once

* Update baselines

* Add missed test update

* Improve unification by moving more logic to getIndexedAccessType

* Add test cases to report errors for decorators in js file

* Report all the js file errors and skip only the nodes that are not allowed in js
Fixes #11800

* Fix 'keyof any' to produce 'string | number'

* Fix #11396: Make error message referene `Promise` explicitly (#11982)

* Simplify the checking for async function return type

* Fix https://github.com/Microsoft/TypeScript/issues/11396: Make error message referene `Promise` explicitly

* Minor fixes

* Adding tests

* Test case for property used in destructuring variable declaration

* Mark property referenced in the destructuring as referenced
Fixes #11324

* Spread types handle nested index [access] types

Nested index [access] types are treated as assignable to themselves only,
just like type parameters.

* Test index [access] types inside spread types

* module resolution: prefer locally defined ambient modules, reuse resolutions to ambient modules from the old program (#11999)

module resolution: prefer locally defined ambient modules, reuse resolutions to ambient modules from the old program

* Parse, bind and check rest elements

* Downlevel emit of rest elements

* Add rest tests

* Update baselines

* Remove spread types, leaving spread syntax/emit

Spreads are still typed, but cannot be created from a non-object type.
Tests still need to be updated.

* Fix lint

* Lock tslint version to 4.0.0-dev.0, because 4.0.0-dev.1 complains about unnecessary semicolons following properties

* Remove spread type tests from spread tests

* Spread handles index signatures from singleton spreads

I broke it when simplifying the logic earlier.

* Correct assignability for keyof types and type parameters

* Update tests

* Accept new baselines

* Update objectRestAssignment test and baselines

* Fix linting errors

* Update objectRestAssignment test

Missed previously, just got the baselines

* Improve readability of ES next destructuring emit

* Ensure transformFlags are correct before visiting a node.

* Port #12027, #11980 and #11932 to master (#12037)

* add test for the fix for overwrite emitting error

* cr feedback

* Address PR comments

1. Remove extra line in __rest shim.
2. Improve __rest vs __assign check for destructuring assignment.

* Move convertForOf to factory for esnext and es2015

Saves a lot of duplicated code

* Update improved baselines

* Move transformFunctionBody to factory

It is shared by es2015 and esNext transformers.

This commit just adds a convertObjectRest flag to be passed on to
flattenDestructuring functions, as well as adding necessary parameters
to use the code outside a transformer.

* Spread any types to any

* add missing bind calls to properly set parent on token nodes (#12057)

* Cache generic signature instantiations

* Accept new baselines

* Properly instantiate aliasTypeArguments

* Add regression test

* Revert incorrect logic from #11392

* Accept new baselines

* Rename SpreadElementExpression -> SpreadAssignment

and SpreadExpression (formerly SpreadElementExpression) -> SpreadElement

* Add SpreadAssignment to visitors

1. visitNode
2. reduceNode
3. emit

This fixes an emit bug for setters.

* Add --target esnext

Currently, this disables the rest and spread transforms. This will
change as proposals enter and leave stage 3.

* Add --target esnext tests and update baselines

* Revert unneeded change and comments per PR

* Rename variable in checkSwitchStatement per PR

* Do not emit __rest for --target esnext

* Add `realpath` implementation for lshost

* Create spread property types eagerly

This avoids the need for a synthetic symbol and later code called from
getTypeOfSymbol.

* Set spread type symbols in checkObjectLiteral

Instead of getSpreadType.

Also clean up special-case handling inside getSpreadType to be more
readable.

* Ports #12051 and #12032 into master (#12090)

* use local registry to check if typings package exist (#12014)

use local registry to check if typings package exist

* enable sending telemetry events to tsserver client (#12035)

enable sending telemetry events

* Address more PR comments

* return empty file watcher in case if target directory does not exist (#12091)

* return empty file watcher in case if target directory does not exist

* linter

* property handle missing config files in external projects (#12094)

* Reuse subtree transform flags for incrementally parsed nodes (#12088)

* Port fix for https://github.com/Microsoft/TypeScript/issues/12069 (#12095)

* reduce set of files being watched, increase polling interval (#12054) (#12092)

* Update authors for release-2.1

* Include declaration file emit

* use createHash from ServerHost instead of explicit require (#12043)

* use createHash from ServerHost instead of explicit require

* added missing method in ServerHost stub

* (signature help) type parameter lists are never variadic (#12112)

* Handle abstract and const modifiers

* Downlevel array destructuring to ES6 in object rest

Previously array destructuring inside an object destructuring with an
object rest would downlevel the array destructuring to ES5. This breaks
if the code that targets ES2015 is using iterators instead of arrays
since iterators don't support [0] or .slice that the ES5 emit uses.

* Improve nested destructuring test for ESNext emit

Now with object destructuring inside array destructuring inside object
destructuring! Each with their own array/object rest!

Also updates baselines.

* Add support for taking in jsxFactory option and report errors for invalid combinations

* Treat `| undefined` like optionality in spread type

* Add strictNullChecks test for object spread

* Verify that jsxFactory is either identifier or qualified name

* Resolve first identifier of the jsxFactory as part of type check

* When emitting use jsx factory entity expression if provided

* Transpile unit test case

* Enabled test case for source map

* Add test cases for when jsxFactory cannot be resolved

* Parse the jsxFactory again in the checker instead of using cached value in the program

* Adds error message for incompatible assignment of identically named type

Fixes issue #12050

* Updated condition for more readability

* Report errors for import helpers missing __rest

* Correctly check spread assignments in strict mode

Previously it crashed in the binder.

* Test error for import helpers with no __rest

* synthesize complete import declaration for tslib (#12151)

* Add ES2017 string padding (#12152)

* add es2017.string.d.ts for String.prototype.{padStart,padEnd}

* append es2017.string.d.ts into es2017.d.ts

* add es2017.string into commandLineParser

* append es2017.string into error message for unit tests of commandLineParser

* append es2017.string into Gulpfile

* append es2017.string into Jakefile

* Exclude js files in non-configured projects compile-on-save emitting (#12118)

* Exclude js files in non-configured projects CoS emitting

* remove unnecessary method

* Merge release-2.1 into master (#12157)

* Update LKG

* Update version

* Update LKG

* Skip overloads with too-short function parameters

If the parameter of an overload is a function and the argument is also a
function, skip the overload if the parameter has fewer arguments than
the argument does. That overload cannot possibly apply, and should not
participate in, for example, contextual typing.

Example:

```ts
interface I {
  (a: number): void;
  (b: string, c): void;
}
declare function f(i: I): void;
f((x, y) => {});
```

This code now skips the first overload instead of considering.

This was a longstanding bug but was only uncovered now that more
functions expressions are context sensitive.

* Test skip overloads w/too-short function params

1. Update changed baseline.
2. Add a new test with baseline.

* Minor style improvements

* Ignore optionality when skipping overloads

* Do not use contextual signatures with too few parameters

* isAritySmaller runs later: getNonGenericSignature

* rewrite void-returning statements in constructors that capture result of super call (#11868)

* rewrite void-returning statements in constructors that capture result of super call

* linter

* Update LKG

* Fix emit inferred type which is a generic type-alias both fully and partially fill type parameters

* Add tests and baselines

* Skip trying to use alias if there is target type

* Update baselines

* Add diagnostics to remind adding tsconfig file for certain external project (#11932)

* Add diagnostics for certain external project

* Show tsconfig suggestion

* fix lint error

* Address pr

* fix comment

* Update error message

* Flag for not overwrite js files by default without generating errors (#11980)

* WIP

* Properly naming things

* refactor

* apply the option to all files and check out options

* Fix typo

* Update LKG

* lockLinter

* use local registry to check if typings package exist (#12014) (#12032)

use local registry to check if typings package exist

* Add test for https://github.com/Microsoft/TypeScript/pull/11980 (#12027)

* add test for the fix for overwrite emitting error

* cr feedback

* enable sending telemetry events to tsserver client (#12034) (#12051)

enable sending telemetry events

* Update LKG

* Reuse subtree transform flags for incrementally parsed nodes (#12088)

* Update LKG

* Update version

* Update LKG

* Do not emit "use strict" when targeting es6 or higher or module kind is es2015 and the file is external module

* Add tests and baselines

* [Release 2.1] fix11754 global augmentation (#12133)

* Exclude global augmentation from module resolution logic

* Address PR: check using string literal instead of NodeFlags.globalAugmentation

* Remove comment
2016-11-10 15:43:53 -08:00
Mohamed Hegazy 15dadc70f5 Update version 2016-11-10 12:20:17 -08:00
Yui f7c40d3d61 [Release 2.1] fix11754 global augmentation (#12133)
* Exclude global augmentation from module resolution logic

* Address PR: check using string literal instead of NodeFlags.globalAugmentation
2016-11-10 10:24:20 -08:00
Yui 6ba4b87dc7 Merge pull request #12134 from Microsoft/release-2.1_fix11806_omitUseStrict
[Release 2.1] fix11806 omit use strict
2016-11-09 17:12:42 -08:00
Kanchalai Tanglertsampan d629bd636d Add tests and baselines 2016-11-09 15:30:34 -08:00
Kanchalai Tanglertsampan afea1105c3 Do not emit "use strict" when targeting es6 or higher or module kind is es2015 and the file is external module 2016-11-09 15:30:15 -08:00
Mohamed Hegazy 34d41de06f Update LKG 2016-11-08 12:23:44 -08:00
Mohamed Hegazy aaf6c1dad4 Update version 2016-11-08 12:11:52 -08:00
Ron Buckton 796a159e63 Update LKG 2016-11-08 12:01:10 -08:00
Ron Buckton da4985e427 Reuse subtree transform flags for incrementally parsed nodes (#12088) 2016-11-08 12:00:50 -08:00
Mohamed Hegazy 8e8ec9f81d Update LKG 2016-11-04 12:01:20 -07:00
Vladimir Matveev f03e04a41e enable sending telemetry events to tsserver client (#12034) (#12051)
enable sending telemetry events
2016-11-04 11:35:44 -07:00
Zhengbo Li afe36be50c Add test for https://github.com/Microsoft/TypeScript/pull/11980 (#12027)
* add test for the fix for overwrite emitting error

* cr feedback
2016-11-03 16:26:03 -07:00
Vladimir Matveev 7d1f0e67b4 use local registry to check if typings package exist (#12014) (#12032)
use local registry to check if typings package exist
2016-11-03 15:12:44 -07:00
zhengbli 0b872109b6 lockLinter 2016-11-03 12:48:16 -07:00
Mohamed Hegazy b98089dc53 Update LKG 2016-11-03 10:35:23 -07:00
Zhengbo Li 73e2328acb Flag for not overwrite js files by default without generating errors (#11980)
* WIP

* Properly naming things

* refactor

* apply the option to all files and check out options

* Fix typo
2016-11-03 10:25:12 -07:00
Zhengbo Li 182bc774b5 Add diagnostics to remind adding tsconfig file for certain external project (#11932)
* Add diagnostics for certain external project

* Show tsconfig suggestion

* fix lint error

* Address pr

* fix comment

* Update error message
2016-11-01 16:42:06 -07:00
Yui ad9c148168 Merge pull request #11931 from Microsoft/release-2.1_fixDeclarationEmitTypeAlaisWithTypeParam
[Release-2.1] Fix declaration emit when using type parameters
2016-10-31 13:18:32 -07:00
Kanchalai Tanglertsampan f9a317ec97 Update baselines 2016-10-28 18:16:33 -07:00
Kanchalai Tanglertsampan f2e343903c Skip trying to use alias if there is target type 2016-10-28 18:16:14 -07:00
Kanchalai Tanglertsampan 01e06f9295 Add tests and baselines 2016-10-28 16:41:17 -07:00
Kanchalai Tanglertsampan 2869f9cb05 Fix emit inferred type which is a generic type-alias both fully and partially fill type parameters 2016-10-28 16:41:10 -07:00
Mohamed Hegazy 467f252583 Update LKG 2016-10-28 10:38:08 -07:00
Vladimir Matveev 86138e33c4 rewrite void-returning statements in constructors that capture result of super call (#11868)
* rewrite void-returning statements in constructors that capture result of super call

* linter
2016-10-28 10:25:34 -07:00
Nathan Shively-Sanders a163641bd3 isAritySmaller runs later: getNonGenericSignature 2016-10-28 10:14:11 -07:00
Nathan Shively-Sanders 2c09574f18 Do not use contextual signatures with too few parameters 2016-10-28 10:14:06 -07:00
Nathan Shively-Sanders 4e57f700d0 Ignore optionality when skipping overloads 2016-10-28 10:13:59 -07:00
Nathan Shively-Sanders b4451b159c Minor style improvements 2016-10-28 10:13:51 -07:00
Nathan Shively-Sanders dfa3dd30fb Test skip overloads w/too-short function params
1. Update changed baseline.
2. Add a new test with baseline.
2016-10-28 10:13:34 -07:00
Nathan Shively-Sanders 1f4d8a1a72 Skip overloads with too-short function parameters
If the parameter of an overload is a function and the argument is also a
function, skip the overload if the parameter has fewer arguments than
the argument does. That overload cannot possibly apply, and should not
participate in, for example, contextual typing.

Example:

```ts
interface I {
  (a: number): void;
  (b: string, c): void;
}
declare function f(i: I): void;
f((x, y) => {});
```

This code now skips the first overload instead of considering.

This was a longstanding bug but was only uncovered now that more
functions expressions are context sensitive.
2016-10-28 10:13:26 -07:00
Mohamed Hegazy 515542b293 Update LKG 2016-10-27 12:55:52 -07:00
Mohamed Hegazy e497d1ee07 Update version 2016-10-27 12:34:51 -07:00
Mohamed Hegazy 5e9494900a Update LKG 2016-10-25 16:02:19 -07:00
157 changed files with 19264 additions and 16423 deletions

View file

@ -256,7 +256,7 @@ var harnessSources = harnessCoreSources.concat([
"commandLineParsing.ts",
"configurationExtension.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts",
"convertTypeAcquisitionFromJson.ts",
"tsserverProjectSystem.ts",
"compileOnSave.ts",
"typingsInstaller.ts",

30
lib/lib.d.ts vendored
View file

@ -200,7 +200,7 @@ interface ObjectConstructor {
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): T;
freeze<T>(o: T): Readonly<T>;
/**
* Prevents the addition of new properties to an object.
@ -1363,6 +1363,34 @@ interface ArrayLike<T> {
readonly [n: number]: T;
}
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends string | number, T> = {
[P in K]: T;
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,

View file

@ -225,13 +225,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(value: any): value is number;
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(value: any): value is number;
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@ -239,13 +239,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(value: any): value is number;
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(value: any): value is number;
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as

30
lib/lib.es5.d.ts vendored
View file

@ -200,7 +200,7 @@ interface ObjectConstructor {
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): T;
freeze<T>(o: T): Readonly<T>;
/**
* Prevents the addition of new properties to an object.
@ -1363,6 +1363,34 @@ interface ArrayLike<T> {
readonly [n: number]: T;
}
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends string | number, T> = {
[P in K]: T;
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,

38
lib/lib.es6.d.ts vendored
View file

@ -200,7 +200,7 @@ interface ObjectConstructor {
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
* @param o Object on which to lock the attributes.
*/
freeze<T>(o: T): T;
freeze<T>(o: T): Readonly<T>;
/**
* Prevents the addition of new properties to an object.
@ -1363,6 +1363,34 @@ interface ArrayLike<T> {
readonly [n: number]: T;
}
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
};
/**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
/**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends string | number, T> = {
[P in K]: T;
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
@ -4362,13 +4390,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(value: any): value is number;
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(value: any): value is number;
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@ -4376,13 +4404,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(value: any): value is number;
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(value: any): value is number;
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as

23
lib/protocol.d.ts vendored
View file

@ -1400,6 +1400,25 @@ declare namespace ts.server.protocol {
body?: ConfigFileDiagnosticEventBody;
event: "configFileDiag";
}
type ProjectLanguageServiceStateEventName = "projectLanguageServiceState";
interface ProjectLanguageServiceStateEvent extends Event {
event: ProjectLanguageServiceStateEventName;
body?: ProjectLanguageServiceStateEventBody;
}
interface ProjectLanguageServiceStateEventBody {
/**
* Project name that has changes in the state of language service.
* For configured projects this will be the config file path.
* For external projects this will be the name of the projects specified when project was open.
* For inferred projects this event is not raised.
*/
projectName: string;
/**
* True if language service state switched from disabled to enabled
* and false otherwise.
*/
languageServiceEnabled: boolean;
}
/**
* Arguments for reload request.
*/
@ -1634,6 +1653,10 @@ declare namespace ts.server.protocol {
* true if install request succeeded, otherwise - false
*/
installSuccess: boolean;
/**
* version of typings installer
*/
typingsInstallerVersion: string;
}
interface NavBarResponse extends Response {
body?: NavigationBarItem[];

5276
lib/tsc.js

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

52
lib/typescript.d.ts vendored
View file

@ -333,7 +333,8 @@ declare namespace ts {
PartiallyEmittedExpression = 293,
MergeDeclarationMarker = 294,
EndOfDeclarationMarker = 295,
Count = 296,
RawExpression = 296,
Count = 297,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
@ -464,14 +465,14 @@ declare namespace ts {
right: Identifier;
}
type EntityName = Identifier | QualifiedName;
type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName;
type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
name?: DeclarationName;
}
interface DeclarationStatement extends Declaration, Statement {
name?: Identifier | LiteralExpression;
name?: Identifier | StringLiteral | NumericLiteral;
}
interface ComputedPropertyName extends Node {
kind: SyntaxKind.ComputedPropertyName;
@ -573,18 +574,16 @@ declare namespace ts {
interface PropertyLikeDeclaration extends Declaration {
name: PropertyName;
}
interface BindingPattern extends Node {
elements: NodeArray<BindingElement | ArrayBindingElement>;
}
interface ObjectBindingPattern extends BindingPattern {
interface ObjectBindingPattern extends Node {
kind: SyntaxKind.ObjectBindingPattern;
elements: NodeArray<BindingElement>;
}
type ArrayBindingElement = BindingElement | OmittedExpression;
interface ArrayBindingPattern extends BindingPattern {
interface ArrayBindingPattern extends Node {
kind: SyntaxKind.ArrayBindingPattern;
elements: NodeArray<ArrayBindingElement>;
}
type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
type ArrayBindingElement = BindingElement | OmittedExpression;
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
@ -809,17 +808,25 @@ declare namespace ts {
operatorToken: BinaryOperatorToken;
right: Expression;
}
interface AssignmentExpression extends BinaryExpression {
type AssignmentOperatorToken = Token<AssignmentOperator>;
interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
operatorToken: TOperator;
}
interface ObjectDestructuringAssignment extends AssignmentExpression {
interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ObjectLiteralExpression;
}
interface ArrayDestructuringAssignment extends AssignmentExpression {
interface ArrayDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ArrayLiteralExpression;
}
type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression<EqualsToken> | Identifier | PropertyAccessExpression | ElementAccessExpression;
type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment;
type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression;
type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression;
type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression;
type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression;
type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern;
interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
condition: Expression;
@ -1180,7 +1187,7 @@ declare namespace ts {
type ModuleName = Identifier | StringLiteral;
interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
interface NamespaceDeclaration extends ModuleDeclaration {
@ -1332,7 +1339,7 @@ declare namespace ts {
type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
interface JSDocRecordMember extends PropertySignature {
kind: SyntaxKind.JSDocRecordMember;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral | NumericLiteral;
type?: JSDocType;
}
interface JSDoc extends Node {
@ -1596,6 +1603,7 @@ declare namespace ts {
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@ -1962,7 +1970,7 @@ declare namespace ts {
target?: ScriptTarget;
traceResolution?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
/** Paths used to compute primary types search locations */
typeRoots?: string[];
[option: string]: CompilerOptionsValue | undefined;
}
@ -2129,6 +2137,10 @@ declare namespace ts {
_children: Node[];
}
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.1.3";
}
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (fileName: string) => void;
@ -2260,7 +2272,7 @@ declare namespace ts {
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function isParameterPropertyDeclaration(node: Node): boolean;
function getCombinedModifierFlags(node: Node): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
}
@ -2273,6 +2285,7 @@ declare namespace ts {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
function moduleHasNonRelativeName(moduleName: string): boolean;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
getCurrentDirectory?: () => string;
@ -2297,8 +2310,6 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.2.0";
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
@ -2393,6 +2404,7 @@ declare namespace ts {
}
interface SourceFile {
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
getLineEndOfPosition(pos: number): number;
getLineStarts(): number[];
getPositionOfLineAndCharacter(line: number, character: number): number;
update(newText: string, textChangeRange: TextChangeRange): SourceFile;

File diff suppressed because it is too large Load diff

View file

@ -333,7 +333,8 @@ declare namespace ts {
PartiallyEmittedExpression = 293,
MergeDeclarationMarker = 294,
EndOfDeclarationMarker = 295,
Count = 296,
RawExpression = 296,
Count = 297,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
@ -464,14 +465,14 @@ declare namespace ts {
right: Identifier;
}
type EntityName = Identifier | QualifiedName;
type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName;
type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
interface Declaration extends Node {
_declarationBrand: any;
name?: DeclarationName;
}
interface DeclarationStatement extends Declaration, Statement {
name?: Identifier | LiteralExpression;
name?: Identifier | StringLiteral | NumericLiteral;
}
interface ComputedPropertyName extends Node {
kind: SyntaxKind.ComputedPropertyName;
@ -573,18 +574,16 @@ declare namespace ts {
interface PropertyLikeDeclaration extends Declaration {
name: PropertyName;
}
interface BindingPattern extends Node {
elements: NodeArray<BindingElement | ArrayBindingElement>;
}
interface ObjectBindingPattern extends BindingPattern {
interface ObjectBindingPattern extends Node {
kind: SyntaxKind.ObjectBindingPattern;
elements: NodeArray<BindingElement>;
}
type ArrayBindingElement = BindingElement | OmittedExpression;
interface ArrayBindingPattern extends BindingPattern {
interface ArrayBindingPattern extends Node {
kind: SyntaxKind.ArrayBindingPattern;
elements: NodeArray<ArrayBindingElement>;
}
type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
type ArrayBindingElement = BindingElement | OmittedExpression;
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
@ -809,17 +808,25 @@ declare namespace ts {
operatorToken: BinaryOperatorToken;
right: Expression;
}
interface AssignmentExpression extends BinaryExpression {
type AssignmentOperatorToken = Token<AssignmentOperator>;
interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
operatorToken: TOperator;
}
interface ObjectDestructuringAssignment extends AssignmentExpression {
interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ObjectLiteralExpression;
}
interface ArrayDestructuringAssignment extends AssignmentExpression {
interface ArrayDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ArrayLiteralExpression;
}
type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression<EqualsToken> | Identifier | PropertyAccessExpression | ElementAccessExpression;
type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment;
type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression;
type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression;
type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression;
type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression;
type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern;
interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
condition: Expression;
@ -1180,7 +1187,7 @@ declare namespace ts {
type ModuleName = Identifier | StringLiteral;
interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
interface NamespaceDeclaration extends ModuleDeclaration {
@ -1332,7 +1339,7 @@ declare namespace ts {
type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType;
interface JSDocRecordMember extends PropertySignature {
kind: SyntaxKind.JSDocRecordMember;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral | NumericLiteral;
type?: JSDocType;
}
interface JSDoc extends Node {
@ -1596,6 +1603,7 @@ declare namespace ts {
getJsxIntrinsicTagNames(): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
}
interface SymbolDisplayBuilder {
buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
@ -1962,7 +1970,7 @@ declare namespace ts {
target?: ScriptTarget;
traceResolution?: boolean;
types?: string[];
/** Paths used to used to compute primary types search locations */
/** Paths used to compute primary types search locations */
typeRoots?: string[];
[option: string]: CompilerOptionsValue | undefined;
}
@ -2129,6 +2137,10 @@ declare namespace ts {
_children: Node[];
}
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.1.3";
}
declare namespace ts {
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (fileName: string) => void;
@ -2260,7 +2272,7 @@ declare namespace ts {
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function isParameterPropertyDeclaration(node: Node): boolean;
function getCombinedModifierFlags(node: Node): ModifierFlags;
function getCombinedNodeFlags(node: Node): NodeFlags;
}
@ -2273,6 +2285,7 @@ declare namespace ts {
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
function moduleHasNonRelativeName(moduleName: string): boolean;
function getEffectiveTypeRoots(options: CompilerOptions, host: {
directoryExists?: (directoryName: string) => boolean;
getCurrentDirectory?: () => string;
@ -2297,8 +2310,6 @@ declare namespace ts {
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
}
declare namespace ts {
/** The version of the TypeScript compiler release */
const version = "2.2.0";
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost;
@ -2393,6 +2404,7 @@ declare namespace ts {
}
interface SourceFile {
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
getLineEndOfPosition(pos: number): number;
getLineStarts(): number[];
getPositionOfLineAndCharacter(line: number, character: number): number;
update(newText: string, textChangeRange: TextChangeRange): SourceFile;

File diff suppressed because it is too large Load diff

View file

@ -136,6 +136,9 @@ var ts;
})(performance = ts.performance || (ts.performance = {}));
})(ts || (ts = {}));
var ts;
(function (ts) {
ts.version = "2.1.3";
})(ts || (ts = {}));
(function (ts) {
var createObject = Object.create;
ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined;
@ -606,7 +609,7 @@ var ts;
if (value === undefined)
return to;
if (to === undefined)
to = [];
return [value];
to.push(value);
return to;
}
@ -621,6 +624,14 @@ var ts;
return to;
}
ts.addRange = addRange;
function stableSort(array, comparer) {
if (comparer === void 0) { comparer = compareValues; }
return array
.map(function (_, i) { return i; })
.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); })
.map(function (i) { return array[i]; });
}
ts.stableSort = stableSort;
function rangeEquals(array1, array2, pos, end) {
while (pos < end) {
if (array1[pos] !== array2[pos]) {
@ -775,6 +786,15 @@ var ts;
}
}
ts.copyProperties = copyProperties;
function appendProperty(map, key, value) {
if (key === undefined || value === undefined)
return map;
if (map === undefined)
map = createMap();
map[key] = value;
return map;
}
ts.appendProperty = appendProperty;
function assign(t) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
@ -1227,6 +1247,14 @@ var ts;
getEmitScriptTarget(compilerOptions) >= 2 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
}
ts.getEmitModuleKind = getEmitModuleKind;
function getEmitModuleResolutionKind(compilerOptions) {
var moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
}
return moduleResolution;
}
ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
function hasZeroOrOneAsteriskCharacter(str) {
var seenAsterisk = false;
for (var i = 0; i < str.length; i++) {
@ -1777,6 +1805,16 @@ var ts;
}
Debug.fail = fail;
})(Debug = ts.Debug || (ts.Debug = {}));
function orderedRemoveItem(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
orderedRemoveItemAt(array, i);
return true;
}
}
return false;
}
ts.orderedRemoveItem = orderedRemoveItem;
function orderedRemoveItemAt(array, index) {
for (var i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
@ -2876,7 +2914,7 @@ var ts;
An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." },
Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." },
Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." },
An_object_rest_element_must_be_an_identifier: { code: 2701, category: ts.DiagnosticCategory.Error, key: "An_object_rest_element_must_be_an_identifier_2701", message: "An object rest element must be an identifier." },
The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@ -3150,6 +3188,7 @@ var ts;
type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." },
Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." },
Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." },
JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." },
JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." },
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." },
@ -3162,7 +3201,7 @@ var ts;
super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." },
Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." },
Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" },
The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." },
A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." },
The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." },
No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." },
Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." },
@ -3174,6 +3213,9 @@ var ts;
Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" },
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig" },
Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." },
Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}" },
Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}" },
Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}" },
};
})(ts || (ts = {}));
var ts;
@ -5525,7 +5567,7 @@ var ts;
};
function tryExtendsName(extendedConfig) {
if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) {
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_path_in_an_extends_options_must_be_relative_or_rooted));
errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
return;
}
var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName);
@ -6057,6 +6099,7 @@ var ts;
function moduleHasNonRelativeName(moduleName) {
return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName));
}
ts.moduleHasNonRelativeName = moduleHasNonRelativeName;
function tryReadTypesSection(extensions, packageJsonPath, baseDirectory, state) {
var jsonContent = readJson(packageJsonPath, state.host);
switch (extensions) {
@ -6618,9 +6661,17 @@ var ts;
isEnabled: function () { return false; },
writeLine: ts.noop
};
function typingToFileName(cachePath, packageName, installTypingHost) {
var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
return result.resolvedModule && result.resolvedModule.resolvedFileName;
function typingToFileName(cachePath, packageName, installTypingHost, log) {
try {
var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
return result.resolvedModule && result.resolvedModule.resolvedFileName;
}
catch (e) {
if (log.isEnabled()) {
log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
}
return undefined;
}
}
var PackageNameValidationResult;
(function (PackageNameValidationResult) {
@ -6749,8 +6800,9 @@ var ts;
if (!packageName) {
continue;
}
var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost);
var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
if (!typingFile) {
this.missingTypingsSet[packageName] = true;
continue;
}
var existingTypingFile = this.packageNameToTypingLocation[packageName];
@ -6781,7 +6833,7 @@ var ts;
var result = [];
for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) {
var typing = typingsToInstall_1[_i];
if (this.missingTypingsSet[typing]) {
if (this.missingTypingsSet[typing] || this.packageNameToTypingLocation[typing]) {
continue;
}
var validationResult = validatePackageName(typing);
@ -6857,7 +6909,8 @@ var ts;
_this.sendResponse({
kind: server.EventInstall,
packagesToInstall: scopedTypings,
installSuccess: ok
installSuccess: ok,
typingsInstallerVersion: ts.version
});
}
if (!ok) {
@ -6871,17 +6924,14 @@ var ts;
return;
}
if (_this.log.isEnabled()) {
_this.log.writeLine("Requested to install typings " + JSON.stringify(scopedTypings) + ", installed typings " + JSON.stringify(scopedTypings));
_this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
}
var installedTypingFiles = [];
for (var _a = 0, scopedTypings_1 = scopedTypings; _a < scopedTypings_1.length; _a++) {
var t = scopedTypings_1[_a];
var packageName = ts.getBaseFileName(t);
if (!packageName) {
continue;
}
var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost);
for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
var packageName = filteredTypings_2[_a];
var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
if (!typingFile) {
_this.missingTypingsSet[packageName] = true;
continue;
}
if (!_this.packageNameToTypingLocation[packageName]) {
@ -7021,14 +7071,13 @@ var ts;
_this.log.writeLine("Process id: " + process.pid);
}
_this.npmPath = getNPMLocation(process.argv[0]);
var execSync;
(_a = require("child_process"), _this.exec = _a.exec, execSync = _a.execSync, _a);
(_this.execSync = require("child_process").execSync);
_this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
try {
if (_this.log.isEnabled()) {
_this.log.writeLine("Updating " + TypesRegistryPackageName + " npm package...");
}
execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" });
_this.execSync(_this.npmPath + " install " + TypesRegistryPackageName, { cwd: globalTypingsCacheLocation, stdio: "ignore" });
}
catch (e) {
if (_this.log.isEnabled()) {
@ -7037,7 +7086,6 @@ var ts;
}
_this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
return _this;
var _a;
}
NodeTypingsInstaller.prototype.listen = function () {
var _this = this;
@ -7061,18 +7109,26 @@ var ts;
}
};
NodeTypingsInstaller.prototype.installWorker = function (requestId, args, cwd, onRequestCompleted) {
var _this = this;
if (this.log.isEnabled()) {
this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(args) + "'.");
}
var command = this.npmPath + " install " + args.join(" ") + " --save-dev";
var start = Date.now();
this.exec(command, { cwd: cwd }, function (err, stdout, stderr) {
if (_this.log.isEnabled()) {
_this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms" + ts.sys.newLine + "stdout: " + stdout + ts.sys.newLine + "stderr: " + stderr);
}
onRequestCompleted(!err);
});
var stdout;
var stderr;
var hasError = false;
try {
stdout = this.execSync(command, { cwd: cwd });
}
catch (e) {
stdout = e.stdout;
stderr = e.stderr;
hasError = true;
}
if (this.log.isEnabled()) {
this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms" + ts.sys.newLine + "stdout: " + (stdout && stdout.toString()) + ts.sys.newLine + "stderr: " + (stderr && stderr.toString()));
}
onRequestCompleted(!hasError);
};
return NodeTypingsInstaller;
}(typingsInstaller.TypingsInstaller));

View file

@ -2,7 +2,7 @@
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "http://typescriptlang.org/",
"version": "2.2.0",
"version": "2.1.3",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
@ -75,8 +75,8 @@
"through2": "latest",
"travis-fold": "latest",
"ts-node": "latest",
"tslint": "next",
"typescript": "next"
"tslint": "4.0.0-dev.2",
"typescript": "^2.1"
},
"scripts": {
"pretest": "jake tests",

View file

@ -3797,6 +3797,16 @@ namespace ts {
}
baseType = getReturnTypeOfSignature(constructors[0]);
}
// In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters
const valueDecl = type.symbol.valueDeclaration;
if (valueDecl && isInJavaScriptFile(valueDecl)) {
const augTag = getJSDocAugmentsTag(type.symbol.valueDeclaration);
if (augTag) {
baseType = getTypeFromTypeNode(augTag.typeExpression.type);
}
}
if (baseType === unknownType) {
return;
}
@ -3805,7 +3815,7 @@ namespace ts {
return;
}
if (type === baseType || hasBaseType(<InterfaceType>baseType, type)) {
error(type.symbol.valueDeclaration, Diagnostics.Type_0_recursively_references_itself_as_a_base_type,
error(valueDecl, Diagnostics.Type_0_recursively_references_itself_as_a_base_type,
typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType));
return;
}

View file

@ -462,11 +462,18 @@ namespace ts {
];
/* @internal */
export let typingOptionDeclarations: CommandLineOption[] = [
export let typeAcquisitionDeclarations: CommandLineOption[] = [
{
/* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
name: "enableAutoDiscovery",
type: "boolean",
},
{
name: "enable",
type: "boolean",
},
{
name: "include",
type: "list",
@ -501,6 +508,20 @@ namespace ts {
let optionNameMapCache: OptionNameMap;
/* @internal */
export function convertEnableAutoDiscoveryToEnable(typeAcquisition: TypeAcquisition): TypeAcquisition {
// Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
const result: TypeAcquisition = {
enable: typeAcquisition.enableAutoDiscovery,
include: typeAcquisition.include || [],
exclude: typeAcquisition.exclude || []
};
return result;
}
return typeAcquisition;
}
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
@ -835,7 +856,7 @@ namespace ts {
return {
options: {},
fileNames: [],
typingOptions: {},
typeAcquisition: {},
raw: json,
errors: [createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))],
wildcardDirectories: {}
@ -843,7 +864,10 @@ namespace ts {
}
let options: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
// typingOptions has been deprecated and is only supported for backward compatibility purposes.
// It should be removed in future releases - use typeAcquisition instead.
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
if (json["extends"]) {
let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}];
@ -874,7 +898,7 @@ namespace ts {
return {
options,
fileNames,
typingOptions,
typeAcquisition,
raw: json,
errors,
wildcardDirectories,
@ -996,9 +1020,9 @@ namespace ts {
return { options, errors };
}
export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypingOptions, errors: Diagnostic[] } {
export function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: TypeAcquisition, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
const options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
@ -1012,16 +1036,18 @@ namespace ts {
return options;
}
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
function convertTypeAcquisitionFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition {
const options: TypeAcquisition = { enable: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
convertOptionsFromJson(typeAcquisitionDeclarations, typeAcquisition, basePath, options, Diagnostics.Unknown_type_acquisition_option_0, errors);
const options: TypingOptions = { enableAutoDiscovery: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return;

View file

@ -3,7 +3,7 @@
namespace ts {
/** The version of the TypeScript compiler release */
export const version = "2.2.0";
export const version = "2.1.3";
}
/* @internal */

View file

@ -3137,7 +3137,7 @@
"category": "Error",
"code": 17009
},
"Unknown typing option '{0}'.": {
"Unknown type acquisition option '{0}'.": {
"category": "Error",
"code": 17010
},

View file

@ -418,6 +418,8 @@ namespace ts {
return visitNode(cbNode, (<JSDocReturnTag>node).typeExpression);
case SyntaxKind.JSDocTypeTag:
return visitNode(cbNode, (<JSDocTypeTag>node).typeExpression);
case SyntaxKind.JSDocAugmentsTag:
return visitNode(cbNode, (<JSDocAugmentsTag>node).typeExpression);
case SyntaxKind.JSDocTemplateTag:
return visitNodes(cbNodes, (<JSDocTemplateTag>node).typeParameters);
case SyntaxKind.JSDocTypedefTag:
@ -6426,6 +6428,9 @@ namespace ts {
let tag: JSDocTag;
if (tagName) {
switch (tagName.text) {
case "augments":
tag = parseAugmentsTag(atToken, tagName);
break;
case "param":
tag = parseParamTag(atToken, tagName);
break;
@ -6642,6 +6647,16 @@ namespace ts {
return finishNode(result);
}
function parseAugmentsTag(atToken: AtToken, tagName: Identifier): JSDocAugmentsTag {
const typeExpression = tryParseTypeExpression();
const result = <JSDocAugmentsTag>createNode(SyntaxKind.JSDocAugmentsTag, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = typeExpression;
return finishNode(result);
}
function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();

View file

@ -349,6 +349,7 @@ namespace ts {
JSDocThisType,
JSDocComment,
JSDocTag,
JSDocAugmentsTag,
JSDocParameterTag,
JSDocReturnTag,
JSDocTypeTag,
@ -1989,6 +1990,11 @@ namespace ts {
kind: SyntaxKind.JSDocTag;
}
export interface JSDocAugmentsTag extends JSDocTag {
kind: SyntaxKind.JSDocAugmentsTag;
typeExpression: JSDocTypeExpression;
}
export interface JSDocTemplateTag extends JSDocTag {
kind: SyntaxKind.JSDocTemplateTag;
typeParameters: NodeArray<TypeParameterDeclaration>;
@ -3199,8 +3205,12 @@ namespace ts {
[option: string]: CompilerOptionsValue | undefined;
}
export interface TypingOptions {
export interface TypeAcquisition {
/* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
enableAutoDiscovery?: boolean;
enable?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean | undefined;
@ -3211,7 +3221,7 @@ namespace ts {
projectRootPath: string; // The path to the project root directory
safeListPath: string; // The path used to retrieve the safe list
packageNameToTypingLocation: Map<string>; // The map of package names to their cached typing locations
typingOptions: TypingOptions; // Used to customize the typing inference process
typeAcquisition: TypeAcquisition; // Used to customize the type acquisition process
compilerOptions: CompilerOptions; // Used as a source for typing inference
unresolvedImports: ReadonlyArray<string>; // List of unresolved module ids from imports
}
@ -3276,7 +3286,7 @@ namespace ts {
/** Either a parsed command line or a parsed tsconfig.json */
export interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
raw?: any;
errors: Diagnostic[];

View file

@ -1539,6 +1539,10 @@ namespace ts {
return tag && tag.typeExpression && tag.typeExpression.type;
}
export function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag {
return getFirstJSDocTag(node, SyntaxKind.JSDocAugmentsTag) as JSDocAugmentsTag;
}
export function getJSDocReturnTag(node: Node): JSDocReturnTag {
return getFirstJSDocTag(node, SyntaxKind.JSDocReturnTag) as JSDocReturnTag;
}

View file

@ -108,7 +108,7 @@
"./unittests/commandLineParsing.ts",
"./unittests/configurationExtension.ts",
"./unittests/convertCompilerOptionsFromJson.ts",
"./unittests/convertTypingOptionsFromJson.ts",
"./unittests/convertTypeAcquisitionFromJson.ts",
"./unittests/tsserverProjectSystem.ts",
"./unittests/matchFiles.ts",
"./unittests/initializeTSConfig.ts",

View file

@ -2,12 +2,13 @@
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
describe("convertTypingOptionsFromJson", () => {
function assertTypingOptions(json: any, configFileName: string, expectedResult: { typingOptions: TypingOptions, errors: Diagnostic[] }) {
const { options: actualTypingOptions, errors: actualErrors } = convertTypingOptionsFromJson(json["typingOptions"], "/apath/", configFileName);
const parsedTypingOptions = JSON.stringify(actualTypingOptions);
const expectedTypingOptions = JSON.stringify(expectedResult.typingOptions);
assert.equal(parsedTypingOptions, expectedTypingOptions);
describe("convertTypeAcquisitionFromJson", () => {
function assertTypeAcquisition(json: any, configFileName: string, expectedResult: { typeAcquisition: TypeAcquisition, errors: Diagnostic[] }) {
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const { options: actualTypeAcquisition, errors: actualErrors } = convertTypeAcquisitionFromJson(jsonOptions, "/apath/", configFileName);
const parsedTypeAcquisition = JSON.stringify(actualTypeAcquisition);
const expectedTypeAcquisition = JSON.stringify(expectedResult.typeAcquisition);
assert.equal(parsedTypeAcquisition, expectedTypeAcquisition);
const expectedErrors = expectedResult.errors;
assert.isTrue(expectedResult.errors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedResult.errors)}. Actual error: ${JSON.stringify(actualErrors)}.`);
@ -20,8 +21,8 @@ namespace ts {
}
// tsconfig.json
it("Convert correctly format tsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert deprecated typingOptions.enableAutoDiscovery format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
{
@ -32,9 +33,9 @@ namespace ts {
},
"tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
@ -42,25 +43,47 @@ namespace ts {
});
});
it("Convert incorrect format tsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert correctly format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enable": true,
"include": ["0.d.ts", "1.d.ts"],
"exclude": ["0.js", "1.js"]
}
},
"tsconfig.json",
{
typeAcquisition:
{
enable: true,
include: ["0.d.ts", "1.d.ts"],
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
});
});
it("Convert incorrect format tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typeAcquisition":
{
"enableAutoDiscovy": true,
}
}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},
errors: [
{
category: Diagnostics.Unknown_typing_option_0.category,
code: Diagnostics.Unknown_typing_option_0.code,
category: Diagnostics.Unknown_type_acquisition_option_0.category,
code: Diagnostics.Unknown_type_acquisition_option_0.code,
file: undefined,
start: 0,
length: 0,
@ -70,12 +93,12 @@ namespace ts {
});
});
it("Convert default tsconfig.json to typing-options ", () => {
assertTypingOptions({}, "tsconfig.json",
it("Convert default tsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition({}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},
@ -83,18 +106,18 @@ namespace ts {
});
});
it("Convert tsconfig.json with only enableAutoDiscovery property to typing-options ", () => {
assertTypingOptions(
it("Convert tsconfig.json with only enable property to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": true
"enable": true
}
}, "tsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
@ -103,20 +126,20 @@ namespace ts {
});
// jsconfig.json
it("Convert jsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": false,
"enable": false,
"include": ["0.d.ts"],
"exclude": ["0.js"]
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: ["0.d.ts"],
exclude: ["0.js"]
},
@ -124,12 +147,12 @@ namespace ts {
});
});
it("Convert default jsconfig.json to typing-options ", () => {
assertTypingOptions({ }, "jsconfig.json",
it("Convert default jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition({ }, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
@ -137,25 +160,25 @@ namespace ts {
});
});
it("Convert incorrect format jsconfig.json to typing-options ", () => {
assertTypingOptions(
it("Convert incorrect format jsconfig.json to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovy": true,
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: true,
enable: true,
include: [],
exclude: []
},
errors: [
{
category: Diagnostics.Unknown_compiler_option_0.category,
code: Diagnostics.Unknown_typing_option_0.code,
code: Diagnostics.Unknown_type_acquisition_option_0.code,
file: undefined,
start: 0,
length: 0,
@ -165,18 +188,18 @@ namespace ts {
});
});
it("Convert jsconfig.json with only enableAutoDiscovery property to typing-options ", () => {
assertTypingOptions(
it("Convert jsconfig.json with only enable property to typeAcquisition ", () => {
assertTypeAcquisition(
{
"typingOptions":
"typeAcquisition":
{
"enableAutoDiscovery": false
"enable": false
}
}, "jsconfig.json",
{
typingOptions:
typeAcquisition:
{
enableAutoDiscovery: false,
enable: false,
include: [],
exclude: []
},

View file

@ -90,8 +90,8 @@ namespace ts.projectSystem {
this.projectService.updateTypingsForProject(response);
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typingOptions, unresolvedImports, this.globalTypingsCacheLocation);
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation);
this.install(request);
}
@ -578,6 +578,35 @@ namespace ts.projectSystem {
checkWatchedDirectories(host, ["/a/b/c", "/a/b", "/a"]);
});
it("can handle tsconfig file name with difference casing", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({
include: []
})
};
const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false });
const service = createProjectService(host);
service.openExternalProject(<protocol.ExternalProject>{
projectFileName: "/a/b/project.csproj",
rootFiles: toExternalFiles([f1.path, combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path))]),
options: {}
});
service.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
service.openClientFile(f1.path);
service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
checkProjectActualFiles(service.inferredProjects[0], [f1.path]);
})
it("create configured project without file list", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
@ -1726,8 +1755,8 @@ namespace ts.projectSystem {
options: {}
});
projectService.checkNumberOfProjects({ externalProjects: 1 });
const typingOptions = projectService.externalProjects[0].getTypingOptions();
assert.isTrue(typingOptions.enableAutoDiscovery, "Typing autodiscovery should be enabled");
const typeAcquisition = projectService.externalProjects[0].getTypeAcquisition();
assert.isTrue(typeAcquisition.enable, "Typine acquisition should be enabled");
});
});
@ -2452,6 +2481,43 @@ namespace ts.projectSystem {
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
});
it("are generated when the config file changes", () => {
const serverEventManager = new TestServerEventManager();
const file = {
path: "/a/b/app.ts",
content: "let x = 10"
};
const configFile = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {}
}`
};
const host = createServerHost([file, configFile]);
const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler);
openFilesForSession([file], session);
serverEventManager.checkEventCountOfType("configFileDiag", 1);
configFile.content = `{
"compilerOptions": {
"haha": 123
}
}`;
host.reloadFS([file, configFile]);
host.triggerFileWatcherCallback(configFile.path);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 2);
configFile.content = `{
"compilerOptions": {}
}`;
host.reloadFS([file, configFile]);
host.triggerFileWatcherCallback(configFile.path);
host.runQueuedTimeoutCallbacks();
serverEventManager.checkEventCountOfType("configFileDiag", 3);
});
});
describe("skipLibCheck", () => {
@ -2663,6 +2729,65 @@ namespace ts.projectSystem {
arguments: { projectFileName: projectName }
}).response;
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.SetCompilerOptionsForInferredProjectsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsForInferredProjects,
seq: 3,
arguments: { options: { module: ModuleKind.CommonJS } }
});
const diagsAfterUpdate = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName: projectName }
}).response;
assert.isTrue(diagsAfterUpdate.length === 0);
});
it("for external project", () => {
const f1 = {
path: "/a/b/f1.js",
content: "function test1() { }"
};
const host = createServerHost([f1, libFile]);
const session = createSession(host);
const projectService = session.getProjectService();
const projectFileName = "/a/b/project.csproj";
const externalFiles = toExternalFiles([f1.path]);
projectService.openExternalProject(<protocol.ExternalProject>{
projectFileName,
rootFiles: externalFiles,
options: {}
});
checkNumberOfProjects(projectService, { externalProjects: 1 });
const diags = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName }
}).response;
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.OpenExternalProjectRequest>{
type: "request",
command: server.CommandNames.OpenExternalProject,
seq: 3,
arguments: {
projectFileName,
rootFiles: externalFiles,
options: { module: ModuleKind.CommonJS }
}
});
const diagsAfterUpdate = session.executeCommand(<server.protocol.CompilerOptionsDiagnosticsRequest>{
type: "request",
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName }
}).response;
assert.isTrue(diagsAfterUpdate.length === 0);
});
});

View file

@ -57,8 +57,8 @@ namespace ts.projectSystem {
compilerOptions: {
allowJs: true
},
typingOptions: {
enableAutoDiscovery: true
typeAcquisition: {
enable: true
}
})
};
@ -145,7 +145,7 @@ namespace ts.projectSystem {
checkProjectActualFiles(p, [file1.path, jquery.path]);
});
it("external project - no typing options, no .d.ts/js files", () => {
it("external project - no type acquisition, no .d.ts/js files", () => {
const file1 = {
path: "/a/b/app.ts",
content: ""
@ -173,7 +173,7 @@ namespace ts.projectSystem {
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
it("external project - no autoDiscovery in typing options, no .d.ts/js files", () => {
it("external project - no auto in typing acquisition, no .d.ts/js files", () => {
const file1 = {
path: "/a/b/app.ts",
content: ""
@ -194,11 +194,11 @@ namespace ts.projectSystem {
projectFileName,
options: {},
rootFiles: [toExternalFile(file1.path)],
typingOptions: { include: ["jquery"] }
typeAcquisition: { include: ["jquery"] }
});
installer.checkPendingCommands(/*expectedCount*/ 0);
// by default auto discovery will kick in if project contain only .js/.d.ts files
// in this case project contain only ts files - no auto discovery even if typing options is set
// in this case project contain only ts files - no auto discovery even if type acquisition is set
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
@ -217,9 +217,9 @@ namespace ts.projectSystem {
constructor() {
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/node"];
@ -234,17 +234,17 @@ namespace ts.projectSystem {
projectFileName,
options: {},
rootFiles: [toExternalFile(file1.path)],
typingOptions: { enableAutoDiscovery: true, include: ["jquery"] }
typeAcquisition: { enable: true, include: ["jquery"] }
});
assert.isTrue(enqueueIsCalled, "expected enqueueIsCalled to be true");
installer.installAll(/*expectedCount*/ 1);
// autoDiscovery is set in typing options - use it even if project contains only .ts files
// auto is set in type acquisition - use it even if project contains only .ts files
projectService.checkNumberOfProjects({ externalProjects: 1 });
});
it("external project - no typing options, with only js, jsx, d.ts files", () => {
it("external project - no type acquisition, with only js, jsx, d.ts files", () => {
// Tests:
// 1. react typings are installed for .jsx
// 2. loose files names are matched against safe list for typings if
@ -288,7 +288,7 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)],
typingOptions: {}
typeAcquisition: {}
});
const p = projectService.externalProjects[0];
@ -301,7 +301,7 @@ namespace ts.projectSystem {
checkProjectActualFiles(p, [file1.path, file2.path, file3.path, lodash.path, react.path]);
});
it("external project - no typing options, with js & ts files", () => {
it("external project - no type acquisition, with js & ts files", () => {
// Tests:
// 1. No typings are included for JS projects when the project contains ts files
const file1 = {
@ -319,9 +319,9 @@ namespace ts.projectSystem {
constructor() {
super(host, { typesRegistry: createTypesRegistry("jquery") });
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings: string[] = [];
@ -336,7 +336,7 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path)],
typingOptions: {}
typeAcquisition: {}
});
const p = projectService.externalProjects[0];
@ -349,11 +349,11 @@ namespace ts.projectSystem {
checkProjectActualFiles(p, [file1.path, file2.path]);
});
it("external project - with typing options, with only js, d.ts files", () => {
it("external project - with type acquisition, with only js, d.ts files", () => {
// Tests:
// 1. Safelist matching, typing options includes/excludes and package.json typings are all acquired
// 2. Types for safelist matches are not included when they also appear in the typing option exclude list
// 3. Multiple includes and excludes are respected in typing options
// 1. Safelist matching, type acquisition includes/excludes and package.json typings are all acquired
// 2. Types for safelist matches are not included when they also appear in the type acquisition exclude list
// 3. Multiple includes and excludes are respected in type acquisition
const file1 = {
path: "/a/b/lodash.js",
content: ""
@ -411,7 +411,7 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file1.path), toExternalFile(file2.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "moment"], exclude: ["lodash"] }
typeAcquisition: { include: ["jquery", "moment"], exclude: ["lodash"] }
});
const p = projectService.externalProjects[0];
@ -486,7 +486,7 @@ namespace ts.projectSystem {
projectFileName,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "moment"] }
typeAcquisition: { include: ["jquery", "moment"] }
});
const p = projectService.externalProjects[0];
@ -572,7 +572,7 @@ namespace ts.projectSystem {
projectFileName: projectFileName1,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "cordova"] }
typeAcquisition: { include: ["jquery", "cordova"] }
});
installer.checkPendingCommands(/*expectedCount*/ 1);
@ -584,7 +584,7 @@ namespace ts.projectSystem {
projectFileName: projectFileName2,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(file3.path)],
typingOptions: { include: ["grunt", "gulp"] }
typeAcquisition: { include: ["grunt", "gulp"] }
});
assert.equal(installer.pendingRunRequests.length, 1, "expect one throttled request");
@ -930,7 +930,7 @@ namespace ts.projectSystem {
const host = createServerHost([f]);
const cache = createMap<string>();
for (const name of JsTyping.nodeCoreModuleList) {
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, [name, "somename"]);
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enable: true }, [name, "somename"]);
assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]);
}
});
@ -946,7 +946,7 @@ namespace ts.projectSystem {
};
const host = createServerHost([f, node]);
const cache = createMap<string>({ "node": node.path });
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, ["fs", "bar"]);
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enable: true }, ["fs", "bar"]);
assert.deepEqual(result.cachedTypingPaths, [node.path]);
assert.deepEqual(result.newTypingNames, ["bar"]);
});

View file

@ -257,7 +257,7 @@ namespace ts.server {
private changedFiles: ScriptInfo[];
private toCanonicalFileName: (f: string) => string;
readonly toCanonicalFileName: (f: string) => string;
public lastDeletedFile: ScriptInfo;
@ -317,7 +317,7 @@ namespace ts.server {
}
switch (response.kind) {
case ActionSet:
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.unresolvedImports, response.typings);
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings);
break;
case ActionInvalidate:
this.typingsCache.deleteTypingsForProject(response.projectName);
@ -520,8 +520,10 @@ namespace ts.server {
}
private onConfigChangedForConfiguredProject(project: ConfiguredProject) {
this.logger.info(`Config file changed: ${project.getConfigFilePath()}`);
this.updateConfiguredProject(project);
const configFileName = project.getConfigFilePath();
this.logger.info(`Config file changed: ${configFileName}`);
const configFileErrors = this.updateConfiguredProject(project);
this.reportConfigFileDiagnostics(configFileName, configFileErrors, /*triggerFile*/ configFileName);
this.refreshInferredProjects();
}
@ -775,7 +777,13 @@ namespace ts.server {
}
private findConfiguredProjectByProjectName(configFileName: NormalizedPath) {
return findProjectByName(configFileName, this.configuredProjects);
// make sure that casing of config file name is consistent
configFileName = asNormalizedPath(this.toCanonicalFileName(configFileName));
for (const proj of this.configuredProjects) {
if (proj.canonicalConfigFilePath === configFileName) {
return proj;
}
}
}
private findExternalProjectByProjectName(projectFileName: string) {
@ -821,7 +829,7 @@ namespace ts.server {
compilerOptions: parsedCommandLine.options,
configHasFilesProperty: config["files"] !== undefined,
wildcardDirectories: createMap(parsedCommandLine.wildcardDirectories),
typingOptions: parsedCommandLine.typingOptions,
typeAcquisition: parsedCommandLine.typeAcquisition,
compileOnSave: parsedCommandLine.compileOnSave
};
return { success: true, projectOptions, configFileErrors: errors };
@ -845,7 +853,7 @@ namespace ts.server {
return false;
}
private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typingOptions: TypingOptions) {
private createAndAddExternalProject(projectFileName: string, files: protocol.ExternalFile[], options: protocol.ExternalProjectCompilerOptions, typeAcquisition: TypeAcquisition) {
const compilerOptions = convertCompilerOptions(options);
const project = new ExternalProject(
projectFileName,
@ -855,7 +863,7 @@ namespace ts.server {
/*languageServiceEnabled*/ !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader),
options.compileOnSave === undefined ? true : options.compileOnSave);
this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typingOptions, /*configFileErrors*/ undefined);
this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, /*clientFileName*/ undefined, typeAcquisition, /*configFileErrors*/ undefined);
this.externalProjects.push(project);
return project;
}
@ -883,7 +891,7 @@ namespace ts.server {
/*languageServiceEnabled*/ !sizeLimitExceeded,
projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave);
this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors);
this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typeAcquisition, configFileErrors);
project.watchConfigFile(project => this.onConfigChangedForConfiguredProject(project));
if (!sizeLimitExceeded) {
@ -902,7 +910,7 @@ namespace ts.server {
}
}
private addFilesToProjectAndUpdateGraph<T>(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader<T>, clientFileName: string, typingOptions: TypingOptions, configFileErrors: Diagnostic[]): void {
private addFilesToProjectAndUpdateGraph<T>(project: ConfiguredProject | ExternalProject, files: T[], propertyReader: FilePropertyReader<T>, clientFileName: string, typeAcquisition: TypeAcquisition, configFileErrors: Diagnostic[]): void {
let errors: Diagnostic[];
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
@ -917,7 +925,7 @@ namespace ts.server {
}
}
project.setProjectErrors(concatenate(configFileErrors, errors));
project.setTypingOptions(typingOptions);
project.setTypeAcquisition(typeAcquisition);
project.updateGraph();
}
@ -934,7 +942,7 @@ namespace ts.server {
};
}
private updateNonInferredProject<T>(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader<T>, newOptions: CompilerOptions, newTypingOptions: TypingOptions, compileOnSave: boolean, configFileErrors: Diagnostic[]) {
private updateNonInferredProject<T>(project: ExternalProject | ConfiguredProject, newUncheckedFiles: T[], propertyReader: FilePropertyReader<T>, newOptions: CompilerOptions, newTypeAcquisition: TypeAcquisition, compileOnSave: boolean, configFileErrors: Diagnostic[]) {
const oldRootScriptInfos = project.getRootScriptInfos();
const newRootScriptInfos: ScriptInfo[] = [];
const newRootScriptInfoMap: NormalizedPathMap<ScriptInfo> = createNormalizedPathMap<ScriptInfo>();
@ -996,7 +1004,7 @@ namespace ts.server {
}
project.setCompilerOptions(newOptions);
(<ExternalProject | ConfiguredProject>project).setTypingOptions(newTypingOptions);
(<ExternalProject | ConfiguredProject>project).setTypeAcquisition(newTypeAcquisition);
// VS only set the CompileOnSaveEnabled option in the request if the option was changed recently
// therefore if it is undefined, it should not be updated.
@ -1015,6 +1023,9 @@ namespace ts.server {
return;
}
// note: the returned "success" is true does not mean the "configFileErrors" is empty.
// because we might have tolerated the errors and kept going. So always return the configFileErrors
// regardless the "success" here is true or not.
const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath());
if (!success) {
// reset project settings to default
@ -1026,7 +1037,7 @@ namespace ts.server {
project.setCompilerOptions(projectOptions.compilerOptions);
if (!project.languageServiceEnabled) {
// language service is already disabled
return;
return configFileErrors;
}
project.disableLanguageService();
project.stopWatchingDirectory();
@ -1036,8 +1047,9 @@ namespace ts.server {
project.enableLanguageService();
}
this.watchConfigDirectoryForProject(project, projectOptions);
this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors);
this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typeAcquisition, projectOptions.compileOnSave, configFileErrors);
}
return configFileErrors;
}
createInferredProjectWithRootFileIfNecessary(root: ScriptInfo) {
@ -1316,6 +1328,12 @@ namespace ts.server {
}
openExternalProject(proj: protocol.ExternalProject): void {
// typingOptions has been deprecated and is only supported for backward compatibility
// purposes. It should be removed in future releases - use typeAcquisition instead.
if (proj.typingOptions && !proj.typeAcquisition) {
const typeAcquisition = convertEnableAutoDiscoveryToEnable(proj.typingOptions);
proj.typeAcquisition = typeAcquisition;
}
let tsConfigFiles: NormalizedPath[];
const rootFiles: protocol.ExternalFile[] = [];
for (const file of proj.rootFiles) {
@ -1340,7 +1358,7 @@ namespace ts.server {
if (externalProject) {
if (!tsConfigFiles) {
// external project already exists and not config files were added - update the project and return;
this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typingOptions, proj.options.compileOnSave, /*configFileErrors*/ undefined);
this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typeAcquisition, proj.options.compileOnSave, /*configFileErrors*/ undefined);
return;
}
// some config files were added to external project (that previously were not there)
@ -1400,7 +1418,7 @@ namespace ts.server {
else {
// no config files - remove the item from the collection
delete this.externalProjectToConfiguredProjectMap[proj.projectFileName];
this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions);
this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition);
}
this.refreshInferredProjects();
}

View file

@ -23,7 +23,7 @@ namespace ts.server {
}
this.resolveModuleName = (moduleName, containingFile, compilerOptions, host) => {
const globalCache = this.project.getTypingOptions().enableAutoDiscovery
const globalCache = this.project.getTypeAcquisition().enable
? this.project.projectService.typingsInstaller.globalTypingsCacheLocation
: undefined;
const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host);

View file

@ -248,9 +248,7 @@ namespace ts.server {
this.compilerOptions.allowNonTsExtensions = true;
}
if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) {
this.compilerOptions.noEmitForJsFiles = true;
}
this.setInternalCompilerOptionsForEmittingJsFiles();
this.lsHost = new LSHost(this.projectService.host, this, this.projectService.cancellationToken);
this.lsHost.setCompilationSettings(this.compilerOptions);
@ -266,6 +264,12 @@ namespace ts.server {
this.markAsDirty();
}
private setInternalCompilerOptionsForEmittingJsFiles() {
if (this.projectKind === ProjectKind.Inferred || this.projectKind === ProjectKind.External) {
this.compilerOptions.noEmitForJsFiles = true;
}
}
getProjectErrors() {
return this.projectErrors;
}
@ -312,7 +316,7 @@ namespace ts.server {
return this.projectName;
}
abstract getProjectRootPath(): string | undefined;
abstract getTypingOptions(): TypingOptions;
abstract getTypeAcquisition(): TypeAcquisition;
getSourceFile(path: Path) {
if (!this.program) {
@ -637,6 +641,7 @@ namespace ts.server {
this.lastCachedUnresolvedImportsList = undefined;
}
this.compilerOptions = compilerOptions;
this.setInternalCompilerOptionsForEmittingJsFiles();
this.lsHost.setCompilationSettings(compilerOptions);
this.markAsDirty();
@ -802,9 +807,9 @@ namespace ts.server {
}
}
getTypingOptions(): TypingOptions {
getTypeAcquisition(): TypeAcquisition {
return {
enableAutoDiscovery: allRootFilesAreJsOrDts(this),
enable: allRootFilesAreJsOrDts(this),
include: [],
exclude: []
};
@ -812,11 +817,12 @@ namespace ts.server {
}
export class ConfiguredProject extends Project {
private typingOptions: TypingOptions;
private typeAcquisition: TypeAcquisition;
private projectFileWatcher: FileWatcher;
private directoryWatcher: FileWatcher;
private directoriesWatchedForWildcards: Map<FileWatcher>;
private typeRootsWatchers: FileWatcher[];
readonly canonicalConfigFilePath: NormalizedPath;
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
@ -830,6 +836,7 @@ namespace ts.server {
languageServiceEnabled: boolean,
public compileOnSaveEnabled: boolean) {
super(configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled);
this.canonicalConfigFilePath = asNormalizedPath(projectService.toCanonicalFileName(configFileName));
}
getConfigFilePath() {
@ -844,12 +851,12 @@ namespace ts.server {
this.projectErrors = projectErrors;
}
setTypingOptions(newTypingOptions: TypingOptions): void {
this.typingOptions = newTypingOptions;
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void {
this.typeAcquisition = newTypeAcquisition;
}
getTypingOptions() {
return this.typingOptions;
getTypeAcquisition() {
return this.typeAcquisition;
}
watchConfigFile(callback: (project: ConfiguredProject) => void) {
@ -939,7 +946,7 @@ namespace ts.server {
}
export class ExternalProject extends Project {
private typingOptions: TypingOptions;
private typeAcquisition: TypeAcquisition;
constructor(externalProjectName: string,
projectService: ProjectService,
documentRegistry: ts.DocumentRegistry,
@ -960,36 +967,36 @@ namespace ts.server {
return getDirectoryPath(normalizeSlashes(this.getProjectName()));
}
getTypingOptions() {
return this.typingOptions;
getTypeAcquisition() {
return this.typeAcquisition;
}
setProjectErrors(projectErrors: Diagnostic[]) {
this.projectErrors = projectErrors;
}
setTypingOptions(newTypingOptions: TypingOptions): void {
if (!newTypingOptions) {
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void {
if (!newTypeAcquisition) {
// set default typings options
newTypingOptions = {
enableAutoDiscovery: allRootFilesAreJsOrDts(this),
newTypeAcquisition = {
enable: allRootFilesAreJsOrDts(this),
include: [],
exclude: []
};
}
else {
if (newTypingOptions.enableAutoDiscovery === undefined) {
if (newTypeAcquisition.enable === undefined) {
// if autoDiscovery was not specified by the caller - set it based on the content of the project
newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this);
newTypeAcquisition.enable = allRootFilesAreJsOrDts(this);
}
if (!newTypingOptions.include) {
newTypingOptions.include = [];
if (!newTypeAcquisition.include) {
newTypeAcquisition.include = [];
}
if (!newTypingOptions.exclude) {
newTypingOptions.exclude = [];
if (!newTypeAcquisition.exclude) {
newTypeAcquisition.exclude = [];
}
}
this.typingOptions = newTypingOptions;
this.typeAcquisition = newTypeAcquisition;
}
}
}

View file

@ -861,9 +861,13 @@ namespace ts.server.protocol {
*/
options: ExternalProjectCompilerOptions;
/**
* Explicitly specified typing options for the project
* @deprecated typingOptions. Use typeAcquisition instead
*/
typingOptions?: TypingOptions;
typingOptions?: TypeAcquisition;
/**
* Explicitly specified type acquisition for the project
*/
typeAcquisition?: TypeAcquisition;
}
export interface CompileOnSaveMixin {

View file

@ -276,8 +276,8 @@ namespace ts.server {
this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
}
enqueueInstallTypingsRequest(project: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>): void {
const request = createInstallTypingsRequest(project, typingOptions, unresolvedImports);
enqueueInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>): void {
const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
if (this.logger.hasLevel(LogLevel.verbose)) {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`Scheduling throttled operation: ${JSON.stringify(request)}`);

View file

@ -31,7 +31,7 @@ declare namespace ts.server {
readonly fileNames: string[];
readonly projectRootPath: ts.Path;
readonly compilerOptions: ts.CompilerOptions;
readonly typingOptions: ts.TypingOptions;
readonly typeAcquisition: ts.TypeAcquisition;
readonly unresolvedImports: SortedReadonlyArray<string>;
readonly cachePath?: string;
readonly kind: "discover";
@ -54,7 +54,7 @@ declare namespace ts.server {
}
export interface SetTypings extends ProjectResponse {
readonly typingOptions: ts.TypingOptions;
readonly typeAcquisition: ts.TypeAcquisition;
readonly compilerOptions: ts.CompilerOptions;
readonly typings: string[];
readonly unresolvedImports: SortedReadonlyArray<string>;

View file

@ -2,7 +2,7 @@
namespace ts.server {
export interface ITypingsInstaller {
enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>): void;
enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>): void;
attach(projectService: ProjectService): void;
onProjectClosed(p: Project): void;
readonly globalTypingsCacheLocation: string;
@ -16,7 +16,7 @@ namespace ts.server {
};
class TypingsCacheEntry {
readonly typingOptions: TypingOptions;
readonly typeAcquisition: TypeAcquisition;
readonly compilerOptions: CompilerOptions;
readonly typings: SortedReadonlyArray<string>;
readonly unresolvedImports: SortedReadonlyArray<string>;
@ -52,8 +52,8 @@ namespace ts.server {
return unique === 0;
}
function typingOptionsChanged(opt1: TypingOptions, opt2: TypingOptions): boolean {
return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery ||
function typeAcquisitionChanged(opt1: TypeAcquisition, opt2: TypeAcquisition): boolean {
return opt1.enable !== opt2.enable ||
!setIsEqualTo(opt1.include, opt2.include) ||
!setIsEqualTo(opt1.exclude, opt2.exclude);
}
@ -77,9 +77,9 @@ namespace ts.server {
}
getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray<string>, forceRefresh: boolean): SortedReadonlyArray<string> {
const typingOptions = project.getTypingOptions();
const typeAcquisition = project.getTypeAcquisition();
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
if (!typeAcquisition || !typeAcquisition.enable) {
return <any>emptyArray;
}
@ -87,28 +87,28 @@ namespace ts.server {
const result: SortedReadonlyArray<string> = entry ? entry.typings : <any>emptyArray;
if (forceRefresh ||
!entry ||
typingOptionsChanged(typingOptions, entry.typingOptions) ||
typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) ||
compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) ||
unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
// Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options.
// instead it acts as a placeholder to prevent issuing multiple requests
this.perProjectCache[project.getProjectName()] = {
compilerOptions: project.getCompilerOptions(),
typingOptions,
typeAcquisition,
typings: result,
unresolvedImports,
poisoned: true
};
// something has been changed, issue a request to update typings
this.installer.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
return result;
}
updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>, newTypings: string[]) {
updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>, newTypings: string[]) {
this.perProjectCache[projectName] = {
compilerOptions,
typingOptions,
typeAcquisition,
typings: toSortedReadonlyArray(newTypings),
unresolvedImports,
poisoned: false

View file

@ -127,7 +127,7 @@ namespace ts.server.typingsInstaller {
if (this.log.isEnabled()) {
this.log.writeLine(`#${requestId} with arguments'${JSON.stringify(args)}'.`);
}
const command = `${this.npmPath} install ${args.join(" ")} --save-dev`;
const command = `${this.npmPath} install ${args.join(" ")} --save-dev --user-agent="typesInstaller/${version}"`;
const start = Date.now();
let stdout: Buffer;
let stderr: Buffer;

View file

@ -150,7 +150,7 @@ namespace ts.server.typingsInstaller {
req.projectRootPath,
this.safeListPath,
this.packageNameToTypingLocation,
req.typingOptions,
req.typeAcquisition,
req.unresolvedImports);
if (this.log.isEnabled()) {
@ -391,7 +391,7 @@ namespace ts.server.typingsInstaller {
private createSetTypings(request: DiscoverTypings, typings: string[]): SetTypings {
return {
projectName: request.projectName,
typingOptions: request.typingOptions,
typeAcquisition: request.typeAcquisition,
compilerOptions: request.compilerOptions,
typings,
unresolvedImports: request.unresolvedImports,

View file

@ -46,12 +46,12 @@ namespace ts.server {
}
}
export function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>, cachePath?: string): DiscoverTypings {
export function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>, cachePath?: string): DiscoverTypings {
return {
projectName: project.getProjectName(),
fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true),
compilerOptions: project.getCompilerOptions(),
typingOptions,
typeAcquisition,
unresolvedImports,
projectRootPath: getProjectRootPath(project),
cachePath,
@ -171,7 +171,7 @@ namespace ts.server {
files?: string[];
wildcardDirectories?: Map<WatchDirectoryFlags>;
compilerOptions?: CompilerOptions;
typingOptions?: TypingOptions;
typeAcquisition?: TypeAcquisition;
compileOnSave?: boolean;
}

File diff suppressed because it is too large Load diff

View file

@ -1,167 +1,167 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: [
Diagnostics._0_is_declared_but_never_used.code,
Diagnostics.Property_0_is_declared_but_never_used.code
],
getCodeActions: (context: CodeFixContext) => {
const sourceFile = context.sourceFile;
const start = context.span.start;
// /* @internal */
// namespace ts.codefix {
// registerCodeFix({
// errorCodes: [
// Diagnostics._0_is_declared_but_never_used.code,
// Diagnostics.Property_0_is_declared_but_never_used.code
// ],
// getCodeActions: (context: CodeFixContext) => {
// const sourceFile = context.sourceFile;
// const start = context.span.start;
let token = getTokenAtPosition(sourceFile, start);
// let token = getTokenAtPosition(sourceFile, start);
// this handles var ["computed"] = 12;
if (token.kind === SyntaxKind.OpenBracketToken) {
token = getTokenAtPosition(sourceFile, start + 1);
}
// // this handles var ["computed"] = 12;
// if (token.kind === SyntaxKind.OpenBracketToken) {
// token = getTokenAtPosition(sourceFile, start + 1);
// }
switch (token.kind) {
case ts.SyntaxKind.Identifier:
switch (token.parent.kind) {
case ts.SyntaxKind.VariableDeclaration:
switch (token.parent.parent.parent.kind) {
case SyntaxKind.ForStatement:
const forStatement = <ForStatement>token.parent.parent.parent;
const forInitializer = <VariableDeclarationList>forStatement.initializer;
if (forInitializer.declarations.length === 1) {
return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos);
}
else {
return removeSingleItem(forInitializer.declarations, token);
}
// switch (token.kind) {
// case ts.SyntaxKind.Identifier:
// switch (token.parent.kind) {
// case ts.SyntaxKind.VariableDeclaration:
// switch (token.parent.parent.parent.kind) {
// case SyntaxKind.ForStatement:
// const forStatement = <ForStatement>token.parent.parent.parent;
// const forInitializer = <VariableDeclarationList>forStatement.initializer;
// if (forInitializer.declarations.length === 1) {
// return createCodeFix("", forInitializer.pos, forInitializer.end - forInitializer.pos);
// }
// else {
// return removeSingleItem(forInitializer.declarations, token);
// }
case SyntaxKind.ForOfStatement:
const forOfStatement = <ForOfStatement>token.parent.parent.parent;
if (forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
const forOfInitializer = <VariableDeclarationList>forOfStatement.initializer;
return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos);
}
break;
// case SyntaxKind.ForOfStatement:
// const forOfStatement = <ForOfStatement>token.parent.parent.parent;
// if (forOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
// const forOfInitializer = <VariableDeclarationList>forOfStatement.initializer;
// return createCodeFix("{}", forOfInitializer.declarations[0].pos, forOfInitializer.declarations[0].end - forOfInitializer.declarations[0].pos);
// }
// break;
case SyntaxKind.ForInStatement:
// There is no valid fix in the case of:
// for .. in
return undefined;
// case SyntaxKind.ForInStatement:
// // There is no valid fix in the case of:
// // for .. in
// return undefined;
case SyntaxKind.CatchClause:
const catchClause = <CatchClause>token.parent.parent;
const parameter = catchClause.variableDeclaration.getChildren()[0];
return createCodeFix("", parameter.pos, parameter.end - parameter.pos);
// case SyntaxKind.CatchClause:
// const catchClause = <CatchClause>token.parent.parent;
// const parameter = catchClause.variableDeclaration.getChildren()[0];
// return createCodeFix("", parameter.pos, parameter.end - parameter.pos);
default:
const variableStatement = <VariableStatement>token.parent.parent.parent;
if (variableStatement.declarationList.declarations.length === 1) {
return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos);
}
else {
const declarations = variableStatement.declarationList.declarations;
return removeSingleItem(declarations, token);
}
}
// default:
// const variableStatement = <VariableStatement>token.parent.parent.parent;
// if (variableStatement.declarationList.declarations.length === 1) {
// return createCodeFix("", variableStatement.pos, variableStatement.end - variableStatement.pos);
// }
// else {
// const declarations = variableStatement.declarationList.declarations;
// return removeSingleItem(declarations, token);
// }
// }
case SyntaxKind.TypeParameter:
const typeParameters = (<DeclarationWithTypeParameters>token.parent.parent).typeParameters;
if (typeParameters.length === 1) {
return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2);
}
else {
return removeSingleItem(typeParameters, token);
}
// case SyntaxKind.TypeParameter:
// const typeParameters = (<DeclarationWithTypeParameters>token.parent.parent).typeParameters;
// if (typeParameters.length === 1) {
// return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 2);
// }
// else {
// return removeSingleItem(typeParameters, token);
// }
case ts.SyntaxKind.Parameter:
const functionDeclaration = <FunctionDeclaration>token.parent.parent;
if (functionDeclaration.parameters.length === 1) {
return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
}
else {
return removeSingleItem(functionDeclaration.parameters, token);
}
// case ts.SyntaxKind.Parameter:
// const functionDeclaration = <FunctionDeclaration>token.parent.parent;
// if (functionDeclaration.parameters.length === 1) {
// return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
// }
// else {
// return removeSingleItem(functionDeclaration.parameters, token);
// }
// handle case where 'import a = A;'
case SyntaxKind.ImportEqualsDeclaration:
const importEquals = findImportDeclaration(token);
return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos);
// // handle case where 'import a = A;'
// case SyntaxKind.ImportEqualsDeclaration:
// const importEquals = findImportDeclaration(token);
// return createCodeFix("", importEquals.pos, importEquals.end - importEquals.pos);
case SyntaxKind.ImportSpecifier:
const namedImports = <NamedImports>token.parent.parent;
if (namedImports.elements.length === 1) {
// Only 1 import and it is unused. So the entire declaration should be removed.
const importSpec = findImportDeclaration(token);
return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos);
}
else {
return removeSingleItem(namedImports.elements, token);
}
// case SyntaxKind.ImportSpecifier:
// const namedImports = <NamedImports>token.parent.parent;
// if (namedImports.elements.length === 1) {
// // Only 1 import and it is unused. So the entire declaration should be removed.
// const importSpec = findImportDeclaration(token);
// return createCodeFix("", importSpec.pos, importSpec.end - importSpec.pos);
// }
// else {
// return removeSingleItem(namedImports.elements, token);
// }
// handle case where "import d, * as ns from './file'"
// or "'import {a, b as ns} from './file'"
case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *'
const importClause = <ImportClause>token.parent;
if (!importClause.namedBindings) { // |import d from './file'| or |import * as ns from './file'|
const importDecl = findImportDeclaration(importClause);
return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
}
else { // import |d,| * as ns from './file'
return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos);
}
// // handle case where "import d, * as ns from './file'"
// // or "'import {a, b as ns} from './file'"
// case SyntaxKind.ImportClause: // this covers both 'import |d|' and 'import |d,| *'
// const importClause = <ImportClause>token.parent;
// if (!importClause.namedBindings) { // |import d from './file'| or |import * as ns from './file'|
// const importDecl = findImportDeclaration(importClause);
// return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
// }
// else { // import |d,| * as ns from './file'
// return createCodeFix("", importClause.name.pos, importClause.namedBindings.pos - importClause.name.pos);
// }
case SyntaxKind.NamespaceImport:
const namespaceImport = <NamespaceImport>token.parent;
if (namespaceImport.name == token && !(<ImportClause>namespaceImport.parent).name) {
const importDecl = findImportDeclaration(namespaceImport);
return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
}
else {
const start = (<ImportClause>namespaceImport.parent).name.end;
return createCodeFix("", start, (<ImportClause>namespaceImport.parent).namedBindings.end - start);
}
}
break;
// case SyntaxKind.NamespaceImport:
// const namespaceImport = <NamespaceImport>token.parent;
// if (namespaceImport.name == token && !(<ImportClause>namespaceImport.parent).name) {
// const importDecl = findImportDeclaration(namespaceImport);
// return createCodeFix("", importDecl.pos, importDecl.end - importDecl.pos);
// }
// else {
// const start = (<ImportClause>namespaceImport.parent).name.end;
// return createCodeFix("", start, (<ImportClause>namespaceImport.parent).namedBindings.end - start);
// }
// }
// break;
case SyntaxKind.PropertyDeclaration:
return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
// case SyntaxKind.PropertyDeclaration:
// return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
case SyntaxKind.NamespaceImport:
return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
}
if (isDeclarationName(token)) {
return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
}
else if (isLiteralComputedPropertyDeclarationName(token)) {
return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos);
}
else {
return undefined;
}
// case SyntaxKind.NamespaceImport:
// return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
// }
// if (isDeclarationName(token)) {
// return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos);
// }
// else if (isLiteralComputedPropertyDeclarationName(token)) {
// return createCodeFix("", token.parent.parent.pos, token.parent.parent.end - token.parent.parent.pos);
// }
// else {
// return undefined;
// }
function findImportDeclaration(token: Node): Node {
let importDecl = token;
while (importDecl.kind != SyntaxKind.ImportDeclaration && importDecl.parent) {
importDecl = importDecl.parent;
}
// function findImportDeclaration(token: Node): Node {
// let importDecl = token;
// while (importDecl.kind != SyntaxKind.ImportDeclaration && importDecl.parent) {
// importDecl = importDecl.parent;
// }
return importDecl;
}
// return importDecl;
// }
function createCodeFix(newText: string, start: number, length: number): CodeAction[] {
return [{
description: getLocaleSpecificMessage(Diagnostics.Remove_unused_identifiers),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{ newText, span: { start, length } }]
}]
}];
}
// function createCodeFix(newText: string, start: number, length: number): CodeAction[] {
// return [{
// description: getLocaleSpecificMessage(Diagnostics.Remove_unused_identifiers),
// changes: [{
// fileName: sourceFile.fileName,
// textChanges: [{ newText, span: { start, length } }]
// }]
// }];
// }
function removeSingleItem<T extends Node>(elements: NodeArray<T>, token: T): CodeAction[] {
if (elements[0] === token.parent) {
return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1);
}
else {
return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1);
}
}
}
});
}
// function removeSingleItem<T extends Node>(elements: NodeArray<T>, token: T): CodeAction[] {
// if (elements[0] === token.parent) {
// return createCodeFix("", token.parent.pos, token.parent.end - token.parent.pos + 1);
// }
// else {
// return createCodeFix("", token.parent.pos - 1, token.parent.end - token.parent.pos + 1);
// }
// }
// }
// });
// }

View file

@ -48,7 +48,7 @@ namespace ts.JsTyping {
* @param projectRootPath is the path to the project root directory
* @param safeListPath is the path used to retrieve the safe list
* @param packageNameToTypingLocation is the map of package names to their cached typing locations
* @param typingOptions are used to customize the typing inference process
* @param typeAcquisition is used to customize the typing acquisition process
* @param compilerOptions are used as a source for typing inference
*/
export function discoverTypings(
@ -57,14 +57,14 @@ namespace ts.JsTyping {
projectRootPath: Path,
safeListPath: Path,
packageNameToTypingLocation: Map<string>,
typingOptions: TypingOptions,
typeAcquisition: TypeAcquisition,
unresolvedImports: ReadonlyArray<string>):
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
const inferredTypings = createMap<string>();
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
if (!typeAcquisition || !typeAcquisition.enable) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
}
@ -84,8 +84,8 @@ namespace ts.JsTyping {
let searchDirs: string[] = [];
let exclude: string[] = [];
mergeTypings(typingOptions.include);
exclude = typingOptions.exclude || [];
mergeTypings(typeAcquisition.include);
exclude = typeAcquisition.exclude || [];
const possibleSearchDirs = map(fileNames, getDirectoryPath);
if (projectRootPath) {

View file

@ -1138,7 +1138,7 @@ namespace ts {
if (result.error) {
return {
options: {},
typingOptions: {},
typeAcquisition: {},
files: [],
raw: {},
errors: [realizeDiagnostic(result.error, "\r\n")]
@ -1150,7 +1150,7 @@ namespace ts {
return {
options: configFile.options,
typingOptions: configFile.typingOptions,
typeAcquisition: configFile.typeAcquisition,
files: configFile.fileNames,
raw: configFile.raw,
errors: realizeDiagnostics(configFile.errors, "\r\n")
@ -1175,7 +1175,7 @@ namespace ts {
toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName),
toPath(info.safeListPath, info.safeListPath, getCanonicalFileName),
info.packageNameToTypingLocation,
info.typingOptions,
info.typeAcquisition,
info.unresolvedImports);
});
}
@ -1272,4 +1272,4 @@ namespace TypeScript.Services {
// TODO: it should be moved into a namespace though.
/* @internal */
const toolsVersion = "2.2";
const toolsVersion = "2.1";

View file

@ -1,10 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{ v1 }|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([`{ v1, f1 }`]);

View file

@ -1,11 +0,0 @@
/// <reference path="fourslash.ts" />
//// import d, [|{ v1 }|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export default var d1 = 6;
verify.importFixAtPosition([`{ v1, f1 }`]);

View file

@ -1,21 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{
//// v1,
//// v2
//// }|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export var v2 = 5;
//// export var v3 = 5;
verify.importFixAtPosition([
`{
v1,
v2,
f1
}`
]);

View file

@ -1,20 +0,0 @@
/// <reference path="fourslash.ts" />
////import [|{
//// v1, v2,
//// v3
////}|] from "./module";
////f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export var v2 = 5;
//// export var v3 = 5;
verify.importFixAtPosition([
`{
v1, v2,
v3, f1
}`
]);

View file

@ -1,12 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{}|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export var v2 = 5;
//// export var v3 = 5;
verify.importFixAtPosition([`{ f1 }`]);

View file

@ -1,16 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|import * as ns from "./module";
//// f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([
`import * as ns from "./module";
import { f1 } from "./module";
f1();`,
`import * as ns from "./module";
ns.f1();`
]);

View file

@ -1,18 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|import d, * as ns from "./module" ;
//// f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export default var d1 = 6;
// Test with some extra spaces before the semicolon
verify.importFixAtPosition([
`import d, * as ns from "./module" ;
ns.f1();`,
`import d, * as ns from "./module" ;
import { f1 } from "./module";
f1();`,
]);

View file

@ -1,14 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|import d from "./module";
//// f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export default var d1 = 6;
verify.importFixAtPosition([
`import d, { f1 } from "./module";
f1();`
]);

View file

@ -1,12 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|import "./module";
//// f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([`import "./module";
import { f1 } from "./module";
f1();`]);

View file

@ -1,13 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{ v1 }|] from "fake-module";
//// f1/*0*/();
// @Filename: ../package.json
//// { "dependencies": { "fake-module": "latest" } }
// @Filename: ../node_modules/fake-module/index.ts
//// export var v1 = 5;
//// export function f1();
verify.importFixAtPosition([`{ v1, f1 }`]);

View file

@ -1,10 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{ v1 }|] from "../other_dir/module";
//// f1/*0*/();
// @Filename: ../other_dir/module.ts
//// export var v1 = 5;
//// export function f1();
verify.importFixAtPosition([`{ v1, f1 }`]);

View file

@ -1,12 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{v1, v2, v3,}|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
//// export var v2 = 5;
//// export var v3 = 5;
verify.importFixAtPosition([`{v1, v2, v3, f1,}`]);

View file

@ -1,17 +0,0 @@
/// <reference path="fourslash.ts" />
//// import [|{
//// v1
//// }|] from "./module";
//// f1/*0*/();
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([
`{
v1,
f1
}`
]);

View file

@ -1,18 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|import ns = require("ambient-module");
//// var x = v1/*0*/ + 5;|]
// @Filename: ambientModule.ts
//// declare module "ambient-module" {
//// export function f1();
//// export var v1;
//// }
verify.importFixAtPosition([
`import ns = require("ambient-module");
var x = ns.v1 + 5;`,
`import ns = require("ambient-module");
import { v1 } from "ambient-module";
var x = v1 + 5;`,
]);

View file

@ -1,15 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: ambientModule.ts
//// declare module "ambient-module" {
//// export function f1();
//// export var v1;
//// }
verify.importFixAtPosition([
`import { f1 } from "ambient-module";
f1();`
]);

View file

@ -1,28 +0,0 @@
/// <reference path="fourslash.ts" />
//// import d from "other-ambient-module";
//// [|import * as ns from "yet-another-ambient-module";
//// var x = v1/*0*/ + 5;|]
// @Filename: ambientModule.ts
//// declare module "ambient-module" {
//// export function f1();
//// export var v1;
//// }
// @Filename: otherAmbientModule.ts
//// declare module "other-ambient-module" {
//// export default function f2();
//// }
// @Filename: yetAnotherAmbientModule.ts
//// declare module "yet-another-ambient-module" {
//// export function f3();
//// export var v3;
//// }
verify.importFixAtPosition([
`import * as ns from "yet-another-ambient-module";
import { v1 } from "ambient-module";
var x = v1 + 5;`
]);

View file

@ -1,21 +0,0 @@
/// <reference path="fourslash.ts" />
////[|/*
//// * I'm a license or something
//// */
////f1/*0*/();|]
// @Filename: ambientModule.ts
//// declare module "ambient-module" {
//// export function f1();
//// export var v1;
//// }
verify.importFixAtPosition([
`/*
* I'm a license or something
*/
import { f1 } from "ambient-module";
f1();`
]);

View file

@ -1,30 +0,0 @@
/// <reference path="fourslash.ts" />
//// let a = "I am a non-trivial statement that appears before imports";
//// import d from "other-ambient-module"
//// [|import * as ns from "yet-another-ambient-module"
//// var x = v1/*0*/ + 5;|]
// @Filename: ambientModule.ts
//// declare module "ambient-module" {
//// export function f1();
//// export var v1;
//// }
// @Filename: otherAmbientModule.ts
//// declare module "other-ambient-module" {
//// export default function f2();
//// }
// @Filename: yetAnotherAmbientModule.ts
//// declare module "yet-another-ambient-module" {
//// export function f3();
//// export var v3;
//// }
// test cases when there are no semicolons at the line end
verify.importFixAtPosition([
`import * as ns from "yet-another-ambient-module"
import { v1 } from "ambient-module";
var x = v1 + 5;`
]);

View file

@ -1,19 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "baseUrl": "./a"
//// }
//// }
// @Filename: a/b.ts
//// export function f1() { };
verify.importFixAtPosition([
`import { f1 } from "b";
f1();`
]);

View file

@ -1,12 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: module.ts
//// export default function f1() { };
verify.importFixAtPosition([
`import f1 from "./module";
f1();`
]);

View file

@ -1,13 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
verify.importFixAtPosition([
`import { f1 } from "./module";
f1();`
]);

View file

@ -1,18 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|/// <reference path="./tripleSlashReference.ts" />
//// f1/*0*/();|]
// @Filename: module.ts
//// export function f1() {}
//// export var v1 = 5;
// @Filename: tripleSlashReference.ts
//// var x = 5;/*dummy*/
verify.importFixAtPosition([
`/// <reference path="./tripleSlashReference.ts" />
import { f1 } from "./module";
f1();`
]);

View file

@ -1,13 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: ../../other_dir/module.ts
//// export var v1 = 5;
//// export function f1();
verify.importFixAtPosition([
`import { f1 } from "../../other_dir/module";
f1();`
]);

View file

@ -1,19 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: ../package.json
//// { "dependencies": { "fake-module": "latest" } }
// @Filename: ../node_modules/fake-module/index.ts
//// export var v1 = 5;
//// export function f1();
// @Filename: ../node_modules/fake-module/package.json
//// {}
verify.importFixAtPosition([
`import { f1 } from "fake-module";
f1();`
]);

View file

@ -1,16 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: ../package.json
//// { "dependencies": { "fake-module": "latest" } }
// @Filename: ../node_modules/fake-module/nested.ts
//// export var v1 = 5;
//// export function f1();
verify.importFixAtPosition([
`import { f1 } from "fake-module/nested";
f1();`
]);

View file

@ -1,25 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|f1/*0*/();|]
// @Filename: ../package.json
//// { "dependencies": { "fake-module": "latest" } }
// @Filename: ../node_modules/fake-module/notindex.d.ts
//// export var v1 = 5;
//// export function f1();
// @Filename: ../node_modules/fake-module/notindex.js
//// module.exports = {
//// v1: 5,
//// f1: function () {}
//// };
// @Filename: ../node_modules/fake-module/package.json
//// { "main":"./notindex.js", "typings":"./notindex.d.ts" }
verify.importFixAtPosition([
`import { f1 } from "fake-module";
f1();`
]);

View file

@ -1,14 +0,0 @@
/// <reference path="fourslash.ts" />
// @Filename: /a.ts
//// [|f1/*0*/();|]
// @Filename: /node_modules/@types/random/index.d.ts
//// export var v1 = 5;
//// export function f1();
verify.importFixAtPosition([
`import { f1 } from "random";
f1();`
]);

View file

@ -1,22 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|foo/*0*/();|]
// @Filename: folder_a/f2.ts
//// export function foo() {};
// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "baseUrl": ".",
//// "paths": {
//// "a": [ "folder_a/f2" ]
//// }
//// }
//// }
verify.importFixAtPosition([
`import { foo } from "a";
foo();`
]);

View file

@ -1,22 +0,0 @@
/// <reference path="fourslash.ts" />
//// [|foo/*0*/();|]
// @Filename: folder_b/f2.ts
//// export function foo() {};
// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "baseUrl": ".",
//// "paths": {
//// "b/*": [ "folder_b/*" ]
//// }
//// }
//// }
verify.importFixAtPosition([
`import { foo } from "b/f2";
foo();`
]);

View file

@ -1,23 +0,0 @@
/// <reference path="fourslash.ts" />
// @Filename: a/f1.ts
//// [|foo/*0*/();|]
// @Filename: b/c/f2.ts
//// export function foo() {};
// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "rootDirs": [
//// "a",
//// "b/c"
//// ]
//// }
//// }
verify.importFixAtPosition([
`import { foo } from "./f2";
foo();`
]);

View file

@ -1,22 +0,0 @@
/// <reference path="fourslash.ts" />
// @Filename: a/f1.ts
//// [|foo/*0*/();|]
// @Filename: types/random/index.ts
//// export function foo() {};
// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "typeRoots": [
//// "./types"
//// ]
//// }
//// }
verify.importFixAtPosition([
`import { foo } from "random";
foo();`
]);

View file

@ -1,20 +0,0 @@
/// <reference path="fourslash.ts" />
// @Filename: a/f1.ts
//// [|import * as ns from "./foo";
//// foo/*0*/();|]
// @Filename: a/foo/bar.ts
//// export function foo() {};
// @Filename: a/foo.ts
//// export { foo } from "./foo/bar";
verify.importFixAtPosition([
`import * as ns from "./foo";
import { foo } from "./foo";
foo();`,
`import * as ns from "./foo";
ns.foo();`,
]);

View file

@ -1,20 +0,0 @@
/// <reference path="fourslash.ts" />
// @Filename: a/f1.ts
//// [|foo/*0*/();|]
// @Filename: a/node_modules/bar/index.ts
//// export function foo() {};
// @Filename: a/foo.ts
//// export { foo } from "bar";
verify.importFixAtPosition([
`import { foo } from "./foo";
foo();`,
`import { foo } from "bar";
foo();`,
]);

View file

@ -0,0 +1,23 @@
///<reference path="fourslash.ts" />
// @allowJs: true
// @Filename: dummy.js
//// /**
//// * @augments {Thing<string>}
//// */
//// class MyStringThing extends Thing {
//// constructor() {
//// var x = this.mine;
//// x/**/;
//// }
//// }
// @Filename: declarations.d.ts
//// declare class Thing<T> {
//// mine: T;
//// }
goTo.marker();
verify.quickInfoIs("(local var) x: string");

View file

@ -1,10 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// class class1 {
//// }
//// } |]
verify.codeFixAtPosition(`namespace greeter {
}`);

View file

@ -1,15 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// export class class2 {
//// }
//// class class1 {
//// }
//// } |]
verify.codeFixAtPosition(`namespace greeter {
export class class2 {
}
}`);

View file

@ -1,25 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters:true
//// [| namespace Validation {
//// class c1 {
////
//// }
////
//// export class c2 {
////
//// }
////
//// class c3 extends c1 {
////
//// }
////} |]
verify.codeFixAtPosition(`namespace Validation {
class c1 {
}
export class c2 {
}
}`);

View file

@ -1,27 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters:true
//// [| namespace Validation {
//// class c1 {
////
//// }
////
//// export class c2 {
////
//// }
////
//// class c3 {
//// public x: c1;
//// }
////} |]
verify.codeFixAtPosition(`namespace Validation {
class c1 {
}
export class c2 {
}
}`);

View file

@ -1,10 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| function f1 () {
//// const x: string = "x";
//// } |]
verify.codeFixAtPosition(`function f1 () {
}`);

View file

@ -1,11 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| function f1 () {
//// enum Directions { Up, Down}
//// } |]
verify.codeFixAtPosition(`function f1 () {
}
`);

View file

@ -1,11 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// enum enum1 {
//// Monday
//// }
//// } |]
verify.codeFixAtPosition(`namespace greeter {
}`);

View file

@ -1,10 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// function function1() {
//// }/*1*/
//// } |]
verify.codeFixAtPosition(`namespace greeter {
}`);

View file

@ -1,14 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// export function function2() {
//// }
//// function function1() {
//// }
////} |]
verify.codeFixAtPosition(`namespace greeter {
export function function2() {
}
}`);

View file

@ -1,12 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters:true
//// [| namespace Validation {
//// function function1() {
//// }
////} |]
verify.codeFixAtPosition(`namespace Validation {
}`);

View file

@ -1,11 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters:true
//// [| namespace Validation {
//// var function1 = function() {
//// }
////} |]
verify.codeFixAtPosition(`namespace Validation {
}`);

View file

@ -1,28 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @noUnusedParameters:true
////namespace Validation {
//// var function1 = function() {
//// }
////
//// export function function2() {
////
//// }
////
//// [| function function3() {
//// function1();
//// }
////
//// function function4() {
////
//// }
////
//// export let a = function3; |]
////}
verify.codeFixAtPosition(`function function3() {
function1();
}
export let a = function3;`);

View file

@ -1,16 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// module A {
//// export class Calculator {
//// public handelChar() {
//// }
//// }
//// }
//// module B {
//// [|import a = A;|]
//// }
verify.codeFixAtPosition("");

View file

@ -1,14 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import f1, * as s from "./file1"; |]
//// s.f2('hello');
// @Filename: file1.ts
//// export var v1;
//// export function f1(n: number){}
//// export function f2(s: string){};
//// export default f1;
verify.codeFixAtPosition('import * as s from "./file1";');

View file

@ -1,13 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import f1, * as s from "./file1"; |]
//// f1(42);
// @Filename: file1.ts
//// export function f1(n: number){}
//// export function f2(s: string){};
//// export default f1;
verify.codeFixAtPosition('import f1 from "./file1";');

View file

@ -1,12 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [|import { Calculator } from "./file1" |]
// @Filename: file1.ts
//// export class Calculator {
////
//// }
verify.codeFixAtPosition('');

View file

@ -1,19 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [|import {Calculator} from "./file1"
//// import {test} from "./file1"|]
//// var x = new Calculator();
//// x.handleChar();
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() {}
//// }
//// export function test() {
////
//// }
verify.codeFixAtPosition(`import {Calculator} from "./file1"`);

View file

@ -1,24 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
////[| import {Calculator, test, test2} from "./file1" |]
//// test();
//// test2();
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() {}
//// }
//// export function test() {
////
//// }
//// export function test2() {
////
//// }
verify.codeFixAtPosition(`import {test, test2} from "./file1"`);

View file

@ -1,24 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import {Calculator, test, test2} from "./file1" |]
////
//// var x = new Calculator();
//// x.handleChar();
//// test2();
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() {}
//// }
////
//// export function test() {
////
//// }
////
//// export function test2() {
////
//// }
verify.codeFixAtPosition(`import {Calculator, test2} from "./file1"`);

View file

@ -1,24 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import {Calculator, test, test2} from "./file1" |]
////
//// var x = new Calculator();
//// x.handleChar();
//// test();
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() {}
//// }
////
//// export function test() {
////
//// }
////
//// export function test2() {
////
//// }
verify.codeFixAtPosition(`import {Calculator, test} from "./file1"`);

View file

@ -1,20 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import d from "./file1" |]
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() { }
//// }
//// export function test() {
////
//// }
//// export default function test2() {
////
//// }
verify.codeFixAtPosition('');

View file

@ -1,16 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [| import * as n from "./file1" |]
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() { }
//// }
//// export function test() {
//// }
//// export default function test2() {
//// }
verify.codeFixAtPosition('');

View file

@ -1,24 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [|import {Calculator as calc, test as t1, test2 as t2} from "./file1"|]
////
//// var x = new calc();
//// x.handleChar();
//// t1();
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() { }
//// }
//// export function test() {
////
//// }
//// export function test2() {
////
//// }
verify.codeFixAtPosition(`import {Calculator as calc, test as t1} from "./file1"`);

View file

@ -1,20 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
// @Filename: file2.ts
//// [|import c = require('./file1')|]
// @Filename: file1.ts
//// export class Calculator {
//// handleChar() { }
//// }
////
//// export function test() {
////
//// }
////
//// export function test2() {
////
//// }
verify.codeFixAtPosition("");

View file

@ -1,11 +0,0 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
//// [| namespace greeter {
//// interface interface1 {
//// }
////} |]
verify.codeFixAtPosition(`
namespace greeter {
}`);

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