Merge branch 'master' into fix16086

This commit is contained in:
Ron Buckton
2017-06-06 16:09:37 -07:00
195 changed files with 6031 additions and 194 deletions
+5 -1
View File
@@ -2333,7 +2333,7 @@ namespace ts {
// A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
// is still pointing to 'module.exports'.
// We do not want to consider this as 'export=' since a module can have only one of these.
// Similarlly we do not want to treat 'module.exports = exports' as an 'export='.
// Similarly we do not want to treat 'module.exports = exports' as an 'export='.
const assignedExpression = getRightMostAssignedExpression(node.right);
if (isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) {
// Mark it as a module in case there are no other exports in the file
@@ -2741,6 +2741,10 @@ namespace ts {
transformFlags |= TransformFlags.AssertES2015;
}
if (expression.kind === SyntaxKind.ImportKeyword) {
transformFlags |= TransformFlags.ContainsDynamicImport;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
+91 -8
View File
@@ -7649,11 +7649,9 @@ namespace ts {
if (left.flags & TypeFlags.Any || right.flags & TypeFlags.Any) {
return anyType;
}
left = filterType(left, t => !(t.flags & TypeFlags.Nullable));
if (left.flags & TypeFlags.Never) {
return right;
}
right = filterType(right, t => !(t.flags & TypeFlags.Nullable));
if (right.flags & TypeFlags.Never) {
return left;
}
@@ -8373,6 +8371,12 @@ namespace ts {
/**
* This is *not* a bi-directional relationship.
* If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
*
* A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T.
* It is used to check following cases:
* - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
* - the types of `case` clause expressions and their respective `switch` expressions.
* - the type of an expression in a type assertion with the type being asserted.
*/
function isTypeComparableTo(source: Type, target: Type): boolean {
return isTypeRelatedTo(source, target, comparableRelation);
@@ -8600,6 +8604,7 @@ namespace ts {
function isEmptyObjectType(type: Type): boolean {
return type.flags & TypeFlags.Object ? isEmptyResolvedType(resolveStructuredTypeMembers(<ObjectType>type)) :
type.flags & TypeFlags.NonPrimitive ? true :
type.flags & TypeFlags.Union ? forEach((<UnionType>type).types, isEmptyObjectType) :
type.flags & TypeFlags.Intersection ? !forEach((<UnionType>type).types, t => !isEmptyObjectType(t)) :
false;
@@ -15894,7 +15899,7 @@ namespace ts {
const callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call);
if (callSignatures.length) {
const signature = resolveCall(node, callSignatures, candidatesOutArray);
if (getReturnTypeOfSignature(signature) !== voidType) {
if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
}
if (getThisTypeOfSignature(signature) === voidType) {
@@ -16121,10 +16126,30 @@ namespace ts {
return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node);
}
/**
* Indicates whether a declaration can be treated as a constructor in a JavaScript
* file.
*/
function isJavaScriptConstructor(node: Declaration): boolean {
if (isInJavaScriptFile(node)) {
// If the node has a @class tag, treat it like a constructor.
if (getJSDocClassTag(node)) return true;
// If the symbol of the node has members, treat it like a constructor.
const symbol = isFunctionDeclaration(node) || isFunctionExpression(node) ? getSymbolOfNode(node) :
isVariableDeclaration(node) && isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) :
undefined;
return symbol && symbol.members !== undefined;
}
return false;
}
function getInferredClassType(symbol: Symbol) {
const links = getSymbolLinks(symbol);
if (!links.inferredClassType) {
links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined);
}
return links.inferredClassType;
}
@@ -16164,7 +16189,7 @@ namespace ts {
if (funcSymbol && isDeclarationOfFunctionOrClassExpression(funcSymbol)) {
funcSymbol = getSymbolOfNode((<VariableDeclaration>funcSymbol.valueDeclaration).initializer);
}
if (funcSymbol && funcSymbol.members && funcSymbol.flags & SymbolFlags.Function) {
if (funcSymbol && funcSymbol.flags & SymbolFlags.Function && (funcSymbol.members || getJSDocClassTag(funcSymbol.valueDeclaration))) {
return getInferredClassType(funcSymbol);
}
else if (noImplicitAny) {
@@ -16182,6 +16207,35 @@ namespace ts {
return getReturnTypeOfSignature(signature);
}
function checkImportCallExpression(node: ImportCall): Type {
// Check grammar of dynamic import
checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node);
if (node.arguments.length === 0) {
return createPromiseReturnType(node, anyType);
}
const specifier = node.arguments[0];
const specifierType = checkExpressionCached(specifier);
// Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion
for (let i = 1; i < node.arguments.length; ++i) {
checkExpressionCached(node.arguments[i]);
}
if (specifierType.flags & TypeFlags.Undefined || specifierType.flags & TypeFlags.Null || !isTypeAssignableTo(specifierType, stringType)) {
error(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
}
// resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
const moduleSymbol = resolveExternalModuleName(node, specifier);
if (moduleSymbol) {
const esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true);
if (esModuleSymbol) {
return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol));
}
}
return createPromiseReturnType(node, anyType);
}
function isCommonJsRequire(node: Node) {
if (!isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
return false;
@@ -16388,14 +16442,18 @@ namespace ts {
return emptyObjectType;
}
function createPromiseReturnType(func: FunctionLikeDeclaration, promisedType: Type) {
function createPromiseReturnType(func: FunctionLikeDeclaration | ImportCall, promisedType: Type) {
const promiseType = createPromiseType(promisedType);
if (promiseType === emptyObjectType) {
error(func, Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
error(func, isImportCall(func) ?
Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option);
return unknownType;
}
else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
error(func, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
error(func, isImportCall(func) ?
Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option :
Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
}
return promiseType;
@@ -17754,6 +17812,10 @@ namespace ts {
case SyntaxKind.ElementAccessExpression:
return checkIndexedAccess(<ElementAccessExpression>node);
case SyntaxKind.CallExpression:
if ((<CallExpression>node).expression.kind === SyntaxKind.ImportKeyword) {
return checkImportCallExpression(<ImportCall>node);
}
/* falls through */
case SyntaxKind.NewExpression:
return checkCallExpression(<CallExpression>node);
case SyntaxKind.TaggedTemplateExpression:
@@ -24681,6 +24743,27 @@ namespace ts {
});
return result;
}
function checkGrammarImportCallExpression(node: ImportCall): boolean {
if (modulekind === ModuleKind.ES2015) {
return grammarErrorOnNode(node, Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules);
}
if (node.typeArguments) {
return grammarErrorOnNode(node, Diagnostics.Dynamic_import_cannot_have_type_arguments);
}
const arguments = node.arguments;
if (arguments.length !== 1) {
return grammarErrorOnNode(node, Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
}
// see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
// parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
if (isSpreadElement(arguments[0])) {
return grammarErrorOnNode(arguments[0], Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
}
}
}
/** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
+2 -1
View File
@@ -100,11 +100,12 @@ namespace ts {
"umd": ModuleKind.UMD,
"es6": ModuleKind.ES2015,
"es2015": ModuleKind.ES2015,
"esnext": ModuleKind.ESNext
}),
paramType: Diagnostics.KIND,
showInSimplifiedHelpView: true,
category: Diagnostics.Basic_Options,
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_es2015_or_ESNext,
},
{
name: "lib",
+31 -5
View File
@@ -883,6 +883,23 @@
"category": "Error",
"code": 1322
},
"Dynamic import cannot be used when targeting ECMAScript 2015 modules.": {
"category": "Error",
"code": 1323
},
"Dynamic import must have one specifier as an argument.": {
"category": "Error",
"code": 1324
},
"Specifier of dynamic import cannot be spread element.": {
"category": "Error",
"code": 1325
},
"Dynamic import cannot have type arguments": {
"category": "Error",
"code": 1326
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -1927,10 +1944,6 @@
"category": "Error",
"code": 2649
},
"Cannot emit namespaced JSX elements in React.": {
"category": "Error",
"code": 2650
},
"A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums.": {
"category": "Error",
"code": 2651
@@ -2163,6 +2176,14 @@
"category": "Error",
"code": 2710
},
"A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.": {
"category": "Error",
"code": 2711
},
"A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.": {
"category": "Error",
"code": 2712
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -2629,7 +2650,7 @@
"category": "Message",
"code": 6015
},
"Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'.": {
"Specify module code generation: 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'.": {
"category": "Message",
"code": 6016
},
@@ -3365,6 +3386,11 @@
"category": "Error",
"code": 7035
},
"Dynamic import's specifier must be of type 'string', but here has type '{0}'.": {
"category": "Error",
"code": 7036
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
+1
View File
@@ -676,6 +676,7 @@ namespace ts {
case SyntaxKind.SuperKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.ImportKeyword:
writeTokenNode(node);
return;
+3 -2
View File
@@ -2503,8 +2503,9 @@ namespace ts {
helpers
} = sourceEmitNode;
if (!destEmitNode) destEmitNode = {};
if (leadingComments) destEmitNode.leadingComments = concatenate(leadingComments, destEmitNode.leadingComments);
if (trailingComments) destEmitNode.trailingComments = concatenate(trailingComments, destEmitNode.trailingComments);
// We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments);
if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments);
if (flags) destEmitNode.flags = flags;
if (commentRange) destEmitNode.commentRange = commentRange;
if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange;
+56 -25
View File
@@ -46,10 +46,16 @@ namespace ts {
}
}
// Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
// stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
// embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
// a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
/**
* Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
* stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
* embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
* a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
*
* @param node a given node to visit its children
* @param cbNode a callback to be invoked for all child nodes
* @param cbNodeArray a callback to be invoked for embedded array
*/
export function forEachChild<T>(node: Node, cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
if (!node) {
return;
@@ -2409,7 +2415,7 @@ namespace ts {
if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) {
return parseSignatureMember(SyntaxKind.CallSignature);
}
if (token() === SyntaxKind.NewKeyword && lookAhead(isStartOfConstructSignature)) {
if (token() === SyntaxKind.NewKeyword && lookAhead(nextTokenIsOpenParenOrLessThan)) {
return parseSignatureMember(SyntaxKind.ConstructSignature);
}
const fullStart = getNodePos();
@@ -2420,7 +2426,7 @@ namespace ts {
return parsePropertyOrMethodSignature(fullStart, modifiers);
}
function isStartOfConstructSignature() {
function nextTokenIsOpenParenOrLessThan() {
nextToken();
return token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken;
}
@@ -2777,6 +2783,8 @@ namespace ts {
case SyntaxKind.SlashEqualsToken:
case SyntaxKind.Identifier:
return true;
case SyntaxKind.ImportKeyword:
return lookAhead(nextTokenIsOpenParenOrLessThan);
default:
return isIdentifier();
}
@@ -3509,10 +3517,10 @@ namespace ts {
* 5) --UnaryExpression[?Yield]
*/
if (isUpdateExpression()) {
const incrementExpression = parseIncrementExpression();
const updateExpression = parseUpdateExpression();
return token() === SyntaxKind.AsteriskAsteriskToken ?
<BinaryExpression>parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) :
incrementExpression;
<BinaryExpression>parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) :
updateExpression;
}
/**
@@ -3578,7 +3586,7 @@ namespace ts {
}
// falls through
default:
return parseIncrementExpression();
return parseUpdateExpression();
}
}
@@ -3594,7 +3602,7 @@ namespace ts {
*/
function isUpdateExpression(): boolean {
// This function is called inside parseUnaryExpression to decide
// whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly
// whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
switch (token()) {
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
@@ -3618,9 +3626,9 @@ namespace ts {
}
/**
* Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression.
* Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
*
* ES7 IncrementExpression[yield]:
* ES7 UpdateExpression[yield]:
* 1) LeftHandSideExpression[?yield]
* 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
* 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
@@ -3628,7 +3636,7 @@ namespace ts {
* 5) --LeftHandSideExpression[?yield]
* In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
*/
function parseIncrementExpression(): IncrementExpression {
function parseUpdateExpression(): UpdateExpression {
if (token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) {
const node = <PrefixUnaryExpression>createNode(SyntaxKind.PrefixUnaryExpression);
node.operator = <PrefixUnaryOperator>token();
@@ -3678,17 +3686,27 @@ namespace ts {
// CallExpression Arguments
// CallExpression[Expression]
// CallExpression.IdentifierName
// super ( ArgumentListopt )
// import (AssignmentExpression)
// super Arguments
// super.IdentifierName
//
// Because of the recursion in these calls, we need to bottom out first. There are two
// bottom out states we can run into. Either we see 'super' which must start either of
// the last two CallExpression productions. Or we have a MemberExpression which either
// completes the LeftHandSideExpression, or starts the beginning of the first four
// CallExpression productions.
const expression = token() === SyntaxKind.SuperKeyword
? parseSuperExpression()
: parseMemberExpressionOrHigher();
// Because of the recursion in these calls, we need to bottom out first. There are three
// bottom out states we can run into: 1) We see 'super' which must start either of
// the last two CallExpression productions. 2) We see 'import' which must start import call.
// 3)we have a MemberExpression which either completes the LeftHandSideExpression,
// or starts the beginning of the first four CallExpression productions.
let expression: MemberExpression;
if (token() === SyntaxKind.ImportKeyword) {
// We don't want to eagerly consume all import keyword as import call expression so we look a head to find "("
// For example:
// var foo3 = require("subfolder
// import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression
sourceFile.flags |= NodeFlags.PossiblyContainDynamicImport;
expression = parseTokenNode<PrimaryExpression>();
}
else {
expression = token() === SyntaxKind.SuperKeyword ? parseSuperExpression() : parseMemberExpressionOrHigher();
}
// Now, we *may* be complete. However, we might have consumed the start of a
// CallExpression. As such, we need to consume the rest of it here to be complete.
@@ -3696,7 +3714,7 @@ namespace ts {
}
function parseMemberExpressionOrHigher(): MemberExpression {
// Note: to make our lives simpler, we decompose the the NewExpression productions and
// Note: to make our lives simpler, we decompose the NewExpression productions and
// place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
// like so:
//
@@ -4792,9 +4810,11 @@ namespace ts {
case SyntaxKind.FinallyKeyword:
return true;
case SyntaxKind.ImportKeyword:
return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan);
case SyntaxKind.ConstKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.ImportKeyword:
return isStartOfDeclaration();
case SyntaxKind.AsyncKeyword:
@@ -6513,6 +6533,10 @@ namespace ts {
case "augments":
tag = parseAugmentsTag(atToken, tagName);
break;
case "class":
case "constructor":
tag = parseClassTag(atToken, tagName);
break;
case "arg":
case "argument":
case "param":
@@ -6732,6 +6756,13 @@ namespace ts {
return finishNode(result);
}
function parseClassTag(atToken: AtToken, tagName: Identifier): JSDocClassTag {
const tag = <JSDocClassTag>createNode(SyntaxKind.JSDocClassTag, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
}
function parseTypedefTag(atToken: AtToken, tagName: Identifier): JSDocTypedefTag {
const typeExpression = tryParseTypeExpression();
skipWhitespace();
+9 -4
View File
@@ -1359,6 +1359,7 @@ namespace ts {
const isJavaScriptFile = isSourceFileJavaScript(file);
const isExternalModuleFile = isExternalModule(file);
// file.imports may not be undefined if there exists dynamic import
let imports: LiteralExpression[];
let moduleAugmentations: LiteralExpression[];
let ambientModules: string[];
@@ -1378,8 +1379,8 @@ namespace ts {
for (const node of file.statements) {
collectModuleReferences(node, /*inAmbientModule*/ false);
if (isJavaScriptFile) {
collectRequireCalls(node);
if ((file.flags & NodeFlags.PossiblyContainDynamicImport) || isJavaScriptFile) {
collectDynamicImportOrRequireCalls(node);
}
}
@@ -1442,12 +1443,16 @@ namespace ts {
}
}
function collectRequireCalls(node: Node): void {
function collectDynamicImportOrRequireCalls(node: Node): void {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
// we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
else if (isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === SyntaxKind.StringLiteral) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
else {
forEachChild(node, collectRequireCalls);
forEachChild(node, collectDynamicImportOrRequireCalls);
}
}
}
+1
View File
@@ -15,6 +15,7 @@
namespace ts {
function getModuleTransformer(moduleKind: ModuleKind): TransformerFactory<SourceFile> {
switch (moduleKind) {
case ModuleKind.ESNext:
case ModuleKind.ES2015:
return transformES2015Module;
case ModuleKind.System:
+7 -5
View File
@@ -351,8 +351,10 @@ namespace ts {
);
}
function awaitAsYield(expression: Expression) {
return createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & FunctionFlags.Generator ? createAwaitHelper(context, expression) : expression);
function createDownlevelAwait(expression: Expression) {
return enclosingFunctionFlags & FunctionFlags.Generator
? createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
: createAwait(expression);
}
function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) {
@@ -385,11 +387,11 @@ namespace ts {
EmitFlags.NoHoisting
),
/*condition*/ createComma(
createAssignment(result, awaitAsYield(callNext)),
createAssignment(result, createDownlevelAwait(callNext)),
createLogicalNot(getDone)
),
/*incrementor*/ undefined,
/*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))
/*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))
),
/*location*/ node
),
@@ -434,7 +436,7 @@ namespace ts {
createPropertyAccess(iterator, "return")
)
),
createStatement(awaitAsYield(callReturn))
createStatement(createDownlevelAwait(callReturn))
),
EmitFlags.SingleLine
)
+124 -13
View File
@@ -46,6 +46,7 @@ namespace ts {
let currentSourceFile: SourceFile; // The current file.
let currentModuleInfo: ExternalModuleInfo; // The ExternalModuleInfo for the current file.
let noSubstitution: boolean[]; // Set of nodes for which substitution rules should be ignored.
let needUMDDynamicImportHelper: boolean;
return transformSourceFile;
@@ -55,7 +56,7 @@ namespace ts {
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) {
if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return node;
}
@@ -66,9 +67,9 @@ namespace ts {
// Perform the transformation.
const transformModule = getTransformModuleDelegate(moduleKind);
const updated = transformModule(node);
currentSourceFile = undefined;
currentModuleInfo = undefined;
needUMDDynamicImportHelper = false;
return aggregateTransformFlags(updated);
}
@@ -107,6 +108,7 @@ namespace ts {
// we need to inform the emitter to add the __export helper.
addEmitHelper(updated, exportStarHelper);
}
addEmitHelpers(updated, context.readEmitHelpers());
return updated;
}
@@ -411,6 +413,9 @@ namespace ts {
// we need to inform the emitter to add the __export helper.
addEmitHelper(body, exportStarHelper);
}
if (needUMDDynamicImportHelper) {
addEmitHelper(body, dynamicImportUMDHelper);
}
return body;
}
@@ -488,12 +493,110 @@ namespace ts {
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
default:
// This visitor does not descend into the tree, as export/import statements
// are only transformed at the top level of a file.
return node;
return visitEachChild(node, importCallExpressionVisitor, context);
}
}
function importCallExpressionVisitor(node: Node): VisitResult<Node> {
// This visitor does not need to descend into the tree if there is no dynamic import,
// as export/import statements are only transformed at the top level of a file.
if (!(node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return node;
}
if (isImportCall(node)) {
return visitImportCallExpression(<ImportCall>node);
}
else {
return visitEachChild(node, importCallExpressionVisitor, context);
}
}
function visitImportCallExpression(node: ImportCall): Expression {
switch (compilerOptions.module) {
case ModuleKind.CommonJS:
return transformImportCallExpressionCommonJS(node);
case ModuleKind.AMD:
return transformImportCallExpressionAMD(node);
case ModuleKind.UMD:
return transformImportCallExpressionUMD(node);
}
Debug.fail("All supported module kind in this transformation step should have been handled");
}
function transformImportCallExpressionUMD(node: ImportCall): Expression {
// (function (factory) {
// ... (regular UMD)
// }
// })(function (require, exports, useSyncRequire) {
// "use strict";
// Object.defineProperty(exports, "__esModule", { value: true });
// var __syncRequire = typeof module === "object" && typeof module.exports === "object";
// var __resolved = new Promise(function (resolve) { resolve(); });
// .....
// __syncRequire
// ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
// : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
// });
needUMDDynamicImportHelper = true;
return createConditional(
/*condition*/ createIdentifier("__syncRequire"),
/*whenTrue*/ transformImportCallExpressionCommonJS(node),
/*whenFalse*/ transformImportCallExpressionAMD(node)
);
}
function transformImportCallExpressionAMD(node: ImportCall): Expression {
// improt("./blah")
// emit as
// define(["require", "exports", "blah"], function (require, exports) {
// ...
// new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
// });
const resolve = createUniqueName("resolve");
const reject = createUniqueName("reject");
return createNew(
createIdentifier("Promise"),
/*typeArguments*/ undefined,
[createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)],
/*type*/ undefined,
createBlock([createStatement(
createCall(
createIdentifier("require"),
/*typeArguments*/ undefined,
[createArrayLiteral([firstOrUndefined(node.arguments) || createOmittedExpression()]), resolve, reject]
))])
)]);
}
function transformImportCallExpressionCommonJS(node: ImportCall): Expression {
// import("./blah")
// emit as
// Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
// We have to wrap require in then callback so that require is done in asynchronously
// if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
return createCall(
createPropertyAccess(
createCall(createPropertyAccess(createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []),
"then"),
/*typeArguments*/ undefined,
[createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ undefined,
/*type*/ undefined,
createBlock([createReturn(createCall(createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))])
)]);
}
/**
* Visits an ImportDeclaration node.
*
@@ -786,9 +889,9 @@ namespace ts {
node.asteriskToken,
getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
node.parameters,
visitNodes(node.parameters, importCallExpressionVisitor),
/*type*/ undefined,
node.body
visitEachChild(node.body, importCallExpressionVisitor, context)
),
/*location*/ node
),
@@ -797,7 +900,7 @@ namespace ts {
);
}
else {
statements = append(statements, node);
statements = append(statements, visitEachChild(node, importCallExpressionVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
@@ -828,7 +931,7 @@ namespace ts {
visitNodes(node.modifiers, modifierVisitor, isModifier),
getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
node.heritageClauses,
visitNodes(node.heritageClauses, importCallExpressionVisitor),
node.members
),
node
@@ -838,7 +941,7 @@ namespace ts {
);
}
else {
statements = append(statements, node);
statements = append(statements, visitEachChild(node, importCallExpressionVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
@@ -890,7 +993,7 @@ namespace ts {
}
}
else {
statements = append(statements, node);
statements = append(statements, visitEachChild(node, importCallExpressionVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
@@ -913,7 +1016,7 @@ namespace ts {
function transformInitializedVariable(node: VariableDeclaration): Expression {
if (isBindingPattern(node.name)) {
return flattenDestructuringAssignment(
node,
visitNode(node, importCallExpressionVisitor),
/*visitor*/ undefined,
context,
FlattenLevel.All,
@@ -930,7 +1033,7 @@ namespace ts {
),
/*location*/ node.name
),
node.initializer
visitNode(node.initializer, importCallExpressionVisitor)
);
}
}
@@ -1497,4 +1600,12 @@ namespace ts {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}`
};
// emit helper for dynamic import
const dynamicImportUMDHelper: EmitHelper = {
name: "typescript:dynamicimport-sync-require",
scoped: true,
text: `
var __syncRequire = typeof module === "object" && typeof module.exports === "object";`
};
}
+49 -25
View File
@@ -50,7 +50,7 @@ namespace ts {
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile || !(isExternalModule(node) || compilerOptions.isolatedModules)) {
if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return node;
}
@@ -646,7 +646,7 @@ namespace ts {
return undefined;
}
const expression = visitNode(node.expression, destructuringVisitor, isExpression);
const expression = visitNode(node.expression, destructuringAndImportCallVisitor, isExpression);
const original = node.original;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -673,12 +673,12 @@ namespace ts {
node.asteriskToken,
getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
visitNodes(node.parameters, destructuringVisitor, isParameterDeclaration),
visitNodes(node.parameters, destructuringAndImportCallVisitor, isParameterDeclaration),
/*type*/ undefined,
visitNode(node.body, destructuringVisitor, isBlock)));
visitNode(node.body, destructuringAndImportCallVisitor, isBlock)));
}
else {
hoistedStatements = append(hoistedStatements, node);
hoistedStatements = append(hoistedStatements, visitEachChild(node, destructuringAndImportCallVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
@@ -716,8 +716,8 @@ namespace ts {
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, destructuringVisitor, isHeritageClause),
visitNodes(node.members, destructuringVisitor, isClassElement)
visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, isHeritageClause),
visitNodes(node.members, destructuringAndImportCallVisitor, isClassElement)
),
node
)
@@ -747,7 +747,7 @@ namespace ts {
*/
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
if (!shouldHoistVariableDeclarationList(node.declarationList)) {
return visitNode(node, destructuringVisitor, isStatement);
return visitNode(node, destructuringAndImportCallVisitor, isStatement);
}
let expressions: Expression[];
@@ -820,13 +820,13 @@ namespace ts {
return isBindingPattern(node.name)
? flattenDestructuringAssignment(
node,
destructuringVisitor,
destructuringAndImportCallVisitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: createAssignment(node.name, visitNode(node.initializer, destructuringVisitor, isExpression));
: createAssignment(node.name, visitNode(node.initializer, destructuringAndImportCallVisitor, isExpression));
}
/**
@@ -1204,7 +1204,7 @@ namespace ts {
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
default:
return destructuringVisitor(node);
return destructuringAndImportCallVisitor(node);
}
}
@@ -1220,8 +1220,8 @@ namespace ts {
node = updateFor(
node,
visitForInitializer(node.initializer),
visitNode(node.condition, destructuringVisitor, isExpression),
visitNode(node.incrementor, destructuringVisitor, isExpression),
visitNode(node.condition, destructuringAndImportCallVisitor, isExpression),
visitNode(node.incrementor, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement)
);
@@ -1241,7 +1241,7 @@ namespace ts {
node = updateForIn(
node,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
@@ -1262,7 +1262,7 @@ namespace ts {
node,
node.awaitModifier,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
@@ -1313,7 +1313,7 @@ namespace ts {
return updateDo(
node,
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock),
visitNode(node.expression, destructuringVisitor, isExpression)
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression)
);
}
@@ -1325,7 +1325,7 @@ namespace ts {
function visitWhileStatement(node: WhileStatement): VisitResult<Statement> {
return updateWhile(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
@@ -1351,7 +1351,7 @@ namespace ts {
function visitWithStatement(node: WithStatement): VisitResult<Statement> {
return updateWith(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
@@ -1364,7 +1364,7 @@ namespace ts {
function visitSwitchStatement(node: SwitchStatement): VisitResult<Statement> {
return updateSwitch(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.caseBlock, nestedElementVisitor, isCaseBlock)
);
}
@@ -1395,7 +1395,7 @@ namespace ts {
function visitCaseClause(node: CaseClause): VisitResult<CaseOrDefaultClause> {
return updateCaseClause(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNodes(node.statements, nestedElementVisitor, isStatement)
);
}
@@ -1461,19 +1461,43 @@ namespace ts {
*
* @param node The node to visit.
*/
function destructuringVisitor(node: Node): VisitResult<Node> {
function destructuringAndImportCallVisitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.DestructuringAssignment
&& node.kind === SyntaxKind.BinaryExpression) {
return visitDestructuringAssignment(<DestructuringAssignment>node);
}
else if (node.transformFlags & TransformFlags.ContainsDestructuringAssignment) {
return visitEachChild(node, destructuringVisitor, context);
else if (isImportCall(node)) {
return visitImportCallExpression(node);
}
else if ((node.transformFlags & TransformFlags.ContainsDestructuringAssignment) || (node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
return node;
}
}
function visitImportCallExpression(node: ImportCall): Expression {
// import("./blah")
// emit as
// System.register([], function (_export, _context) {
// return {
// setters: [],
// execute: () => {
// _context.import('./blah');
// }
// };
// });
return createCall(
createPropertyAccess(
contextObject,
createIdentifier("import")
),
/*typeArguments*/ undefined,
node.arguments
);
}
/**
* Visits a DestructuringAssignment to flatten destructuring to exported symbols.
*
@@ -1483,14 +1507,14 @@ namespace ts {
if (hasExportedReferenceInDestructuringTarget(node.left)) {
return flattenDestructuringAssignment(
node,
destructuringVisitor,
destructuringAndImportCallVisitor,
context,
FlattenLevel.All,
/*needsValue*/ true
);
}
return visitEachChild(node, destructuringVisitor, context);
return visitEachChild(node, destructuringAndImportCallVisitor, context);
}
/**
+37 -11
View File
@@ -374,6 +374,7 @@ namespace ts {
JSDocComment,
JSDocTag,
JSDocAugmentsTag,
JSDocClassTag,
JSDocParameterTag,
JSDocReturnTag,
JSDocTypeTag,
@@ -395,6 +396,7 @@ namespace ts {
// Enum value count
Count,
// Markers
FirstAssignment = EqualsToken,
LastAssignment = CaretEqualsToken,
@@ -449,6 +451,14 @@ namespace ts {
ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node
// This flag will be set to true when the parse encounter dynamic import so that post-parsing process of module resolution
// will not walk the tree if the flag is not set. However, this flag is just a approximation because once it is set, the flag never get reset.
// (hence it is named "possiblyContainDynamicImport").
// During editing, if dynamic import is remove, incremental parsing will *NOT* update this flag. This will then causes walking of the tree during module resolution.
// However, the removal operation should not occur often and in the case of the removal, it is likely that users will add back the import anyway.
// The advantage of this approach is its simplicity. For the case of batch compilation, we garuntee that users won't have to pay the price of walking the tree if dynamic import isn't used.
PossiblyContainDynamicImport = 1 << 19,
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
@@ -1001,8 +1011,10 @@ namespace ts {
_unaryExpressionBrand: any;
}
export interface IncrementExpression extends UnaryExpression {
_incrementExpressionBrand: any;
/** Deprecated, please use UpdateExpression */
export type IncrementExpression = UpdateExpression;
export interface UpdateExpression extends UnaryExpression {
_updateExpressionBrand: any;
}
// see: https://tc39.github.io/ecma262/#prod-UpdateExpression
@@ -1013,10 +1025,9 @@ namespace ts {
| SyntaxKind.PlusToken
| SyntaxKind.MinusToken
| SyntaxKind.TildeToken
| SyntaxKind.ExclamationToken
;
| SyntaxKind.ExclamationToken;
export interface PrefixUnaryExpression extends IncrementExpression {
export interface PrefixUnaryExpression extends UpdateExpression {
kind: SyntaxKind.PrefixUnaryExpression;
operator: PrefixUnaryOperator;
operand: UnaryExpression;
@@ -1028,13 +1039,13 @@ namespace ts {
| SyntaxKind.MinusMinusToken
;
export interface PostfixUnaryExpression extends IncrementExpression {
export interface PostfixUnaryExpression extends UpdateExpression {
kind: SyntaxKind.PostfixUnaryExpression;
operand: LeftHandSideExpression;
operator: PostfixUnaryOperator;
}
export interface LeftHandSideExpression extends IncrementExpression {
export interface LeftHandSideExpression extends UpdateExpression {
_leftHandSideExpressionBrand: any;
}
@@ -1062,6 +1073,10 @@ namespace ts {
kind: SyntaxKind.SuperKeyword;
}
export interface ImportExpression extends PrimaryExpression {
kind: SyntaxKind.ImportKeyword;
}
export interface DeleteExpression extends UnaryExpression {
kind: SyntaxKind.DeleteExpression;
expression: UnaryExpression;
@@ -1454,10 +1469,7 @@ namespace ts {
}
// see: https://tc39.github.io/ecma262/#prod-SuperProperty
export type SuperProperty
= SuperPropertyAccessExpression
| SuperElementAccessExpression
;
export type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression;
export interface CallExpression extends LeftHandSideExpression, Declaration {
kind: SyntaxKind.CallExpression;
@@ -1471,6 +1483,10 @@ namespace ts {
expression: SuperExpression;
}
export interface ImportCall extends CallExpression {
expression: ImportExpression;
}
export interface ExpressionWithTypeArguments extends TypeNode {
kind: SyntaxKind.ExpressionWithTypeArguments;
parent?: HeritageClause;
@@ -2117,6 +2133,10 @@ namespace ts {
typeExpression: JSDocTypeExpression;
}
export interface JSDocClassTag extends JSDocTag {
kind: SyntaxKind.JSDocClassTag;
}
export interface JSDocTemplateTag extends JSDocTag {
kind: SyntaxKind.JSDocTemplateTag;
typeParameters: NodeArray<TypeParameterDeclaration>;
@@ -3566,6 +3586,7 @@ namespace ts {
UMD = 3,
System = 4,
ES2015 = 5,
ESNext = 6
}
export const enum JsxEmit {
@@ -3950,6 +3971,11 @@ namespace ts {
ContainsYield = 1 << 24,
ContainsHoistedDeclarationOrCompletion = 1 << 25,
ContainsDynamicImport = 1 << 26,
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
HasComputedFlags = 1 << 29, // Transform flags have been computed.
// Assertions
+8
View File
@@ -596,6 +596,10 @@ namespace ts {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.SuperKeyword;
}
export function isImportCall(n: Node): n is ImportCall {
return n.kind === SyntaxKind.CallExpression && (<CallExpression>n).expression.kind === SyntaxKind.ImportKeyword;
}
export function isPrologueDirective(node: Node): node is PrologueDirective {
return node.kind === SyntaxKind.ExpressionStatement
&& (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
@@ -1558,6 +1562,10 @@ namespace ts {
return getFirstJSDocTag(node, SyntaxKind.JSDocAugmentsTag) as JSDocAugmentsTag;
}
export function getJSDocClassTag(node: Node): JSDocClassTag {
return getFirstJSDocTag(node, SyntaxKind.JSDocClassTag) as JSDocClassTag;
}
export function getJSDocReturnTag(node: Node): JSDocReturnTag {
return getFirstJSDocTag(node, SyntaxKind.JSDocReturnTag) as JSDocReturnTag;
}
+1
View File
@@ -857,6 +857,7 @@ namespace Harness {
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
switch (options.target) {
case ts.ScriptTarget.ESNext:
case ts.ScriptTarget.ES2017:
return "lib.es2017.d.ts";
case ts.ScriptTarget.ES2016:
+1 -1
View File
@@ -113,7 +113,7 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'.",
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.",
category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
@@ -122,7 +122,7 @@ namespace ts {
file: undefined,
start: 0,
length: 0,
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015'.",
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.",
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category
}]
@@ -13,7 +13,8 @@ namespace ts.projectSystem {
express: "express",
jquery: "jquery",
lodash: "lodash",
moment: "moment"
moment: "moment",
chroma: "chroma-js"
})
};
@@ -61,7 +62,6 @@ namespace ts.projectSystem {
super(installTypingHost, globalTypingsCacheLocation, safeList.path, throttleLimit, log);
}
safeFileList = safeList.path;
protected postExecActions: PostExecAction[] = [];
executePendingCommands() {
+24 -3
View File
@@ -1009,6 +1009,26 @@ namespace ts.projectSystem {
});
describe("discover typings", () => {
it("should use mappings from safe list", () => {
const app = {
path: "/a/b/app.js",
content: ""
};
const jquery = {
path: "/a/b/jquery.js",
content: ""
};
const chroma = {
path: "/a/b/chroma.min.js",
content: ""
};
const cache = createMap<string>();
const host = createServerHost([app, jquery, chroma]);
const result = JsTyping.discoverTypings(host, [app.path, jquery.path, chroma.path], getDirectoryPath(<Path>app.path), /*safeListPath*/ undefined, cache, { enable: true }, []);
assert.deepEqual(result.newTypingNames, ["jquery", "chroma-js"]);
});
it("should return node for core modules", () => {
const f = {
path: "/a/b/app.js",
@@ -1016,6 +1036,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, { enable: true }, [name, "somename"]);
assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]);
@@ -1040,7 +1061,7 @@ namespace ts.projectSystem {
});
describe("telemetry events", () => {
it ("should be received", () => {
it("should be received", () => {
const f1 = {
path: "/a/app.js",
content: ""
@@ -1089,7 +1110,7 @@ namespace ts.projectSystem {
});
describe("progress notifications", () => {
it ("should be sent for success", () => {
it("should be sent for success", () => {
const f1 = {
path: "/a/app.js",
content: ""
@@ -1140,7 +1161,7 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[0], [f1.path, commander.path]);
});
it ("should be sent for error", () => {
it("should be sent for error", () => {
const f1 = {
path: "/a/app.js",
content: ""
+2 -2
View File
@@ -143,7 +143,7 @@ namespace ts.JsTyping {
/**
* Merge a given list of typingNames to the inferredTypings map
*/
function mergeTypings(typingNames: string[]) {
function mergeTypings(typingNames: ReadonlyArray<string>) {
if (!typingNames) {
return;
}
@@ -192,7 +192,7 @@ namespace ts.JsTyping {
const cleanedTypingNames = map(inferredTypingNames, f => f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""));
if (safeList !== EmptySafeList) {
mergeTypings(filter(cleanedTypingNames, f => safeList.has(f)));
mergeTypings(ts.mapDefined(cleanedTypingNames, f => safeList.get(f)));
}
const hasJsxFile = forEach(fileNames, f => ensureScriptKind(f, getScriptKindFromFileName(f)) === ScriptKind.JSX);
+2 -1
View File
@@ -368,7 +368,7 @@ namespace ts {
_primaryExpressionBrand: any;
_memberExpressionBrand: any;
_leftHandSideExpressionBrand: any;
_incrementExpressionBrand: any;
_updateExpressionBrand: any;
_unaryExpressionBrand: any;
_expressionBrand: any;
/*@internal*/typeArguments: NodeArray<TypeNode>;
@@ -521,6 +521,7 @@ namespace ts {
private namedDeclarations: Map<Declaration[]>;
public ambientModuleNames: string[];
public checkJsDirective: CheckJsDirective | undefined;
public possiblyContainDynamicImport: boolean;
constructor(kind: SyntaxKind, pos: number, end: number) {
super(kind, pos, end);