mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'master' into attach_property_to_default_export
This commit is contained in:
@@ -35,8 +35,8 @@ function createCancellationToken(args: string[]): ServerCancellationToken {
|
||||
}
|
||||
// cancellationPipeName is a string without '*' inside that can optionally end with '*'
|
||||
// when client wants to signal cancellation it should create a named pipe with name=<cancellationPipeName>
|
||||
// server will synchronously check the presence of the pipe and treat its existance as indicator that current request should be canceled.
|
||||
// in case if client prefers to use more fine-grained schema than one name for all request it can add '*' to the end of cancelellationPipeName.
|
||||
// server will synchronously check the presence of the pipe and treat its existence as indicator that current request should be canceled.
|
||||
// in case if client prefers to use more fine-grained schema than one name for all request it can add '*' to the end of cancellationPipeName.
|
||||
// in this case pipe name will be build dynamically as <cancellationPipeName><request_seq>.
|
||||
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
|
||||
const namePrefix = cancellationPipeName.slice(0, -1);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"extends": "../tsconfig-base",
|
||||
"extends": "../tsconfig-noncomposite-base",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../built/local/",
|
||||
"rootDir": ".",
|
||||
@@ -7,6 +7,7 @@
|
||||
"declaration": false,
|
||||
"declarationMap": false,
|
||||
"removeComments": true,
|
||||
"incremental": false,
|
||||
"module": "commonjs",
|
||||
"types": [
|
||||
"node"
|
||||
|
||||
+125
-153
@@ -100,6 +100,8 @@ namespace ts {
|
||||
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
|
||||
}
|
||||
|
||||
let flowNodeCreated: <T extends FlowNode>(node: T) => T = identity;
|
||||
|
||||
const binder = createBinder();
|
||||
|
||||
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
|
||||
@@ -401,13 +403,15 @@ namespace ts {
|
||||
messageNeedsName = false;
|
||||
}
|
||||
|
||||
if (symbol.declarations && symbol.declarations.length) {
|
||||
let multipleDefaultExports = false;
|
||||
if (length(symbol.declarations)) {
|
||||
// If the current node is a default export of some sort, then check if
|
||||
// there are any other default exports that we need to error on.
|
||||
// We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
|
||||
if (isDefaultExport) {
|
||||
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
|
||||
messageNeedsName = false;
|
||||
multipleDefaultExports = true;
|
||||
}
|
||||
else {
|
||||
// This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
|
||||
@@ -418,15 +422,26 @@ namespace ts {
|
||||
(node.kind === SyntaxKind.ExportAssignment && !(<ExportAssignment>node).isExportEquals)) {
|
||||
message = Diagnostics.A_module_cannot_have_multiple_default_exports;
|
||||
messageNeedsName = false;
|
||||
multipleDefaultExports = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const addError = (decl: Declaration): void => {
|
||||
file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(decl) || decl, message, messageNeedsName ? getDisplayName(decl) : undefined));
|
||||
};
|
||||
forEach(symbol.declarations, addError);
|
||||
addError(node);
|
||||
const declarationName = getNameOfDeclaration(node) || node;
|
||||
const relatedInformation: DiagnosticRelatedInformation[] = [];
|
||||
forEach(symbol.declarations, (declaration, index) => {
|
||||
const decl = getNameOfDeclaration(declaration) || declaration;
|
||||
const diag = createDiagnosticForNode(decl, message, messageNeedsName ? getDisplayName(declaration) : undefined);
|
||||
file.bindDiagnostics.push(
|
||||
multipleDefaultExports ? addRelatedInfo(diag, createDiagnosticForNode(declarationName, index === 0 ? Diagnostics.Another_export_default_is_here : Diagnostics.and_here)) : diag
|
||||
);
|
||||
if (multipleDefaultExports) {
|
||||
relatedInformation.push(createDiagnosticForNode(decl, Diagnostics.The_first_export_default_is_here));
|
||||
}
|
||||
});
|
||||
|
||||
const diag = createDiagnosticForNode(declarationName, message, messageNeedsName ? getDisplayName(node) : undefined);
|
||||
file.bindDiagnostics.push(multipleDefaultExports ? addRelatedInfo(diag, ...relatedInformation) : diag);
|
||||
|
||||
symbol = createSymbol(SymbolFlags.None, name);
|
||||
}
|
||||
@@ -530,6 +545,7 @@ namespace ts {
|
||||
blockScopeContainer.locals = undefined;
|
||||
}
|
||||
if (containerFlags & ContainerFlags.IsControlFlowContainer) {
|
||||
const saveFlowNodeCreated = flowNodeCreated;
|
||||
const saveCurrentFlow = currentFlow;
|
||||
const saveBreakTarget = currentBreakTarget;
|
||||
const saveContinueTarget = currentContinueTarget;
|
||||
@@ -547,12 +563,13 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
// We create a return control flow graph for IIFEs and constructors. For constructors
|
||||
// we use the return control flow graph in strict property intialization checks.
|
||||
// we use the return control flow graph in strict property initialization checks.
|
||||
currentReturnTarget = isIIFE || node.kind === SyntaxKind.Constructor ? createBranchLabel() : undefined;
|
||||
currentBreakTarget = undefined;
|
||||
currentContinueTarget = undefined;
|
||||
activeLabels = undefined;
|
||||
hasExplicitReturn = false;
|
||||
flowNodeCreated = identity;
|
||||
bindChildren(node);
|
||||
// Reset all reachability check related flags on node (for incremental scenarios)
|
||||
node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
|
||||
@@ -579,6 +596,7 @@ namespace ts {
|
||||
currentReturnTarget = saveReturnTarget;
|
||||
activeLabels = saveActiveLabels;
|
||||
hasExplicitReturn = saveHasExplicitReturn;
|
||||
flowNodeCreated = saveFlowNodeCreated;
|
||||
}
|
||||
else if (containerFlags & ContainerFlags.IsInterface) {
|
||||
seenThisKeyword = false;
|
||||
@@ -753,7 +771,7 @@ namespace ts {
|
||||
|
||||
function isNarrowableReference(expr: Expression): boolean {
|
||||
return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword ||
|
||||
isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) ||
|
||||
(isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
|
||||
isElementAccessExpression(expr) && expr.argumentExpression &&
|
||||
(isStringLiteral(expr.argumentExpression) || isNumericLiteral(expr.argumentExpression)) &&
|
||||
isNarrowableReference(expr.expression);
|
||||
@@ -858,7 +876,7 @@ namespace ts {
|
||||
return antecedent;
|
||||
}
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return { flags, expression, antecedent };
|
||||
return flowNodeCreated({ flags, expression, antecedent });
|
||||
}
|
||||
|
||||
function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode {
|
||||
@@ -866,17 +884,17 @@ namespace ts {
|
||||
return antecedent;
|
||||
}
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return { flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent };
|
||||
return flowNodeCreated({ flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent });
|
||||
}
|
||||
|
||||
function createFlowAssignment(antecedent: FlowNode, node: Expression | VariableDeclaration | BindingElement): FlowNode {
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return { flags: FlowFlags.Assignment, antecedent, node };
|
||||
return flowNodeCreated({ flags: FlowFlags.Assignment, antecedent, node });
|
||||
}
|
||||
|
||||
function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode {
|
||||
setFlowNodeReferenced(antecedent);
|
||||
const res: FlowArrayMutation = { flags: FlowFlags.ArrayMutation, antecedent, node };
|
||||
const res: FlowArrayMutation = flowNodeCreated({ flags: FlowFlags.ArrayMutation, antecedent, node });
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -1080,8 +1098,16 @@ namespace ts {
|
||||
function bindTryStatement(node: TryStatement): void {
|
||||
const preFinallyLabel = createBranchLabel();
|
||||
const preTryFlow = currentFlow;
|
||||
// TODO: Every statement in try block is potentially an exit point!
|
||||
const tryPriors: FlowNode[] = [];
|
||||
const oldFlowNodeCreated = flowNodeCreated;
|
||||
// We hook the creation of all flow nodes within the `try` scope and store them so we can add _all_ of them
|
||||
// as possible antecedents of the start of the `catch` or `finally` blocks.
|
||||
// Don't bother intercepting the call if there's no finally or catch block that needs the information
|
||||
if (node.catchClause || node.finallyBlock) {
|
||||
flowNodeCreated = node => (tryPriors.push(node), node);
|
||||
}
|
||||
bind(node.tryBlock);
|
||||
flowNodeCreated = oldFlowNodeCreated;
|
||||
addAntecedent(preFinallyLabel, currentFlow);
|
||||
|
||||
const flowAfterTry = currentFlow;
|
||||
@@ -1089,12 +1115,36 @@ namespace ts {
|
||||
|
||||
if (node.catchClause) {
|
||||
currentFlow = preTryFlow;
|
||||
if (tryPriors.length) {
|
||||
const preCatchFlow = createBranchLabel();
|
||||
addAntecedent(preCatchFlow, currentFlow);
|
||||
for (const p of tryPriors) {
|
||||
addAntecedent(preCatchFlow, p);
|
||||
}
|
||||
currentFlow = finishFlowLabel(preCatchFlow);
|
||||
}
|
||||
|
||||
bind(node.catchClause);
|
||||
addAntecedent(preFinallyLabel, currentFlow);
|
||||
|
||||
flowAfterCatch = currentFlow;
|
||||
}
|
||||
if (node.finallyBlock) {
|
||||
// We add the nodes within the `try` block to the `finally`'s antecedents if there's no catch block
|
||||
// (If there is a `catch` block, it will have all these antecedents instead, and the `finally` will
|
||||
// have the end of the `try` block and the end of the `catch` block)
|
||||
let preFinallyPrior = preTryFlow;
|
||||
if (!node.catchClause) {
|
||||
if (tryPriors.length) {
|
||||
const preFinallyFlow = createBranchLabel();
|
||||
addAntecedent(preFinallyFlow, preTryFlow);
|
||||
for (const p of tryPriors) {
|
||||
addAntecedent(preFinallyFlow, p);
|
||||
}
|
||||
preFinallyPrior = finishFlowLabel(preFinallyFlow);
|
||||
}
|
||||
}
|
||||
|
||||
// in finally flow is combined from pre-try/flow from try/flow from catch
|
||||
// pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable
|
||||
|
||||
@@ -1123,7 +1173,7 @@ namespace ts {
|
||||
//
|
||||
// extra edges that we inject allows to control this behavior
|
||||
// if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
|
||||
const preFinallyFlow: PreFinallyFlow = { flags: FlowFlags.PreFinally, antecedent: preTryFlow, lock: {} };
|
||||
const preFinallyFlow: PreFinallyFlow = { flags: FlowFlags.PreFinally, antecedent: preFinallyPrior, lock: {} };
|
||||
addAntecedent(preFinallyLabel, preFinallyFlow);
|
||||
|
||||
currentFlow = finishFlowLabel(preFinallyLabel);
|
||||
@@ -1142,7 +1192,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
if (!(currentFlow.flags & FlowFlags.Unreachable)) {
|
||||
const afterFinallyFlow: AfterFinallyFlow = { flags: FlowFlags.AfterFinally, antecedent: currentFlow };
|
||||
const afterFinallyFlow: AfterFinallyFlow = flowNodeCreated({ flags: FlowFlags.AfterFinally, antecedent: currentFlow });
|
||||
preFinallyFlow.lock = afterFinallyFlow;
|
||||
currentFlow = afterFinallyFlow;
|
||||
}
|
||||
@@ -2462,8 +2512,13 @@ namespace ts {
|
||||
declareSymbol(symbolTable, containingClass.symbol, node, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true);
|
||||
break;
|
||||
case SyntaxKind.SourceFile:
|
||||
// this.foo assignment in a source file
|
||||
// Do not bind. It would be nice to support this someday though.
|
||||
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
|
||||
if ((thisContainer as SourceFile).commonJsModuleIndicator) {
|
||||
declareSymbol(thisContainer.symbol.exports!, thisContainer.symbol, node, SymbolFlags.Property | SymbolFlags.ExportValue, SymbolFlags.None);
|
||||
}
|
||||
else {
|
||||
declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -3051,32 +3106,24 @@ namespace ts {
|
||||
|
||||
function computeCallExpression(node: CallExpression, subtreeFlags: TransformFlags) {
|
||||
let transformFlags = subtreeFlags;
|
||||
const callee = skipOuterExpressions(node.expression);
|
||||
const expression = node.expression;
|
||||
|
||||
if (node.typeArguments) {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsRestOrSpread
|
||||
|| (expression.transformFlags & (TransformFlags.Super | TransformFlags.ContainsSuper))) {
|
||||
if (subtreeFlags & TransformFlags.ContainsRestOrSpread || isSuperOrSuperProperty(callee)) {
|
||||
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
|
||||
// node.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
// super property or element accesses could be inside lambdas, etc, and need a captured `this`,
|
||||
// while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor)
|
||||
if (expression.transformFlags & TransformFlags.ContainsSuper) {
|
||||
if (isSuperProperty(callee)) {
|
||||
transformFlags |= TransformFlags.ContainsLexicalThis;
|
||||
}
|
||||
}
|
||||
|
||||
if (expression.kind === SyntaxKind.ImportKeyword) {
|
||||
transformFlags |= TransformFlags.ContainsDynamicImport;
|
||||
|
||||
// A dynamic 'import()' call that contains a lexical 'this' will
|
||||
// require a captured 'this' when emitting down-level.
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
|
||||
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
|
||||
}
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3104,8 +3151,8 @@ namespace ts {
|
||||
|
||||
if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ObjectLiteralExpression) {
|
||||
// Destructuring object assignments with are ES2015 syntax
|
||||
// and possibly ESNext if they contain rest
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
|
||||
// and possibly ES2018 if they contain rest
|
||||
transformFlags |= TransformFlags.AssertES2018 | TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
|
||||
}
|
||||
else if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ArrayLiteralExpression) {
|
||||
// Destructuring assignments are ES2015 syntax.
|
||||
@@ -3141,15 +3188,15 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsTypeScriptClassSyntax;
|
||||
}
|
||||
|
||||
// parameters with object rest destructuring are ES Next syntax
|
||||
// parameters with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
|
||||
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
|
||||
if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) {
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments;
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3160,7 +3207,6 @@ namespace ts {
|
||||
let transformFlags = subtreeFlags;
|
||||
const expression = node.expression;
|
||||
const expressionKind = expression.kind;
|
||||
const expressionTransformFlags = expression.transformFlags;
|
||||
|
||||
// If the node is synthesized, it means the emitter put the parentheses there,
|
||||
// not the user. If we didn't want them, the emitter would not have put them
|
||||
@@ -3170,12 +3216,6 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
// If the expression of a ParenthesizedExpression is a destructuring assignment,
|
||||
// then the ParenthesizedExpression is a destructuring assignment.
|
||||
if (expressionTransformFlags & TransformFlags.DestructuringAssignment) {
|
||||
transformFlags |= TransformFlags.DestructuringAssignment;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.OuterExpressionExcludes;
|
||||
}
|
||||
@@ -3199,12 +3239,6 @@ namespace ts {
|
||||
|| node.typeParameters) {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
|
||||
// A computed property name containing `this` might need to be rewritten,
|
||||
// so propagate the ContainsLexicalThis flag upward.
|
||||
transformFlags |= TransformFlags.ContainsLexicalThis;
|
||||
}
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3222,12 +3256,6 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
|
||||
// A computed property name containing `this` might need to be rewritten,
|
||||
// so propagate the ContainsLexicalThis flag upward.
|
||||
transformFlags |= TransformFlags.ContainsLexicalThis;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.ClassExcludes;
|
||||
}
|
||||
@@ -3259,7 +3287,7 @@ namespace ts {
|
||||
let transformFlags = subtreeFlags;
|
||||
|
||||
if (!node.variableDeclaration) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2019;
|
||||
}
|
||||
else if (isBindingPattern(node.variableDeclaration.name)) {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
@@ -3293,9 +3321,9 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
// function declarations with object rest destructuring are ES Next syntax
|
||||
// function declarations with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3317,14 +3345,14 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
// function declarations with object rest destructuring are ES Next syntax
|
||||
// function declarations with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
// An async method declaration is ES2017 syntax.
|
||||
if (hasModifier(node, ModifierFlags.Async)) {
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertESNext : TransformFlags.AssertES2017;
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertES2018 : TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
if (node.asteriskToken) {
|
||||
@@ -3332,7 +3360,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
|
||||
return propagatePropertyNameFlags(node.name, transformFlags & ~TransformFlags.MethodOrAccessorExcludes);
|
||||
}
|
||||
|
||||
function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) {
|
||||
@@ -3348,13 +3376,13 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
// function declarations with object rest destructuring are ES Next syntax
|
||||
// function declarations with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
|
||||
return propagatePropertyNameFlags(node.name, transformFlags & ~TransformFlags.MethodOrAccessorExcludes);
|
||||
}
|
||||
|
||||
function computePropertyDeclaration(node: PropertyDeclaration, subtreeFlags: TransformFlags) {
|
||||
@@ -3368,7 +3396,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.NodeExcludes;
|
||||
return propagatePropertyNameFlags(node.name, transformFlags & ~TransformFlags.PropertyExcludes);
|
||||
}
|
||||
|
||||
function computeFunctionDeclaration(node: FunctionDeclaration, subtreeFlags: TransformFlags) {
|
||||
@@ -3394,25 +3422,18 @@ namespace ts {
|
||||
|
||||
// An async function declaration is ES2017 syntax.
|
||||
if (modifierFlags & ModifierFlags.Async) {
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertESNext : TransformFlags.AssertES2017;
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertES2018 : TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// function declarations with object rest destructuring are ES Next syntax
|
||||
// function declarations with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
// If a FunctionDeclaration's subtree has marked the container as needing to capture the
|
||||
// lexical this, or the function contains parameters with initializers, then this node is
|
||||
// ES6 syntax.
|
||||
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
// If a FunctionDeclaration is generator function and is the body of a
|
||||
// transformed async function, then this node can be transformed to a
|
||||
// down-level generator.
|
||||
// Currently we do not support transforming any other generator fucntions
|
||||
// Currently we do not support transforming any other generator functions
|
||||
// down level.
|
||||
if (node.asteriskToken) {
|
||||
transformFlags |= TransformFlags.AssertGenerator;
|
||||
@@ -3436,20 +3457,12 @@ namespace ts {
|
||||
|
||||
// An async function expression is ES2017 syntax.
|
||||
if (hasModifier(node, ModifierFlags.Async)) {
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertESNext : TransformFlags.AssertES2017;
|
||||
transformFlags |= node.asteriskToken ? TransformFlags.AssertES2018 : TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// function expressions with object rest destructuring are ES Next syntax
|
||||
// function expressions with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
|
||||
// If a FunctionExpression's subtree has marked the container as needing to capture the
|
||||
// lexical this, or the function contains parameters with initializers, then this node is
|
||||
// ES6 syntax.
|
||||
if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
// If a FunctionExpression is generator function and is the body of a
|
||||
@@ -3480,14 +3493,9 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// arrow functions with object rest destructuring are ES Next syntax
|
||||
// arrow functions with object rest destructuring are ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
|
||||
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3499,11 +3507,10 @@ namespace ts {
|
||||
|
||||
// If a PropertyAccessExpression starts with a super keyword, then it is
|
||||
// ES6 syntax, and requires a lexical `this` binding.
|
||||
if (transformFlags & TransformFlags.Super) {
|
||||
transformFlags ^= TransformFlags.Super;
|
||||
if (node.expression.kind === SyntaxKind.SuperKeyword) {
|
||||
// super inside of an async function requires hoisting the super access (ES2017).
|
||||
// same for super inside of an async generator, which is ESNext.
|
||||
transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext;
|
||||
// same for super inside of an async generator, which is ES2018.
|
||||
transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3512,16 +3519,13 @@ namespace ts {
|
||||
|
||||
function computeElementAccess(node: ElementAccessExpression, subtreeFlags: TransformFlags) {
|
||||
let transformFlags = subtreeFlags;
|
||||
const expression = node.expression;
|
||||
const expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing
|
||||
|
||||
// If an ElementAccessExpression starts with a super keyword, then it is
|
||||
// ES6 syntax, and requires a lexical `this` binding.
|
||||
if (expressionFlags & TransformFlags.Super) {
|
||||
transformFlags &= ~TransformFlags.Super;
|
||||
if (node.expression.kind === SyntaxKind.SuperKeyword) {
|
||||
// super inside of an async function requires hoisting the super access (ES2017).
|
||||
// same for super inside of an async generator, which is ESNext.
|
||||
transformFlags |= TransformFlags.ContainsSuper | TransformFlags.ContainsES2017 | TransformFlags.ContainsESNext;
|
||||
// same for super inside of an async generator, which is ES2018.
|
||||
transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018;
|
||||
}
|
||||
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
@@ -3530,11 +3534,11 @@ namespace ts {
|
||||
|
||||
function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) {
|
||||
let transformFlags = subtreeFlags;
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; // TODO(rbuckton): Why are these set unconditionally?
|
||||
|
||||
// A VariableDeclaration containing ObjectRest is ESNext syntax
|
||||
// A VariableDeclaration containing ObjectRest is ES2018 syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
// Type annotations are TypeScript syntax.
|
||||
@@ -3592,15 +3596,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function computeExpressionStatement(node: ExpressionStatement, subtreeFlags: TransformFlags) {
|
||||
let transformFlags = subtreeFlags;
|
||||
|
||||
// If the expression of an expression statement is a destructuring assignment,
|
||||
// then we treat the statement as ES6 so that we can indicate that we do not
|
||||
// need to hold on to the right-hand side.
|
||||
if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
const transformFlags = subtreeFlags;
|
||||
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
|
||||
return transformFlags & ~TransformFlags.NodeExcludes;
|
||||
}
|
||||
@@ -3641,8 +3637,8 @@ namespace ts {
|
||||
switch (kind) {
|
||||
case SyntaxKind.AsyncKeyword:
|
||||
case SyntaxKind.AwaitExpression:
|
||||
// async/await is ES2017 syntax, but may be ESNext syntax (for async generators)
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2017;
|
||||
// async/await is ES2017 syntax, but may be ES2018 syntax (for async generators)
|
||||
transformFlags |= TransformFlags.AssertES2018 | TransformFlags.AssertES2017;
|
||||
break;
|
||||
|
||||
case SyntaxKind.TypeAssertionExpression:
|
||||
@@ -3714,7 +3710,7 @@ namespace ts {
|
||||
case SyntaxKind.ForOfStatement:
|
||||
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
|
||||
if ((<ForOfStatement>node).awaitModifier) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
break;
|
||||
@@ -3722,7 +3718,7 @@ namespace ts {
|
||||
case SyntaxKind.YieldExpression:
|
||||
// This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
|
||||
// generator).
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.ContainsYield;
|
||||
transformFlags |= TransformFlags.AssertES2018 | TransformFlags.AssertES2015 | TransformFlags.ContainsYield;
|
||||
break;
|
||||
|
||||
case SyntaxKind.AnyKeyword:
|
||||
@@ -3773,17 +3769,6 @@ namespace ts {
|
||||
// This is so that they can flow through PropertyName transforms unaffected.
|
||||
// Instead, we mark the container as ES6, so that it can properly handle the transform.
|
||||
transformFlags |= TransformFlags.ContainsComputedPropertyName;
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
|
||||
// A computed method name like `[this.getName()](x: string) { ... }` needs to
|
||||
// distinguish itself from the normal case of a method body containing `this`:
|
||||
// `this` inside a method doesn't need to be rewritten (the method provides `this`),
|
||||
// whereas `this` inside a computed name *might* need to be rewritten if the class/object
|
||||
// is inside an arrow function:
|
||||
// `_this = this; () => class K { [_this.getName()]() { ... } }`
|
||||
// To make this distinction, use ContainsLexicalThisInComputedPropertyName
|
||||
// instead of ContainsLexicalThis for computed property names
|
||||
transformFlags |= TransformFlags.ContainsLexicalThisInComputedPropertyName;
|
||||
}
|
||||
break;
|
||||
|
||||
case SyntaxKind.SpreadElement:
|
||||
@@ -3791,12 +3776,12 @@ namespace ts {
|
||||
break;
|
||||
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread;
|
||||
transformFlags |= TransformFlags.AssertES2018 | TransformFlags.ContainsObjectRestOrSpread;
|
||||
break;
|
||||
|
||||
case SyntaxKind.SuperKeyword:
|
||||
// This node is ES6 syntax.
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.Super;
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
excludeFlags = TransformFlags.OuterExpressionExcludes; // must be set to persist `Super`
|
||||
break;
|
||||
|
||||
@@ -3808,7 +3793,7 @@ namespace ts {
|
||||
case SyntaxKind.ObjectBindingPattern:
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
if (subtreeFlags & TransformFlags.ContainsRestOrSpread) {
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRestOrSpread;
|
||||
transformFlags |= TransformFlags.AssertES2018 | TransformFlags.ContainsObjectRestOrSpread;
|
||||
}
|
||||
excludeFlags = TransformFlags.BindingPatternExcludes;
|
||||
break;
|
||||
@@ -3838,29 +3823,16 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) {
|
||||
// A computed property name containing `this` might need to be rewritten,
|
||||
// so propagate the ContainsLexicalThis flag upward.
|
||||
transformFlags |= TransformFlags.ContainsLexicalThis;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
// If an ObjectLiteralExpression contains a spread element, then it
|
||||
// is an ES next node.
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
// is an ES2018 node.
|
||||
transformFlags |= TransformFlags.AssertES2018;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case SyntaxKind.ArrayLiteralExpression:
|
||||
case SyntaxKind.NewExpression:
|
||||
excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes;
|
||||
if (subtreeFlags & TransformFlags.ContainsRestOrSpread) {
|
||||
// If the this node contains a SpreadExpression, then it is an ES6
|
||||
// node.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case SyntaxKind.DoStatement:
|
||||
@@ -3875,15 +3847,11 @@ namespace ts {
|
||||
break;
|
||||
|
||||
case SyntaxKind.SourceFile:
|
||||
if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) {
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case SyntaxKind.ReturnStatement:
|
||||
// Return statements may require an `await` in ESNext.
|
||||
transformFlags |= TransformFlags.ContainsHoistedDeclarationOrCompletion | TransformFlags.AssertESNext;
|
||||
// Return statements may require an `await` in ES2018.
|
||||
transformFlags |= TransformFlags.ContainsHoistedDeclarationOrCompletion | TransformFlags.AssertES2018;
|
||||
break;
|
||||
|
||||
case SyntaxKind.ContinueStatement:
|
||||
@@ -3896,6 +3864,10 @@ namespace ts {
|
||||
return transformFlags & ~excludeFlags;
|
||||
}
|
||||
|
||||
function propagatePropertyNameFlags(node: PropertyName, transformFlags: TransformFlags) {
|
||||
return transformFlags | (node.transformFlags & TransformFlags.PropertyNamePropagatingFlags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the transform flags to exclude when unioning the transform flags of a subtree.
|
||||
*
|
||||
|
||||
+536
-78
@@ -1,5 +1,80 @@
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation {
|
||||
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
|
||||
reportsUnnecessary?: {};
|
||||
source?: string;
|
||||
relatedInformation?: ReusableDiagnosticRelatedInformation[];
|
||||
}
|
||||
|
||||
export interface ReusableDiagnosticRelatedInformation {
|
||||
category: DiagnosticCategory;
|
||||
code: number;
|
||||
file: Path | undefined;
|
||||
start: number | undefined;
|
||||
length: number | undefined;
|
||||
messageText: string | ReusableDiagnosticMessageChain;
|
||||
}
|
||||
|
||||
export interface ReusableDiagnosticMessageChain {
|
||||
messageText: string;
|
||||
category: DiagnosticCategory;
|
||||
code: number;
|
||||
next?: ReusableDiagnosticMessageChain;
|
||||
}
|
||||
|
||||
export interface ReusableBuilderProgramState extends ReusableBuilderState {
|
||||
/**
|
||||
* Cache of semantic diagnostics for files with their Path being the key
|
||||
*/
|
||||
semanticDiagnosticsPerFile?: ReadonlyMap<ReadonlyArray<ReusableDiagnostic> | ReadonlyArray<Diagnostic>> | undefined;
|
||||
/**
|
||||
* The map has key by source file's path that has been changed
|
||||
*/
|
||||
changedFilesSet?: ReadonlyMap<true>;
|
||||
/**
|
||||
* Set of affected files being iterated
|
||||
*/
|
||||
affectedFiles?: ReadonlyArray<SourceFile> | undefined;
|
||||
/**
|
||||
* Current changed file for iterating over affected files
|
||||
*/
|
||||
currentChangedFilePath?: Path | undefined;
|
||||
/**
|
||||
* Map of file signatures, with key being file path, calculated while getting current changed file's affected files
|
||||
* These will be committed whenever the iteration through affected files of current changed file is complete
|
||||
*/
|
||||
currentAffectedFilesSignatures?: ReadonlyMap<string> | undefined;
|
||||
/**
|
||||
* Newly computed visible to outside referencedSet
|
||||
*/
|
||||
currentAffectedFilesExportedModulesMap?: Readonly<BuilderState.ComputingExportedModulesMap> | undefined;
|
||||
/**
|
||||
* True if the semantic diagnostics were copied from the old state
|
||||
*/
|
||||
semanticDiagnosticsFromOldState?: Map<true>;
|
||||
/**
|
||||
* program corresponding to this state
|
||||
*/
|
||||
program?: Program | undefined;
|
||||
/**
|
||||
* compilerOptions for the program
|
||||
*/
|
||||
compilerOptions: CompilerOptions;
|
||||
/**
|
||||
* Files pending to be emitted
|
||||
*/
|
||||
affectedFilesPendingEmit?: ReadonlyArray<Path> | undefined;
|
||||
/**
|
||||
* Current index to retrieve pending affected file
|
||||
*/
|
||||
affectedFilesPendingEmitIndex?: number | undefined;
|
||||
/*
|
||||
* true if semantic diagnostics are ReusableDiagnostic instead of Diagnostic
|
||||
*/
|
||||
hasReusableDiagnostic?: true;
|
||||
}
|
||||
|
||||
/**
|
||||
* State to store the changed files, affected files and cache semantic diagnostics
|
||||
*/
|
||||
@@ -27,7 +102,7 @@ namespace ts {
|
||||
currentChangedFilePath: Path | undefined;
|
||||
/**
|
||||
* Map of file signatures, with key being file path, calculated while getting current changed file's affected files
|
||||
* These will be commited whenever the iteration through affected files of current changed file is complete
|
||||
* These will be committed whenever the iteration through affected files of current changed file is complete
|
||||
*/
|
||||
currentAffectedFilesSignatures: Map<string> | undefined;
|
||||
/**
|
||||
@@ -49,7 +124,31 @@ namespace ts {
|
||||
/**
|
||||
* program corresponding to this state
|
||||
*/
|
||||
program: Program;
|
||||
program: Program | undefined;
|
||||
/**
|
||||
* compilerOptions for the program
|
||||
*/
|
||||
compilerOptions: CompilerOptions;
|
||||
/**
|
||||
* Files pending to be emitted
|
||||
*/
|
||||
affectedFilesPendingEmit: ReadonlyArray<Path> | undefined;
|
||||
/**
|
||||
* Current index to retrieve pending affected file
|
||||
*/
|
||||
affectedFilesPendingEmitIndex: number | undefined;
|
||||
/**
|
||||
* true if build info is emitted
|
||||
*/
|
||||
emittedBuildInfo?: boolean;
|
||||
/**
|
||||
* Already seen affected files
|
||||
*/
|
||||
seenEmittedFiles: Map<true> | undefined;
|
||||
/**
|
||||
* true if program has been emitted
|
||||
*/
|
||||
programEmitComplete?: true;
|
||||
}
|
||||
|
||||
function hasSameKeys<T, U>(map1: ReadonlyMap<T> | undefined, map2: ReadonlyMap<U> | undefined): boolean {
|
||||
@@ -60,30 +159,41 @@ namespace ts {
|
||||
/**
|
||||
* Create the state so that we can iterate on changedFiles/affected files
|
||||
*/
|
||||
function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly<BuilderProgramState>): BuilderProgramState {
|
||||
function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly<ReusableBuilderProgramState>): BuilderProgramState {
|
||||
const state = BuilderState.create(newProgram, getCanonicalFileName, oldState) as BuilderProgramState;
|
||||
state.program = newProgram;
|
||||
const compilerOptions = newProgram.getCompilerOptions();
|
||||
if (!compilerOptions.outFile && !compilerOptions.out) {
|
||||
state.compilerOptions = compilerOptions;
|
||||
// With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
|
||||
// With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors
|
||||
if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) {
|
||||
state.semanticDiagnosticsPerFile = createMap<ReadonlyArray<Diagnostic>>();
|
||||
}
|
||||
state.changedFilesSet = createMap<true>();
|
||||
|
||||
const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
|
||||
const oldCompilerOptions = useOldState ? oldState!.program.getCompilerOptions() : undefined;
|
||||
const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined;
|
||||
const canCopySemanticDiagnostics = useOldState && oldState!.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
|
||||
!compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions!);
|
||||
if (useOldState) {
|
||||
// Verify the sanity of old state
|
||||
if (!oldState!.currentChangedFilePath) {
|
||||
Debug.assert(!oldState!.affectedFiles && (!oldState!.currentAffectedFilesSignatures || !oldState!.currentAffectedFilesSignatures!.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
|
||||
const affectedSignatures = oldState!.currentAffectedFilesSignatures;
|
||||
Debug.assert(!oldState!.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
|
||||
}
|
||||
const changedFilesSet = oldState!.changedFilesSet;
|
||||
if (canCopySemanticDiagnostics) {
|
||||
Debug.assert(!forEachKey(oldState!.changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
|
||||
Debug.assert(!changedFilesSet || !forEachKey(changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
|
||||
}
|
||||
|
||||
// Copy old state's changed files set
|
||||
copyEntries(oldState!.changedFilesSet, state.changedFilesSet);
|
||||
if (changedFilesSet) {
|
||||
copyEntries(changedFilesSet, state.changedFilesSet);
|
||||
}
|
||||
if (!compilerOptions.outFile && !compilerOptions.out && oldState!.affectedFilesPendingEmit) {
|
||||
state.affectedFilesPendingEmit = oldState!.affectedFilesPendingEmit;
|
||||
state.affectedFilesPendingEmitIndex = oldState!.affectedFilesPendingEmitIndex;
|
||||
}
|
||||
}
|
||||
|
||||
// Update changed files and copy semantic diagnostics if we can
|
||||
@@ -109,7 +219,7 @@ namespace ts {
|
||||
state.changedFilesSet.set(sourceFilePath, true);
|
||||
}
|
||||
else if (canCopySemanticDiagnostics) {
|
||||
const sourceFile = state.program.getSourceFileByPath(sourceFilePath as Path)!;
|
||||
const sourceFile = newProgram.getSourceFileByPath(sourceFilePath as Path)!;
|
||||
|
||||
if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; }
|
||||
if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { return; }
|
||||
@@ -117,7 +227,7 @@ namespace ts {
|
||||
// Unchanged file copy diagnostics
|
||||
const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath);
|
||||
if (diagnostics) {
|
||||
state.semanticDiagnosticsPerFile!.set(sourceFilePath, diagnostics);
|
||||
state.semanticDiagnosticsPerFile!.set(sourceFilePath, oldState!.hasReusableDiagnostic ? convertToDiagnostics(diagnostics as ReadonlyArray<ReusableDiagnostic>, newProgram) : diagnostics as ReadonlyArray<Diagnostic>);
|
||||
if (!state.semanticDiagnosticsFromOldState) {
|
||||
state.semanticDiagnosticsFromOldState = createMap<true>();
|
||||
}
|
||||
@@ -126,9 +236,88 @@ namespace ts {
|
||||
}
|
||||
});
|
||||
|
||||
if (oldCompilerOptions &&
|
||||
(oldCompilerOptions.outDir !== compilerOptions.outDir ||
|
||||
oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
|
||||
(oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
|
||||
// Add all files to affectedFilesPendingEmit since emit changed
|
||||
state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(f => f.path));
|
||||
if (state.affectedFilesPendingEmitIndex === undefined) {
|
||||
state.affectedFilesPendingEmitIndex = 0;
|
||||
}
|
||||
Debug.assert(state.seenAffectedFiles === undefined);
|
||||
state.seenAffectedFiles = createMap<true>();
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
function convertToDiagnostics(diagnostics: ReadonlyArray<ReusableDiagnostic>, newProgram: Program): ReadonlyArray<Diagnostic> {
|
||||
if (!diagnostics.length) return emptyArray;
|
||||
return diagnostics.map(diagnostic => {
|
||||
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
|
||||
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
|
||||
result.source = diagnostic.source;
|
||||
const { relatedInformation } = diagnostic;
|
||||
result.relatedInformation = relatedInformation ?
|
||||
relatedInformation.length ?
|
||||
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram)) :
|
||||
emptyArray :
|
||||
undefined;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function convertToDiagnosticRelatedInformation(diagnostic: ReusableDiagnosticRelatedInformation, newProgram: Program): DiagnosticRelatedInformation {
|
||||
const { file, messageText } = diagnostic;
|
||||
return {
|
||||
...diagnostic,
|
||||
file: file && newProgram.getSourceFileByPath(file),
|
||||
messageText: messageText === undefined || isString(messageText) ?
|
||||
messageText :
|
||||
convertToDiagnosticMessageChain(messageText, newProgram)
|
||||
};
|
||||
}
|
||||
|
||||
function convertToDiagnosticMessageChain(diagnostic: ReusableDiagnosticMessageChain, newProgram: Program): DiagnosticMessageChain {
|
||||
return {
|
||||
...diagnostic,
|
||||
next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases program and other related not needed properties
|
||||
*/
|
||||
function releaseCache(state: BuilderProgramState) {
|
||||
BuilderState.releaseCache(state);
|
||||
state.program = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a clone of the state
|
||||
*/
|
||||
function cloneBuilderProgramState(state: Readonly<BuilderProgramState>): BuilderProgramState {
|
||||
const newState = BuilderState.clone(state) as BuilderProgramState;
|
||||
newState.semanticDiagnosticsPerFile = cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
|
||||
newState.changedFilesSet = cloneMap(state.changedFilesSet);
|
||||
newState.affectedFiles = state.affectedFiles;
|
||||
newState.affectedFilesIndex = state.affectedFilesIndex;
|
||||
newState.currentChangedFilePath = state.currentChangedFilePath;
|
||||
newState.currentAffectedFilesSignatures = cloneMapOrUndefined(state.currentAffectedFilesSignatures);
|
||||
newState.currentAffectedFilesExportedModulesMap = cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
|
||||
newState.seenAffectedFiles = cloneMapOrUndefined(state.seenAffectedFiles);
|
||||
newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
|
||||
newState.semanticDiagnosticsFromOldState = cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
|
||||
newState.program = state.program;
|
||||
newState.compilerOptions = state.compilerOptions;
|
||||
newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit;
|
||||
newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
|
||||
newState.seenEmittedFiles = cloneMapOrUndefined(state.seenEmittedFiles);
|
||||
newState.programEmitComplete = state.programEmitComplete;
|
||||
return newState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that source file is ok to be used in calls that arent handled by next
|
||||
*/
|
||||
@@ -179,10 +368,11 @@ namespace ts {
|
||||
|
||||
// With --out or --outFile all outputs go into single file
|
||||
// so operations are performed directly on program, return program
|
||||
const compilerOptions = state.program.getCompilerOptions();
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const compilerOptions = program.getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
return state.program;
|
||||
return program;
|
||||
}
|
||||
|
||||
// Get next batch of affected files
|
||||
@@ -190,13 +380,34 @@ namespace ts {
|
||||
if (state.exportedModulesMap) {
|
||||
state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || createMap<BuilderState.ReferencedSet | false>();
|
||||
}
|
||||
state.affectedFiles = BuilderState.getFilesAffectedBy(state, state.program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
|
||||
state.affectedFiles = BuilderState.getFilesAffectedBy(state, program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
|
||||
state.currentChangedFilePath = nextKey.value as Path;
|
||||
state.affectedFilesIndex = 0;
|
||||
state.seenAffectedFiles = state.seenAffectedFiles || createMap<true>();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
|
||||
*/
|
||||
function getNextAffectedFilePendingEmit(state: BuilderProgramState): SourceFile | undefined {
|
||||
const { affectedFilesPendingEmit } = state;
|
||||
if (affectedFilesPendingEmit) {
|
||||
const seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = createMap());
|
||||
for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) {
|
||||
const affectedFile = Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
|
||||
if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) {
|
||||
// emit this file
|
||||
state.affectedFilesPendingEmitIndex = i;
|
||||
return affectedFile;
|
||||
}
|
||||
}
|
||||
state.affectedFilesPendingEmit = undefined;
|
||||
state.affectedFilesPendingEmitIndex = undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file
|
||||
*/
|
||||
@@ -209,9 +420,10 @@ namespace ts {
|
||||
// Clean lib file diagnostics if its all files excluding default files to emit
|
||||
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) {
|
||||
state.cleanedDiagnosticsOfLibFiles = true;
|
||||
const options = state.program.getCompilerOptions();
|
||||
if (forEach(state.program.getSourceFiles(), f =>
|
||||
state.program.isSourceFileDefaultLibrary(f) &&
|
||||
const program = Debug.assertDefined(state.program);
|
||||
const options = program.getCompilerOptions();
|
||||
if (forEach(program.getSourceFiles(), f =>
|
||||
program.isSourceFileDefaultLibrary(f) &&
|
||||
!skipTypeChecking(f, options) &&
|
||||
removeSemanticDiagnosticsOf(state, f.path)
|
||||
)) {
|
||||
@@ -281,10 +493,19 @@ namespace ts {
|
||||
}
|
||||
|
||||
// If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
|
||||
return !!forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
if (forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) =>
|
||||
!state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it
|
||||
exportedModules.has(filePath) &&
|
||||
removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile)
|
||||
)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Remove diagnostics of files that import this file (without going to exports of referencing files)
|
||||
return !!forEachEntry(state.referencedMap!, (referencesInFile, referencingFilePath) =>
|
||||
referencesInFile.has(filePath) &&
|
||||
!seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
|
||||
removeSemanticDiagnosticsOf(state, referencingFilePath as Path) // Dont add to seen since this is not yet done with the export removal
|
||||
);
|
||||
}
|
||||
|
||||
@@ -305,21 +526,30 @@ namespace ts {
|
||||
* This is called after completing operation on the next affected file.
|
||||
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
|
||||
*/
|
||||
function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program) {
|
||||
if (affected === state.program) {
|
||||
function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program, isPendingEmit?: boolean, isBuildInfoEmit?: boolean) {
|
||||
if (isBuildInfoEmit) {
|
||||
state.emittedBuildInfo = true;
|
||||
}
|
||||
else if (affected === state.program) {
|
||||
state.changedFilesSet.clear();
|
||||
state.programEmitComplete = true;
|
||||
}
|
||||
else {
|
||||
state.seenAffectedFiles!.set((affected as SourceFile).path, true);
|
||||
state.affectedFilesIndex!++;
|
||||
if (isPendingEmit) {
|
||||
state.affectedFilesPendingEmitIndex!++;
|
||||
}
|
||||
else {
|
||||
state.affectedFilesIndex!++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the result with affected file
|
||||
*/
|
||||
function toAffectedFileResult<T>(state: BuilderProgramState, result: T, affected: SourceFile | Program): AffectedFileResult<T> {
|
||||
doneWithAffectedFile(state, affected);
|
||||
function toAffectedFileResult<T>(state: BuilderProgramState, result: T, affected: SourceFile | Program, isPendingEmit?: boolean, isBuildInfoEmit?: boolean): AffectedFileResult<T> {
|
||||
doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
|
||||
return { result, affected };
|
||||
}
|
||||
|
||||
@@ -329,18 +559,116 @@ namespace ts {
|
||||
*/
|
||||
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<Diagnostic> {
|
||||
const path = sourceFile.path;
|
||||
const cachedDiagnostics = state.semanticDiagnosticsPerFile!.get(path);
|
||||
// Report the semantic diagnostics from the cache if we already have those diagnostics present
|
||||
if (cachedDiagnostics) {
|
||||
return cachedDiagnostics;
|
||||
if (state.semanticDiagnosticsPerFile) {
|
||||
const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
|
||||
// Report the semantic diagnostics from the cache if we already have those diagnostics present
|
||||
if (cachedDiagnostics) {
|
||||
return cachedDiagnostics;
|
||||
}
|
||||
}
|
||||
|
||||
// Diagnostics werent cached, get them from program, and cache the result
|
||||
const diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
state.semanticDiagnosticsPerFile!.set(path, diagnostics);
|
||||
const diagnostics = Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
if (state.semanticDiagnosticsPerFile) {
|
||||
state.semanticDiagnosticsPerFile.set(path, diagnostics);
|
||||
}
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
export type ProgramBuildInfoDiagnostic = string | [string, ReadonlyArray<ReusableDiagnostic>];
|
||||
export interface ProgramBuildInfo {
|
||||
fileInfos: MapLike<BuilderState.FileInfo>;
|
||||
options: CompilerOptions;
|
||||
referencedMap?: MapLike<string[]>;
|
||||
exportedModulesMap?: MapLike<string[]>;
|
||||
semanticDiagnosticsPerFile?: ProgramBuildInfoDiagnostic[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the program information to be emitted in buildInfo so that we can use it to create new program
|
||||
*/
|
||||
function getProgramBuildInfo(state: Readonly<ReusableBuilderProgramState>): ProgramBuildInfo | undefined {
|
||||
if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined;
|
||||
const fileInfos: MapLike<BuilderState.FileInfo> = {};
|
||||
state.fileInfos.forEach((value, key) => {
|
||||
const signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
|
||||
fileInfos[key] = signature === undefined ? value : { version: value.version, signature };
|
||||
});
|
||||
|
||||
const result: ProgramBuildInfo = { fileInfos, options: state.compilerOptions };
|
||||
if (state.referencedMap) {
|
||||
const referencedMap: MapLike<string[]> = {};
|
||||
state.referencedMap.forEach((value, key) => {
|
||||
referencedMap[key] = arrayFrom(value.keys());
|
||||
});
|
||||
result.referencedMap = referencedMap;
|
||||
}
|
||||
|
||||
if (state.exportedModulesMap) {
|
||||
const exportedModulesMap: MapLike<string[]> = {};
|
||||
state.exportedModulesMap.forEach((value, key) => {
|
||||
const newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
|
||||
// Not in temporary cache, use existing value
|
||||
if (newValue === undefined) exportedModulesMap[key] = arrayFrom(value.keys());
|
||||
// Value in cache and has updated value map, use that
|
||||
else if (newValue) exportedModulesMap[key] = arrayFrom(newValue.keys());
|
||||
});
|
||||
result.exportedModulesMap = exportedModulesMap;
|
||||
}
|
||||
|
||||
if (state.semanticDiagnosticsPerFile) {
|
||||
const semanticDiagnosticsPerFile: ProgramBuildInfoDiagnostic[] = [];
|
||||
// Currently not recording actual errors since those mean no emit for tsc --build
|
||||
state.semanticDiagnosticsPerFile.forEach((value, key) => semanticDiagnosticsPerFile.push(
|
||||
value.length ?
|
||||
[
|
||||
key,
|
||||
state.hasReusableDiagnostic ?
|
||||
value as ReadonlyArray<ReusableDiagnostic> :
|
||||
convertToReusableDiagnostics(value as ReadonlyArray<Diagnostic>)
|
||||
] :
|
||||
key
|
||||
));
|
||||
result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function convertToReusableDiagnostics(diagnostics: ReadonlyArray<Diagnostic>): ReadonlyArray<ReusableDiagnostic> {
|
||||
Debug.assert(!!diagnostics.length);
|
||||
return diagnostics.map(diagnostic => {
|
||||
const result: ReusableDiagnostic = convertToReusableDiagnosticRelatedInformation(diagnostic);
|
||||
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
|
||||
result.source = diagnostic.source;
|
||||
const { relatedInformation } = diagnostic;
|
||||
result.relatedInformation = relatedInformation ?
|
||||
relatedInformation.length ?
|
||||
relatedInformation.map(r => convertToReusableDiagnosticRelatedInformation(r)) :
|
||||
emptyArray :
|
||||
undefined;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function convertToReusableDiagnosticRelatedInformation(diagnostic: DiagnosticRelatedInformation): ReusableDiagnosticRelatedInformation {
|
||||
const { file, messageText } = diagnostic;
|
||||
return {
|
||||
...diagnostic,
|
||||
file: file && file.path,
|
||||
messageText: messageText === undefined || isString(messageText) ?
|
||||
messageText :
|
||||
convertToReusableDiagnosticMessageChain(messageText)
|
||||
};
|
||||
}
|
||||
|
||||
function convertToReusableDiagnosticMessageChain(diagnostic: DiagnosticMessageChain): ReusableDiagnosticMessageChain {
|
||||
return {
|
||||
...diagnostic,
|
||||
next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next)
|
||||
};
|
||||
}
|
||||
|
||||
export enum BuilderProgramKind {
|
||||
SemanticDiagnosticsBuilderProgram,
|
||||
EmitAndSemanticDiagnosticsBuilderProgram
|
||||
@@ -370,7 +698,7 @@ namespace ts {
|
||||
rootNames: newProgramOrRootNames,
|
||||
options: hostOrOptions as CompilerOptions,
|
||||
host: oldProgramOrHost as CompilerHost,
|
||||
oldProgram: oldProgram && oldProgram.getProgram(),
|
||||
oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
|
||||
configFileParsingDiagnostics,
|
||||
projectReferences
|
||||
});
|
||||
@@ -403,28 +731,32 @@ namespace ts {
|
||||
/**
|
||||
* Computing hash to for signature verification
|
||||
*/
|
||||
const computeHash = host.createHash || identity;
|
||||
const state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
|
||||
const computeHash = host.createHash || generateDjb2Hash;
|
||||
let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
|
||||
let backupState: BuilderProgramState | undefined;
|
||||
newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state);
|
||||
|
||||
// To ensure that we arent storing any references to old program or new program without state
|
||||
newProgram = undefined!; // TODO: GH#18217
|
||||
oldProgram = undefined;
|
||||
oldState = undefined;
|
||||
|
||||
const result: BuilderProgram = {
|
||||
getState: () => state,
|
||||
getProgram: () => state.program,
|
||||
getCompilerOptions: () => state.program.getCompilerOptions(),
|
||||
getSourceFile: fileName => state.program.getSourceFile(fileName),
|
||||
getSourceFiles: () => state.program.getSourceFiles(),
|
||||
getOptionsDiagnostics: cancellationToken => state.program.getOptionsDiagnostics(cancellationToken),
|
||||
getGlobalDiagnostics: cancellationToken => state.program.getGlobalDiagnostics(cancellationToken),
|
||||
getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(),
|
||||
getSyntacticDiagnostics: (sourceFile, cancellationToken) => state.program.getSyntacticDiagnostics(sourceFile, cancellationToken),
|
||||
getSemanticDiagnostics,
|
||||
emit,
|
||||
getAllDependencies: sourceFile => BuilderState.getAllDependencies(state, state.program, sourceFile),
|
||||
getCurrentDirectory: () => state.program.getCurrentDirectory()
|
||||
const result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
|
||||
result.getState = () => state;
|
||||
result.backupState = () => {
|
||||
Debug.assert(backupState === undefined);
|
||||
backupState = cloneBuilderProgramState(state);
|
||||
};
|
||||
result.restoreState = () => {
|
||||
state = Debug.assertDefined(backupState);
|
||||
backupState = undefined;
|
||||
};
|
||||
result.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.assertDefined(state.program), sourceFile);
|
||||
result.getSemanticDiagnostics = getSemanticDiagnostics;
|
||||
result.emit = emit;
|
||||
result.releaseProgram = () => {
|
||||
releaseCache(state);
|
||||
backupState = undefined;
|
||||
};
|
||||
|
||||
if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
|
||||
@@ -445,18 +777,52 @@ namespace ts {
|
||||
* in that order would be used to write the files
|
||||
*/
|
||||
function emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult<EmitResult> {
|
||||
const affected = getNextAffectedFile(state, cancellationToken, computeHash);
|
||||
let affected = getNextAffectedFile(state, cancellationToken, computeHash);
|
||||
let isPendingEmitFile = false;
|
||||
if (!affected) {
|
||||
// Done
|
||||
return undefined;
|
||||
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
|
||||
affected = getNextAffectedFilePendingEmit(state);
|
||||
if (!affected) {
|
||||
if (state.emittedBuildInfo) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const affected = Debug.assertDefined(state.program);
|
||||
return toAffectedFileResult(
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
// Otherwise just affected file
|
||||
affected.emitBuildInfo(writeFile || host.writeFile, cancellationToken),
|
||||
affected,
|
||||
/*isPendingEmitFile*/ false,
|
||||
/*isBuildInfoEmit*/ true
|
||||
);
|
||||
}
|
||||
isPendingEmitFile = true;
|
||||
}
|
||||
else {
|
||||
const program = Debug.assertDefined(state.program);
|
||||
// Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes
|
||||
if (state.programEmitComplete || !some(program.getProjectReferences(), ref => !!ref.prepend)) {
|
||||
state.programEmitComplete = true;
|
||||
return undefined;
|
||||
}
|
||||
affected = program;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark seen emitted files if there are pending files to be emitted
|
||||
if (state.affectedFilesPendingEmit && state.program !== affected) {
|
||||
(state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).path, true);
|
||||
}
|
||||
|
||||
return toAffectedFileResult(
|
||||
state,
|
||||
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
|
||||
// Otherwise just affected file
|
||||
state.program.emit(affected === state.program ? undefined : affected as SourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers),
|
||||
affected
|
||||
Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected as SourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers),
|
||||
affected,
|
||||
isPendingEmitFile
|
||||
);
|
||||
}
|
||||
|
||||
@@ -496,7 +862,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
}
|
||||
return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
return Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,33 +910,121 @@ namespace ts {
|
||||
*/
|
||||
function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<Diagnostic> {
|
||||
assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
|
||||
const compilerOptions = state.program.getCompilerOptions();
|
||||
const compilerOptions = Debug.assertDefined(state.program).getCompilerOptions();
|
||||
if (compilerOptions.outFile || compilerOptions.out) {
|
||||
Debug.assert(!state.semanticDiagnosticsPerFile);
|
||||
// We dont need to cache the diagnostics just return them from program
|
||||
return state.program.getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
return Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
|
||||
}
|
||||
|
||||
if (sourceFile) {
|
||||
return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
|
||||
}
|
||||
|
||||
if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
|
||||
// When semantic builder asks for diagnostics of the whole program,
|
||||
// ensure that all the affected files are handled
|
||||
let affected: SourceFile | Program | undefined;
|
||||
while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) {
|
||||
doneWithAffectedFile(state, affected);
|
||||
// When semantic builder asks for diagnostics of the whole program,
|
||||
// ensure that all the affected files are handled
|
||||
let affected: SourceFile | Program | undefined;
|
||||
let affectedFilesPendingEmit: Path[] | undefined;
|
||||
while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) {
|
||||
if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
|
||||
(affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push((affected as SourceFile).path);
|
||||
}
|
||||
doneWithAffectedFile(state, affected);
|
||||
}
|
||||
|
||||
// In case of emit builder, cache the files to be emitted
|
||||
if (affectedFilesPendingEmit) {
|
||||
state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit);
|
||||
// affectedFilesPendingEmitIndex === undefined
|
||||
// - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
|
||||
// so start from 0 as array would be affectedFilesPendingEmit
|
||||
// else, continue to iterate from existing index, the current set is appended to existing files
|
||||
if (state.affectedFilesPendingEmitIndex === undefined) {
|
||||
state.affectedFilesPendingEmitIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
let diagnostics: Diagnostic[] | undefined;
|
||||
for (const sourceFile of state.program.getSourceFiles()) {
|
||||
for (const sourceFile of Debug.assertDefined(state.program).getSourceFiles()) {
|
||||
diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken));
|
||||
}
|
||||
return diagnostics || emptyArray;
|
||||
}
|
||||
}
|
||||
|
||||
function getMapOfReferencedSet(mapLike: MapLike<ReadonlyArray<string>> | undefined): ReadonlyMap<BuilderState.ReferencedSet> | undefined {
|
||||
if (!mapLike) return undefined;
|
||||
const map = createMap<BuilderState.ReferencedSet>();
|
||||
// Copies keys/values from template. Note that for..in will not throw if
|
||||
// template is undefined, and instead will just exit the loop.
|
||||
for (const key in mapLike) {
|
||||
if (hasProperty(mapLike, key)) {
|
||||
map.set(key, arrayToSet(mapLike[key]));
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function createBuildProgramUsingProgramBuildInfo(program: ProgramBuildInfo): EmitAndSemanticDiagnosticsBuilderProgram & SemanticDiagnosticsBuilderProgram {
|
||||
const fileInfos = createMapFromTemplate(program.fileInfos);
|
||||
const state: ReusableBuilderProgramState = {
|
||||
fileInfos,
|
||||
compilerOptions: program.options,
|
||||
referencedMap: getMapOfReferencedSet(program.referencedMap),
|
||||
exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
|
||||
semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => isString(value) ? value : value[0], value => isString(value) ? emptyArray : value[1]),
|
||||
hasReusableDiagnostic: true
|
||||
};
|
||||
return {
|
||||
getState: () => state,
|
||||
backupState: noop,
|
||||
restoreState: noop,
|
||||
getProgram: notImplemented,
|
||||
getProgramOrUndefined: returnUndefined,
|
||||
releaseProgram: noop,
|
||||
getCompilerOptions: () => state.compilerOptions,
|
||||
getSourceFile: notImplemented,
|
||||
getSourceFiles: notImplemented,
|
||||
getOptionsDiagnostics: notImplemented,
|
||||
getGlobalDiagnostics: notImplemented,
|
||||
getConfigFileParsingDiagnostics: notImplemented,
|
||||
getSyntacticDiagnostics: notImplemented,
|
||||
getDeclarationDiagnostics: notImplemented,
|
||||
getSemanticDiagnostics: notImplemented,
|
||||
emit: notImplemented,
|
||||
getAllDependencies: notImplemented,
|
||||
getCurrentDirectory: notImplemented,
|
||||
emitNextAffectedFile: notImplemented,
|
||||
getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
|
||||
};
|
||||
}
|
||||
|
||||
export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: ReadonlyArray<Diagnostic>): BuilderProgram {
|
||||
return {
|
||||
getState: notImplemented,
|
||||
backupState: noop,
|
||||
restoreState: noop,
|
||||
getProgram,
|
||||
getProgramOrUndefined: () => state.program,
|
||||
releaseProgram: () => state.program = undefined,
|
||||
getCompilerOptions: () => state.compilerOptions,
|
||||
getSourceFile: fileName => getProgram().getSourceFile(fileName),
|
||||
getSourceFiles: () => getProgram().getSourceFiles(),
|
||||
getOptionsDiagnostics: cancellationToken => getProgram().getOptionsDiagnostics(cancellationToken),
|
||||
getGlobalDiagnostics: cancellationToken => getProgram().getGlobalDiagnostics(cancellationToken),
|
||||
getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics,
|
||||
getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken),
|
||||
getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken),
|
||||
getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken),
|
||||
emit: (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers),
|
||||
getAllDependencies: notImplemented,
|
||||
getCurrentDirectory: () => getProgram().getCurrentDirectory(),
|
||||
};
|
||||
|
||||
function getProgram() {
|
||||
return Debug.assertDefined(state.program);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ts {
|
||||
@@ -597,11 +1051,25 @@ namespace ts {
|
||||
*/
|
||||
export interface BuilderProgram {
|
||||
/*@internal*/
|
||||
getState(): BuilderProgramState;
|
||||
getState(): ReusableBuilderProgramState;
|
||||
/*@internal*/
|
||||
backupState(): void;
|
||||
/*@internal*/
|
||||
restoreState(): void;
|
||||
/**
|
||||
* Returns current program
|
||||
*/
|
||||
getProgram(): Program;
|
||||
/**
|
||||
* Returns current program that could be undefined if the program was released
|
||||
*/
|
||||
/*@internal*/
|
||||
getProgramOrUndefined(): Program | undefined;
|
||||
/**
|
||||
* Releases reference to the program, making all the other operations that need program to fail.
|
||||
*/
|
||||
/*@internal*/
|
||||
releaseProgram(): void;
|
||||
/**
|
||||
* Get compiler options of the program
|
||||
*/
|
||||
@@ -630,10 +1098,15 @@ namespace ts {
|
||||
* Get the syntax diagnostics, for all source files if source file is not supplied
|
||||
*/
|
||||
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<Diagnostic>;
|
||||
/**
|
||||
* Get the declaration diagnostics, for all source files if source file is not supplied
|
||||
*/
|
||||
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray<DiagnosticWithLocation>;
|
||||
/**
|
||||
* Get all the dependencies of the file
|
||||
*/
|
||||
getAllDependencies(sourceFile: SourceFile): ReadonlyArray<string>;
|
||||
|
||||
/**
|
||||
* Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
|
||||
* The semantic diagnostics are cached and managed here
|
||||
@@ -710,22 +1183,7 @@ namespace ts {
|
||||
export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>): BuilderProgram;
|
||||
export function createAbstractBuilder(rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>, projectReferences?: ReadonlyArray<ProjectReference>): BuilderProgram;
|
||||
export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray<string> | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray<Diagnostic> | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>, projectReferences?: ReadonlyArray<ProjectReference>): BuilderProgram {
|
||||
const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences);
|
||||
return {
|
||||
// Only return program, all other methods are not implemented
|
||||
getProgram: () => program,
|
||||
getState: notImplemented,
|
||||
getCompilerOptions: notImplemented,
|
||||
getSourceFile: notImplemented,
|
||||
getSourceFiles: notImplemented,
|
||||
getOptionsDiagnostics: notImplemented,
|
||||
getGlobalDiagnostics: notImplemented,
|
||||
getConfigFileParsingDiagnostics: notImplemented,
|
||||
getSyntacticDiagnostics: notImplemented,
|
||||
getSemanticDiagnostics: notImplemented,
|
||||
emit: notImplemented,
|
||||
getAllDependencies: notImplemented,
|
||||
getCurrentDirectory: notImplemented
|
||||
};
|
||||
const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences);
|
||||
return createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,24 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReusableBuilderState {
|
||||
/**
|
||||
* Information of the file eg. its version, signature etc
|
||||
*/
|
||||
fileInfos: ReadonlyMap<BuilderState.FileInfo>;
|
||||
/**
|
||||
* Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled
|
||||
* Otherwise undefined
|
||||
* Thus non undefined value indicates, module emit
|
||||
*/
|
||||
readonly referencedMap?: ReadonlyMap<BuilderState.ReferencedSet> | undefined;
|
||||
/**
|
||||
* Contains the map of exported modules ReferencedSet=exported module files from the file if module emit is enabled
|
||||
* Otherwise undefined
|
||||
*/
|
||||
readonly exportedModulesMap?: ReadonlyMap<BuilderState.ReferencedSet> | undefined;
|
||||
}
|
||||
|
||||
export interface BuilderState {
|
||||
/**
|
||||
* Information of the file eg. its version, signature etc
|
||||
@@ -37,7 +55,7 @@ namespace ts {
|
||||
*/
|
||||
readonly referencedMap: ReadonlyMap<BuilderState.ReferencedSet> | undefined;
|
||||
/**
|
||||
* Contains the map of exported modules ReferencedSet=exorted module files from the file if module emit is enabled
|
||||
* Contains the map of exported modules ReferencedSet=exported module files from the file if module emit is enabled
|
||||
* Otherwise undefined
|
||||
*/
|
||||
readonly exportedModulesMap: Map<BuilderState.ReferencedSet> | undefined;
|
||||
@@ -50,11 +68,15 @@ namespace ts {
|
||||
/**
|
||||
* Cache of all files excluding default library file for the current program
|
||||
*/
|
||||
allFilesExcludingDefaultLibraryFile: ReadonlyArray<SourceFile> | undefined;
|
||||
allFilesExcludingDefaultLibraryFile?: ReadonlyArray<SourceFile>;
|
||||
/**
|
||||
* Cache of all the file names
|
||||
*/
|
||||
allFileNames: ReadonlyArray<string> | undefined;
|
||||
allFileNames?: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export function cloneMapOrUndefined<T>(map: ReadonlyMap<T> | undefined) {
|
||||
return map ? cloneMap(map) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,14 +214,14 @@ namespace ts.BuilderState {
|
||||
/**
|
||||
* Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
|
||||
*/
|
||||
export function canReuseOldState(newReferencedMap: ReadonlyMap<ReferencedSet> | undefined, oldState: Readonly<BuilderState> | undefined) {
|
||||
export function canReuseOldState(newReferencedMap: ReadonlyMap<ReferencedSet> | undefined, oldState: Readonly<ReusableBuilderState> | undefined) {
|
||||
return oldState && !oldState.referencedMap === !newReferencedMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the state of file references and signature for the new program from oldState if it is safe
|
||||
*/
|
||||
export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly<BuilderState>): BuilderState {
|
||||
export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly<ReusableBuilderState>): BuilderState {
|
||||
const fileInfos = createMap<FileInfo>();
|
||||
const referencedMap = newProgram.getCompilerOptions().module !== ModuleKind.None ? createMap<ReferencedSet>() : undefined;
|
||||
const exportedModulesMap = referencedMap ? createMap<ReferencedSet>() : undefined;
|
||||
@@ -230,9 +252,32 @@ namespace ts.BuilderState {
|
||||
fileInfos,
|
||||
referencedMap,
|
||||
exportedModulesMap,
|
||||
hasCalledUpdateShapeSignature,
|
||||
allFilesExcludingDefaultLibraryFile: undefined,
|
||||
allFileNames: undefined
|
||||
hasCalledUpdateShapeSignature
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases needed properties
|
||||
*/
|
||||
export function releaseCache(state: BuilderState) {
|
||||
state.allFilesExcludingDefaultLibraryFile = undefined;
|
||||
state.allFileNames = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a clone of the state
|
||||
*/
|
||||
export function clone(state: Readonly<BuilderState>): BuilderState {
|
||||
const fileInfos = createMap<FileInfo>();
|
||||
state.fileInfos.forEach((value, key) => {
|
||||
fileInfos.set(key, { ...value });
|
||||
});
|
||||
// Dont need to backup allFiles info since its cache anyway
|
||||
return {
|
||||
fileInfos,
|
||||
referencedMap: cloneMapOrUndefined(state.referencedMap),
|
||||
exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
|
||||
hasCalledUpdateShapeSignature: cloneMap(state.hasCalledUpdateShapeSignature),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -241,9 +286,9 @@ namespace ts.BuilderState {
|
||||
*/
|
||||
export function getFilesAffectedBy(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, cacheToUpdateSignature?: Map<string>, exportedModulesMapCache?: ComputingExportedModulesMap): ReadonlyArray<SourceFile> {
|
||||
// Since the operation could be cancelled, the signatures are always stored in the cache
|
||||
// They will be commited once it is safe to use them
|
||||
// They will be committed once it is safe to use them
|
||||
// eg when calling this api from tsserver, if there is no cancellation of the operation
|
||||
// In the other cases the affected files signatures are commited only after the iteration through the result is complete
|
||||
// In the other cases the affected files signatures are committed only after the iteration through the result is complete
|
||||
const signatureCache = cacheToUpdateSignature || createMap();
|
||||
const sourceFile = programOfThisState.getSourceFileByPath(path);
|
||||
if (!sourceFile) {
|
||||
@@ -505,14 +550,14 @@ namespace ts.BuilderState {
|
||||
|
||||
// Start with the paths this file was referenced by
|
||||
seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape);
|
||||
const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path);
|
||||
const queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
|
||||
while (queue.length > 0) {
|
||||
const currentPath = queue.pop()!;
|
||||
if (!seenFileNamesMap.has(currentPath)) {
|
||||
const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath)!;
|
||||
seenFileNamesMap.set(currentPath, currentSourceFile);
|
||||
if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash!, exportedModulesMapCache)) { // TODO: GH#18217
|
||||
queue.push(...getReferencedByPaths(state, currentPath));
|
||||
queue.push(...getReferencedByPaths(state, currentSourceFile.resolvedPath));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1601
-876
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,7 @@ namespace ts {
|
||||
["es2016", "lib.es2016.d.ts"],
|
||||
["es2017", "lib.es2017.d.ts"],
|
||||
["es2018", "lib.es2018.d.ts"],
|
||||
["es2019", "lib.es2019.d.ts"],
|
||||
["esnext", "lib.esnext.d.ts"],
|
||||
// Host only
|
||||
["dom", "lib.dom.d.ts"],
|
||||
@@ -38,12 +39,16 @@ namespace ts {
|
||||
["es2017.string", "lib.es2017.string.d.ts"],
|
||||
["es2017.intl", "lib.es2017.intl.d.ts"],
|
||||
["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
|
||||
["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
|
||||
["es2018.intl", "lib.es2018.intl.d.ts"],
|
||||
["es2018.promise", "lib.es2018.promise.d.ts"],
|
||||
["es2018.regexp", "lib.es2018.regexp.d.ts"],
|
||||
["esnext.array", "lib.esnext.array.d.ts"],
|
||||
["esnext.symbol", "lib.esnext.symbol.d.ts"],
|
||||
["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"],
|
||||
["es2019.array", "lib.es2019.array.d.ts"],
|
||||
["es2019.string", "lib.es2019.string.d.ts"],
|
||||
["es2019.symbol", "lib.es2019.symbol.d.ts"],
|
||||
["esnext.array", "lib.es2019.array.d.ts"],
|
||||
["esnext.symbol", "lib.es2019.symbol.d.ts"],
|
||||
["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
|
||||
["esnext.intl", "lib.esnext.intl.d.ts"],
|
||||
["esnext.bigint", "lib.esnext.bigint.d.ts"]
|
||||
];
|
||||
@@ -197,6 +202,7 @@ namespace ts {
|
||||
es2016: ScriptTarget.ES2016,
|
||||
es2017: ScriptTarget.ES2017,
|
||||
es2018: ScriptTarget.ES2018,
|
||||
es2019: ScriptTarget.ES2019,
|
||||
esnext: ScriptTarget.ESNext,
|
||||
}),
|
||||
affectsSourceFile: true,
|
||||
@@ -204,7 +210,7 @@ namespace ts {
|
||||
paramType: Diagnostics.VERSION,
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Basic_Options,
|
||||
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT,
|
||||
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT,
|
||||
},
|
||||
{
|
||||
name: "module",
|
||||
@@ -325,6 +331,22 @@ namespace ts {
|
||||
category: Diagnostics.Basic_Options,
|
||||
description: Diagnostics.Enable_project_compilation,
|
||||
},
|
||||
{
|
||||
name: "incremental",
|
||||
type: "boolean",
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Basic_Options,
|
||||
description: Diagnostics.Enable_incremental_compilation,
|
||||
},
|
||||
{
|
||||
name: "tsBuildInfoFile",
|
||||
type: "string",
|
||||
isFilePath: true,
|
||||
paramType: Diagnostics.FILE,
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Basic_Options,
|
||||
description: Diagnostics.Specify_file_to_store_incremental_compilation_information,
|
||||
},
|
||||
{
|
||||
name: "removeComments",
|
||||
type: "boolean",
|
||||
@@ -1421,6 +1443,7 @@ namespace ts {
|
||||
return _tsconfigRootOptions;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
interface JsonConversionNotifier {
|
||||
/**
|
||||
* Notifies parent option object is being set with the optionKey and a valid optionValue
|
||||
@@ -1935,7 +1958,7 @@ namespace ts {
|
||||
|
||||
function directoryOfCombinedPath(fileName: string, basePath: string) {
|
||||
// Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
|
||||
// until consistient casing errors are reported
|
||||
// until consistent casing errors are reported
|
||||
return getDirectoryPath(getNormalizedAbsolutePath(fileName, basePath));
|
||||
}
|
||||
|
||||
|
||||
+176
-30
@@ -1,7 +1,7 @@
|
||||
namespace ts {
|
||||
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
|
||||
// If changing the text in this section, be sure to test `configureNightly` too.
|
||||
export const versionMajorMinor = "3.3";
|
||||
export const versionMajorMinor = "3.4";
|
||||
/** The version of the TypeScript compiler release */
|
||||
export const version = `${versionMajorMinor}.0-dev`;
|
||||
}
|
||||
@@ -118,42 +118,105 @@ namespace ts {
|
||||
export const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
|
||||
|
||||
// Keep the class inside a function so it doesn't get compiled if it's not used.
|
||||
function shimMap(): new <T>() => Map<T> {
|
||||
export function shimMap(): new <T>() => Map<T> {
|
||||
|
||||
interface MapEntry<T> {
|
||||
readonly key?: string;
|
||||
value?: T;
|
||||
|
||||
// Linked list references for iterators.
|
||||
nextEntry?: MapEntry<T>;
|
||||
previousEntry?: MapEntry<T>;
|
||||
|
||||
/**
|
||||
* Specifies if iterators should skip the next entry.
|
||||
* This will be set when an entry is deleted.
|
||||
* See https://github.com/Microsoft/TypeScript/pull/27292 for more information.
|
||||
*/
|
||||
skipNext?: boolean;
|
||||
}
|
||||
|
||||
class MapIterator<T, U extends (string | T | [string, T])> {
|
||||
private data: MapLike<T>;
|
||||
private keys: ReadonlyArray<string>;
|
||||
private index = 0;
|
||||
private selector: (data: MapLike<T>, key: string) => U;
|
||||
constructor(data: MapLike<T>, selector: (data: MapLike<T>, key: string) => U) {
|
||||
this.data = data;
|
||||
private currentEntry?: MapEntry<T>;
|
||||
private selector: (key: string, value: T) => U;
|
||||
|
||||
constructor(currentEntry: MapEntry<T>, selector: (key: string, value: T) => U) {
|
||||
this.currentEntry = currentEntry;
|
||||
this.selector = selector;
|
||||
this.keys = Object.keys(data);
|
||||
}
|
||||
|
||||
public next(): { value: U, done: false } | { value: never, done: true } {
|
||||
const index = this.index;
|
||||
if (index < this.keys.length) {
|
||||
this.index++;
|
||||
return { value: this.selector(this.data, this.keys[index]), done: false };
|
||||
// Navigate to the next entry.
|
||||
while (this.currentEntry) {
|
||||
const skipNext = !!this.currentEntry.skipNext;
|
||||
this.currentEntry = this.currentEntry.nextEntry;
|
||||
|
||||
if (!skipNext) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.currentEntry) {
|
||||
return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false };
|
||||
}
|
||||
else {
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
}
|
||||
|
||||
return class <T> implements Map<T> {
|
||||
private data = createDictionaryObject<T>();
|
||||
private data = createDictionaryObject<MapEntry<T>>();
|
||||
public size = 0;
|
||||
|
||||
// Linked list references for iterators.
|
||||
// See https://github.com/Microsoft/TypeScript/pull/27292
|
||||
// for more information.
|
||||
|
||||
/**
|
||||
* The first entry in the linked list.
|
||||
* Note that this is only a stub that serves as starting point
|
||||
* for iterators and doesn't contain a key and a value.
|
||||
*/
|
||||
private readonly firstEntry: MapEntry<T>;
|
||||
private lastEntry: MapEntry<T>;
|
||||
|
||||
constructor() {
|
||||
// Create a first (stub) map entry that will not contain a key
|
||||
// and value but serves as starting point for iterators.
|
||||
this.firstEntry = {};
|
||||
// When the map is empty, the last entry is the same as the
|
||||
// first one.
|
||||
this.lastEntry = this.firstEntry;
|
||||
}
|
||||
|
||||
get(key: string): T | undefined {
|
||||
return this.data[key];
|
||||
const entry = this.data[key] as MapEntry<T> | undefined;
|
||||
return entry && entry.value!;
|
||||
}
|
||||
|
||||
set(key: string, value: T): this {
|
||||
if (!this.has(key)) {
|
||||
this.size++;
|
||||
|
||||
// Create a new entry that will be appended at the
|
||||
// end of the linked list.
|
||||
const newEntry: MapEntry<T> = {
|
||||
key,
|
||||
value
|
||||
};
|
||||
this.data[key] = newEntry;
|
||||
|
||||
// Adjust the references.
|
||||
const previousLastEntry = this.lastEntry;
|
||||
previousLastEntry.nextEntry = newEntry;
|
||||
newEntry.previousEntry = previousLastEntry;
|
||||
this.lastEntry = newEntry;
|
||||
}
|
||||
this.data[key] = value;
|
||||
else {
|
||||
this.data[key].value = value;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -165,32 +228,81 @@ namespace ts {
|
||||
delete(key: string): boolean {
|
||||
if (this.has(key)) {
|
||||
this.size--;
|
||||
const entry = this.data[key];
|
||||
delete this.data[key];
|
||||
|
||||
// Adjust the linked list references of the neighbor entries.
|
||||
const previousEntry = entry.previousEntry!;
|
||||
previousEntry.nextEntry = entry.nextEntry;
|
||||
if (entry.nextEntry) {
|
||||
entry.nextEntry.previousEntry = previousEntry;
|
||||
}
|
||||
|
||||
// When the deleted entry was the last one, we need to
|
||||
// adust the lastEntry reference.
|
||||
if (this.lastEntry === entry) {
|
||||
this.lastEntry = previousEntry;
|
||||
}
|
||||
|
||||
// Adjust the forward reference of the deleted entry
|
||||
// in case an iterator still references it. This allows us
|
||||
// to throw away the entry, but when an active iterator
|
||||
// (which points to the current entry) continues, it will
|
||||
// navigate to the entry that originally came before the
|
||||
// current one and skip it.
|
||||
entry.previousEntry = undefined;
|
||||
entry.nextEntry = previousEntry;
|
||||
entry.skipNext = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.data = createDictionaryObject<T>();
|
||||
this.data = createDictionaryObject<MapEntry<T>>();
|
||||
this.size = 0;
|
||||
|
||||
// Reset the linked list. Note that we must adjust the forward
|
||||
// references of the deleted entries to ensure iterators stuck
|
||||
// in the middle of the list don't continue with deleted entries,
|
||||
// but can continue with new entries added after the clear()
|
||||
// operation.
|
||||
const firstEntry = this.firstEntry;
|
||||
let currentEntry = firstEntry.nextEntry;
|
||||
while (currentEntry) {
|
||||
const nextEntry = currentEntry.nextEntry;
|
||||
currentEntry.previousEntry = undefined;
|
||||
currentEntry.nextEntry = firstEntry;
|
||||
currentEntry.skipNext = true;
|
||||
|
||||
currentEntry = nextEntry;
|
||||
}
|
||||
firstEntry.nextEntry = undefined;
|
||||
this.lastEntry = firstEntry;
|
||||
}
|
||||
|
||||
keys(): Iterator<string> {
|
||||
return new MapIterator(this.data, (_data, key) => key);
|
||||
return new MapIterator(this.firstEntry, key => key);
|
||||
}
|
||||
|
||||
values(): Iterator<T> {
|
||||
return new MapIterator(this.data, (data, key) => data[key]);
|
||||
return new MapIterator(this.firstEntry, (_key, value) => value);
|
||||
}
|
||||
|
||||
entries(): Iterator<[string, T]> {
|
||||
return new MapIterator(this.data, (data, key) => [key, data[key]] as [string, T]);
|
||||
return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]);
|
||||
}
|
||||
|
||||
forEach(action: (value: T, key: string) => void): void {
|
||||
for (const key in this.data) {
|
||||
action(this.data[key], key);
|
||||
const iterator = this.entries();
|
||||
while (true) {
|
||||
const { value: entry, done } = iterator.next();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
action(entry[1], entry[0]);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -805,7 +917,7 @@ namespace ts {
|
||||
|
||||
/**
|
||||
* Deduplicates an unsorted array.
|
||||
* @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
|
||||
* @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
|
||||
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
|
||||
* result will remain in the original order in `array`.
|
||||
*/
|
||||
@@ -884,8 +996,11 @@ namespace ts {
|
||||
/**
|
||||
* Compacts an array, removing any falsey elements.
|
||||
*/
|
||||
export function compact<T>(array: T[]): T[];
|
||||
export function compact<T>(array: ReadonlyArray<T>): ReadonlyArray<T>;
|
||||
export function compact<T>(array: (T | undefined | null | false | 0 | "")[]): T[];
|
||||
export function compact<T>(array: ReadonlyArray<T | undefined | null | false | 0 | "">): ReadonlyArray<T>;
|
||||
// TSLint thinks these can be combined with the above - they cannot; they'd produce higher-priority inferences and prevent the falsey types from being stripped
|
||||
export function compact<T>(array: T[]): T[]; // tslint:disable-line unified-signatures
|
||||
export function compact<T>(array: ReadonlyArray<T>): ReadonlyArray<T>; // tslint:disable-line unified-signatures
|
||||
export function compact<T>(array: T[]): T[] {
|
||||
let result: T[] | undefined;
|
||||
if (array) {
|
||||
@@ -1058,6 +1173,21 @@ namespace ts {
|
||||
}};
|
||||
}
|
||||
|
||||
export function arrayReverseIterator<T>(array: ReadonlyArray<T>): Iterator<T> {
|
||||
let i = array.length;
|
||||
return {
|
||||
next: () => {
|
||||
if (i === 0) {
|
||||
return { value: undefined as never, done: true };
|
||||
}
|
||||
else {
|
||||
i--;
|
||||
return { value: array[i], done: false };
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
|
||||
*/
|
||||
@@ -1281,9 +1411,10 @@ namespace ts {
|
||||
|
||||
export function assign<T extends object>(t: T, ...args: (T | undefined)[]) {
|
||||
for (const arg of args) {
|
||||
for (const p in arg!) {
|
||||
if (hasProperty(arg!, p)) {
|
||||
t![p] = arg![p]; // TODO: GH#23368
|
||||
if (arg === undefined) continue;
|
||||
for (const p in arg) {
|
||||
if (hasProperty(arg, p)) {
|
||||
t[p] = arg[p];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1387,6 +1518,18 @@ namespace ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
export function copyProperties<T1 extends T2, T2>(first: T1, second: T2) {
|
||||
for (const id in second) {
|
||||
if (hasOwnProperty.call(second, id)) {
|
||||
(first as any)[id] = second[id];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function maybeBind<T, A extends any[], R>(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined {
|
||||
return fn ? fn.bind(obj) : undefined;
|
||||
}
|
||||
|
||||
export interface MultiMap<T> extends Map<T[]> {
|
||||
/**
|
||||
* Adds the value to an array of values associated with the key, and returns the array.
|
||||
@@ -1471,6 +1614,9 @@ namespace ts {
|
||||
/** Do nothing and return true */
|
||||
export function returnTrue(): true { return true; }
|
||||
|
||||
/** Do nothing and return undefined */
|
||||
export function returnUndefined(): undefined { return undefined; }
|
||||
|
||||
/** Returns its argument. */
|
||||
export function identity<T>(x: T) { return x; }
|
||||
|
||||
@@ -1637,7 +1783,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
|
||||
const detail = "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member);
|
||||
const detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + showSyntaxKind(member as Node) : JSON.stringify(member);
|
||||
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
|
||||
}
|
||||
|
||||
|
||||
@@ -659,10 +659,6 @@
|
||||
"category": "Error",
|
||||
"code": 1208
|
||||
},
|
||||
"Ambient const enums are not allowed when the '--isolatedModules' flag is provided.": {
|
||||
"category": "Error",
|
||||
"code": 1209
|
||||
},
|
||||
"Invalid use of '{0}'. Class definitions are automatically in strict mode.": {
|
||||
"category": "Error",
|
||||
"code": 1210
|
||||
@@ -1023,6 +1019,14 @@
|
||||
"category": "Error",
|
||||
"code": 1353
|
||||
},
|
||||
"'readonly' type modifier is only permitted on array and tuple literal types.": {
|
||||
"category": "Error",
|
||||
"code": 1354
|
||||
},
|
||||
"A 'const' assertion can only be applied to a string, number, boolean, array, or object literal.": {
|
||||
"category": "Error",
|
||||
"code": 1355
|
||||
},
|
||||
|
||||
"Duplicate identifier '{0}'.": {
|
||||
"category": "Error",
|
||||
@@ -1400,7 +1404,7 @@
|
||||
"category": "Error",
|
||||
"code": 2393
|
||||
},
|
||||
"Overload signature is not compatible with function implementation.": {
|
||||
"This overload signature is not compatible with its implementation signature.": {
|
||||
"category": "Error",
|
||||
"code": 2394
|
||||
},
|
||||
@@ -1776,7 +1780,7 @@
|
||||
"category": "Error",
|
||||
"code": 2496
|
||||
},
|
||||
"Module '{0}' resolves to a non-module entity and cannot be imported using this construct.": {
|
||||
"This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export.": {
|
||||
"category": "Error",
|
||||
"code": 2497
|
||||
},
|
||||
@@ -2056,10 +2060,6 @@
|
||||
"category": "Error",
|
||||
"code": 2567
|
||||
},
|
||||
"Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": {
|
||||
"category": "Error",
|
||||
"code": 2568
|
||||
},
|
||||
"Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.": {
|
||||
"category": "Error",
|
||||
"code": 2569
|
||||
@@ -2096,15 +2096,15 @@
|
||||
"category": "Error",
|
||||
"code": 2577
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.": {
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": {
|
||||
"category": "Error",
|
||||
"code": 2580
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig.": {
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.": {
|
||||
"category": "Error",
|
||||
"code": 2581
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.": {
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.": {
|
||||
"category": "Error",
|
||||
"code": 2582
|
||||
},
|
||||
@@ -2132,6 +2132,26 @@
|
||||
"category": "Error",
|
||||
"code": 2588
|
||||
},
|
||||
"Type instantiation is excessively deep and possibly infinite.": {
|
||||
"category": "Error",
|
||||
"code": 2589
|
||||
},
|
||||
"Expression produces a union type that is too complex to represent.": {
|
||||
"category": "Error",
|
||||
"code": 2590
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig.": {
|
||||
"category": "Error",
|
||||
"code": 2591
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig.": {
|
||||
"category": "Error",
|
||||
"code": 2592
|
||||
},
|
||||
"Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.": {
|
||||
"category": "Error",
|
||||
"code": 2593
|
||||
},
|
||||
"JSX element attributes type '{0}' may not be a union type.": {
|
||||
"category": "Error",
|
||||
"code": 2600
|
||||
@@ -2437,7 +2457,7 @@
|
||||
"category": "Error",
|
||||
"code": 2717
|
||||
},
|
||||
"Duplicate declaration '{0}'.": {
|
||||
"Duplicate property '{0}'.": {
|
||||
"category": "Error",
|
||||
"code": 2718
|
||||
},
|
||||
@@ -2497,6 +2517,10 @@
|
||||
"category": "Error",
|
||||
"code": 2732
|
||||
},
|
||||
"Property '{0}' was also declared here.": {
|
||||
"category": "Error",
|
||||
"code": 2733
|
||||
},
|
||||
"It is highly likely that you are missing a semicolon.": {
|
||||
"category": "Error",
|
||||
"code": 2734
|
||||
@@ -2541,6 +2565,42 @@
|
||||
"category": "Error",
|
||||
"code": 2744
|
||||
},
|
||||
"This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided.": {
|
||||
"category": "Error",
|
||||
"code": 2745
|
||||
},
|
||||
"This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided.": {
|
||||
"category": "Error",
|
||||
"code": 2746
|
||||
},
|
||||
"'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'.": {
|
||||
"category": "Error",
|
||||
"code": 2747
|
||||
},
|
||||
"Cannot access ambient const enums when the '--isolatedModules' flag is provided.": {
|
||||
"category": "Error",
|
||||
"code": 2748
|
||||
},
|
||||
"'{0}' refers to a value, but is being used as a type here.": {
|
||||
"category": "Error",
|
||||
"code": 2749
|
||||
},
|
||||
"The implementation signature is declared here.": {
|
||||
"category": "Error",
|
||||
"code": 2750
|
||||
},
|
||||
"Circularity originates in type at this location.": {
|
||||
"category": "Error",
|
||||
"code": 2751
|
||||
},
|
||||
"The first export default is here.": {
|
||||
"category": "Error",
|
||||
"code": 2752
|
||||
},
|
||||
"Another export default is here.": {
|
||||
"category": "Error",
|
||||
"code": 2753
|
||||
},
|
||||
|
||||
"Import declaration '{0}' is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
@@ -2875,6 +2935,10 @@
|
||||
"category": "Error",
|
||||
"code": 4102
|
||||
},
|
||||
"Type parameter '{0}' of exported mapped object type is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 4103
|
||||
},
|
||||
|
||||
"The current host does not support the '{0}' option.": {
|
||||
"category": "Error",
|
||||
@@ -3069,7 +3133,7 @@
|
||||
"category": "Message",
|
||||
"code": 6014
|
||||
},
|
||||
"Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.": {
|
||||
"Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'.": {
|
||||
"category": "Message",
|
||||
"code": 6015
|
||||
},
|
||||
@@ -3880,7 +3944,6 @@
|
||||
"category": "Message",
|
||||
"code": 6353
|
||||
},
|
||||
|
||||
"Project '{0}' is up to date with .d.ts files from its dependencies": {
|
||||
"category": "Message",
|
||||
"code": 6354
|
||||
@@ -3949,6 +4012,50 @@
|
||||
"category": "Error",
|
||||
"code": 6370
|
||||
},
|
||||
"Updating unchanged output timestamps of project '{0}'...": {
|
||||
"category": "Message",
|
||||
"code": 6371
|
||||
},
|
||||
"Project '{0}' is out of date because output of its dependency '{1}' has changed": {
|
||||
"category": "Message",
|
||||
"code": 6372
|
||||
},
|
||||
"Updating output of project '{0}'...": {
|
||||
"category": "Message",
|
||||
"code": 6373
|
||||
},
|
||||
"A non-dry build would update timestamps for output of project '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 6374
|
||||
},
|
||||
"A non-dry build would update output of project '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 6375
|
||||
},
|
||||
"Cannot update output of project '{0}' because there was error reading file '{1}'": {
|
||||
"category": "Message",
|
||||
"code": 6376
|
||||
},
|
||||
"Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'": {
|
||||
"category": "Error",
|
||||
"code": 6377
|
||||
},
|
||||
"Enable incremental compilation": {
|
||||
"category": "Message",
|
||||
"code": 6378
|
||||
},
|
||||
"Composite projects may not disable incremental compilation.": {
|
||||
"category": "Error",
|
||||
"code": 6379
|
||||
},
|
||||
"Specify file to store incremental compilation information": {
|
||||
"category": "Message",
|
||||
"code": 6380
|
||||
},
|
||||
"Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'": {
|
||||
"category": "Message",
|
||||
"code": 6381
|
||||
},
|
||||
|
||||
"The expected type comes from property '{0}' which is declared here on type '{1}'": {
|
||||
"category": "Message",
|
||||
@@ -4097,7 +4204,7 @@
|
||||
"category": "Error",
|
||||
"code": 7040
|
||||
},
|
||||
"The containing arrow function captures the global value of 'this' which implicitly has type 'any'.": {
|
||||
"The containing arrow function captures the global value of 'this'.": {
|
||||
"category": "Error",
|
||||
"code": 7041
|
||||
},
|
||||
@@ -4266,6 +4373,10 @@
|
||||
"category": "Error",
|
||||
"code": 8031
|
||||
},
|
||||
"Qualified name '{0}' is not allowed without a leading '@param {object} {1}'.": {
|
||||
"category": "Error",
|
||||
"code": 8032
|
||||
},
|
||||
"Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.": {
|
||||
"category": "Error",
|
||||
"code": 9002
|
||||
@@ -4811,5 +4922,13 @@
|
||||
"Add names to all parameters without names": {
|
||||
"category": "Message",
|
||||
"code": 95073
|
||||
},
|
||||
"Enable the 'experimentalDecorators' option in your configuration file": {
|
||||
"category": "Message",
|
||||
"code": 95074
|
||||
},
|
||||
"Convert parameters to destructured object": {
|
||||
"category": "Message",
|
||||
"code": 95075
|
||||
}
|
||||
}
|
||||
|
||||
+660
-93
File diff suppressed because it is too large
Load Diff
+312
-31
@@ -89,10 +89,10 @@ namespace ts {
|
||||
return createLiteralFromNode(value);
|
||||
}
|
||||
|
||||
export function createNumericLiteral(value: string): NumericLiteral {
|
||||
export function createNumericLiteral(value: string, numericLiteralFlags: TokenFlags = TokenFlags.None): NumericLiteral {
|
||||
const node = <NumericLiteral>createSynthesizedNode(SyntaxKind.NumericLiteral);
|
||||
node.text = value;
|
||||
node.numericLiteralFlags = 0;
|
||||
node.numericLiteralFlags = numericLiteralFlags;
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -143,8 +143,8 @@ namespace ts {
|
||||
export function updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode | TypeParameterDeclaration> | undefined): Identifier; // tslint:disable-line unified-signatures
|
||||
export function updateIdentifier(node: Identifier, typeArguments?: NodeArray<TypeNode | TypeParameterDeclaration> | undefined): Identifier {
|
||||
return node.typeArguments !== typeArguments
|
||||
? updateNode(createIdentifier(idText(node), typeArguments), node)
|
||||
: node;
|
||||
? updateNode(createIdentifier(idText(node), typeArguments), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
let nextAutoGenerateId = 0;
|
||||
@@ -876,8 +876,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function createTypeOperatorNode(type: TypeNode): TypeOperatorNode;
|
||||
export function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode;
|
||||
export function createTypeOperatorNode(operatorOrType: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | TypeNode, type?: TypeNode) {
|
||||
export function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode;
|
||||
export function createTypeOperatorNode(operatorOrType: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword | TypeNode, type?: TypeNode) {
|
||||
const node = createSynthesizedNode(SyntaxKind.TypeOperator) as TypeOperatorNode;
|
||||
node.operator = typeof operatorOrType === "number" ? operatorOrType : SyntaxKind.KeyOfKeyword;
|
||||
node.type = parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type! : operatorOrType);
|
||||
@@ -2299,6 +2299,28 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
export function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean) {
|
||||
const node = <JsxText>createSynthesizedNode(SyntaxKind.JsxText);
|
||||
node.text = text;
|
||||
node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean) {
|
||||
return node.text !== text
|
||||
|| node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
|
||||
? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
export function createJsxOpeningFragment() {
|
||||
return <JsxOpeningFragment>createSynthesizedNode(SyntaxKind.JsxOpeningFragment);
|
||||
}
|
||||
|
||||
export function createJsxJsxClosingFragment() {
|
||||
return <JsxClosingFragment>createSynthesizedNode(SyntaxKind.JsxClosingFragment);
|
||||
}
|
||||
|
||||
export function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray<JsxChild>, closingFragment: JsxClosingFragment) {
|
||||
return node.openingFragment !== openingFragment
|
||||
|| node.children !== children
|
||||
@@ -2629,42 +2651,301 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
export function createUnparsedSourceFile(text: string): UnparsedSource;
|
||||
export function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
|
||||
export function createUnparsedSourceFile(text: string, mapPath?: string, map?: string): UnparsedSource {
|
||||
let allUnscopedEmitHelpers: ReadonlyMap<UnscopedEmitHelper> | undefined;
|
||||
function getAllUnscopedEmitHelpers() {
|
||||
return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = arrayToMap([
|
||||
valuesHelper,
|
||||
readHelper,
|
||||
spreadHelper,
|
||||
restHelper,
|
||||
decorateHelper,
|
||||
metadataHelper,
|
||||
paramHelper,
|
||||
awaiterHelper,
|
||||
assignHelper,
|
||||
awaitHelper,
|
||||
asyncGeneratorHelper,
|
||||
asyncDelegator,
|
||||
asyncValues,
|
||||
extendsHelper,
|
||||
templateObjectHelper,
|
||||
generatorHelper,
|
||||
importStarHelper,
|
||||
importDefaultHelper
|
||||
], helper => helper.name));
|
||||
}
|
||||
|
||||
function createUnparsedSource() {
|
||||
const node = <UnparsedSource>createNode(SyntaxKind.UnparsedSource);
|
||||
node.text = text;
|
||||
node.sourceMapPath = mapPath;
|
||||
node.sourceMapText = map;
|
||||
node.prologues = emptyArray;
|
||||
node.referencedFiles = emptyArray;
|
||||
node.libReferenceDirectives = emptyArray;
|
||||
node.getLineAndCharacterOfPosition = pos => getLineAndCharacterOfPosition(node, pos);
|
||||
return node;
|
||||
}
|
||||
|
||||
export function createUnparsedSourceFile(text: string): UnparsedSource;
|
||||
export function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
|
||||
export function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
|
||||
export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, mapPathOrType?: string, mapTextOrStripInternal?: string | boolean): UnparsedSource {
|
||||
const node = createUnparsedSource();
|
||||
let stripInternal: boolean | undefined;
|
||||
let bundleFileInfo: BundleFileInfo | undefined;
|
||||
if (!isString(textOrInputFiles)) {
|
||||
Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
|
||||
node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
|
||||
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
|
||||
Object.defineProperties(node, {
|
||||
text: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
|
||||
sourceMapText: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
|
||||
});
|
||||
|
||||
|
||||
if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
|
||||
node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
|
||||
Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
|
||||
stripInternal = mapTextOrStripInternal as boolean | undefined;
|
||||
bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
|
||||
if (node.oldFileOfCurrentEmit) {
|
||||
parseOldFileOfCurrentEmit(node, Debug.assertDefined(bundleFileInfo));
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
node.fileName = "";
|
||||
node.text = textOrInputFiles;
|
||||
node.sourceMapPath = mapPathOrType;
|
||||
node.sourceMapText = mapTextOrStripInternal as string;
|
||||
}
|
||||
Debug.assert(!node.oldFileOfCurrentEmit);
|
||||
parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
|
||||
return node;
|
||||
}
|
||||
|
||||
function parseUnparsedSourceFile(node: UnparsedSource, bundleFileInfo: BundleFileInfo | undefined, stripInternal: boolean | undefined) {
|
||||
let prologues: UnparsedPrologue[] | undefined;
|
||||
let helpers: UnscopedEmitHelper[] | undefined;
|
||||
let referencedFiles: FileReference[] | undefined;
|
||||
let typeReferenceDirectives: string[] | undefined;
|
||||
let libReferenceDirectives: FileReference[] | undefined;
|
||||
let texts: UnparsedSourceText[] | undefined;
|
||||
|
||||
for (const section of bundleFileInfo ? bundleFileInfo.sections : emptyArray) {
|
||||
switch (section.kind) {
|
||||
case BundleFileSectionKind.Prologue:
|
||||
(prologues || (prologues = [])).push(createUnparsedNode(section, node) as UnparsedPrologue);
|
||||
break;
|
||||
case BundleFileSectionKind.EmitHelpers:
|
||||
(helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data)!);
|
||||
break;
|
||||
case BundleFileSectionKind.NoDefaultLib:
|
||||
node.hasNoDefaultLib = true;
|
||||
break;
|
||||
case BundleFileSectionKind.Reference:
|
||||
(referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
|
||||
break;
|
||||
case BundleFileSectionKind.Type:
|
||||
(typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
|
||||
break;
|
||||
case BundleFileSectionKind.Lib:
|
||||
(libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
|
||||
break;
|
||||
case BundleFileSectionKind.Prepend:
|
||||
const prependNode = createUnparsedNode(section, node) as UnparsedPrepend;
|
||||
let prependTexts: UnparsedTextLike[] | undefined;
|
||||
for (const text of section.texts) {
|
||||
if (!stripInternal || text.kind !== BundleFileSectionKind.Internal) {
|
||||
(prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node) as UnparsedTextLike);
|
||||
}
|
||||
}
|
||||
prependNode.texts = prependTexts || emptyArray;
|
||||
(texts || (texts = [])).push(prependNode);
|
||||
break;
|
||||
case BundleFileSectionKind.Internal:
|
||||
if (stripInternal) break;
|
||||
// falls through
|
||||
case BundleFileSectionKind.Text:
|
||||
(texts || (texts = [])).push(createUnparsedNode(section, node) as UnparsedTextLike);
|
||||
break;
|
||||
default:
|
||||
Debug.assertNever(section);
|
||||
}
|
||||
}
|
||||
|
||||
node.prologues = prologues || emptyArray;
|
||||
node.helpers = helpers;
|
||||
node.referencedFiles = referencedFiles || emptyArray;
|
||||
node.typeReferenceDirectives = typeReferenceDirectives;
|
||||
node.libReferenceDirectives = libReferenceDirectives || emptyArray;
|
||||
node.texts = texts || [<UnparsedTextLike>createUnparsedNode({ kind: BundleFileSectionKind.Text, pos: 0, end: node.text.length }, node)];
|
||||
}
|
||||
|
||||
function parseOldFileOfCurrentEmit(node: UnparsedSource, bundleFileInfo: BundleFileInfo) {
|
||||
Debug.assert(!!node.oldFileOfCurrentEmit);
|
||||
let texts: UnparsedTextLike[] | undefined;
|
||||
let syntheticReferences: UnparsedSyntheticReference[] | undefined;
|
||||
for (const section of bundleFileInfo.sections) {
|
||||
switch (section.kind) {
|
||||
case BundleFileSectionKind.Internal:
|
||||
case BundleFileSectionKind.Text:
|
||||
(texts || (texts = [])).push(createUnparsedNode(section, node) as UnparsedTextLike);
|
||||
break;
|
||||
|
||||
case BundleFileSectionKind.NoDefaultLib:
|
||||
case BundleFileSectionKind.Reference:
|
||||
case BundleFileSectionKind.Type:
|
||||
case BundleFileSectionKind.Lib:
|
||||
(syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
|
||||
break;
|
||||
|
||||
// Ignore
|
||||
case BundleFileSectionKind.Prologue:
|
||||
case BundleFileSectionKind.EmitHelpers:
|
||||
case BundleFileSectionKind.Prepend:
|
||||
break;
|
||||
|
||||
default:
|
||||
Debug.assertNever(section);
|
||||
}
|
||||
}
|
||||
node.texts = texts || emptyArray;
|
||||
node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, name => getAllUnscopedEmitHelpers().get(name)!);
|
||||
node.syntheticReferences = syntheticReferences;
|
||||
return node;
|
||||
}
|
||||
|
||||
function mapBundleFileSectionKindToSyntaxKind(kind: BundleFileSectionKind): SyntaxKind {
|
||||
switch (kind) {
|
||||
case BundleFileSectionKind.Prologue: return SyntaxKind.UnparsedPrologue;
|
||||
case BundleFileSectionKind.Prepend: return SyntaxKind.UnparsedPrepend;
|
||||
case BundleFileSectionKind.Internal: return SyntaxKind.UnparsedInternalText;
|
||||
case BundleFileSectionKind.Text: return SyntaxKind.UnparsedText;
|
||||
|
||||
case BundleFileSectionKind.EmitHelpers:
|
||||
case BundleFileSectionKind.NoDefaultLib:
|
||||
case BundleFileSectionKind.Reference:
|
||||
case BundleFileSectionKind.Type:
|
||||
case BundleFileSectionKind.Lib:
|
||||
return Debug.fail(`BundleFileSectionKind: ${kind} not yet mapped to SyntaxKind`);
|
||||
|
||||
default:
|
||||
return Debug.assertNever(kind);
|
||||
}
|
||||
}
|
||||
|
||||
function createUnparsedNode(section: BundleFileSection, parent: UnparsedSource): UnparsedNode {
|
||||
const node = createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end) as UnparsedNode;
|
||||
node.parent = parent;
|
||||
node.data = section.data;
|
||||
return node;
|
||||
}
|
||||
|
||||
function createUnparsedSyntheticReference(section: BundleFileHasNoDefaultLib | BundleFileReference, parent: UnparsedSource) {
|
||||
const node = createNode(SyntaxKind.UnparsedSyntheticReference, section.pos, section.end) as UnparsedSyntheticReference;
|
||||
node.parent = parent;
|
||||
node.data = section.data;
|
||||
node.section = section;
|
||||
return node;
|
||||
}
|
||||
|
||||
export function createInputFiles(
|
||||
javascript: string,
|
||||
declaration: string
|
||||
javascriptText: string,
|
||||
declarationText: string
|
||||
): InputFiles;
|
||||
export function createInputFiles(
|
||||
javascript: string,
|
||||
declaration: string,
|
||||
readFileText: (path: string) => string | undefined,
|
||||
javascriptPath: string,
|
||||
javascriptMapPath: string | undefined,
|
||||
declarationPath: string,
|
||||
declarationMapPath: string | undefined,
|
||||
buildInfoPath: string | undefined
|
||||
): InputFiles;
|
||||
export function createInputFiles(
|
||||
javascriptText: string,
|
||||
declarationText: string,
|
||||
javascriptMapPath: string | undefined,
|
||||
javascriptMapText: string | undefined,
|
||||
declarationMapPath: string | undefined,
|
||||
declarationMapText: string | undefined
|
||||
): InputFiles;
|
||||
/*@internal*/
|
||||
export function createInputFiles(
|
||||
javascript: string,
|
||||
declaration: string,
|
||||
javascriptText: string,
|
||||
declarationText: string,
|
||||
javascriptMapPath: string | undefined,
|
||||
javascriptMapText: string | undefined,
|
||||
declarationMapPath: string | undefined,
|
||||
declarationMapText: string | undefined,
|
||||
javascriptPath: string | undefined,
|
||||
declarationPath: string | undefined,
|
||||
buildInfoPath?: string | undefined,
|
||||
buildInfo?: BuildInfo,
|
||||
oldFileOfCurrentEmit?: boolean
|
||||
): InputFiles;
|
||||
export function createInputFiles(
|
||||
javascriptTextOrReadFileText: string | ((path: string) => string | undefined),
|
||||
declarationTextOrJavascriptPath: string,
|
||||
javascriptMapPath?: string,
|
||||
javascriptMapText?: string,
|
||||
javascriptMapTextOrDeclarationPath?: string,
|
||||
declarationMapPath?: string,
|
||||
declarationMapText?: string
|
||||
declarationMapTextOrBuildInfoPath?: string,
|
||||
javascriptPath?: string | undefined,
|
||||
declarationPath?: string | undefined,
|
||||
buildInfoPath?: string | undefined,
|
||||
buildInfo?: BuildInfo,
|
||||
oldFileOfCurrentEmit?: boolean
|
||||
): InputFiles {
|
||||
const node = <InputFiles>createNode(SyntaxKind.InputFiles);
|
||||
node.javascriptText = javascript;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.javascriptMapText = javascriptMapText;
|
||||
node.declarationText = declaration;
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.declarationMapText = declarationMapText;
|
||||
if (!isString(javascriptTextOrReadFileText)) {
|
||||
const cache = createMap<string | false>();
|
||||
const textGetter = (path: string | undefined) => {
|
||||
if (path === undefined) return undefined;
|
||||
let value = cache.get(path);
|
||||
if (value === undefined) {
|
||||
value = javascriptTextOrReadFileText(path);
|
||||
cache.set(path, value !== undefined ? value : false);
|
||||
}
|
||||
return value !== false ? value as string : undefined;
|
||||
};
|
||||
const definedTextGetter = (path: string) => {
|
||||
const result = textGetter(path);
|
||||
return result !== undefined ? result : `/* Input file ${path} was missing */\r\n`;
|
||||
};
|
||||
let buildInfo: BuildInfo | false;
|
||||
const getAndCacheBuildInfo = (getText: () => string | undefined) => {
|
||||
if (buildInfo === undefined) {
|
||||
const result = getText();
|
||||
buildInfo = result !== undefined ? getBuildInfo(result) : false;
|
||||
}
|
||||
return buildInfo || undefined;
|
||||
};
|
||||
node.javascriptPath = declarationTextOrJavascriptPath;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.buildInfoPath = declarationMapTextOrBuildInfoPath;
|
||||
Object.defineProperties(node, {
|
||||
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
|
||||
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
|
||||
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
|
||||
declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that
|
||||
buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
|
||||
});
|
||||
}
|
||||
else {
|
||||
node.javascriptText = javascriptTextOrReadFileText;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
|
||||
node.declarationText = declarationTextOrJavascriptPath;
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.declarationMapText = declarationMapTextOrBuildInfoPath;
|
||||
node.javascriptPath = javascriptPath;
|
||||
node.declarationPath = declarationPath,
|
||||
node.buildInfoPath = buildInfoPath;
|
||||
node.buildInfo = buildInfo;
|
||||
node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -2827,7 +3108,7 @@ namespace ts {
|
||||
return node.emitNode = { annotatedNodes: [node] } as EmitNode;
|
||||
}
|
||||
|
||||
const sourceFile = getSourceFileOfNode(node);
|
||||
const sourceFile = getSourceFileOfNode(getParseTreeNode(getSourceFileOfNode(node)));
|
||||
getOrCreateEmitNode(sourceFile).annotatedNodes!.push(node);
|
||||
}
|
||||
|
||||
@@ -3124,7 +3405,7 @@ namespace ts {
|
||||
export const nullTransformationContext: TransformationContext = {
|
||||
enableEmitNotification: noop,
|
||||
enableSubstitution: noop,
|
||||
endLexicalEnvironment: () => undefined,
|
||||
endLexicalEnvironment: returnUndefined,
|
||||
getCompilerOptions: notImplemented,
|
||||
getEmitHost: notImplemented,
|
||||
getEmitResolver: notImplemented,
|
||||
@@ -3325,7 +3606,7 @@ namespace ts {
|
||||
return setEmitFlags(createIdentifier(name), EmitFlags.HelperName | EmitFlags.AdviseOnEmitNode);
|
||||
}
|
||||
|
||||
const valuesHelper: EmitHelper = {
|
||||
export const valuesHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:values",
|
||||
scoped: false,
|
||||
text: `
|
||||
@@ -3353,7 +3634,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
const readHelper: EmitHelper = {
|
||||
export const readHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:read",
|
||||
scoped: false,
|
||||
text: `
|
||||
@@ -3389,7 +3670,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
const spreadHelper: EmitHelper = {
|
||||
export const spreadHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:spread",
|
||||
scoped: false,
|
||||
text: `
|
||||
|
||||
@@ -437,6 +437,8 @@ namespace ts.moduleSpecifiers {
|
||||
case Extension.Jsx:
|
||||
case Extension.Json:
|
||||
return ext;
|
||||
case Extension.TsBuildInfo:
|
||||
return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported:: FileName:: ${fileName}`);
|
||||
default:
|
||||
return Debug.assertNever(ext);
|
||||
}
|
||||
|
||||
+22
-11
@@ -1093,6 +1093,10 @@ namespace ts {
|
||||
return currentToken = scanner.reScanTemplateToken();
|
||||
}
|
||||
|
||||
function reScanLessThanToken(): SyntaxKind {
|
||||
return currentToken = scanner.reScanLessThanToken();
|
||||
}
|
||||
|
||||
function scanJsxIdentifier(): SyntaxKind {
|
||||
return currentToken = scanner.scanJsxIdentifier();
|
||||
}
|
||||
@@ -2276,7 +2280,7 @@ namespace ts {
|
||||
function parseTypeReference(): TypeReferenceNode {
|
||||
const node = <TypeReferenceNode>createNode(SyntaxKind.TypeReference);
|
||||
node.typeName = parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected);
|
||||
if (!scanner.hasPrecedingLineBreak() && token() === SyntaxKind.LessThanToken) {
|
||||
if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === SyntaxKind.LessThanToken) {
|
||||
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
|
||||
}
|
||||
return finishNode(node);
|
||||
@@ -2962,6 +2966,7 @@ namespace ts {
|
||||
case SyntaxKind.NumberKeyword:
|
||||
case SyntaxKind.BigIntKeyword:
|
||||
case SyntaxKind.BooleanKeyword:
|
||||
case SyntaxKind.ReadonlyKeyword:
|
||||
case SyntaxKind.SymbolKeyword:
|
||||
case SyntaxKind.UniqueKeyword:
|
||||
case SyntaxKind.VoidKeyword:
|
||||
@@ -3051,7 +3056,7 @@ namespace ts {
|
||||
return finishNode(postfix);
|
||||
}
|
||||
|
||||
function parseTypeOperator(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword) {
|
||||
function parseTypeOperator(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword) {
|
||||
const node = <TypeOperatorNode>createNode(SyntaxKind.TypeOperator);
|
||||
parseExpected(operator);
|
||||
node.operator = operator;
|
||||
@@ -3073,6 +3078,7 @@ namespace ts {
|
||||
switch (operator) {
|
||||
case SyntaxKind.KeyOfKeyword:
|
||||
case SyntaxKind.UniqueKeyword:
|
||||
case SyntaxKind.ReadonlyKeyword:
|
||||
return parseTypeOperator(operator);
|
||||
case SyntaxKind.InferKeyword:
|
||||
return parseInferType();
|
||||
@@ -4250,7 +4256,8 @@ namespace ts {
|
||||
|
||||
function parseJsxText(): JsxText {
|
||||
const node = <JsxText>createNode(SyntaxKind.JsxText);
|
||||
node.containsOnlyWhiteSpaces = currentToken === SyntaxKind.JsxTextAllWhiteSpaces;
|
||||
node.text = scanner.getTokenValue();
|
||||
node.containsOnlyTriviaWhiteSpaces = currentToken === SyntaxKind.JsxTextAllWhiteSpaces;
|
||||
currentToken = scanner.scanJsxToken();
|
||||
return finishNode(node);
|
||||
}
|
||||
@@ -4523,7 +4530,8 @@ namespace ts {
|
||||
function parseCallExpressionRest(expression: LeftHandSideExpression): LeftHandSideExpression {
|
||||
while (true) {
|
||||
expression = parseMemberExpressionRest(expression);
|
||||
if (token() === SyntaxKind.LessThanToken) {
|
||||
// handle 'foo<<T>()'
|
||||
if (token() === SyntaxKind.LessThanToken || token() === SyntaxKind.LessThanLessThanToken) {
|
||||
// See if this is the start of a generic invocation. If so, consume it and
|
||||
// keep checking for postfix expressions. Otherwise, it's just a '<' that's
|
||||
// part of an arithmetic expression. Break out so we consume it higher in the
|
||||
@@ -4565,9 +4573,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
function parseTypeArgumentsInExpression() {
|
||||
if (!parseOptional(SyntaxKind.LessThanToken)) {
|
||||
if (reScanLessThanToken() !== SyntaxKind.LessThanToken) {
|
||||
return undefined;
|
||||
}
|
||||
nextToken();
|
||||
|
||||
const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType);
|
||||
if (!parseExpected(SyntaxKind.GreaterThanToken)) {
|
||||
@@ -7754,6 +7763,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
type PragmaDiagnosticReporter = (pos: number, length: number, message: DiagnosticMessage) => void;
|
||||
|
||||
/*@internal*/
|
||||
@@ -7774,17 +7784,18 @@ namespace ts {
|
||||
const libReferenceDirectives = context.libReferenceDirectives;
|
||||
forEach(toArray(entryOrList), (arg: PragmaPseudoMap["reference"]) => {
|
||||
// TODO: GH#18217
|
||||
const { types, lib, path } = arg!.arguments;
|
||||
if (arg!.arguments["no-default-lib"]) {
|
||||
context.hasNoDefaultLib = true;
|
||||
}
|
||||
else if (arg!.arguments.types) {
|
||||
typeReferenceDirectives.push({ pos: arg!.arguments.types!.pos, end: arg!.arguments.types!.end, fileName: arg!.arguments.types!.value });
|
||||
else if (types) {
|
||||
typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value });
|
||||
}
|
||||
else if (arg!.arguments.lib) {
|
||||
libReferenceDirectives.push({ pos: arg!.arguments.lib!.pos, end: arg!.arguments.lib!.end, fileName: arg!.arguments.lib!.value });
|
||||
else if (lib) {
|
||||
libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
|
||||
}
|
||||
else if (arg!.arguments.path) {
|
||||
referencedFiles.push({ pos: arg!.arguments.path!.pos, end: arg!.arguments.path!.end, fileName: arg!.arguments.path!.value });
|
||||
else if (path) {
|
||||
referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value });
|
||||
}
|
||||
else {
|
||||
reportDiagnostic(arg!.range.pos, arg!.range.end - arg!.range.pos, Diagnostics.Invalid_reference_directive_syntax);
|
||||
|
||||
+154
-87
@@ -69,6 +69,7 @@ namespace ts {
|
||||
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
|
||||
return createCompilerHostWorker(options, setParentNodes);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
// TODO(shkamat): update this after reworking ts build API
|
||||
export function createCompilerHostWorker(options: CompilerOptions, setParentNodes?: boolean, system = sys): CompilerHost {
|
||||
@@ -93,7 +94,6 @@ namespace ts {
|
||||
}
|
||||
text = "";
|
||||
}
|
||||
|
||||
return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
|
||||
}
|
||||
|
||||
@@ -204,17 +204,25 @@ namespace ts {
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export function changeCompilerHostToUseCache(
|
||||
host: CompilerHost,
|
||||
interface CompilerHostLikeForCache {
|
||||
fileExists(fileName: string): boolean;
|
||||
readFile(fileName: string, encoding?: string): string | undefined;
|
||||
directoryExists?(directory: string): boolean;
|
||||
createDirectory?(directory: string): void;
|
||||
writeFile?: WriteFileCallback;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export function changeCompilerHostLikeToUseCache(
|
||||
host: CompilerHostLikeForCache,
|
||||
toPath: (fileName: string) => Path,
|
||||
useCacheForSourceFile: boolean
|
||||
getSourceFile?: CompilerHost["getSourceFile"]
|
||||
) {
|
||||
const originalReadFile = host.readFile;
|
||||
const originalFileExists = host.fileExists;
|
||||
const originalDirectoryExists = host.directoryExists;
|
||||
const originalCreateDirectory = host.createDirectory;
|
||||
const originalWriteFile = host.writeFile;
|
||||
const originalGetSourceFile = host.getSourceFile;
|
||||
const readFileCache = createMap<string | false>();
|
||||
const fileExistsCache = createMap<boolean>();
|
||||
const directoryExistsCache = createMap<boolean>();
|
||||
@@ -223,38 +231,37 @@ namespace ts {
|
||||
const readFileWithCache = (fileName: string): string | undefined => {
|
||||
const key = toPath(fileName);
|
||||
const value = readFileCache.get(key);
|
||||
if (value !== undefined) return value || undefined;
|
||||
if (value !== undefined) return value !== false ? value : undefined;
|
||||
return setReadFileCache(key, fileName);
|
||||
};
|
||||
const setReadFileCache = (key: Path, fileName: string) => {
|
||||
const newValue = originalReadFile.call(host, fileName);
|
||||
readFileCache.set(key, newValue || false);
|
||||
readFileCache.set(key, newValue !== undefined ? newValue : false);
|
||||
return newValue;
|
||||
};
|
||||
host.readFile = fileName => {
|
||||
const key = toPath(fileName);
|
||||
const value = readFileCache.get(key);
|
||||
if (value !== undefined) return value; // could be .d.ts from output
|
||||
if (!fileExtensionIs(fileName, Extension.Json)) {
|
||||
if (value !== undefined) return value !== false ? value : undefined; // could be .d.ts from output
|
||||
// Cache json or buildInfo
|
||||
if (!fileExtensionIs(fileName, Extension.Json) && !isBuildInfoFile(fileName)) {
|
||||
return originalReadFile.call(host, fileName);
|
||||
}
|
||||
|
||||
return setReadFileCache(key, fileName);
|
||||
};
|
||||
|
||||
if (useCacheForSourceFile) {
|
||||
host.getSourceFile = (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
|
||||
const key = toPath(fileName);
|
||||
const value = sourceFileCache.get(key);
|
||||
if (value) return value;
|
||||
const getSourceFileWithCache: CompilerHost["getSourceFile"] | undefined = getSourceFile ? (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
|
||||
const key = toPath(fileName);
|
||||
const value = sourceFileCache.get(key);
|
||||
if (value) return value;
|
||||
|
||||
const sourceFile = originalGetSourceFile.call(host, fileName, languageVersion, onError, shouldCreateNewSourceFile);
|
||||
if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, Extension.Json))) {
|
||||
sourceFileCache.set(key, sourceFile);
|
||||
}
|
||||
return sourceFile;
|
||||
};
|
||||
}
|
||||
const sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
|
||||
if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, Extension.Json))) {
|
||||
sourceFileCache.set(key, sourceFile);
|
||||
}
|
||||
return sourceFile;
|
||||
} : undefined;
|
||||
|
||||
// fileExists for any kind of extension
|
||||
host.fileExists = fileName => {
|
||||
@@ -265,23 +272,25 @@ namespace ts {
|
||||
fileExistsCache.set(key, !!newValue);
|
||||
return newValue;
|
||||
};
|
||||
host.writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
|
||||
const key = toPath(fileName);
|
||||
fileExistsCache.delete(key);
|
||||
if (originalWriteFile) {
|
||||
host.writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
|
||||
const key = toPath(fileName);
|
||||
fileExistsCache.delete(key);
|
||||
|
||||
const value = readFileCache.get(key);
|
||||
if (value && value !== data) {
|
||||
readFileCache.delete(key);
|
||||
sourceFileCache.delete(key);
|
||||
}
|
||||
else if (useCacheForSourceFile) {
|
||||
const sourceFile = sourceFileCache.get(key);
|
||||
if (sourceFile && sourceFile.text !== data) {
|
||||
const value = readFileCache.get(key);
|
||||
if (value !== undefined && value !== data) {
|
||||
readFileCache.delete(key);
|
||||
sourceFileCache.delete(key);
|
||||
}
|
||||
}
|
||||
originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
|
||||
};
|
||||
else if (getSourceFileWithCache) {
|
||||
const sourceFile = sourceFileCache.get(key);
|
||||
if (sourceFile && sourceFile.text !== data) {
|
||||
sourceFileCache.delete(key);
|
||||
}
|
||||
}
|
||||
originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
|
||||
};
|
||||
}
|
||||
|
||||
// directoryExists
|
||||
if (originalDirectoryExists && originalCreateDirectory) {
|
||||
@@ -306,7 +315,7 @@ namespace ts {
|
||||
originalDirectoryExists,
|
||||
originalCreateDirectory,
|
||||
originalWriteFile,
|
||||
originalGetSourceFile,
|
||||
getSourceFileWithCache,
|
||||
readFileWithCache
|
||||
};
|
||||
}
|
||||
@@ -735,7 +744,7 @@ namespace ts {
|
||||
performance.mark("beforeProgram");
|
||||
|
||||
const host = createProgramOptions.host || createCompilerHost(options);
|
||||
const configParsingHost = parseConfigHostFromCompilerHost(host);
|
||||
const configParsingHost = parseConfigHostFromCompilerHostLike(host);
|
||||
|
||||
let skipDefaultLib = options.noLib;
|
||||
const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options));
|
||||
@@ -816,11 +825,16 @@ namespace ts {
|
||||
}
|
||||
if (rootNames.length) {
|
||||
for (const parsedRef of resolvedProjectReferences) {
|
||||
if (parsedRef) {
|
||||
const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
|
||||
if (out) {
|
||||
const dtsOutfile = changeExtension(out, ".d.ts");
|
||||
processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
if (!parsedRef) continue;
|
||||
const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
|
||||
if (out) {
|
||||
processSourceFile(changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
}
|
||||
else if (getEmitModuleKind(parsedRef.commandLine.options) === ModuleKind.None) {
|
||||
for (const fileName of parsedRef.commandLine.fileNames) {
|
||||
if (!fileExtensionIs(fileName, Extension.Dts) && hasTSFileExtension(fileName)) {
|
||||
processSourceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -930,7 +944,8 @@ namespace ts {
|
||||
getProjectReferenceRedirect,
|
||||
getResolvedProjectReferenceToRedirect,
|
||||
getResolvedProjectReferenceByPath,
|
||||
forEachResolvedProjectReference
|
||||
forEachResolvedProjectReference,
|
||||
emitBuildInfo
|
||||
};
|
||||
|
||||
verifyCompilerOptions();
|
||||
@@ -964,7 +979,7 @@ namespace ts {
|
||||
|
||||
function getCommonSourceDirectory() {
|
||||
if (commonSourceDirectory === undefined) {
|
||||
const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary));
|
||||
const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect));
|
||||
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
|
||||
// If a rootDir is specified use it as the commonSourceDirectory
|
||||
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
|
||||
@@ -1410,6 +1425,7 @@ namespace ts {
|
||||
getSourceFiles: program.getSourceFiles,
|
||||
getLibFileFromReference: program.getLibFileFromReference,
|
||||
isSourceFileFromExternalLibrary,
|
||||
getResolvedProjectReferenceToRedirect,
|
||||
writeFile: writeFileCallback || (
|
||||
(fileName, data, writeByteOrderMark, onError, sourceFiles) => host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles)),
|
||||
isEmitBlocked,
|
||||
@@ -1424,9 +1440,28 @@ namespace ts {
|
||||
},
|
||||
...(host.directoryExists ? { directoryExists: f => host.directoryExists!(f) } : {}),
|
||||
useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
|
||||
getProgramBuildInfo: () => program.getProgramBuildInfo && program.getProgramBuildInfo()
|
||||
};
|
||||
}
|
||||
|
||||
function emitBuildInfo(writeFileCallback?: WriteFileCallback): EmitResult {
|
||||
Debug.assert(!options.out && !options.outFile);
|
||||
performance.mark("beforeEmit");
|
||||
const emitResult = emitFiles(
|
||||
notImplementedResolver,
|
||||
getEmitHost(writeFileCallback),
|
||||
/*targetSourceFile*/ undefined,
|
||||
/*emitOnlyDtsFiles*/ false,
|
||||
/*transformers*/ undefined,
|
||||
/*declaraitonTransformers*/ undefined,
|
||||
/*onlyBuildInfo*/ true
|
||||
);
|
||||
|
||||
performance.mark("afterEmit");
|
||||
performance.measure("Emit", "beforeEmit", "afterEmit");
|
||||
return emitResult;
|
||||
}
|
||||
|
||||
function getResolvedProjectReferences() {
|
||||
return resolvedProjectReferences;
|
||||
}
|
||||
@@ -1435,32 +1470,16 @@ namespace ts {
|
||||
return projectReferences;
|
||||
}
|
||||
|
||||
function getPrependNodes(): InputFiles[] {
|
||||
if (!projectReferences) {
|
||||
return emptyArray;
|
||||
}
|
||||
|
||||
const nodes: InputFiles[] = [];
|
||||
for (let i = 0; i < projectReferences.length; i++) {
|
||||
const ref = projectReferences[i];
|
||||
const resolvedRefOpts = resolvedProjectReferences![i]!.commandLine;
|
||||
if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
|
||||
const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
|
||||
// Upstream project didn't have outFile set -- skip (error will have been issued earlier)
|
||||
if (!out) continue;
|
||||
|
||||
const dtsFilename = changeExtension(out, ".d.ts");
|
||||
const js = host.readFile(out) || `/* Input file ${out} was missing */\r\n`;
|
||||
const jsMapPath = out + ".map"; // TODO: try to read sourceMappingUrl comment from the file
|
||||
const jsMap = host.readFile(jsMapPath);
|
||||
const dts = host.readFile(dtsFilename) || `/* Input file ${dtsFilename} was missing */\r\n`;
|
||||
const dtsMapPath = dtsFilename + ".map";
|
||||
const dtsMap = host.readFile(dtsMapPath);
|
||||
const node = createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap);
|
||||
nodes.push(node);
|
||||
function getPrependNodes() {
|
||||
return createPrependNodes(
|
||||
projectReferences,
|
||||
(_ref, index) => resolvedProjectReferences![index]!.commandLine,
|
||||
fileName => {
|
||||
const path = toPath(fileName);
|
||||
const sourceFile = getSourceFileByPath(path);
|
||||
return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
);
|
||||
}
|
||||
|
||||
function isSourceFileFromExternalLibrary(file: SourceFile): boolean {
|
||||
@@ -1557,7 +1576,7 @@ namespace ts {
|
||||
const emitResult = emitFiles(
|
||||
emitResolver,
|
||||
getEmitHost(writeFileCallback),
|
||||
sourceFile!, // TODO: GH#18217
|
||||
sourceFile,
|
||||
emitOnlyDtsFiles,
|
||||
transformers,
|
||||
customTransformers && customTransformers.afterDeclarations
|
||||
@@ -2227,8 +2246,9 @@ namespace ts {
|
||||
processReferencedFiles(file, isDefaultLib);
|
||||
processTypeReferenceDirectives(file);
|
||||
}
|
||||
|
||||
processLibReferenceDirectives(file);
|
||||
if (!options.noLib) {
|
||||
processLibReferenceDirectives(file);
|
||||
}
|
||||
|
||||
modulesWithElidedImports.set(file.path, false);
|
||||
processImportedModules(file);
|
||||
@@ -2315,8 +2335,10 @@ namespace ts {
|
||||
processReferencedFiles(file, isDefaultLib);
|
||||
processTypeReferenceDirectives(file);
|
||||
}
|
||||
if (!options.noLib) {
|
||||
processLibReferenceDirectives(file);
|
||||
}
|
||||
|
||||
processLibReferenceDirectives(file);
|
||||
|
||||
// always process imported modules to record module name resolutions
|
||||
processImportedModules(file);
|
||||
@@ -2357,7 +2379,7 @@ namespace ts {
|
||||
const out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
|
||||
return out ?
|
||||
changeExtension(out, Extension.Dts) :
|
||||
getOutputDeclarationFileName(fileName, referencedProject.commandLine);
|
||||
getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2704,19 +2726,29 @@ namespace ts {
|
||||
if (options.declaration === false) {
|
||||
createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
|
||||
}
|
||||
if (options.incremental === false) {
|
||||
createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
|
||||
}
|
||||
}
|
||||
|
||||
if (options.tsBuildInfoFile) {
|
||||
if (!isIncrementalCompilation(options)) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
|
||||
}
|
||||
}
|
||||
|
||||
verifyProjectReferences();
|
||||
|
||||
// List of collected files is complete; validate exhautiveness if this is a project with a file list
|
||||
if (options.composite) {
|
||||
const sourceFiles = files.filter(f => !f.isDeclarationFile);
|
||||
if (rootNames.length < sourceFiles.length) {
|
||||
const normalizedRootNames = rootNames.map(r => normalizePath(r).toLowerCase());
|
||||
for (const file of sourceFiles.map(f => normalizePath(f.path).toLowerCase())) {
|
||||
if (normalizedRootNames.indexOf(file) === -1) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file));
|
||||
}
|
||||
const rootPaths = rootNames.map(toPath);
|
||||
for (const file of files) {
|
||||
// Ignore declaration files
|
||||
if (file.isDeclarationFile) continue;
|
||||
// Ignore json file thats from project reference
|
||||
if (isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName)) continue;
|
||||
if (rootPaths.indexOf(file.path) === -1) {
|
||||
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2925,6 +2957,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function verifyProjectReferences() {
|
||||
const buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? getOutputPathForBuildInfo(options) : undefined;
|
||||
forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => {
|
||||
const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index];
|
||||
const parentFile = parent && parent.sourceFile as JsonSourceFile;
|
||||
@@ -2951,6 +2984,10 @@ namespace ts {
|
||||
createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
|
||||
}
|
||||
}
|
||||
if (!parent && buildInfoPath && buildInfoPath === getOutputPathForBuildInfo(options)) {
|
||||
createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
|
||||
hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3101,18 +3138,29 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
interface CompilerHostLike {
|
||||
useCaseSensitiveFileNames(): boolean;
|
||||
getCurrentDirectory(): string;
|
||||
fileExists(fileName: string): boolean;
|
||||
readFile(fileName: string): string | undefined;
|
||||
readDirectory?(rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number): string[];
|
||||
trace?(s: string): void;
|
||||
onUnRecoverableConfigFileDiagnostic?: DiagnosticReporter;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function parseConfigHostFromCompilerHost(host: CompilerHost): ParseConfigFileHost {
|
||||
export function parseConfigHostFromCompilerHostLike(host: CompilerHostLike, directoryStructureHost: DirectoryStructureHost = host): ParseConfigFileHost {
|
||||
return {
|
||||
fileExists: f => host.fileExists(f),
|
||||
fileExists: f => directoryStructureHost.fileExists(f),
|
||||
readDirectory(root, extensions, excludes, includes, depth) {
|
||||
Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return host.readDirectory!(root, extensions, excludes, includes, depth);
|
||||
Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
|
||||
return directoryStructureHost.readDirectory!(root, extensions, excludes, includes, depth);
|
||||
},
|
||||
readFile: f => host.readFile(f),
|
||||
readFile: f => directoryStructureHost.readFile(f),
|
||||
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
|
||||
getCurrentDirectory: () => host.getCurrentDirectory(),
|
||||
onUnRecoverableConfigFileDiagnostic: () => undefined,
|
||||
onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || returnUndefined,
|
||||
trace: host.trace ? (s) => host.trace!(s) : undefined
|
||||
};
|
||||
}
|
||||
@@ -3122,6 +3170,25 @@ namespace ts {
|
||||
fileExists(fileName: string): boolean;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function createPrependNodes(projectReferences: ReadonlyArray<ProjectReference> | undefined, getCommandLine: (ref: ProjectReference, index: number) => ParsedCommandLine | undefined, readFile: (path: string) => string | undefined) {
|
||||
if (!projectReferences) return emptyArray;
|
||||
let nodes: InputFiles[] | undefined;
|
||||
for (let i = 0; i < projectReferences.length; i++) {
|
||||
const ref = projectReferences[i];
|
||||
const resolvedRefOpts = getCommandLine(ref, i);
|
||||
if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
|
||||
const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
|
||||
// Upstream project didn't have outFile set -- skip (error will have been issued earlier)
|
||||
if (!out) continue;
|
||||
|
||||
const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true);
|
||||
const node = createInputFiles(readFile, jsFilePath!, sourceMapFilePath, declarationFilePath!, declarationMapPath, buildInfoPath);
|
||||
(nodes || (nodes = [])).push(node);
|
||||
}
|
||||
}
|
||||
return nodes || emptyArray;
|
||||
}
|
||||
/**
|
||||
* Returns the target config filename of a project reference.
|
||||
* Note: The file might not exist.
|
||||
|
||||
@@ -71,8 +71,8 @@ namespace ts {
|
||||
nonRecursive?: boolean;
|
||||
}
|
||||
|
||||
export function isPathInNodeModulesStartingWithDot(path: Path) {
|
||||
return stringContains(path, "/node_modules/.");
|
||||
export function isPathIgnored(path: Path) {
|
||||
return some(ignoredPaths, searchPath => stringContains(path, searchPath));
|
||||
}
|
||||
|
||||
export const maxNumberOfFilesToIterateForInvalidation = 256;
|
||||
@@ -696,7 +696,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
// If something to do with folder/file starting with "." in node_modules folder, skip it
|
||||
if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return false;
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return false;
|
||||
|
||||
// Some file or directory in the watching directory is created
|
||||
// Return early if it does not have any of the watching extension or not the custom failed lookup path
|
||||
|
||||
+23
-3
@@ -31,6 +31,7 @@ namespace ts {
|
||||
scanJsxIdentifier(): SyntaxKind;
|
||||
scanJsxAttributeValue(): SyntaxKind;
|
||||
reScanJsxToken(): JsxTokenSyntaxKind;
|
||||
reScanLessThanToken(): SyntaxKind;
|
||||
scanJsxToken(): JsxTokenSyntaxKind;
|
||||
scanJSDocToken(): JsDocSyntaxKind;
|
||||
scan(): SyntaxKind;
|
||||
@@ -622,13 +623,15 @@ namespace ts {
|
||||
|
||||
const shebangTriviaRegex = /^#!.*/;
|
||||
|
||||
function isShebangTrivia(text: string, pos: number) {
|
||||
/*@internal*/
|
||||
export function isShebangTrivia(text: string, pos: number) {
|
||||
// Shebangs check must only be done at the start of the file
|
||||
Debug.assert(pos === 0);
|
||||
return shebangTriviaRegex.test(text);
|
||||
}
|
||||
|
||||
function scanShebangTrivia(text: string, pos: number) {
|
||||
/*@internal*/
|
||||
export function scanShebangTrivia(text: string, pos: number) {
|
||||
const shebang = shebangTriviaRegex.exec(text)![0];
|
||||
pos = pos + shebang.length;
|
||||
return pos;
|
||||
@@ -660,8 +663,15 @@ namespace ts {
|
||||
let pendingKind!: CommentKind;
|
||||
let pendingHasTrailingNewLine!: boolean;
|
||||
let hasPendingCommentRange = false;
|
||||
let collecting = trailing || pos === 0;
|
||||
let collecting = trailing;
|
||||
let accumulator = initial;
|
||||
if (pos === 0) {
|
||||
collecting = true;
|
||||
const shebang = getShebang(text);
|
||||
if (shebang) {
|
||||
pos = shebang.length;
|
||||
}
|
||||
}
|
||||
scan: while (pos >= 0 && pos < text.length) {
|
||||
const ch = text.charCodeAt(pos);
|
||||
switch (ch) {
|
||||
@@ -874,6 +884,7 @@ namespace ts {
|
||||
scanJsxIdentifier,
|
||||
scanJsxAttributeValue,
|
||||
reScanJsxToken,
|
||||
reScanLessThanToken,
|
||||
scanJsxToken,
|
||||
scanJSDocToken,
|
||||
scan,
|
||||
@@ -1939,6 +1950,14 @@ namespace ts {
|
||||
return token = scanJsxToken();
|
||||
}
|
||||
|
||||
function reScanLessThanToken(): SyntaxKind {
|
||||
if (token === SyntaxKind.LessThanLessThanToken) {
|
||||
pos = tokenPos + 1;
|
||||
return token = SyntaxKind.LessThanToken;
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
function scanJsxToken(): JsxTokenSyntaxKind {
|
||||
startPos = tokenPos = pos;
|
||||
|
||||
@@ -1994,6 +2013,7 @@ namespace ts {
|
||||
pos++;
|
||||
}
|
||||
|
||||
tokenValue = text.substring(startPos, pos);
|
||||
return firstNonWhitespace === -1 ? SyntaxKind.JsxTextAllWhiteSpaces : SyntaxKind.JsxText;
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ namespace ts {
|
||||
exit();
|
||||
}
|
||||
|
||||
function appendSourceMap(generatedLine: number, generatedCharacter: number, map: RawSourceMap, sourceMapPath: string) {
|
||||
function appendSourceMap(generatedLine: number, generatedCharacter: number, map: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter) {
|
||||
Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
|
||||
Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
|
||||
enter();
|
||||
@@ -149,6 +149,17 @@ namespace ts {
|
||||
let nameIndexToNewNameIndexMap: number[] | undefined;
|
||||
const mappingIterator = decodeMappings(map.mappings);
|
||||
for (let { value: raw, done } = mappingIterator.next(); !done; { value: raw, done } = mappingIterator.next()) {
|
||||
if (end && (
|
||||
raw.generatedLine > end.line ||
|
||||
(raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (start && (
|
||||
raw.generatedLine < start.line ||
|
||||
(start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
|
||||
continue;
|
||||
}
|
||||
// Then reencode all the updated mappings into the overall map
|
||||
let newSourceIndex: number | undefined;
|
||||
let newSourceLine: number | undefined;
|
||||
@@ -178,8 +189,10 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const newGeneratedLine = raw.generatedLine + generatedLine;
|
||||
const newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
|
||||
const rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
|
||||
const newGeneratedLine = rawGeneratedLine + generatedLine;
|
||||
const rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
|
||||
const newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
|
||||
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
|
||||
}
|
||||
exit();
|
||||
|
||||
+102
-19
@@ -2,6 +2,19 @@ declare function setTimeout(handler: (...args: any[]) => void, timeout: number):
|
||||
declare function clearTimeout(handle: any): void;
|
||||
|
||||
namespace ts {
|
||||
/**
|
||||
* djb2 hashing algorithm
|
||||
* http://www.cse.yorku.ca/~oz/hash.html
|
||||
*/
|
||||
/* @internal */
|
||||
export function generateDjb2Hash(data: string): string {
|
||||
let acc = 5381;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
acc = ((acc << 5) + acc) + data.charCodeAt(i);
|
||||
}
|
||||
return acc.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a high stack trace limit to provide more information in case of an error.
|
||||
* Called for command-line and server use cases.
|
||||
@@ -316,6 +329,9 @@ namespace ts {
|
||||
: FileWatcherEventKind.Changed;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export const ignoredPaths = ["/node_modules/.", "/.git"];
|
||||
|
||||
/*@internal*/
|
||||
export interface RecursiveDirectoryWatcherHost {
|
||||
watchDirectory: HostWatchDirectory;
|
||||
@@ -361,6 +377,8 @@ namespace ts {
|
||||
else {
|
||||
directoryWatcher = {
|
||||
watcher: host.watchDirectory(dirName, fileName => {
|
||||
if (isIgnoredPath(fileName)) return;
|
||||
|
||||
// Call the actual callback
|
||||
callbackCache.forEach((callbacks, rootDirName) => {
|
||||
if (rootDirName === dirPath || (startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === directorySeparator)) {
|
||||
@@ -416,7 +434,7 @@ namespace ts {
|
||||
const childFullName = getNormalizedAbsolutePath(child, parentDir);
|
||||
// Filter our the symbolic link directories since those arent included in recursive watch
|
||||
// which is same behaviour when recursive: true is passed to fs.watch
|
||||
return filePathComparer(childFullName, normalizePath(host.realpath(childFullName))) === Comparison.EqualTo ? childFullName : undefined;
|
||||
return !isIgnoredPath(childFullName) && filePathComparer(childFullName, normalizePath(host.realpath(childFullName))) === Comparison.EqualTo ? childFullName : undefined;
|
||||
}) : emptyArray,
|
||||
existingChildWatches,
|
||||
(child, childWatcher) => filePathComparer(child, childWatcher.dirName),
|
||||
@@ -442,8 +460,78 @@ namespace ts {
|
||||
(newChildWatches || (newChildWatches = [])).push(childWatcher);
|
||||
}
|
||||
}
|
||||
|
||||
function isIgnoredPath(path: string) {
|
||||
return some(ignoredPaths, searchPath => isInPath(path, searchPath));
|
||||
}
|
||||
|
||||
function isInPath(path: string, searchPath: string) {
|
||||
if (stringContains(path, searchPath)) return true;
|
||||
if (host.useCaseSensitiveFileNames) return false;
|
||||
return stringContains(toCanonicalFilePath(path), searchPath);
|
||||
}
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
interface NodeBuffer extends Uint8Array {
|
||||
write(str: string, offset?: number, length?: number, encoding?: string): number;
|
||||
toString(encoding?: string, start?: number, end?: number): string;
|
||||
toJSON(): { type: "Buffer", data: any[] };
|
||||
equals(otherBuffer: Buffer): boolean;
|
||||
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
||||
slice(start?: number, end?: number): Buffer;
|
||||
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
|
||||
readUInt8(offset: number, noAssert?: boolean): number;
|
||||
readUInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readUInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readInt8(offset: number, noAssert?: boolean): number;
|
||||
readInt16LE(offset: number, noAssert?: boolean): number;
|
||||
readInt16BE(offset: number, noAssert?: boolean): number;
|
||||
readInt32LE(offset: number, noAssert?: boolean): number;
|
||||
readInt32BE(offset: number, noAssert?: boolean): number;
|
||||
readFloatLE(offset: number, noAssert?: boolean): number;
|
||||
readFloatBE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleLE(offset: number, noAssert?: boolean): number;
|
||||
readDoubleBE(offset: number, noAssert?: boolean): number;
|
||||
swap16(): Buffer;
|
||||
swap32(): Buffer;
|
||||
swap64(): Buffer;
|
||||
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt8(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
|
||||
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
|
||||
fill(value: any, offset?: number, end?: number): this;
|
||||
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
|
||||
entries(): IterableIterator<[number, number]>;
|
||||
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
|
||||
keys(): IterableIterator<number>;
|
||||
values(): IterableIterator<number>;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
interface Buffer extends NodeBuffer { }
|
||||
|
||||
// TODO: GH#18217 Methods on System are often used as if they are certainly defined
|
||||
export interface System {
|
||||
args: string[];
|
||||
@@ -605,7 +693,17 @@ namespace ts {
|
||||
directoryExists,
|
||||
createDirectory(directoryName: string) {
|
||||
if (!nodeSystem.directoryExists(directoryName)) {
|
||||
_fs.mkdirSync(directoryName);
|
||||
// Wrapped in a try-catch to prevent crashing if we are in a race
|
||||
// with another copy of ourselves to create the same directory
|
||||
try {
|
||||
_fs.mkdirSync(directoryName);
|
||||
}
|
||||
catch (e) {
|
||||
if (e.code !== "EEXIST") {
|
||||
// Failed for some other reason (access denied?); still throw
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
getExecutingFilePath() {
|
||||
@@ -622,7 +720,7 @@ namespace ts {
|
||||
getModifiedTime,
|
||||
setModifiedTime,
|
||||
deleteFile,
|
||||
createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash,
|
||||
createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
|
||||
createSHA256Hash: _crypto ? createSHA256Hash : undefined,
|
||||
getMemoryUsage() {
|
||||
if (global.gc) {
|
||||
@@ -1050,7 +1148,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function readDirectory(path: string, extensions?: ReadonlyArray<string>, excludes?: ReadonlyArray<string>, includes?: ReadonlyArray<string>, depth?: number): string[] {
|
||||
return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries);
|
||||
return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
|
||||
}
|
||||
|
||||
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
|
||||
@@ -1115,21 +1213,6 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* djb2 hashing algorithm
|
||||
* http://www.cse.yorku.ca/~oz/hash.html
|
||||
*/
|
||||
function generateDjb2Hash(data: string): string {
|
||||
const chars = data.split("").map(str => str.charCodeAt(0));
|
||||
return `${chars.reduce((prev, curr) => ((prev << 5) + prev) + curr, 5381)}`;
|
||||
}
|
||||
|
||||
function createMD5HashUsingNativeCrypto(data: string): string {
|
||||
const hash = _crypto!.createHash("md5");
|
||||
hash.update(data);
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
||||
function createSHA256Hash(data: string): string {
|
||||
const hash = _crypto!.createHash("sha256");
|
||||
hash.update(data);
|
||||
|
||||
@@ -42,6 +42,14 @@ namespace ts {
|
||||
transformers.push(transformESNext);
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ES2019) {
|
||||
transformers.push(transformES2019);
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ES2018) {
|
||||
transformers.push(transformES2018);
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ES2017) {
|
||||
transformers.push(transformES2017);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,34 @@ namespace ts {
|
||||
return result.diagnostics;
|
||||
}
|
||||
|
||||
function hasInternalAnnotation(range: CommentRange, currentSourceFile: SourceFile) {
|
||||
const comment = currentSourceFile.text.substring(range.pos, range.end);
|
||||
return stringContains(comment, "@internal");
|
||||
}
|
||||
|
||||
export function isInternalDeclaration(node: Node, currentSourceFile: SourceFile) {
|
||||
const parseTreeNode = getParseTreeNode(node);
|
||||
if (parseTreeNode && parseTreeNode.kind === SyntaxKind.Parameter) {
|
||||
const paramIdx = (parseTreeNode.parent as FunctionLike).parameters.indexOf(parseTreeNode as ParameterDeclaration);
|
||||
const previousSibling = paramIdx > 0 ? (parseTreeNode.parent as FunctionLike).parameters[paramIdx - 1] : undefined;
|
||||
const text = currentSourceFile.text;
|
||||
const commentRanges = previousSibling
|
||||
? concatenate(
|
||||
// to handle
|
||||
// ... parameters, /* @internal */
|
||||
// public param: string
|
||||
getTrailingCommentRanges(text, skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)),
|
||||
getLeadingCommentRanges(text, node.pos)
|
||||
)
|
||||
: getTrailingCommentRanges(text, skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
|
||||
return commentRanges && commentRanges.length && hasInternalAnnotation(last(commentRanges), currentSourceFile);
|
||||
}
|
||||
const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
|
||||
return !!forEach(leadingCommentRanges, range => {
|
||||
return hasInternalAnnotation(range, currentSourceFile);
|
||||
});
|
||||
}
|
||||
|
||||
const declarationEmitNodeBuilderFlags =
|
||||
NodeBuilderFlags.MultilineObjectLiterals |
|
||||
NodeBuilderFlags.WriteClassExpressionAsTypeLiteral |
|
||||
@@ -61,7 +89,7 @@ namespace ts {
|
||||
const { noResolve, stripInternal } = options;
|
||||
return transformRoot;
|
||||
|
||||
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[] | undefined): void {
|
||||
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: ReadonlyArray<string> | undefined): void {
|
||||
if (!typeReferenceDirectives) {
|
||||
return;
|
||||
}
|
||||
@@ -207,8 +235,14 @@ namespace ts {
|
||||
}
|
||||
), mapDefined(node.prepends, prepend => {
|
||||
if (prepend.kind === SyntaxKind.InputFiles) {
|
||||
return createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText);
|
||||
const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal);
|
||||
hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib;
|
||||
collectReferences(sourceFile, refs);
|
||||
recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
|
||||
collectLibs(sourceFile, libs);
|
||||
return sourceFile;
|
||||
}
|
||||
return prepend;
|
||||
}));
|
||||
bundle.syntheticFileReferences = [];
|
||||
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
|
||||
@@ -311,8 +345,8 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function collectReferences(sourceFile: SourceFile, ret: Map<SourceFile>) {
|
||||
if (noResolve || isSourceFileJS(sourceFile)) return ret;
|
||||
function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: Map<SourceFile>) {
|
||||
if (noResolve || (!isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile))) return ret;
|
||||
forEach(sourceFile.referencedFiles, f => {
|
||||
const elem = tryResolveScriptReference(host, sourceFile, f);
|
||||
if (elem) {
|
||||
@@ -322,7 +356,7 @@ namespace ts {
|
||||
return ret;
|
||||
}
|
||||
|
||||
function collectLibs(sourceFile: SourceFile, ret: Map<boolean>) {
|
||||
function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: Map<boolean>) {
|
||||
forEach(sourceFile.libReferenceDirectives, ref => {
|
||||
const lib = host.getLibFileFromReference(ref);
|
||||
if (lib) {
|
||||
@@ -634,7 +668,10 @@ namespace ts {
|
||||
if (!isLateVisibilityPaintedStatement(i)) {
|
||||
return Debug.fail(`Late replaced statement was found which is not handled by the declaration transformer!: ${(ts as any).SyntaxKind ? (ts as any).SyntaxKind[(i as any).kind] : (i as any).kind}`);
|
||||
}
|
||||
const priorNeedsDeclare = needsDeclare;
|
||||
needsDeclare = i.parent && isSourceFile(i.parent) && !(isExternalModule(i.parent) && isBundledEmit);
|
||||
const result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
|
||||
needsDeclare = priorNeedsDeclare;
|
||||
lateStatementReplacementMap.set("" + getOriginalNodeId(i), result);
|
||||
}
|
||||
|
||||
@@ -1003,7 +1040,9 @@ namespace ts {
|
||||
if (!isPropertyAccessExpression(p.valueDeclaration)) {
|
||||
return undefined;
|
||||
}
|
||||
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
|
||||
const type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker);
|
||||
getSymbolAccessibilityDiagnostic = oldDiag;
|
||||
const varDecl = createVariableDeclaration(unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
|
||||
return createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList([varDecl]));
|
||||
});
|
||||
@@ -1091,8 +1130,8 @@ namespace ts {
|
||||
let parameterProperties: ReadonlyArray<PropertyDeclaration> | undefined;
|
||||
if (ctor) {
|
||||
const oldDiag = getSymbolAccessibilityDiagnostic;
|
||||
parameterProperties = compact(flatMap(ctor.parameters, param => {
|
||||
if (!hasModifier(param, ModifierFlags.ParameterPropertyModifier)) return;
|
||||
parameterProperties = compact(flatMap(ctor.parameters, (param) => {
|
||||
if (!hasModifier(param, ModifierFlags.ParameterPropertyModifier) || shouldStripInternal(param)) return;
|
||||
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param);
|
||||
if (param.name.kind === SyntaxKind.Identifier) {
|
||||
return preserveJsDoc(createProperty(
|
||||
@@ -1255,19 +1294,8 @@ namespace ts {
|
||||
errorNameNode = undefined;
|
||||
}
|
||||
|
||||
function hasInternalAnnotation(range: CommentRange) {
|
||||
const comment = currentSourceFile.text.substring(range.pos, range.end);
|
||||
return stringContains(comment, "@internal");
|
||||
}
|
||||
|
||||
function shouldStripInternal(node: Node) {
|
||||
if (stripInternal && node) {
|
||||
const leadingCommentRanges = getLeadingCommentRangesOfNode(getParseTreeNode(node), currentSourceFile);
|
||||
if (forEach(leadingCommentRanges, hasInternalAnnotation)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
|
||||
}
|
||||
|
||||
function isScopeMarker(node: Node) {
|
||||
|
||||
@@ -26,7 +26,8 @@ namespace ts {
|
||||
| ImportEqualsDeclaration
|
||||
| TypeAliasDeclaration
|
||||
| ConstructorDeclaration
|
||||
| IndexSignatureDeclaration;
|
||||
| IndexSignatureDeclaration
|
||||
| PropertyAccessExpression;
|
||||
|
||||
export function canProduceDiagnostics(node: Node): node is DeclarationDiagnosticProducing {
|
||||
return isVariableDeclaration(node) ||
|
||||
@@ -46,7 +47,8 @@ namespace ts {
|
||||
isImportEqualsDeclaration(node) ||
|
||||
isTypeAliasDeclaration(node) ||
|
||||
isConstructorDeclaration(node) ||
|
||||
isIndexSignatureDeclaration(node);
|
||||
isIndexSignatureDeclaration(node) ||
|
||||
isPropertyAccessExpression(node);
|
||||
}
|
||||
|
||||
export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing) {
|
||||
@@ -123,7 +125,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined {
|
||||
if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isConstructorDeclaration(node)) {
|
||||
if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) {
|
||||
return getVariableDeclarationTypeVisibilityError;
|
||||
}
|
||||
else if (isSetAccessor(node) || isGetAccessor(node)) {
|
||||
@@ -164,7 +166,7 @@ namespace ts {
|
||||
}
|
||||
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
|
||||
// The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
|
||||
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature ||
|
||||
else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.PropertySignature ||
|
||||
(node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) {
|
||||
// TODO(jfreeman): Deal with computed properties in error reporting.
|
||||
if (hasModifier(node, ModifierFlags.Static)) {
|
||||
@@ -389,6 +391,10 @@ namespace ts {
|
||||
diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
|
||||
break;
|
||||
|
||||
case SyntaxKind.MappedType:
|
||||
diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
|
||||
break;
|
||||
|
||||
case SyntaxKind.ConstructorType:
|
||||
case SyntaxKind.ConstructSignature:
|
||||
diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
|
||||
|
||||
@@ -512,7 +512,7 @@ namespace ts {
|
||||
return name;
|
||||
}
|
||||
|
||||
const restHelper: EmitHelper = {
|
||||
export const restHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:rest",
|
||||
scoped: false,
|
||||
text: `
|
||||
|
||||
+283
-310
File diff suppressed because it is too large
Load Diff
@@ -420,8 +420,10 @@ namespace ts {
|
||||
|
||||
const savedCapturedSuperProperties = capturedSuperProperties;
|
||||
const savedHasSuperElementAccess = hasSuperElementAccess;
|
||||
capturedSuperProperties = createUnderscoreEscapedMap<true>();
|
||||
hasSuperElementAccess = false;
|
||||
if (!isArrowFunction) {
|
||||
capturedSuperProperties = createUnderscoreEscapedMap<true>();
|
||||
hasSuperElementAccess = false;
|
||||
}
|
||||
|
||||
let result: ConciseBody;
|
||||
if (!isArrowFunction) {
|
||||
@@ -438,7 +440,7 @@ namespace ts {
|
||||
)
|
||||
);
|
||||
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
|
||||
// This step isn't needed if we eventually transform this to ES5.
|
||||
@@ -446,9 +448,11 @@ namespace ts {
|
||||
|
||||
if (emitSuperHelpers) {
|
||||
enableSubstitutionForAsyncMethodsWithSuper();
|
||||
const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
|
||||
substitutedSuperAccessors[getNodeId(variableStatement)] = true;
|
||||
addStatementsAfterPrologue(statements, [variableStatement]);
|
||||
if (hasEntries(capturedSuperProperties)) {
|
||||
const variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
|
||||
substitutedSuperAccessors[getNodeId(variableStatement)] = true;
|
||||
insertStatementsAfterStandardPrologue(statements, [variableStatement]);
|
||||
}
|
||||
}
|
||||
|
||||
const block = createBlock(statements, /*multiLine*/ true);
|
||||
@@ -485,8 +489,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
|
||||
capturedSuperProperties = savedCapturedSuperProperties;
|
||||
hasSuperElementAccess = savedHasSuperElementAccess;
|
||||
if (!isArrowFunction) {
|
||||
capturedSuperProperties = savedCapturedSuperProperties;
|
||||
hasSuperElementAccess = savedHasSuperElementAccess;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -684,9 +690,15 @@ namespace ts {
|
||||
/* parameters */ [],
|
||||
/* type */ undefined,
|
||||
/* equalsGreaterThanToken */ undefined,
|
||||
createPropertyAccess(
|
||||
createSuper(),
|
||||
name
|
||||
setEmitFlags(
|
||||
createPropertyAccess(
|
||||
setEmitFlags(
|
||||
createSuper(),
|
||||
EmitFlags.NoSubstitution
|
||||
),
|
||||
name
|
||||
),
|
||||
EmitFlags.NoSubstitution
|
||||
)
|
||||
)
|
||||
));
|
||||
@@ -711,9 +723,16 @@ namespace ts {
|
||||
/* type */ undefined,
|
||||
/* equalsGreaterThanToken */ undefined,
|
||||
createAssignment(
|
||||
createPropertyAccess(
|
||||
createSuper(),
|
||||
name),
|
||||
setEmitFlags(
|
||||
createPropertyAccess(
|
||||
setEmitFlags(
|
||||
createSuper(),
|
||||
EmitFlags.NoSubstitution
|
||||
),
|
||||
name
|
||||
),
|
||||
EmitFlags.NoSubstitution
|
||||
),
|
||||
createIdentifier("v")
|
||||
)
|
||||
)
|
||||
@@ -750,7 +769,7 @@ namespace ts {
|
||||
NodeFlags.Const));
|
||||
}
|
||||
|
||||
const awaiterHelper: EmitHelper = {
|
||||
export const awaiterHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:awaiter",
|
||||
scoped: false,
|
||||
priority: 5,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export function transformES2019(context: TransformationContext) {
|
||||
return chainBundle(transformSourceFile);
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
if (node.isDeclarationFile) {
|
||||
return node;
|
||||
}
|
||||
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
if ((node.transformFlags & TransformFlags.ContainsES2019) === 0) {
|
||||
return node;
|
||||
}
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.CatchClause:
|
||||
return visitCatchClause(node as CatchClause);
|
||||
default:
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
|
||||
function visitCatchClause(node: CatchClause): CatchClause {
|
||||
if (!node.variableDeclaration) {
|
||||
return updateCatchClause(
|
||||
node,
|
||||
createVariableDeclaration(createTempVariable(/*recordTempVariable*/ undefined)),
|
||||
visitNode(node.block, visitor, isBlock)
|
||||
);
|
||||
}
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -316,7 +316,7 @@ namespace ts {
|
||||
else if (inGeneratorFunctionBody) {
|
||||
return visitJavaScriptInGeneratorFunctionBody(node);
|
||||
}
|
||||
else if (transformFlags & TransformFlags.Generator) {
|
||||
else if (isFunctionLikeDeclaration(node) && node.asteriskToken) {
|
||||
return visitGenerator(node);
|
||||
}
|
||||
else if (transformFlags & TransformFlags.ContainsGenerator) {
|
||||
@@ -587,7 +587,7 @@ namespace ts {
|
||||
transformAndEmitStatements(body.statements, statementOffset);
|
||||
|
||||
const buildResult = build();
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
statements.push(createReturn(buildResult));
|
||||
|
||||
// Restore previous generator state
|
||||
@@ -3240,7 +3240,7 @@ namespace ts {
|
||||
// entering a finally block.
|
||||
//
|
||||
// For examples of how these are used, see the comments in ./transformers/generators.ts
|
||||
const generatorHelper: EmitHelper = {
|
||||
export const generatorHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:generator",
|
||||
scoped: false,
|
||||
priority: 6,
|
||||
|
||||
@@ -182,7 +182,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function visitJsxText(node: JsxText): StringLiteral | undefined {
|
||||
const fixed = fixupWhitespaceAndDecodeEntities(getTextOfNode(node, /*includeTrivia*/ true));
|
||||
const fixed = fixupWhitespaceAndDecodeEntities(node.text);
|
||||
return fixed === undefined ? undefined : createLiteral(fixed);
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ namespace ts {
|
||||
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement));
|
||||
addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset));
|
||||
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
const updated = updateSourceFileNode(node, setTextRange(createNodeArray(statements), node.statements));
|
||||
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
|
||||
@@ -432,7 +432,7 @@ namespace ts {
|
||||
|
||||
// End the lexical environment for the module body
|
||||
// and merge any new lexical declarations.
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
const body = createBlock(statements, /*multiLine*/ true);
|
||||
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
|
||||
@@ -537,8 +537,8 @@ namespace ts {
|
||||
if (isImportCall(node)) {
|
||||
return visitImportCallExpression(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.DestructuringAssignment && isBinaryExpression(node)) {
|
||||
return visitDestructuringAssignment(node as DestructuringAssignment);
|
||||
else if (isDestructuringAssignment(node)) {
|
||||
return visitDestructuringAssignment(node);
|
||||
}
|
||||
else {
|
||||
return visitEachChild(node, moduleExpressionElementVisitor, context);
|
||||
@@ -1806,7 +1806,7 @@ namespace ts {
|
||||
};
|
||||
|
||||
// emit helper for `import * as Name from "foo"`
|
||||
const importStarHelper: EmitHelper = {
|
||||
export const importStarHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:commonjsimportstar",
|
||||
scoped: false,
|
||||
text: `
|
||||
@@ -1820,7 +1820,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
||||
};
|
||||
|
||||
// emit helper for `import Name from "foo"`
|
||||
const importDefaultHelper: EmitHelper = {
|
||||
export const importDefaultHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:commonjsimportdefault",
|
||||
scoped: false,
|
||||
text: `
|
||||
|
||||
@@ -257,7 +257,7 @@ namespace ts {
|
||||
// We emit hoisted variables early to align roughly with our previous emit output.
|
||||
// Two key differences in this approach are:
|
||||
// - Temporary variables will appear at the top rather than at the bottom of the file
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
|
||||
const exportStarFunction = addExportStarIfNeeded(statements)!; // TODO: GH#18217
|
||||
const moduleObject = createObjectLiteral([
|
||||
@@ -1463,9 +1463,8 @@ namespace ts {
|
||||
* @param node The node to visit.
|
||||
*/
|
||||
function destructuringAndImportCallVisitor(node: Node): VisitResult<Node> {
|
||||
if (node.transformFlags & TransformFlags.DestructuringAssignment
|
||||
&& node.kind === SyntaxKind.BinaryExpression) {
|
||||
return visitDestructuringAssignment(<DestructuringAssignment>node);
|
||||
if (isDestructuringAssignment(node)) {
|
||||
return visitDestructuringAssignment(node);
|
||||
}
|
||||
else if (isImportCall(node)) {
|
||||
return visitImportCallExpression(node);
|
||||
|
||||
+64
-148
@@ -101,7 +101,7 @@ namespace ts {
|
||||
function transformBundle(node: Bundle) {
|
||||
return createBundle(node.sourceFiles.map(transformSourceFile), mapDefined(node.prepends, prepend => {
|
||||
if (prepend.kind === SyntaxKind.InputFiles) {
|
||||
return createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText);
|
||||
return createUnparsedSourceFile(prepend, "js");
|
||||
}
|
||||
return prepend;
|
||||
}));
|
||||
@@ -208,15 +208,9 @@ namespace ts {
|
||||
* @param node The node to visit.
|
||||
*/
|
||||
function visitorWorker(node: Node): VisitResult<Node> {
|
||||
if (node.transformFlags & TransformFlags.TypeScript) {
|
||||
// This node is explicitly marked as TypeScript, so we should transform the node.
|
||||
if (node.transformFlags & TransformFlags.ContainsTypeScript) {
|
||||
return visitTypeScript(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.ContainsTypeScript) {
|
||||
// This node contains TypeScript, so we should visit its children.
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -296,15 +290,9 @@ namespace ts {
|
||||
(<ImportEqualsDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference)) {
|
||||
// do not emit ES6 imports and exports since they are illegal inside a namespace
|
||||
return undefined;
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.TypeScript || hasModifier(node, ModifierFlags.Export)) {
|
||||
// This node is explicitly marked as TypeScript, or is exported at the namespace
|
||||
// level, so we should transform the node.
|
||||
return visitTypeScript(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.ContainsTypeScript) {
|
||||
// This node contains TypeScript, so we should visit its children.
|
||||
return visitEachChild(node, visitor, context);
|
||||
else if (node.transformFlags & TransformFlags.ContainsTypeScript || hasModifier(node, ModifierFlags.Export)) {
|
||||
return visitTypeScript(node);
|
||||
}
|
||||
|
||||
return node;
|
||||
@@ -365,7 +353,7 @@ namespace ts {
|
||||
* @param node The node to visit.
|
||||
*/
|
||||
function visitTypeScript(node: Node): VisitResult<Node> {
|
||||
if (hasModifier(node, ModifierFlags.Ambient) && isStatement(node)) {
|
||||
if (isStatement(node) && hasModifier(node, ModifierFlags.Ambient)) {
|
||||
// TypeScript ambient declarations are elided, but some comments may be preserved.
|
||||
// See the implementation of `getLeadingComments` in comments.ts for more details.
|
||||
return createNotEmittedStatement(node);
|
||||
@@ -443,7 +431,7 @@ namespace ts {
|
||||
return createNotEmittedStatement(node);
|
||||
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
// This is a class declaration with TypeScript syntax extensions.
|
||||
// This may be a class declaration with TypeScript syntax extensions.
|
||||
//
|
||||
// TypeScript class syntax extensions include:
|
||||
// - decorators
|
||||
@@ -455,7 +443,7 @@ namespace ts {
|
||||
return visitClassDeclaration(<ClassDeclaration>node);
|
||||
|
||||
case SyntaxKind.ClassExpression:
|
||||
// This is a class expression with TypeScript syntax extensions.
|
||||
// This may be a class expression with TypeScript syntax extensions.
|
||||
//
|
||||
// TypeScript class syntax extensions include:
|
||||
// - decorators
|
||||
@@ -467,7 +455,7 @@ namespace ts {
|
||||
return visitClassExpression(<ClassExpression>node);
|
||||
|
||||
case SyntaxKind.HeritageClause:
|
||||
// This is a heritage clause with TypeScript syntax extensions.
|
||||
// This may be a heritage clause with TypeScript syntax extensions.
|
||||
//
|
||||
// TypeScript heritage clause extensions include:
|
||||
// - `implements` clause
|
||||
@@ -503,7 +491,7 @@ namespace ts {
|
||||
return visitArrowFunction(<ArrowFunction>node);
|
||||
|
||||
case SyntaxKind.Parameter:
|
||||
// This is a parameter declaration with TypeScript syntax extensions.
|
||||
// This may be a parameter declaration with TypeScript syntax extensions.
|
||||
//
|
||||
// TypeScript parameter declaration syntax extensions include:
|
||||
// - decorators
|
||||
@@ -556,7 +544,8 @@ namespace ts {
|
||||
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
|
||||
|
||||
default:
|
||||
return Debug.failBadSyntaxKind(node);
|
||||
// node contains some other TypeScript syntax
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -607,18 +596,22 @@ namespace ts {
|
||||
return facts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a class declaration with TypeScript syntax into compatible ES6.
|
||||
*
|
||||
* This function will only be called when one of the following conditions are met:
|
||||
* - The class has decorators.
|
||||
* - The class has property declarations with initializers.
|
||||
* - The class contains a constructor that contains parameters with accessibility modifiers.
|
||||
* - The class is an export in a TypeScript namespace.
|
||||
*
|
||||
* @param node The node to transform.
|
||||
*/
|
||||
function hasTypeScriptClassSyntax(node: Node) {
|
||||
return !!(node.transformFlags & TransformFlags.ContainsTypeScriptClassSyntax);
|
||||
}
|
||||
|
||||
function isClassLikeDeclarationWithTypeScriptSyntax(node: ClassLikeDeclaration) {
|
||||
return some(node.decorators)
|
||||
|| some(node.typeParameters)
|
||||
|| some(node.heritageClauses, hasTypeScriptClassSyntax)
|
||||
|| some(node.members, hasTypeScriptClassSyntax);
|
||||
}
|
||||
|
||||
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
|
||||
if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && hasModifier(node, ModifierFlags.Export))) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
const savedPendingExpressions = pendingExpressions;
|
||||
pendingExpressions = undefined;
|
||||
|
||||
@@ -682,7 +675,7 @@ namespace ts {
|
||||
setEmitFlags(statement, EmitFlags.NoComments | EmitFlags.NoTokenSourceMaps);
|
||||
statements.push(statement);
|
||||
|
||||
addStatementsAfterPrologue(statements, context.endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
|
||||
|
||||
const iife = createImmediatelyInvokedArrowFunction(statements);
|
||||
setEmitFlags(iife, EmitFlags.TypeScriptClassWrapper);
|
||||
@@ -890,16 +883,11 @@ namespace ts {
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a class expression with TypeScript syntax into compatible ES6.
|
||||
*
|
||||
* This function will only be called when one of the following conditions are met:
|
||||
* - The class has property declarations with initializers.
|
||||
* - The class contains a constructor that contains parameters with accessibility modifiers.
|
||||
*
|
||||
* @param node The node to transform.
|
||||
*/
|
||||
function visitClassExpression(node: ClassExpression): Expression {
|
||||
if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
const savedPendingExpressions = pendingExpressions;
|
||||
pendingExpressions = undefined;
|
||||
|
||||
@@ -1350,11 +1338,14 @@ namespace ts {
|
||||
let decorators: (ReadonlyArray<Decorator> | undefined)[] | undefined;
|
||||
if (node) {
|
||||
const parameters = node.parameters;
|
||||
for (let i = 0; i < parameters.length; i++) {
|
||||
const parameter = parameters[i];
|
||||
const firstParameterIsThis = parameters.length > 0 && parameterIsThisKeyword(parameters[0]);
|
||||
const firstParameterOffset = firstParameterIsThis ? 1 : 0;
|
||||
const numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
|
||||
for (let i = 0; i < numParameters; i++) {
|
||||
const parameter = parameters[i + firstParameterOffset];
|
||||
if (decorators || parameter.decorators) {
|
||||
if (!decorators) {
|
||||
decorators = new Array(parameters.length);
|
||||
decorators = new Array(numParameters);
|
||||
}
|
||||
|
||||
decorators[i] = parameter.decorators;
|
||||
@@ -1898,6 +1889,7 @@ namespace ts {
|
||||
case SyntaxKind.StringLiteral:
|
||||
return createIdentifier("String");
|
||||
|
||||
case SyntaxKind.PrefixUnaryExpression:
|
||||
case SyntaxKind.NumericLiteral:
|
||||
return createIdentifier("Number");
|
||||
|
||||
@@ -1933,8 +1925,13 @@ namespace ts {
|
||||
case SyntaxKind.ConditionalType:
|
||||
return serializeTypeList([(<ConditionalTypeNode>node).trueType, (<ConditionalTypeNode>node).falseType]);
|
||||
|
||||
case SyntaxKind.TypeQuery:
|
||||
case SyntaxKind.TypeOperator:
|
||||
if ((<TypeOperatorNode>node).operator === SyntaxKind.ReadonlyKeyword) {
|
||||
return serializeTypeNode((<TypeOperatorNode>node).type);
|
||||
}
|
||||
break;
|
||||
|
||||
case SyntaxKind.TypeQuery:
|
||||
case SyntaxKind.IndexedAccessType:
|
||||
case SyntaxKind.MappedType:
|
||||
case SyntaxKind.TypeLiteral:
|
||||
@@ -2231,18 +2228,11 @@ namespace ts {
|
||||
* @param node The HeritageClause to transform.
|
||||
*/
|
||||
function visitHeritageClause(node: HeritageClause): HeritageClause | undefined {
|
||||
if (node.token === SyntaxKind.ExtendsKeyword) {
|
||||
const types = visitNodes(node.types, visitor, isExpressionWithTypeArguments, 0, 1);
|
||||
return setTextRange(
|
||||
createHeritageClause(
|
||||
SyntaxKind.ExtendsKeyword,
|
||||
types
|
||||
),
|
||||
node
|
||||
);
|
||||
if (node.token === SyntaxKind.ImplementsKeyword) {
|
||||
// implements clauses are elided
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2293,16 +2283,6 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a method declaration of a class.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node is an overload
|
||||
* - The node is marked as abstract, public, private, protected, or readonly
|
||||
* - The node has a computed property name
|
||||
*
|
||||
* @param node The method node.
|
||||
*/
|
||||
function visitMethodDeclaration(node: MethodDeclaration) {
|
||||
if (!shouldEmitFunctionLikeDeclaration(node)) {
|
||||
return undefined;
|
||||
@@ -2338,15 +2318,6 @@ namespace ts {
|
||||
return !(nodeIsMissing(node.body) && hasModifier(node, ModifierFlags.Abstract));
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a get accessor declaration of a class.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node is marked as abstract, public, private, or protected
|
||||
* - The node has a computed property name
|
||||
*
|
||||
* @param node The get accessor node.
|
||||
*/
|
||||
function visitGetAccessor(node: GetAccessorDeclaration) {
|
||||
if (!shouldEmitAccessorDeclaration(node)) {
|
||||
return undefined;
|
||||
@@ -2369,15 +2340,6 @@ namespace ts {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a set accessor declaration of a class.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node is marked as abstract, public, private, or protected
|
||||
* - The node has a computed property name
|
||||
*
|
||||
* @param node The set accessor node.
|
||||
*/
|
||||
function visitSetAccessor(node: SetAccessorDeclaration) {
|
||||
if (!shouldEmitAccessorDeclaration(node)) {
|
||||
return undefined;
|
||||
@@ -2399,16 +2361,6 @@ namespace ts {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a function declaration.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node is an overload
|
||||
* - The node is exported from a TypeScript namespace
|
||||
* - The node has decorators
|
||||
*
|
||||
* @param node The function node.
|
||||
*/
|
||||
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
|
||||
if (!shouldEmitFunctionLikeDeclaration(node)) {
|
||||
return createNotEmittedStatement(node);
|
||||
@@ -2432,14 +2384,6 @@ namespace ts {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a function expression node.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node has type annotations
|
||||
*
|
||||
* @param node The function expression node.
|
||||
*/
|
||||
function visitFunctionExpression(node: FunctionExpression): Expression {
|
||||
if (!shouldEmitFunctionLikeDeclaration(node)) {
|
||||
return createOmittedExpression();
|
||||
@@ -2457,11 +2401,6 @@ namespace ts {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @remarks
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node has type annotations
|
||||
*/
|
||||
function visitArrowFunction(node: ArrowFunction) {
|
||||
const updated = updateArrowFunction(
|
||||
node,
|
||||
@@ -2475,22 +2414,12 @@ namespace ts {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a parameter declaration node.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node has an accessibility modifier.
|
||||
* - The node has a questionToken.
|
||||
* - The node's kind is ThisKeyword.
|
||||
*
|
||||
* @param node The parameter declaration node.
|
||||
*/
|
||||
function visitParameter(node: ParameterDeclaration) {
|
||||
if (parameterIsThisKeyword(node)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parameter = createParameter(
|
||||
const updated = updateParameter(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
node.dotDotDotToken,
|
||||
@@ -2499,24 +2428,17 @@ namespace ts {
|
||||
/*type*/ undefined,
|
||||
visitNode(node.initializer, visitor, isExpression)
|
||||
);
|
||||
|
||||
// While we emit the source map for the node after skipping decorators and modifiers,
|
||||
// we need to emit the comments for the original range.
|
||||
setOriginalNode(parameter, node);
|
||||
setTextRange(parameter, moveRangePastModifiers(node));
|
||||
setCommentRange(parameter, node);
|
||||
setSourceMapRange(parameter, moveRangePastModifiers(node));
|
||||
setEmitFlags(parameter.name, EmitFlags.NoTrailingSourceMap);
|
||||
|
||||
return parameter;
|
||||
if (updated !== node) {
|
||||
// While we emit the source map for the node after skipping decorators and modifiers,
|
||||
// we need to emit the comments for the original range.
|
||||
setCommentRange(updated, node);
|
||||
setTextRange(updated, moveRangePastModifiers(node));
|
||||
setSourceMapRange(updated, moveRangePastModifiers(node));
|
||||
setEmitFlags(updated.name, EmitFlags.NoTrailingSourceMap);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a variable statement in a namespace.
|
||||
*
|
||||
* This function will be called when one of the following conditions are met:
|
||||
* - The node is exported from a TypeScript namespace.
|
||||
*/
|
||||
function visitVariableStatement(node: VariableStatement): Statement | undefined {
|
||||
if (isExportOfNamespace(node)) {
|
||||
const variables = getInitializedVariables(node.declarationList);
|
||||
@@ -2570,12 +2492,6 @@ namespace ts {
|
||||
visitNode(node.initializer, visitor, isExpression));
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a parenthesized expression that contains either a type assertion or an `as`
|
||||
* expression.
|
||||
*
|
||||
* @param node The parenthesized expression node.
|
||||
*/
|
||||
function visitParenthesizedExpression(node: ParenthesizedExpression): Expression {
|
||||
const innerExpression = skipOuterExpressions(node.expression, ~OuterExpressionKinds.Assertions);
|
||||
if (isAssertionExpression(innerExpression)) {
|
||||
@@ -2759,7 +2675,7 @@ namespace ts {
|
||||
const statements: Statement[] = [];
|
||||
startLexicalEnvironment();
|
||||
const members = map(node.members, transformEnumMember);
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
addRange(statements, members);
|
||||
|
||||
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
|
||||
@@ -3080,7 +2996,7 @@ namespace ts {
|
||||
statementsLocation = moveRangePos(moduleBlock.statements, -1);
|
||||
}
|
||||
|
||||
addStatementsAfterPrologue(statements, endLexicalEnvironment());
|
||||
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
|
||||
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
|
||||
currentNamespace = savedCurrentNamespace;
|
||||
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
|
||||
@@ -3674,7 +3590,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
const decorateHelper: EmitHelper = {
|
||||
export const decorateHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:decorate",
|
||||
scoped: false,
|
||||
priority: 2,
|
||||
@@ -3699,7 +3615,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
const metadataHelper: EmitHelper = {
|
||||
export const metadataHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:metadata",
|
||||
scoped: false,
|
||||
priority: 3,
|
||||
@@ -3724,7 +3640,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
const paramHelper: EmitHelper = {
|
||||
export const paramHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:param",
|
||||
scoped: false,
|
||||
priority: 4,
|
||||
|
||||
+357
-191
@@ -67,12 +67,19 @@ namespace ts {
|
||||
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
|
||||
*/
|
||||
UpToDateWithUpstreamTypes,
|
||||
/**
|
||||
* The project appears out of date because its upstream inputs are newer than its outputs,
|
||||
* but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
|
||||
* This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
|
||||
*/
|
||||
OutOfDateWithPrepend,
|
||||
OutputMissing,
|
||||
OutOfDateWithSelf,
|
||||
OutOfDateWithUpstream,
|
||||
UpstreamOutOfDate,
|
||||
UpstreamBlocked,
|
||||
ComputingUpstream,
|
||||
TsVersionOutputOfDate,
|
||||
|
||||
/**
|
||||
* Projects with no outputs (i.e. "solution" files)
|
||||
@@ -83,12 +90,14 @@ namespace ts {
|
||||
export type UpToDateStatus =
|
||||
| Status.Unbuildable
|
||||
| Status.UpToDate
|
||||
| Status.OutOfDateWithPrepend
|
||||
| Status.OutputMissing
|
||||
| Status.OutOfDateWithSelf
|
||||
| Status.OutOfDateWithUpstream
|
||||
| Status.UpstreamOutOfDate
|
||||
| Status.UpstreamBlocked
|
||||
| Status.ComputingUpstream
|
||||
| Status.TsVersionOutOfDate
|
||||
| Status.ContainerOnly;
|
||||
|
||||
export namespace Status {
|
||||
@@ -119,7 +128,16 @@ namespace ts {
|
||||
newestDeclarationFileContentChangedTime?: Date;
|
||||
newestOutputFileTime?: Date;
|
||||
newestOutputFileName?: string;
|
||||
oldestOutputFileName?: string;
|
||||
oldestOutputFileName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The project is up to date with respect to its inputs except for prepend output changed (no declaration file change in prepend).
|
||||
*/
|
||||
export interface OutOfDateWithPrepend {
|
||||
type: UpToDateStatusType.OutOfDateWithPrepend;
|
||||
outOfDateOutputFileName: string;
|
||||
newerProjectName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -165,6 +183,11 @@ namespace ts {
|
||||
type: UpToDateStatusType.ComputingUpstream;
|
||||
}
|
||||
|
||||
export interface TsVersionOutOfDate {
|
||||
type: UpToDateStatusType.TsVersionOutputOfDate;
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One or more of the project's outputs is older than the newest output of
|
||||
* an upstream project.
|
||||
@@ -253,66 +276,6 @@ namespace ts {
|
||||
return getOrCreateValueFromConfigFileMap<Map<T>>(configFileMap, resolved, createMap);
|
||||
}
|
||||
|
||||
export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) {
|
||||
const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true);
|
||||
const outputPath = resolvePath(configFile.options.declarationDir || configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath);
|
||||
return changeExtension(outputPath, Extension.Dts);
|
||||
}
|
||||
|
||||
function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLine) {
|
||||
const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true);
|
||||
const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath);
|
||||
const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json :
|
||||
fileExtensionIs(inputFileName, Extension.Tsx) && configFile.options.jsx === JsxEmit.Preserve ? Extension.Jsx : Extension.Js;
|
||||
return changeExtension(outputPath, newExtension);
|
||||
}
|
||||
|
||||
function getOutputFileNames(inputFileName: string, configFile: ParsedCommandLine): ReadonlyArray<string> {
|
||||
// outFile is handled elsewhere; .d.ts files don't generate outputs
|
||||
if (configFile.options.outFile || configFile.options.out || fileExtensionIs(inputFileName, Extension.Dts)) {
|
||||
return emptyArray;
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
const js = getOutputJSFileName(inputFileName, configFile);
|
||||
outputs.push(js);
|
||||
if (configFile.options.sourceMap) {
|
||||
outputs.push(`${js}.map`);
|
||||
}
|
||||
if (getEmitDeclarations(configFile.options) && !fileExtensionIs(inputFileName, Extension.Json)) {
|
||||
const dts = getOutputDeclarationFileName(inputFileName, configFile);
|
||||
outputs.push(dts);
|
||||
if (configFile.options.declarationMap) {
|
||||
outputs.push(`${dts}.map`);
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
function getOutFileOutputs(project: ParsedCommandLine): ReadonlyArray<string> {
|
||||
const out = project.options.outFile || project.options.out;
|
||||
if (!out) {
|
||||
return Debug.fail("outFile must be set");
|
||||
}
|
||||
const outputs: string[] = [];
|
||||
outputs.push(out);
|
||||
if (project.options.sourceMap) {
|
||||
outputs.push(`${out}.map`);
|
||||
}
|
||||
if (getEmitDeclarations(project.options)) {
|
||||
const dts = changeExtension(out, Extension.Dts);
|
||||
outputs.push(dts);
|
||||
if (project.options.declarationMap) {
|
||||
outputs.push(`${dts}.map`);
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
function rootDirOfOptions(opts: CompilerOptions, configFileName: string) {
|
||||
return opts.rootDir || getDirectoryPath(configFileName);
|
||||
}
|
||||
|
||||
function newer(date1: Date, date2: Date): Date {
|
||||
return date2 > date1 ? date2 : date1;
|
||||
}
|
||||
@@ -321,7 +284,7 @@ namespace ts {
|
||||
return fileExtensionIs(fileName, Extension.Dts);
|
||||
}
|
||||
|
||||
export interface SolutionBuilderHostBase extends CompilerHost {
|
||||
export interface SolutionBuilderHostBase<T extends BuilderProgram> extends ProgramHost<T> {
|
||||
getModifiedTime(fileName: string): Date | undefined;
|
||||
setModifiedTime(fileName: string, date: Date): void;
|
||||
deleteFile(fileName: string): void;
|
||||
@@ -331,15 +294,17 @@ namespace ts {
|
||||
|
||||
// TODO: To do better with watch mode and normal build mode api that creates program and emits files
|
||||
// This currently helps enable --diagnostics and --extendedDiagnostics
|
||||
beforeCreateProgram?(options: CompilerOptions): void;
|
||||
afterProgramEmitAndDiagnostics?(program: Program): void;
|
||||
afterProgramEmitAndDiagnostics?(program: T): void;
|
||||
|
||||
// For testing
|
||||
now?(): Date;
|
||||
}
|
||||
|
||||
export interface SolutionBuilderHost extends SolutionBuilderHostBase {
|
||||
export interface SolutionBuilderHost<T extends BuilderProgram> extends SolutionBuilderHostBase<T> {
|
||||
reportErrorSummary?: ReportEmitErrorSummary;
|
||||
}
|
||||
|
||||
export interface SolutionBuilderWithWatchHost extends SolutionBuilderHostBase, WatchHost {
|
||||
export interface SolutionBuilderWithWatchHost<T extends BuilderProgram> extends SolutionBuilderHostBase<T>, WatchHost {
|
||||
}
|
||||
|
||||
export interface SolutionBuilder {
|
||||
@@ -372,9 +337,9 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function createSolutionBuilderHostBase(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) {
|
||||
const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) as SolutionBuilderHostBase;
|
||||
host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime!(path) : () => undefined;
|
||||
function createSolutionBuilderHostBase<T extends BuilderProgram>(system: System, createProgram: CreateProgram<T> | undefined, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) {
|
||||
const host = createProgramHost(system, createProgram) as SolutionBuilderHostBase<T>;
|
||||
host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime!(path) : returnUndefined;
|
||||
host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime!(path, date) : noop;
|
||||
host.deleteFile = system.deleteFile ? path => system.deleteFile!(path) : noop;
|
||||
host.reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system);
|
||||
@@ -382,20 +347,16 @@ namespace ts {
|
||||
return host;
|
||||
}
|
||||
|
||||
export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) {
|
||||
const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost;
|
||||
export function createSolutionBuilderHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) {
|
||||
const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost<T>;
|
||||
host.reportErrorSummary = reportErrorSummary;
|
||||
return host;
|
||||
}
|
||||
|
||||
export function createSolutionBuilderWithWatchHost(system?: System, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) {
|
||||
const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost;
|
||||
export function createSolutionBuilderWithWatchHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram?: CreateProgram<T>, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) {
|
||||
const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost<T>;
|
||||
const watchHost = createWatchHost(system, reportWatchStatus);
|
||||
host.onWatchStatusChange = watchHost.onWatchStatusChange;
|
||||
host.watchFile = watchHost.watchFile;
|
||||
host.watchDirectory = watchHost.watchDirectory;
|
||||
host.setTimeout = watchHost.setTimeout;
|
||||
host.clearTimeout = watchHost.clearTimeout;
|
||||
copyProperties(host, watchHost);
|
||||
return host;
|
||||
}
|
||||
|
||||
@@ -413,13 +374,13 @@ namespace ts {
|
||||
* TODO: use SolutionBuilderWithWatchHost => watchedSolution
|
||||
* use SolutionBuilderHost => Solution
|
||||
*/
|
||||
export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilder;
|
||||
export function createSolutionBuilder(host: SolutionBuilderWithWatchHost, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilderWithWatch;
|
||||
export function createSolutionBuilder(host: SolutionBuilderHost | SolutionBuilderWithWatchHost, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilderWithWatch {
|
||||
const hostWithWatch = host as SolutionBuilderWithWatchHost;
|
||||
export function createSolutionBuilder<T extends BuilderProgram>(host: SolutionBuilderHost<T>, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilder;
|
||||
export function createSolutionBuilder<T extends BuilderProgram>(host: SolutionBuilderWithWatchHost<T>, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilderWithWatch;
|
||||
export function createSolutionBuilder<T extends BuilderProgram>(host: SolutionBuilderHost<T> | SolutionBuilderWithWatchHost<T>, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions): SolutionBuilderWithWatch {
|
||||
const hostWithWatch = host as SolutionBuilderWithWatchHost<T>;
|
||||
const currentDirectory = host.getCurrentDirectory();
|
||||
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
|
||||
const parseConfigFileHost = parseConfigHostFromCompilerHost(host);
|
||||
const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host);
|
||||
|
||||
// State of the solution
|
||||
let options = defaultOptions;
|
||||
@@ -434,8 +395,14 @@ namespace ts {
|
||||
let globalDependencyGraph: DependencyGraph | undefined;
|
||||
const writeFileName = (s: string) => host.trace && host.trace(s);
|
||||
let readFileWithCache = (f: string) => host.readFile(f);
|
||||
let projectCompilerOptions = baseCompilerOptions;
|
||||
const compilerHost = createCompilerHostFromProgramHost(host, () => projectCompilerOptions);
|
||||
setGetSourceFileAsHashVersioned(compilerHost, host);
|
||||
|
||||
const buildInfoChecked = createFileMap<true>(toPath);
|
||||
|
||||
// Watch state
|
||||
const builderPrograms = createFileMap<T>(toPath);
|
||||
const diagnostics = createFileMap<ReadonlyArray<Diagnostic>>(toPath);
|
||||
const projectPendingBuild = createFileMap<ConfigFileProgramReloadLevel>(toPath);
|
||||
const projectErrorsReported = createFileMap<true>(toPath);
|
||||
@@ -443,6 +410,7 @@ namespace ts {
|
||||
let nextProjectToBuild = 0;
|
||||
let timerToBuildInvalidatedProject: any;
|
||||
let reportFileChangeDetected = false;
|
||||
const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory<ResolvedConfigFileName>(host, options);
|
||||
|
||||
// Watches for the solution
|
||||
const allWatchedWildcardDirectories = createFileMap<Map<WildcardDirectoryWatcher>>(toPath);
|
||||
@@ -478,6 +446,7 @@ namespace ts {
|
||||
projectStatus.clear();
|
||||
missingRoots.clear();
|
||||
globalDependencyGraph = undefined;
|
||||
buildInfoChecked.clear();
|
||||
|
||||
diagnostics.clear();
|
||||
projectPendingBuild.clear();
|
||||
@@ -492,6 +461,7 @@ namespace ts {
|
||||
clearMap(allWatchedWildcardDirectories, wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf));
|
||||
clearMap(allWatchedInputFiles, inputFileWatches => clearMap(inputFileWatches, closeFileWatcher));
|
||||
clearMap(allWatchedConfigFiles, closeFileWatcher);
|
||||
builderPrograms.clear();
|
||||
}
|
||||
|
||||
function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine {
|
||||
@@ -542,9 +512,16 @@ namespace ts {
|
||||
|
||||
function watchConfigFile(resolved: ResolvedConfigFileName) {
|
||||
if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) {
|
||||
allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, () => {
|
||||
invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full);
|
||||
}));
|
||||
allWatchedConfigFiles.setValue(resolved, watchFile(
|
||||
hostWithWatch,
|
||||
resolved,
|
||||
() => {
|
||||
invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full);
|
||||
},
|
||||
PollingInterval.High,
|
||||
WatchType.ConfigFile,
|
||||
resolved
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,20 +531,27 @@ namespace ts {
|
||||
getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved),
|
||||
createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories),
|
||||
(dir, flags) => {
|
||||
return hostWithWatch.watchDirectory(dir, fileOrDirectory => {
|
||||
const fileOrDirectoryPath = toPath(fileOrDirectory);
|
||||
if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
|
||||
// writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`);
|
||||
return;
|
||||
}
|
||||
return watchDirectory(
|
||||
hostWithWatch,
|
||||
dir,
|
||||
fileOrDirectory => {
|
||||
const fileOrDirectoryPath = toPath(fileOrDirectory);
|
||||
if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
|
||||
writeLog(`Project: ${resolved} Detected file add/remove of non supported extension: ${fileOrDirectory}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isOutputFile(fileOrDirectory, parsed)) {
|
||||
// writeLog(`${fileOrDirectory} is output file`);
|
||||
return;
|
||||
}
|
||||
if (isOutputFile(fileOrDirectory, parsed)) {
|
||||
writeLog(`${fileOrDirectory} is output file`);
|
||||
return;
|
||||
}
|
||||
|
||||
invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial);
|
||||
}, !!(flags & WatchDirectoryFlags.Recursive));
|
||||
invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial);
|
||||
},
|
||||
flags,
|
||||
WatchType.WildcardDirectory,
|
||||
resolved
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -578,9 +562,15 @@ namespace ts {
|
||||
getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved),
|
||||
arrayToMap(parsed.fileNames, toPath),
|
||||
{
|
||||
createNewValue: (_key, input) => hostWithWatch.watchFile(input, () => {
|
||||
invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None);
|
||||
}),
|
||||
createNewValue: (path, input) => watchFilePath(
|
||||
hostWithWatch,
|
||||
input,
|
||||
() => invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None),
|
||||
PollingInterval.Low,
|
||||
path as Path,
|
||||
WatchType.SourceFile,
|
||||
resolved
|
||||
),
|
||||
onDeleteValue: closeFileWatcher,
|
||||
}
|
||||
);
|
||||
@@ -670,15 +660,16 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
// Collect the expected outputs of this project
|
||||
const outputs = getAllProjectOutputs(project);
|
||||
|
||||
if (outputs.length === 0) {
|
||||
// Container if no files are specified in the project
|
||||
if (!project.fileNames.length && !canJsonReportNoInutFiles(project.raw)) {
|
||||
return {
|
||||
type: UpToDateStatusType.ContainerOnly
|
||||
};
|
||||
}
|
||||
|
||||
// Collect the expected outputs of this project
|
||||
const outputs = getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
|
||||
|
||||
// Now see if all outputs are newer than the newest input
|
||||
let oldestOutputFileName = "(none)";
|
||||
let oldestOutputFileTime = maximumDate;
|
||||
@@ -760,27 +751,30 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
// If the upstream project's newest file is older than our oldest output, we
|
||||
// can't be out of date because of it
|
||||
if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
|
||||
continue;
|
||||
}
|
||||
// Check oldest output file name only if there is no missing output file name
|
||||
if (!missingOutputFileName) {
|
||||
// If the upstream project's newest file is older than our oldest output, we
|
||||
// can't be out of date because of it
|
||||
if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the upstream project has only change .d.ts files, and we've built
|
||||
// *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
|
||||
if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
|
||||
pseudoUpToDate = true;
|
||||
upstreamChangedProject = ref.path;
|
||||
continue;
|
||||
}
|
||||
// If the upstream project has only change .d.ts files, and we've built
|
||||
// *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
|
||||
if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
|
||||
pseudoUpToDate = true;
|
||||
upstreamChangedProject = ref.path;
|
||||
continue;
|
||||
}
|
||||
|
||||
// We have an output older than an upstream output - we are out of date
|
||||
Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
|
||||
return {
|
||||
type: UpToDateStatusType.OutOfDateWithUpstream,
|
||||
outOfDateOutputFileName: oldestOutputFileName,
|
||||
newerProjectName: ref.path
|
||||
};
|
||||
// We have an output older than an upstream output - we are out of date
|
||||
Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
|
||||
return {
|
||||
type: UpToDateStatusType.OutOfDateWithUpstream,
|
||||
outOfDateOutputFileName: oldestOutputFileName,
|
||||
newerProjectName: ref.path
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -798,10 +792,34 @@ namespace ts {
|
||||
newerInputFileName: newestInputFileName
|
||||
};
|
||||
}
|
||||
else {
|
||||
// Check tsconfig time
|
||||
const configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath!, oldestOutputFileTime, oldestOutputFileName);
|
||||
if (configStatus) return configStatus;
|
||||
|
||||
// Check extended config time
|
||||
const extendedConfigStatus = forEach(project.options.configFile!.extendedSourceFiles || emptyArray, configFile => checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName));
|
||||
if (extendedConfigStatus) return extendedConfigStatus;
|
||||
}
|
||||
|
||||
if (!buildInfoChecked.hasKey(project.options.configFilePath as ResolvedConfigFileName)) {
|
||||
buildInfoChecked.setValue(project.options.configFilePath as ResolvedConfigFileName, true);
|
||||
const buildInfoPath = getOutputPathForBuildInfo(project.options);
|
||||
if (buildInfoPath) {
|
||||
const value = readFileWithCache(buildInfoPath);
|
||||
const buildInfo = value && getBuildInfo(value);
|
||||
if (buildInfo && buildInfo.version !== version) {
|
||||
return {
|
||||
type: UpToDateStatusType.TsVersionOutputOfDate,
|
||||
version: buildInfo.version
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (usesPrepend && pseudoUpToDate) {
|
||||
return {
|
||||
type: UpToDateStatusType.OutOfDateWithUpstream,
|
||||
type: UpToDateStatusType.OutOfDateWithPrepend,
|
||||
outOfDateOutputFileName: oldestOutputFileName,
|
||||
newerProjectName: upstreamChangedProject!
|
||||
};
|
||||
@@ -819,6 +837,18 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function checkConfigFileUpToDateStatus(configFile: string, oldestOutputFileTime: Date, oldestOutputFileName: string): Status.OutOfDateWithSelf | undefined {
|
||||
// Check tsconfig time
|
||||
const tsconfigTime = host.getModifiedTime(configFile) || missingFileModifiedTime;
|
||||
if (oldestOutputFileTime < tsconfigTime) {
|
||||
return {
|
||||
type: UpToDateStatusType.OutOfDateWithSelf,
|
||||
outOfDateOutputFileName: oldestOutputFileName,
|
||||
newerInputFileName: configFile
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel) {
|
||||
invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel);
|
||||
}
|
||||
@@ -898,7 +928,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function reportErrorSummary() {
|
||||
if (options.watch || (host as SolutionBuilderHost).reportErrorSummary) {
|
||||
if (options.watch || (host as SolutionBuilderHost<T>).reportErrorSummary) {
|
||||
// Report errors from the other projects
|
||||
getGlobalDependencyGraph().buildQueue.forEach(project => {
|
||||
if (!projectErrorsReported.hasKey(project)) {
|
||||
@@ -911,7 +941,7 @@ namespace ts {
|
||||
reportWatchStatus(getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
|
||||
}
|
||||
else {
|
||||
(host as SolutionBuilderHost).reportErrorSummary!(totalErrors);
|
||||
(host as SolutionBuilderHost<T>).reportErrorSummary!(totalErrors);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -944,16 +974,51 @@ namespace ts {
|
||||
return;
|
||||
}
|
||||
|
||||
const buildResult = buildSingleProject(resolved);
|
||||
const dependencyGraph = getGlobalDependencyGraph();
|
||||
const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved);
|
||||
if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) {
|
||||
// Fake that files have been built by updating output file stamps
|
||||
updateOutputTimestamps(proj);
|
||||
return;
|
||||
}
|
||||
|
||||
const buildResult = needsBuild(status, resolved) ?
|
||||
buildSingleProject(resolved) : // Actual build
|
||||
updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output
|
||||
if (buildResult & BuildResultFlags.AnyErrors) return;
|
||||
|
||||
const { referencingProjectsMap, buildQueue } = getGlobalDependencyGraph();
|
||||
const referencingProjects = referencingProjectsMap.getValue(resolved);
|
||||
if (!referencingProjects) return;
|
||||
|
||||
// Always use build order to queue projects
|
||||
for (const project of dependencyGraph.buildQueue) {
|
||||
for (let index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) {
|
||||
const project = buildQueue[index];
|
||||
const prepend = referencingProjects.getValue(project);
|
||||
// If the project is referenced with prepend, always build downstream projectm,
|
||||
// otherwise queue it only if declaration output changed
|
||||
if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) {
|
||||
if (prepend !== undefined) {
|
||||
// If the project is referenced with prepend, always build downstream projects,
|
||||
// If declaration output is changed, build the project
|
||||
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
|
||||
const status = projectStatus.getValue(project);
|
||||
if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
|
||||
if (status && (status.type === UpToDateStatusType.UpToDate || status.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === UpToDateStatusType.OutOfDateWithPrepend)) {
|
||||
projectStatus.setValue(project, {
|
||||
type: UpToDateStatusType.OutOfDateWithUpstream,
|
||||
outOfDateOutputFileName: status.type === UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
|
||||
newerProjectName: resolved
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (status && status.type === UpToDateStatusType.UpToDate) {
|
||||
if (prepend) {
|
||||
projectStatus.setValue(project, {
|
||||
type: UpToDateStatusType.OutOfDateWithPrepend,
|
||||
outOfDateOutputFileName: status.oldestOutputFileName,
|
||||
newerProjectName: resolved
|
||||
});
|
||||
}
|
||||
else {
|
||||
status.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
|
||||
}
|
||||
}
|
||||
addProjToQueue(project);
|
||||
}
|
||||
}
|
||||
@@ -1013,8 +1078,7 @@ namespace ts {
|
||||
|
||||
if (options.verbose) reportStatus(Diagnostics.Building_project_0, proj);
|
||||
|
||||
let resultFlags = BuildResultFlags.None;
|
||||
resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
|
||||
let resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
|
||||
|
||||
const configFile = parseConfigFile(proj);
|
||||
if (!configFile) {
|
||||
@@ -1030,22 +1094,22 @@ namespace ts {
|
||||
return BuildResultFlags.None;
|
||||
}
|
||||
|
||||
const programOptions: CreateProgramOptions = {
|
||||
projectReferences: configFile.projectReferences,
|
||||
host,
|
||||
rootNames: configFile.fileNames,
|
||||
options: configFile.options,
|
||||
configFileParsingDiagnostics: configFile.errors
|
||||
};
|
||||
if (host.beforeCreateProgram) {
|
||||
host.beforeCreateProgram(options);
|
||||
}
|
||||
const program = createProgram(programOptions);
|
||||
// TODO: handle resolve module name to cache result in project reference redirect
|
||||
projectCompilerOptions = configFile.options;
|
||||
const program = host.createProgram(
|
||||
configFile.fileNames,
|
||||
configFile.options,
|
||||
compilerHost,
|
||||
getOldProgram(proj, configFile),
|
||||
configFile.errors,
|
||||
configFile.projectReferences
|
||||
);
|
||||
|
||||
// Don't emit anything in the presence of syntactic errors or options diagnostics
|
||||
const syntaxDiagnostics = [
|
||||
...program.getOptionsDiagnostics(),
|
||||
...program.getConfigFileParsingDiagnostics(),
|
||||
...program.getOptionsDiagnostics(),
|
||||
...program.getGlobalDiagnostics(),
|
||||
...program.getSyntacticDiagnostics()];
|
||||
if (syntaxDiagnostics.length) {
|
||||
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
|
||||
@@ -1057,6 +1121,8 @@ namespace ts {
|
||||
return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic");
|
||||
}
|
||||
|
||||
// Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
|
||||
program.backupState();
|
||||
let newestDeclarationFileContentChangedTime = minimumDate;
|
||||
let anyDtsChanged = false;
|
||||
let declDiagnostics: Diagnostic[] | undefined;
|
||||
@@ -1065,11 +1131,13 @@ namespace ts {
|
||||
emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, (name, text, writeByteOrderMark) => outputFiles.push({ name, text, writeByteOrderMark }));
|
||||
// Don't emit .d.ts if there are decl file errors
|
||||
if (declDiagnostics) {
|
||||
program.restoreState();
|
||||
return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
|
||||
}
|
||||
|
||||
// Actual Emit
|
||||
const emitterDiagnostics = createDiagnosticCollection();
|
||||
const emittedOutputs = createFileMap<true>(toPath as ToPath);
|
||||
outputFiles.forEach(({ name, text, writeByteOrderMark }) => {
|
||||
let priorChangeTime: Date | undefined;
|
||||
if (!anyDtsChanged && isDeclarationFile(name)) {
|
||||
@@ -1083,7 +1151,8 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
writeFile(host, emitterDiagnostics, name, text, writeByteOrderMark);
|
||||
emittedOutputs.setValue(name, true);
|
||||
writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
|
||||
if (priorChangeTime !== undefined) {
|
||||
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
|
||||
unchangedOutputs.setValue(name, priorChangeTime);
|
||||
@@ -1095,49 +1164,135 @@ namespace ts {
|
||||
return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
|
||||
}
|
||||
|
||||
const status: UpToDateStatus = {
|
||||
// Update time stamps for rest of the outputs
|
||||
newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
|
||||
|
||||
const status: Status.UpToDate = {
|
||||
type: UpToDateStatusType.UpToDate,
|
||||
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime
|
||||
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime,
|
||||
oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames())
|
||||
};
|
||||
diagnostics.removeKey(proj);
|
||||
projectStatus.setValue(proj, status);
|
||||
if (host.afterProgramEmitAndDiagnostics) {
|
||||
host.afterProgramEmitAndDiagnostics(program);
|
||||
}
|
||||
afterProgramCreate(proj, program);
|
||||
projectCompilerOptions = baseCompilerOptions;
|
||||
return resultFlags;
|
||||
|
||||
function buildErrors(diagnostics: ReadonlyArray<Diagnostic>, errorFlags: BuildResultFlags, errorType: string) {
|
||||
resultFlags |= errorFlags;
|
||||
reportAndStoreErrors(proj, diagnostics);
|
||||
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` });
|
||||
if (host.afterProgramEmitAndDiagnostics) {
|
||||
host.afterProgramEmitAndDiagnostics(program);
|
||||
}
|
||||
afterProgramCreate(proj, program);
|
||||
projectCompilerOptions = baseCompilerOptions;
|
||||
return resultFlags;
|
||||
}
|
||||
}
|
||||
|
||||
function afterProgramCreate(proj: ResolvedConfigFileName, program: T) {
|
||||
if (host.afterProgramEmitAndDiagnostics) {
|
||||
host.afterProgramEmitAndDiagnostics(program);
|
||||
}
|
||||
if (options.watch) {
|
||||
program.releaseProgram();
|
||||
builderPrograms.setValue(proj, program);
|
||||
}
|
||||
}
|
||||
|
||||
function getOldProgram(proj: ResolvedConfigFileName, parsed: ParsedCommandLine) {
|
||||
if (options.force) return undefined;
|
||||
const value = builderPrograms.getValue(proj);
|
||||
if (value) return value;
|
||||
return readBuilderProgram(parsed.options, readFileWithCache) as any as T;
|
||||
}
|
||||
|
||||
function updateBundle(proj: ResolvedConfigFileName): BuildResultFlags {
|
||||
if (options.dry) {
|
||||
reportStatus(Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
|
||||
return BuildResultFlags.Success;
|
||||
}
|
||||
|
||||
if (options.verbose) reportStatus(Diagnostics.Updating_output_of_project_0, proj);
|
||||
|
||||
// Update js, and source map
|
||||
const config = Debug.assertDefined(parseConfigFile(proj));
|
||||
projectCompilerOptions = config.options;
|
||||
const outputFiles = emitUsingBuildInfo(
|
||||
config,
|
||||
compilerHost,
|
||||
ref => parseConfigFile(resolveProjectName(ref.path)));
|
||||
if (isString(outputFiles)) {
|
||||
reportStatus(Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
|
||||
return buildSingleProject(proj);
|
||||
}
|
||||
|
||||
// Actual Emit
|
||||
Debug.assert(!!outputFiles.length);
|
||||
const emitterDiagnostics = createDiagnosticCollection();
|
||||
const emittedOutputs = createFileMap<true>(toPath as ToPath);
|
||||
outputFiles.forEach(({ name, text, writeByteOrderMark }) => {
|
||||
emittedOutputs.setValue(name, true);
|
||||
writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
|
||||
});
|
||||
const emitDiagnostics = emitterDiagnostics.getDiagnostics();
|
||||
if (emitDiagnostics.length) {
|
||||
reportAndStoreErrors(proj, emitDiagnostics);
|
||||
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
|
||||
projectCompilerOptions = baseCompilerOptions;
|
||||
return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
|
||||
}
|
||||
|
||||
// Update timestamps for dts
|
||||
const newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
|
||||
|
||||
const status: Status.UpToDate = {
|
||||
type: UpToDateStatusType.UpToDate,
|
||||
newestDeclarationFileContentChangedTime,
|
||||
oldestOutputFileName: outputFiles[0].name
|
||||
};
|
||||
|
||||
diagnostics.removeKey(proj);
|
||||
projectStatus.setValue(proj, status);
|
||||
projectCompilerOptions = baseCompilerOptions;
|
||||
return BuildResultFlags.DeclarationOutputUnchanged;
|
||||
}
|
||||
|
||||
function updateOutputTimestamps(proj: ParsedCommandLine) {
|
||||
if (options.dry) {
|
||||
return reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!);
|
||||
return reportStatus(Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath!);
|
||||
}
|
||||
const priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, Diagnostics.Updating_output_timestamps_of_project_0);
|
||||
const status: Status.UpToDate = {
|
||||
type: UpToDateStatusType.UpToDate,
|
||||
newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
|
||||
oldestOutputFileName: getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames())
|
||||
};
|
||||
projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, status);
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
reportStatus(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const outputs = getAllProjectOutputs(proj);
|
||||
let priorNewestUpdateTime = minimumDate;
|
||||
for (const file of outputs) {
|
||||
if (isDeclarationFile(file)) {
|
||||
priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || missingFileModifiedTime);
|
||||
function updateOutputTimestampsWorker(proj: ParsedCommandLine, priorNewestUpdateTime: Date, verboseMessage: DiagnosticMessage, skipOutputs?: FileMap<true>) {
|
||||
const outputs = getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
|
||||
if (!skipOutputs || outputs.length !== skipOutputs.getSize()) {
|
||||
if (options.verbose) {
|
||||
reportStatus(verboseMessage, proj.options.configFilePath!);
|
||||
}
|
||||
const now = host.now ? host.now() : new Date();
|
||||
for (const file of outputs) {
|
||||
if (skipOutputs && skipOutputs.hasKey(file)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
host.setModifiedTime(file, now);
|
||||
if (isDeclarationFile(file)) {
|
||||
priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || missingFileModifiedTime);
|
||||
}
|
||||
|
||||
host.setModifiedTime(file, now);
|
||||
if (proj.options.listEmittedFiles) {
|
||||
writeFileName(`TSFILE: ${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus);
|
||||
return priorNewestUpdateTime;
|
||||
}
|
||||
|
||||
function getFilesToClean(): string[] {
|
||||
@@ -1151,7 +1306,7 @@ namespace ts {
|
||||
reportParseConfigFileDiagnostic(proj);
|
||||
continue;
|
||||
}
|
||||
const outputs = getAllProjectOutputs(parsed);
|
||||
const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
|
||||
for (const output of outputs) {
|
||||
if (host.fileExists(output)) {
|
||||
filesToDelete.push(output);
|
||||
@@ -1187,12 +1342,15 @@ namespace ts {
|
||||
if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); }
|
||||
// TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api
|
||||
// Override readFile for json files and output .d.ts to cache the text
|
||||
const { originalReadFile, originalFileExists, originalDirectoryExists,
|
||||
originalCreateDirectory, originalWriteFile, originalGetSourceFile,
|
||||
readFileWithCache: newReadFileWithCache
|
||||
} = changeCompilerHostToUseCache(host, toPath, /*useCacheForSourceFile*/ true);
|
||||
const savedReadFileWithCache = readFileWithCache;
|
||||
const savedGetSourceFile = compilerHost.getSourceFile;
|
||||
|
||||
const { originalReadFile, originalFileExists, originalDirectoryExists,
|
||||
originalCreateDirectory, originalWriteFile, getSourceFileWithCache,
|
||||
readFileWithCache: newReadFileWithCache
|
||||
} = changeCompilerHostLikeToUseCache(host, toPath, (...args) => savedGetSourceFile.call(compilerHost, ...args));
|
||||
readFileWithCache = newReadFileWithCache;
|
||||
compilerHost.getSourceFile = getSourceFileWithCache!;
|
||||
|
||||
const graph = getGlobalDependencyGraph();
|
||||
reportBuildQueue(graph);
|
||||
@@ -1240,7 +1398,10 @@ namespace ts {
|
||||
continue;
|
||||
}
|
||||
|
||||
const buildResult = buildSingleProject(next);
|
||||
const buildResult = needsBuild(status, next) ?
|
||||
buildSingleProject(next) : // Actual build
|
||||
updateBundle(next); // Fake that files have been built by manipulating prepend and existing output
|
||||
|
||||
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
|
||||
}
|
||||
reportErrorSummary();
|
||||
@@ -1249,11 +1410,20 @@ namespace ts {
|
||||
host.directoryExists = originalDirectoryExists;
|
||||
host.createDirectory = originalCreateDirectory;
|
||||
host.writeFile = originalWriteFile;
|
||||
compilerHost.getSourceFile = savedGetSourceFile;
|
||||
readFileWithCache = savedReadFileWithCache;
|
||||
host.getSourceFile = originalGetSourceFile;
|
||||
return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success;
|
||||
}
|
||||
|
||||
function needsBuild(status: UpToDateStatus, configFile: ResolvedConfigFileName) {
|
||||
if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force) return true;
|
||||
const config = parseConfigFile(configFile);
|
||||
return !config ||
|
||||
config.fileNames.length === 0 ||
|
||||
!!config.errors.length ||
|
||||
!isIncrementalCompilation(config.options);
|
||||
}
|
||||
|
||||
function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) {
|
||||
reportAndStoreErrors(proj, [configFileCache.getValue(proj) as Diagnostic]);
|
||||
}
|
||||
@@ -1278,7 +1448,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function relName(path: string): string {
|
||||
return convertToRelativePath(path, host.getCurrentDirectory(), f => host.getCanonicalFileName(f));
|
||||
return convertToRelativePath(path, host.getCurrentDirectory(), f => compilerHost.getCanonicalFileName(f));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1298,19 +1468,6 @@ namespace ts {
|
||||
return combinePaths(project, "tsconfig.json") as ResolvedConfigFileName;
|
||||
}
|
||||
|
||||
export function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray<string> {
|
||||
if (project.options.outFile || project.options.out) {
|
||||
return getOutFileOutputs(project);
|
||||
}
|
||||
else {
|
||||
const outputs: string[] = [];
|
||||
for (const inputFile of project.fileNames) {
|
||||
outputs.push(...getOutputFileNames(inputFile, project));
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatUpToDateStatus<T>(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T) {
|
||||
switch (status.type) {
|
||||
case UpToDateStatusType.OutOfDateWithSelf:
|
||||
@@ -1336,6 +1493,10 @@ namespace ts {
|
||||
}
|
||||
// Don't report anything for "up to date because it was already built" -- too verbose
|
||||
break;
|
||||
case UpToDateStatusType.OutOfDateWithPrepend:
|
||||
return formatMessage(Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed,
|
||||
relName(configFileName),
|
||||
relName(status.newerProjectName));
|
||||
case UpToDateStatusType.UpToDateWithUpstreamTypes:
|
||||
return formatMessage(Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies,
|
||||
relName(configFileName));
|
||||
@@ -1351,6 +1512,11 @@ namespace ts {
|
||||
return formatMessage(Diagnostics.Failed_to_parse_file_0_Colon_1,
|
||||
relName(configFileName),
|
||||
status.reason);
|
||||
case UpToDateStatusType.TsVersionOutputOfDate:
|
||||
return formatMessage(Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2,
|
||||
relName(configFileName),
|
||||
status.version,
|
||||
version);
|
||||
case UpToDateStatusType.ContainerOnly:
|
||||
// Don't report status on "solution" projects
|
||||
case UpToDateStatusType.ComputingUpstream:
|
||||
|
||||
@@ -30,6 +30,8 @@
|
||||
"transformers/destructuring.ts",
|
||||
"transformers/ts.ts",
|
||||
"transformers/es2017.ts",
|
||||
"transformers/es2018.ts",
|
||||
"transformers/es2019.ts",
|
||||
"transformers/esnext.ts",
|
||||
"transformers/jsx.ts",
|
||||
"transformers/es2016.ts",
|
||||
|
||||
+325
-119
@@ -428,6 +428,13 @@ namespace ts {
|
||||
|
||||
// Enum
|
||||
EnumMember,
|
||||
// Unparsed
|
||||
UnparsedPrologue,
|
||||
UnparsedPrepend,
|
||||
UnparsedText,
|
||||
UnparsedInternalText,
|
||||
UnparsedSyntheticReference,
|
||||
|
||||
// Top-level nodes
|
||||
SourceFile,
|
||||
Bundle,
|
||||
@@ -609,7 +616,7 @@ namespace ts {
|
||||
export interface Node extends TextRange {
|
||||
kind: SyntaxKind;
|
||||
flags: NodeFlags;
|
||||
/* @internal */ modifierFlagsCache?: ModifierFlags;
|
||||
/* @internal */ modifierFlagsCache: ModifierFlags;
|
||||
/* @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined
|
||||
decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
|
||||
modifiers?: ModifiersArray; // Array of modifiers
|
||||
@@ -623,7 +630,7 @@ namespace ts {
|
||||
/* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding)
|
||||
/* @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms)
|
||||
/* @internal */ contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution
|
||||
/* @internal */ contextualMapper?: TypeMapper; // Mapper for contextual type
|
||||
/* @internal */ inferenceContext?: InferenceContext; // Inference context for contextual type
|
||||
}
|
||||
|
||||
export interface JSDocContainer {
|
||||
@@ -1233,7 +1240,7 @@ namespace ts {
|
||||
|
||||
export interface TypeOperatorNode extends TypeNode {
|
||||
kind: SyntaxKind.TypeOperator;
|
||||
operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword;
|
||||
operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword;
|
||||
type: TypeNode;
|
||||
}
|
||||
|
||||
@@ -1648,20 +1655,26 @@ namespace ts {
|
||||
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum TokenFlags {
|
||||
None = 0,
|
||||
/* @internal */
|
||||
PrecedingLineBreak = 1 << 0,
|
||||
/* @internal */
|
||||
PrecedingJSDocComment = 1 << 1,
|
||||
/* @internal */
|
||||
Unterminated = 1 << 2,
|
||||
/* @internal */
|
||||
ExtendedUnicodeEscape = 1 << 3,
|
||||
Scientific = 1 << 4, // e.g. `10e2`
|
||||
Octal = 1 << 5, // e.g. `0777`
|
||||
HexSpecifier = 1 << 6, // e.g. `0x00000000`
|
||||
BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000`
|
||||
OctalSpecifier = 1 << 8, // e.g. `0o777`
|
||||
/* @internal */
|
||||
ContainsSeparator = 1 << 9, // e.g. `0b1100_0101`
|
||||
/* @internal */
|
||||
BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier,
|
||||
/* @internal */
|
||||
NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator
|
||||
}
|
||||
|
||||
@@ -1932,9 +1945,9 @@ namespace ts {
|
||||
expression?: Expression;
|
||||
}
|
||||
|
||||
export interface JsxText extends Node {
|
||||
export interface JsxText extends LiteralLikeNode {
|
||||
kind: SyntaxKind.JsxText;
|
||||
containsOnlyWhiteSpaces: boolean;
|
||||
containsOnlyTriviaWhiteSpaces: boolean;
|
||||
parent: JsxElement;
|
||||
}
|
||||
|
||||
@@ -2761,19 +2774,74 @@ namespace ts {
|
||||
|
||||
export interface InputFiles extends Node {
|
||||
kind: SyntaxKind.InputFiles;
|
||||
javascriptPath?: string;
|
||||
javascriptText: string;
|
||||
javascriptMapPath?: string;
|
||||
javascriptMapText?: string;
|
||||
declarationPath?: string;
|
||||
declarationText: string;
|
||||
declarationMapPath?: string;
|
||||
declarationMapText?: string;
|
||||
/*@internal*/ buildInfoPath?: string;
|
||||
/*@internal*/ buildInfo?: BuildInfo;
|
||||
/*@internal*/ oldFileOfCurrentEmit?: boolean;
|
||||
}
|
||||
|
||||
export interface UnparsedSource extends Node {
|
||||
kind: SyntaxKind.UnparsedSource;
|
||||
fileName: string;
|
||||
text: string;
|
||||
prologues: ReadonlyArray<UnparsedPrologue>;
|
||||
helpers: ReadonlyArray<UnscopedEmitHelper> | undefined;
|
||||
|
||||
// References and noDefaultLibAre Dts only
|
||||
referencedFiles: ReadonlyArray<FileReference>;
|
||||
typeReferenceDirectives: ReadonlyArray<string> | undefined;
|
||||
libReferenceDirectives: ReadonlyArray<FileReference>;
|
||||
hasNoDefaultLib?: boolean;
|
||||
|
||||
sourceMapPath?: string;
|
||||
sourceMapText?: string;
|
||||
syntheticReferences?: ReadonlyArray<UnparsedSyntheticReference>;
|
||||
texts: ReadonlyArray<UnparsedSourceText>;
|
||||
/*@internal*/ oldFileOfCurrentEmit?: boolean;
|
||||
/*@internal*/ parsedSourceMap?: RawSourceMap | false | undefined;
|
||||
// Adding this to satisfy services, fix later
|
||||
/*@internal*/
|
||||
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
|
||||
}
|
||||
|
||||
export type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
|
||||
export type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
|
||||
|
||||
export interface UnparsedSection extends Node {
|
||||
kind: SyntaxKind;
|
||||
data?: string;
|
||||
parent: UnparsedSource;
|
||||
}
|
||||
|
||||
export interface UnparsedPrologue extends UnparsedSection {
|
||||
kind: SyntaxKind.UnparsedPrologue;
|
||||
data: string;
|
||||
parent: UnparsedSource;
|
||||
}
|
||||
|
||||
export interface UnparsedPrepend extends UnparsedSection {
|
||||
kind: SyntaxKind.UnparsedPrepend;
|
||||
data: string;
|
||||
parent: UnparsedSource;
|
||||
texts: ReadonlyArray<UnparsedTextLike>;
|
||||
}
|
||||
|
||||
export interface UnparsedTextLike extends UnparsedSection {
|
||||
kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
|
||||
parent: UnparsedSource;
|
||||
}
|
||||
|
||||
export interface UnparsedSyntheticReference extends UnparsedSection {
|
||||
kind: SyntaxKind.UnparsedSyntheticReference;
|
||||
parent: UnparsedSource;
|
||||
/*@internal*/ section: BundleFileHasNoDefaultLib | BundleFileReference;
|
||||
}
|
||||
|
||||
export interface JsonSourceFile extends SourceFile {
|
||||
@@ -2827,7 +2895,7 @@ namespace ts {
|
||||
fileName: string,
|
||||
data: string,
|
||||
writeByteOrderMark: boolean,
|
||||
onError: ((message: string) => void) | undefined,
|
||||
onError?: (message: string) => void,
|
||||
sourceFiles?: ReadonlyArray<SourceFile>,
|
||||
) => void;
|
||||
|
||||
@@ -2926,6 +2994,8 @@ namespace ts {
|
||||
/*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
|
||||
/*@internal*/ forEachResolvedProjectReference<T>(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined;
|
||||
/*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined;
|
||||
/*@internal*/ getProgramBuildInfo?(): ProgramBuildInfo | undefined;
|
||||
/*@internal*/ emitBuildInfo(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -3037,8 +3107,10 @@ namespace ts {
|
||||
/* @internal */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): TypeNode | undefined; // tslint:disable-line unified-signatures
|
||||
/** Note that the resulting nodes cannot be checked. */
|
||||
signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & {typeArguments?: NodeArray<TypeNode>} | undefined;
|
||||
/* @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray<TypeNode>} | undefined; // tslint:disable-line unified-signatures
|
||||
/** Note that the resulting nodes cannot be checked. */
|
||||
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined;
|
||||
/* @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // tslint:disable-line unified-signatures
|
||||
/** Note that the resulting nodes cannot be checked. */
|
||||
symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName | undefined;
|
||||
/** Note that the resulting nodes cannot be checked. */
|
||||
@@ -3098,6 +3170,8 @@ namespace ts {
|
||||
*/
|
||||
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
|
||||
/* @internal */ getResolvedSignatureForSignatureHelp(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
|
||||
/* @internal */ getExpandedParameters(sig: Signature): ReadonlyArray<Symbol>;
|
||||
/* @internal */ hasEffectiveRestParameter(sig: Signature): boolean;
|
||||
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
|
||||
isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined;
|
||||
isUndefinedSymbol(symbol: Symbol): boolean;
|
||||
@@ -3178,6 +3252,8 @@ namespace ts {
|
||||
/* @internal */ getSymbolCount(): number;
|
||||
/* @internal */ getTypeCount(): number;
|
||||
|
||||
/* @internal */ isArrayType(type: Type): boolean;
|
||||
/* @internal */ isTupleType(type: Type): boolean;
|
||||
/* @internal */ isArrayLikeType(type: Type): boolean;
|
||||
/* @internal */ getObjectFlags(type: Type): ObjectFlags;
|
||||
|
||||
@@ -3212,7 +3288,7 @@ namespace ts {
|
||||
*/
|
||||
/* @internal */ resolveExternalModuleSymbol(symbol: Symbol): Symbol;
|
||||
/** @param node A location where we might consider accessing `this`. Not necessarily a ThisExpression. */
|
||||
/* @internal */ tryGetThisTypeAt(node: Node): Type | undefined;
|
||||
/* @internal */ tryGetThisTypeAt(node: Node, includeGlobalThis?: boolean): Type | undefined;
|
||||
/* @internal */ getTypeArgumentConstraint(node: TypeNode): Type | undefined;
|
||||
|
||||
/**
|
||||
@@ -3813,39 +3889,33 @@ namespace ts {
|
||||
}
|
||||
|
||||
export const enum TypeFlags {
|
||||
Any = 1 << 0,
|
||||
Unknown = 1 << 1,
|
||||
String = 1 << 2,
|
||||
Number = 1 << 3,
|
||||
Boolean = 1 << 4,
|
||||
Enum = 1 << 5,
|
||||
BigInt = 1 << 6,
|
||||
StringLiteral = 1 << 7,
|
||||
NumberLiteral = 1 << 8,
|
||||
BooleanLiteral = 1 << 9,
|
||||
EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union
|
||||
BigIntLiteral = 1 << 11,
|
||||
ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6
|
||||
UniqueESSymbol = 1 << 13, // unique symbol
|
||||
Void = 1 << 14,
|
||||
Undefined = 1 << 15,
|
||||
Null = 1 << 16,
|
||||
Never = 1 << 17, // Never type
|
||||
TypeParameter = 1 << 18, // Type parameter
|
||||
Object = 1 << 19, // Object type
|
||||
Union = 1 << 20, // Union (T | U)
|
||||
Intersection = 1 << 21, // Intersection (T & U)
|
||||
Index = 1 << 22, // keyof T
|
||||
IndexedAccess = 1 << 23, // T[K]
|
||||
Conditional = 1 << 24, // T extends U ? X : Y
|
||||
Substitution = 1 << 25, // Type parameter substitution
|
||||
NonPrimitive = 1 << 26, // intrinsic object type
|
||||
/* @internal */
|
||||
ContainsWideningType = 1 << 27, // Type is or contains undefined or null widening type
|
||||
/* @internal */
|
||||
ContainsObjectLiteral = 1 << 28, // Type is or contains object literal type
|
||||
/* @internal */
|
||||
ContainsAnyFunctionType = 1 << 29, // Type is or contains the anyFunctionType
|
||||
Any = 1 << 0,
|
||||
Unknown = 1 << 1,
|
||||
String = 1 << 2,
|
||||
Number = 1 << 3,
|
||||
Boolean = 1 << 4,
|
||||
Enum = 1 << 5,
|
||||
BigInt = 1 << 6,
|
||||
StringLiteral = 1 << 7,
|
||||
NumberLiteral = 1 << 8,
|
||||
BooleanLiteral = 1 << 9,
|
||||
EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union
|
||||
BigIntLiteral = 1 << 11,
|
||||
ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6
|
||||
UniqueESSymbol = 1 << 13, // unique symbol
|
||||
Void = 1 << 14,
|
||||
Undefined = 1 << 15,
|
||||
Null = 1 << 16,
|
||||
Never = 1 << 17, // Never type
|
||||
TypeParameter = 1 << 18, // Type parameter
|
||||
Object = 1 << 19, // Object type
|
||||
Union = 1 << 20, // Union (T | U)
|
||||
Intersection = 1 << 21, // Intersection (T & U)
|
||||
Index = 1 << 22, // keyof T
|
||||
IndexedAccess = 1 << 23, // T[K]
|
||||
Conditional = 1 << 24, // T extends U ? X : Y
|
||||
Substitution = 1 << 25, // Type parameter substitution
|
||||
NonPrimitive = 1 << 26, // intrinsic object type
|
||||
|
||||
/* @internal */
|
||||
AnyOrUnknown = Any | Unknown,
|
||||
@@ -3879,29 +3949,29 @@ namespace ts {
|
||||
InstantiablePrimitive = Index,
|
||||
Instantiable = InstantiableNonPrimitive | InstantiablePrimitive,
|
||||
StructuredOrInstantiable = StructuredType | Instantiable,
|
||||
|
||||
/* @internal */
|
||||
ObjectFlagsType = Nullable | Object | Union | Intersection,
|
||||
// 'Narrowable' types are types where narrowing actually narrows.
|
||||
// This *should* be every type other than null, undefined, void, and never
|
||||
Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive,
|
||||
NotUnionOrUnit = Any | Unknown | ESSymbol | Object | NonPrimitive,
|
||||
/* @internal */
|
||||
NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | StructuredOrInstantiable,
|
||||
// The following flags are aggregated during union and intersection type construction
|
||||
/* @internal */
|
||||
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
|
||||
/* @internal */
|
||||
PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType,
|
||||
IncludesMask = Any | Unknown | Primitive | Never | Object | Union,
|
||||
// The following flags are used for different purposes during union and intersection type construction
|
||||
/* @internal */
|
||||
NonWideningType = ContainsWideningType,
|
||||
IncludesStructuredOrInstantiable = TypeParameter,
|
||||
/* @internal */
|
||||
Wildcard = ContainsObjectLiteral,
|
||||
IncludesNonWideningType = Intersection,
|
||||
/* @internal */
|
||||
EmptyObject = ContainsAnyFunctionType,
|
||||
IncludesWildcard = Index,
|
||||
/* @internal */
|
||||
ConstructionFlags = NonWideningType | Wildcard | EmptyObject,
|
||||
IncludesEmptyObject = IndexedAccess,
|
||||
// The following flag is used for different purposes by maybeTypeOfKind
|
||||
/* @internal */
|
||||
GenericMappedType = ContainsWideningType
|
||||
GenericMappedType = Never,
|
||||
}
|
||||
|
||||
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
|
||||
@@ -3917,7 +3987,9 @@ namespace ts {
|
||||
aliasTypeArguments?: ReadonlyArray<Type>; // Alias type arguments (if any)
|
||||
/* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any)
|
||||
/* @internal */
|
||||
wildcardInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type
|
||||
permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type
|
||||
/* @internal */
|
||||
restrictiveInstantiation?: Type; // Instantiation with type parameters mapped to unconstrained form
|
||||
/* @internal */
|
||||
immediateBaseConstraint?: Type; // Immediate base constraint cache
|
||||
}
|
||||
@@ -3926,6 +3998,12 @@ namespace ts {
|
||||
// Intrinsic types (TypeFlags.Intrinsic)
|
||||
export interface IntrinsicType extends Type {
|
||||
intrinsicName: string; // Name of intrinsic type
|
||||
objectFlags: ObjectFlags;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface NullableType extends IntrinsicType {
|
||||
objectFlags: ObjectFlags;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -3949,6 +4027,7 @@ namespace ts {
|
||||
// Unique symbol types (TypeFlags.UniqueESSymbol)
|
||||
export interface UniqueESSymbolType extends Type {
|
||||
symbol: Symbol;
|
||||
escapedName: __String;
|
||||
}
|
||||
|
||||
export interface StringLiteralType extends LiteralType {
|
||||
@@ -3984,9 +4063,24 @@ namespace ts {
|
||||
MarkerType = 1 << 13, // Marker type used for variance probing
|
||||
JSLiteral = 1 << 14, // Object type declared in JS - disables errors on read/write of nonexisting members
|
||||
FreshLiteral = 1 << 15, // Fresh object literal
|
||||
ClassOrInterface = Class | Interface
|
||||
/* @internal */
|
||||
PrimitiveUnion = 1 << 16, // Union of only primitive types
|
||||
/* @internal */
|
||||
ContainsWideningType = 1 << 17, // Type is or contains undefined or null widening type
|
||||
/* @internal */
|
||||
ContainsObjectLiteral = 1 << 18, // Type is or contains object literal type
|
||||
/* @internal */
|
||||
ContainsAnyFunctionType = 1 << 19, // Type is or contains the anyFunctionType
|
||||
ClassOrInterface = Class | Interface,
|
||||
/* @internal */
|
||||
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
|
||||
/* @internal */
|
||||
PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType;
|
||||
|
||||
// Object types (TypeFlags.ObjectType)
|
||||
export interface ObjectType extends Type {
|
||||
objectFlags: ObjectFlags;
|
||||
@@ -4056,6 +4150,7 @@ namespace ts {
|
||||
export interface TupleType extends GenericType {
|
||||
minLength: number;
|
||||
hasRestElement: boolean;
|
||||
readonly: boolean;
|
||||
associatedNames?: __String[];
|
||||
}
|
||||
|
||||
@@ -4066,6 +4161,8 @@ namespace ts {
|
||||
export interface UnionOrIntersectionType extends Type {
|
||||
types: Type[]; // Constituent types
|
||||
/* @internal */
|
||||
objectFlags: ObjectFlags;
|
||||
/* @internal */
|
||||
propertyCache: SymbolTable; // Cache of resolved properties
|
||||
/* @internal */
|
||||
resolvedProperties: Symbol[];
|
||||
@@ -4080,8 +4177,6 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface UnionType extends UnionOrIntersectionType {
|
||||
/* @internal */
|
||||
primitiveTypesOnly: boolean;
|
||||
}
|
||||
|
||||
export interface IntersectionType extends UnionOrIntersectionType {
|
||||
@@ -4106,7 +4201,6 @@ namespace ts {
|
||||
templateType?: Type;
|
||||
modifiersType?: Type;
|
||||
resolvedApparentType?: Type;
|
||||
instantiating?: boolean;
|
||||
}
|
||||
|
||||
export interface EvolvingArrayType extends ObjectType {
|
||||
@@ -4333,6 +4427,7 @@ namespace ts {
|
||||
None = 0, // No special inference behaviors
|
||||
NoDefault = 1 << 0, // Infer unknownType for no inferences (otherwise anyType or emptyObjectType)
|
||||
AnyDefault = 1 << 1, // Infer anyType for no inferences (otherwise emptyObjectType)
|
||||
SkippedGenericFunction = 1 << 2, // A generic function was skipped during inference
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4355,12 +4450,15 @@ namespace ts {
|
||||
export type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
|
||||
|
||||
/* @internal */
|
||||
export interface InferenceContext extends TypeMapper {
|
||||
typeParameters: ReadonlyArray<TypeParameter>; // Type parameters for which inferences are made
|
||||
signature?: Signature; // Generic signature for which inferences are made (if any)
|
||||
export interface InferenceContext {
|
||||
inferences: InferenceInfo[]; // Inferences made for each type parameter
|
||||
signature?: Signature; // Generic signature for which inferences are made (if any)
|
||||
flags: InferenceFlags; // Inference flags
|
||||
compareTypes: TypeComparer; // Type comparer function
|
||||
mapper: TypeMapper; // Mapper that fixes inferences
|
||||
nonFixingMapper: TypeMapper; // Mapper that doesn't fix inferences
|
||||
returnMapper?: TypeMapper; // Type mapper for inferences from return types (if any)
|
||||
inferredTypeParameters?: ReadonlyArray<TypeParameter>; // Inferred type parameters for function result
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4555,6 +4653,8 @@ namespace ts {
|
||||
reactNamespace?: string;
|
||||
jsxFactory?: string;
|
||||
composite?: boolean;
|
||||
incremental?: boolean;
|
||||
tsBuildInfoFile?: string;
|
||||
removeComments?: boolean;
|
||||
rootDir?: string;
|
||||
rootDirs?: string[];
|
||||
@@ -4649,7 +4749,8 @@ namespace ts {
|
||||
ES2016 = 3,
|
||||
ES2017 = 4,
|
||||
ES2018 = 5,
|
||||
ESNext = 6,
|
||||
ES2019 = 6,
|
||||
ESNext = 7,
|
||||
JSON = 100,
|
||||
Latest = ESNext,
|
||||
}
|
||||
@@ -4964,7 +5065,8 @@ namespace ts {
|
||||
Dts = ".d.ts",
|
||||
Js = ".js",
|
||||
Jsx = ".jsx",
|
||||
Json = ".json"
|
||||
Json = ".json",
|
||||
TsBuildInfo = ".tsbuildinfo"
|
||||
}
|
||||
|
||||
export interface ResolvedModuleWithFailedLookupLocations {
|
||||
@@ -4999,7 +5101,6 @@ namespace ts {
|
||||
getDefaultLibLocation?(): string;
|
||||
writeFile: WriteFileCallback;
|
||||
getCurrentDirectory(): string;
|
||||
getDirectories(path: string): string[];
|
||||
getCanonicalFileName(fileName: string): string;
|
||||
useCaseSensitiveFileNames(): boolean;
|
||||
getNewLine(): string;
|
||||
@@ -5033,36 +5134,29 @@ namespace ts {
|
||||
|
||||
// Facts
|
||||
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
|
||||
TypeScript = 1 << 0,
|
||||
ContainsTypeScript = 1 << 1,
|
||||
ContainsJsx = 1 << 2,
|
||||
ContainsESNext = 1 << 3,
|
||||
ContainsES2017 = 1 << 4,
|
||||
ContainsES2016 = 1 << 5,
|
||||
ES2015 = 1 << 6,
|
||||
ContainsTypeScript = 1 << 0,
|
||||
ContainsJsx = 1 << 1,
|
||||
ContainsESNext = 1 << 2,
|
||||
ContainsES2019 = 1 << 3,
|
||||
ContainsES2018 = 1 << 4,
|
||||
ContainsES2017 = 1 << 5,
|
||||
ContainsES2016 = 1 << 6,
|
||||
ContainsES2015 = 1 << 7,
|
||||
Generator = 1 << 8,
|
||||
ContainsGenerator = 1 << 9,
|
||||
DestructuringAssignment = 1 << 10,
|
||||
ContainsDestructuringAssignment = 1 << 11,
|
||||
ContainsGenerator = 1 << 8,
|
||||
ContainsDestructuringAssignment = 1 << 9,
|
||||
|
||||
// Markers
|
||||
// - Flags used to indicate that a subtree contains a specific transformation.
|
||||
ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers
|
||||
ContainsLexicalThis = 1 << 13,
|
||||
ContainsCapturedLexicalThis = 1 << 14,
|
||||
ContainsLexicalThisInComputedPropertyName = 1 << 15,
|
||||
ContainsDefaultValueAssignments = 1 << 16,
|
||||
ContainsRestOrSpread = 1 << 17,
|
||||
ContainsObjectRestOrSpread = 1 << 18,
|
||||
ContainsComputedPropertyName = 1 << 19,
|
||||
ContainsBlockScopedBinding = 1 << 20,
|
||||
ContainsBindingPattern = 1 << 21,
|
||||
ContainsYield = 1 << 22,
|
||||
ContainsHoistedDeclarationOrCompletion = 1 << 23,
|
||||
ContainsDynamicImport = 1 << 24,
|
||||
Super = 1 << 25,
|
||||
ContainsSuper = 1 << 26,
|
||||
ContainsTypeScriptClassSyntax = 1 << 10, // Decorators, Property Initializers, Parameter Property Initializers
|
||||
ContainsLexicalThis = 1 << 11,
|
||||
ContainsRestOrSpread = 1 << 12,
|
||||
ContainsObjectRestOrSpread = 1 << 13,
|
||||
ContainsComputedPropertyName = 1 << 14,
|
||||
ContainsBlockScopedBinding = 1 << 15,
|
||||
ContainsBindingPattern = 1 << 16,
|
||||
ContainsYield = 1 << 17,
|
||||
ContainsHoistedDeclarationOrCompletion = 1 << 18,
|
||||
ContainsDynamicImport = 1 << 19,
|
||||
|
||||
// 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.
|
||||
@@ -5071,38 +5165,44 @@ namespace ts {
|
||||
|
||||
// Assertions
|
||||
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
|
||||
AssertTypeScript = TypeScript | ContainsTypeScript,
|
||||
AssertTypeScript = ContainsTypeScript,
|
||||
AssertJsx = ContainsJsx,
|
||||
AssertESNext = ContainsESNext,
|
||||
AssertES2019 = ContainsES2019,
|
||||
AssertES2018 = ContainsES2018,
|
||||
AssertES2017 = ContainsES2017,
|
||||
AssertES2016 = ContainsES2016,
|
||||
AssertES2015 = ES2015 | ContainsES2015,
|
||||
AssertGenerator = Generator | ContainsGenerator,
|
||||
AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment,
|
||||
AssertES2015 = ContainsES2015,
|
||||
AssertGenerator = ContainsGenerator,
|
||||
AssertDestructuringAssignment = ContainsDestructuringAssignment,
|
||||
|
||||
// Scope Exclusions
|
||||
// - Bitmasks that exclude flags from propagating out of a specific context
|
||||
// into the subtree flags of their container.
|
||||
OuterExpressionExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
|
||||
PropertyAccessExcludes = OuterExpressionExcludes | Super,
|
||||
NodeExcludes = PropertyAccessExcludes | ContainsSuper,
|
||||
ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
|
||||
ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
|
||||
OuterExpressionExcludes = HasComputedFlags,
|
||||
PropertyAccessExcludes = OuterExpressionExcludes,
|
||||
NodeExcludes = PropertyAccessExcludes,
|
||||
ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
ConstructorExcludes = NodeExcludes | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
MethodOrAccessorExcludes = NodeExcludes | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
PropertyExcludes = NodeExcludes | ContainsLexicalThis,
|
||||
ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName,
|
||||
ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
|
||||
TypeExcludes = ~ContainsTypeScript,
|
||||
ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectRestOrSpread,
|
||||
ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsObjectRestOrSpread,
|
||||
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsRestOrSpread,
|
||||
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRestOrSpread,
|
||||
ParameterExcludes = NodeExcludes,
|
||||
CatchClauseExcludes = NodeExcludes | ContainsObjectRestOrSpread,
|
||||
BindingPatternExcludes = NodeExcludes | ContainsRestOrSpread,
|
||||
|
||||
// Propagating flags
|
||||
// - Bitmasks for flags that should propagate from a child
|
||||
PropertyNamePropagatingFlags = ContainsLexicalThis,
|
||||
|
||||
// Masks
|
||||
// - Additional bitmasks
|
||||
ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments,
|
||||
}
|
||||
|
||||
export interface SourceMapRange extends TextRange {
|
||||
@@ -5172,6 +5272,11 @@ namespace ts {
|
||||
readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node.
|
||||
}
|
||||
|
||||
export interface UnscopedEmitHelper extends EmitHelper {
|
||||
readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope.
|
||||
readonly text: string; // ES3-compatible raw script text, or a function yielding such a string
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string;
|
||||
|
||||
@@ -5236,6 +5341,7 @@ namespace ts {
|
||||
getCurrentDirectory(): string;
|
||||
|
||||
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
|
||||
getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
|
||||
getLibFileFromReference(ref: FileReference): SourceFile | undefined;
|
||||
|
||||
getCommonSourceDirectory(): string;
|
||||
@@ -5244,9 +5350,10 @@ namespace ts {
|
||||
|
||||
isEmitBlocked(emitFileName: string): boolean;
|
||||
|
||||
getPrependNodes(): ReadonlyArray<InputFiles>;
|
||||
getPrependNodes(): ReadonlyArray<InputFiles | UnparsedSource>;
|
||||
|
||||
writeFile: WriteFileCallback;
|
||||
getProgramBuildInfo(): ProgramBuildInfo | undefined;
|
||||
}
|
||||
|
||||
export interface TransformationContext {
|
||||
@@ -5397,23 +5504,116 @@ namespace ts {
|
||||
/*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
|
||||
/*@internal*/ writeList<T extends Node>(format: ListFormat, list: NodeArray<T> | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
|
||||
/*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
|
||||
/*@internal*/ writeBundle(bundle: Bundle, info: BundleInfo | undefined, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
|
||||
/*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
|
||||
/*@internal*/ bundleFileInfo?: BundleFileInfo;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export const enum BundleFileSectionKind {
|
||||
Prologue = "prologue",
|
||||
EmitHelpers = "emitHelpers",
|
||||
NoDefaultLib = "no-default-lib",
|
||||
Reference = "reference",
|
||||
Type = "type",
|
||||
Lib = "lib",
|
||||
Prepend = "prepend",
|
||||
Text = "text",
|
||||
Internal = "internal",
|
||||
// comments?
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileSectionBase extends TextRange {
|
||||
kind: BundleFileSectionKind;
|
||||
data?: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFilePrologue extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.Prologue;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileEmitHelpers extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.EmitHelpers;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileHasNoDefaultLib extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.NoDefaultLib;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileReference extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFilePrepend extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.Prepend;
|
||||
data: string;
|
||||
texts: BundleFileTextLike[];
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export type BundleFileTextLikeKind = BundleFileSectionKind.Text | BundleFileSectionKind.Internal;
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileTextLike extends BundleFileSectionBase {
|
||||
kind: BundleFileTextLikeKind;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export type BundleFileSection = BundleFilePrologue | BundleFileEmitHelpers |
|
||||
BundleFileHasNoDefaultLib | BundleFileReference | BundleFilePrepend |
|
||||
BundleFileTextLike;
|
||||
|
||||
/*@internal*/
|
||||
export interface SourceFilePrologueDirectiveExpression extends TextRange {
|
||||
text: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface SourceFilePrologueDirective extends TextRange {
|
||||
expression: SourceFilePrologueDirectiveExpression;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface SourceFilePrologueInfo {
|
||||
file: number;
|
||||
text: string;
|
||||
directives: SourceFilePrologueDirective[];
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface SourceFileInfo {
|
||||
// List of helpers in own source files emitted if no prepend is present
|
||||
helpers?: string[];
|
||||
prologues?: SourceFilePrologueInfo[];
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileInfo {
|
||||
sections: BundleFileSection[];
|
||||
sources?: SourceFileInfo;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleBuildInfo {
|
||||
js?: BundleFileInfo;
|
||||
dts?: BundleFileInfo;
|
||||
commonSourceDirectory: string;
|
||||
sourceFiles: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* When a bundle contains prepended content, we store a file on disk indicating where the non-prepended
|
||||
* content of that file starts. On a subsequent build where there are no upstream .d.ts changes, we
|
||||
* read the bundle info file and the original .js file to quickly re-use portion of the file
|
||||
* that didn't originate in prepended content.
|
||||
*/
|
||||
/* @internal */
|
||||
export interface BundleInfo {
|
||||
// The offset (in characters, i.e. suitable for .substr) at which the
|
||||
// non-prepended portion of the emitted file starts.
|
||||
originalOffset: number;
|
||||
// The total length of this bundle. Used to ensure we're pulling from
|
||||
// the same source as we originally wrote.
|
||||
totalLength: number;
|
||||
export interface BuildInfo {
|
||||
bundle?: BundleBuildInfo;
|
||||
program?: ProgramBuildInfo;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export interface PrintHandlers {
|
||||
@@ -5481,6 +5681,9 @@ namespace ts {
|
||||
/*@internal*/ extendedDiagnostics?: boolean;
|
||||
/*@internal*/ onlyPrintJsDocStyle?: boolean;
|
||||
/*@internal*/ neverAsciiEscape?: boolean;
|
||||
/*@internal*/ writeBundleFileInfo?: boolean;
|
||||
/*@internal*/ recordInternalSection?: boolean;
|
||||
/*@internal*/ stripInternal?: boolean;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -5523,7 +5726,7 @@ namespace ts {
|
||||
/**
|
||||
* Appends a source map.
|
||||
*/
|
||||
appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string): void;
|
||||
appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter): void;
|
||||
/**
|
||||
* Gets the source map as a `RawSourceMap` object.
|
||||
*/
|
||||
@@ -5569,6 +5772,7 @@ namespace ts {
|
||||
getColumn(): number;
|
||||
getIndent(): number;
|
||||
isAtStartOfLine(): boolean;
|
||||
getTextPosWithWriteLine?(): number;
|
||||
}
|
||||
|
||||
export interface GetEffectiveTypeRootsHost {
|
||||
@@ -5826,6 +6030,7 @@ namespace ts {
|
||||
// The above fallback to `object` when there's no args to allow `{}` (as intended), but not the number 2, for example
|
||||
// TODO: Swap to `undefined` for a cleaner API once strictNullChecks is enabled
|
||||
|
||||
/* @internal */
|
||||
type ConcretePragmaSpecs = typeof commentPragmas;
|
||||
|
||||
/* @internal */
|
||||
@@ -5854,13 +6059,14 @@ namespace ts {
|
||||
|
||||
export interface UserPreferences {
|
||||
readonly disableSuggestions?: boolean;
|
||||
readonly quotePreference?: "double" | "single";
|
||||
readonly quotePreference?: "auto" | "double" | "single";
|
||||
readonly includeCompletionsForModuleExports?: boolean;
|
||||
readonly includeCompletionsWithInsertText?: boolean;
|
||||
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
|
||||
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
|
||||
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
|
||||
readonly allowTextChangesInNewFiles?: boolean;
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
}
|
||||
|
||||
/** Represents a bigint literal value without requiring bigint support */
|
||||
|
||||
+139
-27
@@ -401,10 +401,7 @@ namespace ts {
|
||||
return !nodeIsMissing(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends statements to an array while taking care of prologue directives.
|
||||
*/
|
||||
export function addStatementsAfterPrologue<T extends Statement>(to: T[], from: ReadonlyArray<T> | undefined): T[] {
|
||||
function insertStatementsAfterPrologue<T extends Statement>(to: T[], from: ReadonlyArray<T> | undefined, isPrologueDirective: (node: Node) => boolean): T[] {
|
||||
if (from === undefined || from.length === 0) return to;
|
||||
let statementIndex = 0;
|
||||
// skip all prologue directives to insert at the correct position
|
||||
@@ -417,6 +414,46 @@ namespace ts {
|
||||
return to;
|
||||
}
|
||||
|
||||
function insertStatementAfterPrologue<T extends Statement>(to: T[], statement: T | undefined, isPrologueDirective: (node: Node) => boolean): T[] {
|
||||
if (statement === undefined) return to;
|
||||
let statementIndex = 0;
|
||||
// skip all prologue directives to insert at the correct position
|
||||
for (; statementIndex < to.length; ++statementIndex) {
|
||||
if (!isPrologueDirective(to[statementIndex])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
to.splice(statementIndex, 0, statement);
|
||||
return to;
|
||||
}
|
||||
|
||||
|
||||
function isAnyPrologueDirective(node: Node) {
|
||||
return isPrologueDirective(node) || !!(getEmitFlags(node) & EmitFlags.CustomPrologue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends statements to an array while taking care of prologue directives.
|
||||
*/
|
||||
export function insertStatementsAfterStandardPrologue<T extends Statement>(to: T[], from: ReadonlyArray<T> | undefined): T[] {
|
||||
return insertStatementsAfterPrologue(to, from, isPrologueDirective);
|
||||
}
|
||||
|
||||
export function insertStatementsAfterCustomPrologue<T extends Statement>(to: T[], from: ReadonlyArray<T> | undefined): T[] {
|
||||
return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends statements to an array while taking care of prologue directives.
|
||||
*/
|
||||
export function insertStatementAfterStandardPrologue<T extends Statement>(to: T[], statement: T | undefined): T[] {
|
||||
return insertStatementAfterPrologue(to, statement, isPrologueDirective);
|
||||
}
|
||||
|
||||
export function insertStatementAfterCustomPrologue<T extends Statement>(to: T[], statement: T | undefined): T[] {
|
||||
return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given comment is a triple-slash
|
||||
*
|
||||
@@ -778,7 +815,8 @@ namespace ts {
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
return escapeLeadingUnderscores(name.text);
|
||||
case SyntaxKind.ComputedPropertyName:
|
||||
return isStringOrNumericLiteralLike(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined!; // TODO: GH#18217 Almost all uses of this assume the result to be defined!
|
||||
if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text);
|
||||
return Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
|
||||
default:
|
||||
return Debug.assertNever(name);
|
||||
}
|
||||
@@ -888,7 +926,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
const isMissing = nodeIsMissing(errorNode);
|
||||
const pos = isMissing
|
||||
const pos = isMissing || isJsxText(node)
|
||||
? errorNode.pos
|
||||
: skipTrivia(sourceFile.text, errorNode.pos);
|
||||
|
||||
@@ -1435,6 +1473,11 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
export function isSuperOrSuperProperty(node: Node): node is SuperExpression | SuperProperty {
|
||||
return node.kind === SyntaxKind.SuperKeyword
|
||||
|| isSuperProperty(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether a node is a property or element access expression for `super`.
|
||||
*/
|
||||
@@ -2513,14 +2556,15 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) {
|
||||
if (isInJSFile(node)) {
|
||||
const baseType = getClassExtendsHeritageElement(node);
|
||||
if (baseType && isInJSFile(node)) {
|
||||
// Prefer an @augments tag because it may have type parameters.
|
||||
const tag = getJSDocAugmentsTag(node);
|
||||
if (tag) {
|
||||
return tag.class;
|
||||
}
|
||||
}
|
||||
return getClassExtendsHeritageElement(node);
|
||||
return baseType;
|
||||
}
|
||||
|
||||
export function getClassExtendsHeritageElement(node: ClassLikeDeclaration | InterfaceDeclaration) {
|
||||
@@ -2557,7 +2601,7 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) {
|
||||
export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile | UnparsedSource, reference: FileReference) {
|
||||
if (!host.getCompilerOptions().noResolve) {
|
||||
const referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName);
|
||||
return host.getSourceFile(referenceFileName);
|
||||
@@ -3200,6 +3244,10 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getTextPosWithWriteLine() {
|
||||
return lineStart ? output.length : (output.length + newLine.length);
|
||||
}
|
||||
|
||||
reset();
|
||||
|
||||
return {
|
||||
@@ -3229,7 +3277,8 @@ namespace ts {
|
||||
writeStringLiteral: write,
|
||||
writeSymbol: (s, _) => write(s),
|
||||
writeTrailingSemicolon: write,
|
||||
writeComment: write
|
||||
writeComment: write,
|
||||
getTextPosWithWriteLine
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3354,11 +3403,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface EmitFileNames {
|
||||
jsFilePath: string | undefined;
|
||||
sourceMapFilePath: string | undefined;
|
||||
declarationFilePath: string | undefined;
|
||||
declarationMapPath: string | undefined;
|
||||
bundleInfoPath: string | undefined;
|
||||
jsFilePath?: string | undefined;
|
||||
sourceMapFilePath?: string | undefined;
|
||||
declarationFilePath?: string | undefined;
|
||||
declarationMapPath?: string | undefined;
|
||||
buildInfoPath?: string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3373,22 +3422,31 @@ namespace ts {
|
||||
export function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): ReadonlyArray<SourceFile> {
|
||||
const options = host.getCompilerOptions();
|
||||
const isSourceFileFromExternalLibrary = (file: SourceFile) => host.isSourceFileFromExternalLibrary(file);
|
||||
const getResolvedProjectReferenceToRedirect = (fileName: string) => host.getResolvedProjectReferenceToRedirect(fileName);
|
||||
if (options.outFile || options.out) {
|
||||
const moduleKind = getEmitModuleKind(options);
|
||||
const moduleEmitEnabled = options.emitDeclarationOnly || moduleKind === ModuleKind.AMD || moduleKind === ModuleKind.System;
|
||||
// Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
|
||||
return filter(host.getSourceFiles(), sourceFile =>
|
||||
(moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary));
|
||||
(moduleEmitEnabled || !isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect));
|
||||
}
|
||||
else {
|
||||
const sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
|
||||
return filter(sourceFiles, sourceFile => sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary));
|
||||
return filter(sourceFiles, sourceFile => sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect));
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
|
||||
export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) {
|
||||
return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile);
|
||||
export function sourceFileMayBeEmitted(
|
||||
sourceFile: SourceFile,
|
||||
options: CompilerOptions,
|
||||
isSourceFileFromExternalLibrary: (file: SourceFile) => boolean,
|
||||
getResolvedProjectReferenceToRedirect: (fileName: string) => ResolvedProjectReference | undefined
|
||||
) {
|
||||
return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
|
||||
!sourceFile.isDeclarationFile &&
|
||||
!isSourceFileFromExternalLibrary(sourceFile) &&
|
||||
!(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName));
|
||||
}
|
||||
|
||||
export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string {
|
||||
@@ -3416,8 +3474,8 @@ namespace ts {
|
||||
return computeLineAndCharacterOfPosition(lineMap, pos).line;
|
||||
}
|
||||
|
||||
export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration | undefined {
|
||||
return find(node.members, (member): member is ConstructorDeclaration => isConstructorDeclaration(member) && nodeIsPresent(member.body));
|
||||
export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration & { body: FunctionBody } | undefined {
|
||||
return find(node.members, (member): member is ConstructorDeclaration & { body: FunctionBody } => isConstructorDeclaration(member) && nodeIsPresent(member.body));
|
||||
}
|
||||
|
||||
function getSetAccessorValueParameter(accessor: SetAccessorDeclaration): ParameterDeclaration | undefined {
|
||||
@@ -3790,8 +3848,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getModifierFlags(node: Node): ModifierFlags {
|
||||
if (node.modifierFlagsCache! & ModifierFlags.HasComputedFlags) {
|
||||
return node.modifierFlagsCache! & ~ModifierFlags.HasComputedFlags;
|
||||
if (node.modifierFlagsCache & ModifierFlags.HasComputedFlags) {
|
||||
return node.modifierFlagsCache & ~ModifierFlags.HasComputedFlags;
|
||||
}
|
||||
|
||||
const flags = getModifierFlagsNoCache(node);
|
||||
@@ -4513,7 +4571,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getObjectFlags(type: Type): ObjectFlags {
|
||||
return type.flags & TypeFlags.Object ? (<ObjectType>type).objectFlags : 0;
|
||||
return type.flags & TypeFlags.ObjectFlagsType ? (<ObjectFlagsType>type).objectFlags : 0;
|
||||
}
|
||||
|
||||
export function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker) {
|
||||
@@ -4594,6 +4652,16 @@ namespace ts {
|
||||
export function isAccessExpression(node: Node): node is AccessExpression {
|
||||
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression;
|
||||
}
|
||||
|
||||
export function isBundleFileTextLike(section: BundleFileSection): section is BundleFileTextLike {
|
||||
switch (section.kind) {
|
||||
case BundleFileSectionKind.Text:
|
||||
case BundleFileSectionKind.Internal:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ts {
|
||||
@@ -4601,6 +4669,8 @@ namespace ts {
|
||||
switch (options.target) {
|
||||
case ScriptTarget.ESNext:
|
||||
return "lib.esnext.full.d.ts";
|
||||
case ScriptTarget.ES2019:
|
||||
return "lib.es2019.full.d.ts";
|
||||
case ScriptTarget.ES2018:
|
||||
return "lib.es2018.full.d.ts";
|
||||
case ScriptTarget.ES2017:
|
||||
@@ -5606,6 +5676,11 @@ namespace ts {
|
||||
return node.kind === SyntaxKind.TypeAssertionExpression;
|
||||
}
|
||||
|
||||
export function isConstTypeReference(node: Node) {
|
||||
return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
|
||||
node.typeName.escapedText === "const" && !node.typeArguments;
|
||||
}
|
||||
|
||||
export function isParenthesizedExpression(node: Node): node is ParenthesizedExpression {
|
||||
return node.kind === SyntaxKind.ParenthesizedExpression;
|
||||
}
|
||||
@@ -5979,6 +6054,26 @@ namespace ts {
|
||||
return node.kind === SyntaxKind.UnparsedSource;
|
||||
}
|
||||
|
||||
export function isUnparsedPrepend(node: Node): node is UnparsedPrepend {
|
||||
return node.kind === SyntaxKind.UnparsedPrepend;
|
||||
}
|
||||
|
||||
export function isUnparsedTextLike(node: Node): node is UnparsedTextLike {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.UnparsedText:
|
||||
case SyntaxKind.UnparsedInternalText:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isUnparsedNode(node: Node): node is UnparsedNode {
|
||||
return isUnparsedTextLike(node) ||
|
||||
node.kind === SyntaxKind.UnparsedPrologue ||
|
||||
node.kind === SyntaxKind.UnparsedSyntheticReference;
|
||||
}
|
||||
|
||||
// JSDoc
|
||||
|
||||
export function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression {
|
||||
@@ -6734,7 +6829,7 @@ namespace ts {
|
||||
/* @internal */
|
||||
export function isDeclaration(node: Node): node is NamedDeclaration {
|
||||
if (node.kind === SyntaxKind.TypeParameter) {
|
||||
return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node);
|
||||
return (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || isInJSFile(node);
|
||||
}
|
||||
|
||||
return isDeclarationKind(node.kind);
|
||||
@@ -7024,6 +7119,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
export function formatMessage(_dummy: any, message: DiagnosticMessage, ...args: (string | number | undefined)[]): string;
|
||||
export function formatMessage(_dummy: any, message: DiagnosticMessage): string {
|
||||
let text = getLocaleSpecificMessage(message);
|
||||
|
||||
@@ -7205,6 +7301,10 @@ namespace ts {
|
||||
return !!(compilerOptions.declaration || compilerOptions.composite);
|
||||
}
|
||||
|
||||
export function isIncrementalCompilation(options: CompilerOptions) {
|
||||
return !!(options.incremental || options.composite);
|
||||
}
|
||||
|
||||
export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictBindCallApply" | "strictPropertyInitialization" | "alwaysStrict";
|
||||
|
||||
export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean {
|
||||
@@ -8010,7 +8110,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/** @param path directory of the tsconfig.json */
|
||||
export function matchFiles(path: string, extensions: ReadonlyArray<string> | undefined, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries): string[] {
|
||||
export function matchFiles(path: string, extensions: ReadonlyArray<string> | undefined, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string> | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string): string[] {
|
||||
path = normalizePath(path);
|
||||
currentDirectory = normalizePath(currentDirectory);
|
||||
|
||||
@@ -8023,7 +8123,8 @@ namespace ts {
|
||||
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
|
||||
// If there are no "includes", then just put everything in results[0].
|
||||
const results: string[][] = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]];
|
||||
|
||||
const visited = createMap<true>();
|
||||
const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames);
|
||||
for (const basePath of patterns.basePaths) {
|
||||
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
|
||||
}
|
||||
@@ -8031,6 +8132,9 @@ namespace ts {
|
||||
return flatten<string>(results);
|
||||
|
||||
function visitDirectory(path: string, absolutePath: string, depth: number | undefined) {
|
||||
const canonicalPath = toCanonical(realpath(absolutePath));
|
||||
if (visited.has(canonicalPath)) return;
|
||||
visited.set(canonicalPath, true);
|
||||
const { files, directories } = getFileSystemEntries(path);
|
||||
|
||||
for (const current of sort<string>(files, compareStringsCaseSensitive)) {
|
||||
@@ -8425,6 +8529,14 @@ namespace ts {
|
||||
return arr.slice(index);
|
||||
}
|
||||
|
||||
export function addRelatedInfo<T extends Diagnostic>(diagnostic: T, ...relatedInformation: DiagnosticRelatedInformation[]): T {
|
||||
if (!diagnostic.relatedInformation) {
|
||||
diagnostic.relatedInformation = [];
|
||||
}
|
||||
diagnostic.relatedInformation.push(...relatedInformation);
|
||||
return diagnostic;
|
||||
}
|
||||
|
||||
export function minAndMax<T>(arr: ReadonlyArray<T>, getValue: (value: T) => number): { readonly min: number, readonly max: number } {
|
||||
Debug.assert(arr.length !== 0);
|
||||
let min = getValue(arr[0]);
|
||||
|
||||
@@ -1478,8 +1478,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
return isNodeArray(statements)
|
||||
? setTextRange(createNodeArray(addStatementsAfterPrologue(statements.slice(), declarations)), statements)
|
||||
: addStatementsAfterPrologue(statements, declarations);
|
||||
? setTextRange(createNodeArray(insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements)
|
||||
: insertStatementsAfterStandardPrologue(statements, declarations);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+257
-207
@@ -88,21 +88,6 @@ namespace ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Program structure needed to emit the files and report diagnostics
|
||||
*/
|
||||
export interface ProgramToEmitFilesAndReportErrors {
|
||||
getCurrentDirectory(): string;
|
||||
getCompilerOptions(): CompilerOptions;
|
||||
getSourceFiles(): ReadonlyArray<SourceFile>;
|
||||
getSyntacticDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getOptionsDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getGlobalDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getSemanticDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getConfigFileParsingDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
|
||||
}
|
||||
|
||||
export type ReportEmitErrorSummary = (errorCount: number) => void;
|
||||
|
||||
export function getErrorCountForSummary(diagnostics: ReadonlyArray<Diagnostic>) {
|
||||
@@ -121,6 +106,21 @@ namespace ts {
|
||||
return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Program structure needed to emit the files and report diagnostics
|
||||
*/
|
||||
export interface ProgramToEmitFilesAndReportErrors {
|
||||
getCurrentDirectory(): string;
|
||||
getCompilerOptions(): CompilerOptions;
|
||||
getSourceFiles(): ReadonlyArray<SourceFile>;
|
||||
getSyntacticDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getOptionsDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getGlobalDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getSemanticDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
getConfigFileParsingDiagnostics(): ReadonlyArray<Diagnostic>;
|
||||
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
|
||||
*/
|
||||
@@ -129,7 +129,6 @@ namespace ts {
|
||||
const diagnostics = program.getConfigFileParsingDiagnostics().slice();
|
||||
const configFileParsingDiagnosticsLength = diagnostics.length;
|
||||
addRange(diagnostics, program.getSyntacticDiagnostics());
|
||||
let reportSemanticDiagnostics = false;
|
||||
|
||||
// If we didn't have any syntactic errors, then also try getting the global and
|
||||
// semantic errors.
|
||||
@@ -138,7 +137,7 @@ namespace ts {
|
||||
addRange(diagnostics, program.getGlobalDiagnostics());
|
||||
|
||||
if (diagnostics.length === configFileParsingDiagnosticsLength) {
|
||||
reportSemanticDiagnostics = true;
|
||||
addRange(diagnostics, program.getSemanticDiagnostics());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,10 +145,6 @@ namespace ts {
|
||||
const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(/*targetSourceFile*/ undefined, writeFile);
|
||||
addRange(diagnostics, emitDiagnostics);
|
||||
|
||||
if (reportSemanticDiagnostics) {
|
||||
addRange(diagnostics, program.getSemanticDiagnostics());
|
||||
}
|
||||
|
||||
sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic);
|
||||
if (writeFileName) {
|
||||
const currentDir = program.getCurrentDirectory();
|
||||
@@ -187,30 +182,122 @@ namespace ts {
|
||||
const onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
|
||||
return {
|
||||
onWatchStatusChange,
|
||||
watchFile: system.watchFile ? ((path, callback, pollingInterval) => system.watchFile!(path, callback, pollingInterval)) : () => noopFileWatcher,
|
||||
watchDirectory: system.watchDirectory ? ((path, callback, recursive) => system.watchDirectory!(path, callback, recursive)) : () => noopFileWatcher,
|
||||
setTimeout: system.setTimeout ? ((callback, ms, ...args: any[]) => system.setTimeout!.call(system, callback, ms, ...args)) : noop,
|
||||
clearTimeout: system.clearTimeout ? (timeoutId => system.clearTimeout!(timeoutId)) : noop
|
||||
watchFile: maybeBind(system, system.watchFile) || (() => noopFileWatcher),
|
||||
watchDirectory: maybeBind(system, system.watchDirectory) || (() => noopFileWatcher),
|
||||
setTimeout: maybeBind(system, system.setTimeout) || noop,
|
||||
clearTimeout: maybeBind(system, system.clearTimeout) || noop
|
||||
};
|
||||
}
|
||||
|
||||
export const enum WatchType {
|
||||
ConfigFile = "Config file",
|
||||
SourceFile = "Source file",
|
||||
MissingFile = "Missing file",
|
||||
WildcardDirectory = "Wild card directory",
|
||||
FailedLookupLocations = "Failed Lookup Locations",
|
||||
TypeRoots = "Type roots"
|
||||
}
|
||||
|
||||
interface WatchFactory<X, Y = undefined> extends ts.WatchFactory<X, Y> {
|
||||
writeLog: (s: string) => void;
|
||||
}
|
||||
|
||||
export function createWatchFactory<Y = undefined>(host: { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }) {
|
||||
const watchLogLevel = host.trace ? options.extendedDiagnostics ? WatchLogLevel.Verbose : options.diagnostics ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None;
|
||||
const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? (s => host.trace!(s)) : noop;
|
||||
const result = getWatchFactory<WatchType, Y>(watchLogLevel, writeLog) as WatchFactory<WatchType, Y>;
|
||||
result.writeLog = writeLog;
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createCompilerHostFromProgramHost(host: ProgramHost<any>, getCompilerOptions: () => CompilerOptions, directoryStructureHost: DirectoryStructureHost = host): CompilerHost {
|
||||
const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
|
||||
const hostGetNewLine = memoize(() => host.getNewLine());
|
||||
return {
|
||||
getSourceFile: (fileName, languageVersion, onError) => {
|
||||
let text: string | undefined;
|
||||
try {
|
||||
performance.mark("beforeIORead");
|
||||
text = host.readFile(fileName, getCompilerOptions().charset);
|
||||
performance.mark("afterIORead");
|
||||
performance.measure("I/O Read", "beforeIORead", "afterIORead");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
onError(e.message);
|
||||
}
|
||||
text = "";
|
||||
}
|
||||
|
||||
return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined;
|
||||
},
|
||||
getDefaultLibLocation: maybeBind(host, host.getDefaultLibLocation),
|
||||
getDefaultLibFileName: options => host.getDefaultLibFileName(options),
|
||||
writeFile,
|
||||
getCurrentDirectory: memoize(() => host.getCurrentDirectory()),
|
||||
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
|
||||
getCanonicalFileName: createGetCanonicalFileName(useCaseSensitiveFileNames),
|
||||
getNewLine: () => getNewLineCharacter(getCompilerOptions(), hostGetNewLine),
|
||||
fileExists: f => host.fileExists(f),
|
||||
readFile: f => host.readFile(f),
|
||||
trace: maybeBind(host, host.trace),
|
||||
directoryExists: maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
|
||||
getDirectories: maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
|
||||
realpath: maybeBind(host, host.realpath),
|
||||
getEnvironmentVariable: maybeBind(host, host.getEnvironmentVariable) || (() => ""),
|
||||
createHash: maybeBind(host, host.createHash),
|
||||
readDirectory: maybeBind(host, host.readDirectory),
|
||||
};
|
||||
|
||||
function ensureDirectoriesExist(directoryPath: string) {
|
||||
if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists!(directoryPath)) {
|
||||
const parentDirectory = getDirectoryPath(directoryPath);
|
||||
ensureDirectoriesExist(parentDirectory);
|
||||
if (host.createDirectory) host.createDirectory(directoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) {
|
||||
try {
|
||||
performance.mark("beforeIOWrite");
|
||||
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
|
||||
|
||||
host.writeFile!(fileName, text, writeByteOrderMark);
|
||||
|
||||
performance.mark("afterIOWrite");
|
||||
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
onError(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function setGetSourceFileAsHashVersioned(compilerHost: CompilerHost, host: ProgramHost<any>) {
|
||||
const originalGetSourceFile = compilerHost.getSourceFile;
|
||||
const computeHash = host.createHash || generateDjb2Hash;
|
||||
compilerHost.getSourceFile = (...args) => {
|
||||
const result = originalGetSourceFile.call(compilerHost, ...args);
|
||||
if (result) {
|
||||
result.version = computeHash.call(host, result.text);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the watch compiler host that can be extended with config file or root file names and options host
|
||||
*/
|
||||
function createWatchCompilerHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram: CreateProgram<T> | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost<T> {
|
||||
if (!createProgram) {
|
||||
createProgram = createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram<T>;
|
||||
}
|
||||
|
||||
export function createProgramHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system: System, createProgram: CreateProgram<T> | undefined): ProgramHost<T> {
|
||||
const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath())));
|
||||
let host: DirectoryStructureHost = system;
|
||||
host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!)
|
||||
const useCaseSensitiveFileNames = () => system.useCaseSensitiveFileNames;
|
||||
const writeFileName = (s: string) => system.write(s + system.newLine);
|
||||
const { onWatchStatusChange, watchFile, watchDirectory, setTimeout, clearTimeout } = createWatchHost(system, reportWatchStatus);
|
||||
return {
|
||||
useCaseSensitiveFileNames,
|
||||
useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames,
|
||||
getNewLine: () => system.newLine,
|
||||
getCurrentDirectory: () => system.getCurrentDirectory(),
|
||||
getCurrentDirectory: memoize(() => system.getCurrentDirectory()),
|
||||
getDefaultLibLocation,
|
||||
getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)),
|
||||
fileExists: path => system.fileExists(path),
|
||||
@@ -218,27 +305,25 @@ namespace ts {
|
||||
directoryExists: path => system.directoryExists(path),
|
||||
getDirectories: path => system.getDirectories(path),
|
||||
readDirectory: (path, extensions, exclude, include, depth) => system.readDirectory(path, extensions, exclude, include, depth),
|
||||
realpath: system.realpath && (path => system.realpath!(path)),
|
||||
getEnvironmentVariable: system.getEnvironmentVariable && (name => system.getEnvironmentVariable(name)),
|
||||
watchFile,
|
||||
watchDirectory,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
trace: s => system.write(s),
|
||||
onWatchStatusChange,
|
||||
realpath: maybeBind(system, system.realpath),
|
||||
getEnvironmentVariable: maybeBind(system, system.getEnvironmentVariable),
|
||||
trace: s => system.write(s + system.newLine),
|
||||
createDirectory: path => system.createDirectory(path),
|
||||
writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
|
||||
onCachedDirectoryStructureHostCreate: cacheHost => host = cacheHost || system,
|
||||
createHash: system.createHash && (s => system.createHash!(s)),
|
||||
createProgram,
|
||||
afterProgramCreate: emitFilesAndReportErrorUsingBuilder
|
||||
createHash: maybeBind(system, system.createHash),
|
||||
createProgram: createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram<T>
|
||||
};
|
||||
}
|
||||
|
||||
function getDefaultLibLocation() {
|
||||
return getDirectoryPath(normalizePath(system.getExecutingFilePath()));
|
||||
}
|
||||
|
||||
function emitFilesAndReportErrorUsingBuilder(builderProgram: BuilderProgram) {
|
||||
/**
|
||||
* Creates the watch compiler host that can be extended with config file or root file names and options host
|
||||
*/
|
||||
function createWatchCompilerHost<T extends BuilderProgram = EmitAndSemanticDiagnosticsBuilderProgram>(system = sys, createProgram: CreateProgram<T> | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost<T> {
|
||||
const writeFileName = (s: string) => system.write(s + system.newLine);
|
||||
const result = createProgramHost(system, createProgram) as WatchCompilerHost<T>;
|
||||
copyProperties(result, createWatchHost(system, reportWatchStatus));
|
||||
result.afterProgramCreate = builderProgram => {
|
||||
const compilerOptions = builderProgram.getCompilerOptions();
|
||||
const newLine = getNewLineCharacter(compilerOptions, () => system.newLine);
|
||||
|
||||
@@ -246,13 +331,14 @@ namespace ts {
|
||||
builderProgram,
|
||||
reportDiagnostic,
|
||||
writeFileName,
|
||||
errorCount => onWatchStatusChange!(
|
||||
errorCount => result.onWatchStatusChange!(
|
||||
createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount),
|
||||
newLine,
|
||||
compilerOptions
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -285,12 +371,25 @@ namespace ts {
|
||||
host.projectReferences = projectReferences;
|
||||
return host;
|
||||
}
|
||||
|
||||
export function readBuilderProgram(compilerOptions: CompilerOptions, readFile: (path: string) => string | undefined) {
|
||||
if (compilerOptions.out || compilerOptions.outFile) return undefined;
|
||||
const buildInfoPath = getOutputPathForBuildInfo(compilerOptions);
|
||||
if (!buildInfoPath) return undefined;
|
||||
const content = readFile(buildInfoPath);
|
||||
if (!content) return undefined;
|
||||
const buildInfo = getBuildInfo(content);
|
||||
if (buildInfo.version !== version) return undefined;
|
||||
if (!buildInfo.program) return undefined;
|
||||
return createBuildProgramUsingProgramBuildInfo(buildInfo.program);
|
||||
}
|
||||
}
|
||||
|
||||
namespace ts {
|
||||
export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
|
||||
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
|
||||
export type CreateProgram<T extends BuilderProgram> = (rootNames: ReadonlyArray<string> | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray<Diagnostic>, projectReferences?: ReadonlyArray<ProjectReference> | undefined) => T;
|
||||
|
||||
/** Host that has watch functionality used in --watch mode */
|
||||
export interface WatchHost {
|
||||
/** If provided, called with Diagnostic message that informs about change in watch status */
|
||||
@@ -305,19 +404,11 @@ namespace ts {
|
||||
/** If provided, will be used to reset existing delayed compilation */
|
||||
clearTimeout?(timeoutId: any): void;
|
||||
}
|
||||
export interface WatchCompilerHost<T extends BuilderProgram> extends WatchHost {
|
||||
// TODO: GH#18217 Optional methods are frequently asserted
|
||||
|
||||
export interface ProgramHost<T extends BuilderProgram> {
|
||||
/**
|
||||
* Used to create the program when need for program creation or recreation detected
|
||||
*/
|
||||
createProgram: CreateProgram<T>;
|
||||
/** If provided, callback to invoke after every new program creation */
|
||||
afterProgramCreate?(program: T): void;
|
||||
|
||||
// Only for testing
|
||||
/*@internal*/
|
||||
maxNumberOfFilesToIterateForInvalidation?: number;
|
||||
|
||||
// Sub set of compiler host methods to read and generate new program
|
||||
useCaseSensitiveFileNames(): boolean;
|
||||
@@ -357,16 +448,25 @@ namespace ts {
|
||||
/** If provided, used to resolve type reference directives, otherwise typescript's default resolution */
|
||||
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
}
|
||||
|
||||
/** Internal interface used to wire emit through same host */
|
||||
|
||||
/*@internal*/
|
||||
export interface WatchCompilerHost<T extends BuilderProgram> {
|
||||
export interface ProgramHost<T extends BuilderProgram> {
|
||||
// TODO: GH#18217 Optional methods are frequently asserted
|
||||
createDirectory?(path: string): void;
|
||||
writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void;
|
||||
onCachedDirectoryStructureHostCreate?(host: CachedDirectoryStructureHost): void;
|
||||
}
|
||||
|
||||
export interface WatchCompilerHost<T extends BuilderProgram> extends ProgramHost<T>, WatchHost {
|
||||
/** If provided, callback to invoke after every new program creation */
|
||||
afterProgramCreate?(program: T): void;
|
||||
|
||||
// Only for testing
|
||||
/*@internal*/
|
||||
maxNumberOfFilesToIterateForInvalidation?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Host to create watch with root files and options
|
||||
*/
|
||||
@@ -413,6 +513,9 @@ namespace ts {
|
||||
/** Gets the existing program without synchronizing with changes on host */
|
||||
/*@internal*/
|
||||
getCurrentProgram(): T;
|
||||
/** Closes the watch */
|
||||
/*@internal*/
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -443,8 +546,6 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const initialVersion = 1;
|
||||
|
||||
/**
|
||||
* Creates the watch from the host for root files and compiler options
|
||||
*/
|
||||
@@ -455,13 +556,14 @@ namespace ts {
|
||||
export function createWatchProgram<T extends BuilderProgram>(host: WatchCompilerHostOfConfigFile<T>): WatchOfConfigFile<T>;
|
||||
export function createWatchProgram<T extends BuilderProgram>(host: WatchCompilerHostOfFilesAndCompilerOptions<T> & WatchCompilerHostOfConfigFile<T>): WatchOfFilesAndCompilerOptions<T> | WatchOfConfigFile<T> {
|
||||
interface FilePresentOnHost {
|
||||
version: number;
|
||||
version: string;
|
||||
sourceFile: SourceFile;
|
||||
fileWatcher: FileWatcher;
|
||||
}
|
||||
type FileMissingOnHost = number;
|
||||
type FileMissingOnHost = false;
|
||||
interface FilePresenceUnknownOnHost {
|
||||
version: number;
|
||||
version: false;
|
||||
fileWatcher?: FileWatcher;
|
||||
}
|
||||
type FileMayBePresentOnHost = FilePresentOnHost | FilePresenceUnknownOnHost;
|
||||
type HostFileInfo = FilePresentOnHost | FileMissingOnHost | FilePresenceUnknownOnHost;
|
||||
@@ -479,8 +581,6 @@ namespace ts {
|
||||
|
||||
const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
|
||||
const currentDirectory = host.getCurrentDirectory();
|
||||
const getCurrentDirectory = () => currentDirectory;
|
||||
const readFile: (path: string, encoding?: string) => string | undefined = (path, encoding) => host.readFile(path, encoding);
|
||||
const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, createProgram } = host;
|
||||
let { rootFiles: rootFileNames, options: compilerOptions, projectReferences } = host;
|
||||
let configFileSpecs: ConfigFileSpecs;
|
||||
@@ -493,15 +593,7 @@ namespace ts {
|
||||
host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost);
|
||||
}
|
||||
const directoryStructureHost: DirectoryStructureHost = cachedDirectoryStructureHost || host;
|
||||
const parseConfigFileHost: ParseConfigFileHost = {
|
||||
useCaseSensitiveFileNames,
|
||||
readDirectory: (path, extensions, exclude, include, depth) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth),
|
||||
fileExists: path => host.fileExists(path),
|
||||
readFile,
|
||||
getCurrentDirectory,
|
||||
onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic,
|
||||
trace: host.trace ? s => host.trace!(s) : undefined
|
||||
};
|
||||
const parseConfigFileHost = parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
|
||||
|
||||
// From tsc we want to get already parsed result and hence check for rootFileNames
|
||||
let newLine = updateNewLine();
|
||||
@@ -517,55 +609,39 @@ namespace ts {
|
||||
newLine = updateNewLine();
|
||||
}
|
||||
|
||||
const trace = host.trace && ((s: string) => { host.trace!(s + newLine); });
|
||||
const watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? WatchLogLevel.Verbose :
|
||||
compilerOptions.diagnostics ? WatchLogLevel.TriggerOnly : WatchLogLevel.None : WatchLogLevel.None;
|
||||
const writeLog: (s: string) => void = watchLogLevel !== WatchLogLevel.None ? trace! : noop; // TODO: GH#18217
|
||||
const { watchFile, watchFilePath, watchDirectory } = getWatchFactory<string>(watchLogLevel, writeLog);
|
||||
|
||||
const { watchFile, watchFilePath, watchDirectory, writeLog } = createWatchFactory<string>(host, compilerOptions);
|
||||
const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
|
||||
|
||||
writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`);
|
||||
let configFileWatcher: FileWatcher | undefined;
|
||||
if (configFileName) {
|
||||
watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, "Config file");
|
||||
configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, WatchType.ConfigFile);
|
||||
}
|
||||
|
||||
const compilerHost: CompilerHost & ResolutionCacheHost = {
|
||||
// Members for CompilerHost
|
||||
getSourceFile: (fileName, languageVersion, onError?, shouldCreateNewSourceFile?) => getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile),
|
||||
getSourceFileByPath: getVersionedSourceFileByPath,
|
||||
getDefaultLibLocation: host.getDefaultLibLocation && (() => host.getDefaultLibLocation!()),
|
||||
getDefaultLibFileName: options => host.getDefaultLibFileName(options),
|
||||
writeFile,
|
||||
getCurrentDirectory,
|
||||
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
|
||||
getCanonicalFileName,
|
||||
getNewLine: () => newLine,
|
||||
fileExists,
|
||||
readFile,
|
||||
trace,
|
||||
directoryExists: directoryStructureHost.directoryExists && (path => directoryStructureHost.directoryExists!(path)),
|
||||
getDirectories: (directoryStructureHost.getDirectories && ((path: string) => directoryStructureHost.getDirectories!(path)))!, // TODO: GH#18217
|
||||
realpath: host.realpath && (s => host.realpath!(s)),
|
||||
getEnvironmentVariable: host.getEnvironmentVariable ? (name => host.getEnvironmentVariable!(name)) : (() => ""),
|
||||
onReleaseOldSourceFile,
|
||||
createHash: host.createHash && (data => host.createHash!(data)),
|
||||
// Members for ResolutionCacheHost
|
||||
toPath,
|
||||
getCompilationSettings: () => compilerOptions,
|
||||
watchDirectoryOfFailedLookupLocation: (dir, cb, flags) => watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"),
|
||||
watchTypeRootsDirectory: (dir, cb, flags) => watchDirectory(host, dir, cb, flags, "Type roots"),
|
||||
getCachedDirectoryStructureHost: () => cachedDirectoryStructureHost,
|
||||
onInvalidatedResolution: scheduleProgramUpdate,
|
||||
onChangedAutomaticTypeDirectiveNames: () => {
|
||||
hasChangedAutomaticTypeDirectiveNames = true;
|
||||
scheduleProgramUpdate();
|
||||
},
|
||||
maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation,
|
||||
getCurrentProgram,
|
||||
writeLog,
|
||||
readDirectory: (path, extensions, exclude, include, depth?) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth),
|
||||
const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost) as CompilerHost & ResolutionCacheHost;
|
||||
setGetSourceFileAsHashVersioned(compilerHost, host);
|
||||
// Members for CompilerHost
|
||||
const getNewSourceFile = compilerHost.getSourceFile;
|
||||
compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath(fileName), ...args);
|
||||
compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
|
||||
compilerHost.getNewLine = () => newLine;
|
||||
compilerHost.fileExists = fileExists;
|
||||
compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
|
||||
// Members for ResolutionCacheHost
|
||||
compilerHost.toPath = toPath;
|
||||
compilerHost.getCompilationSettings = () => compilerOptions;
|
||||
compilerHost.watchDirectoryOfFailedLookupLocation = (dir, cb, flags) => watchDirectory(host, dir, cb, flags, WatchType.FailedLookupLocations);
|
||||
compilerHost.watchTypeRootsDirectory = (dir, cb, flags) => watchDirectory(host, dir, cb, flags, WatchType.TypeRoots);
|
||||
compilerHost.getCachedDirectoryStructureHost = () => cachedDirectoryStructureHost;
|
||||
compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
|
||||
compilerHost.onChangedAutomaticTypeDirectiveNames = () => {
|
||||
hasChangedAutomaticTypeDirectiveNames = true;
|
||||
scheduleProgramUpdate();
|
||||
};
|
||||
compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation;
|
||||
compilerHost.getCurrentProgram = getCurrentProgram;
|
||||
compilerHost.writeLog = writeLog;
|
||||
|
||||
// Cache for the module resolution
|
||||
const resolutionCache = createResolutionCache(compilerHost, configFileName ?
|
||||
getDirectoryPath(getNormalizedAbsolutePath(configFileName, currentDirectory)) :
|
||||
@@ -581,27 +657,50 @@ namespace ts {
|
||||
((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference));
|
||||
const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
|
||||
|
||||
builderProgram = readBuilderProgram(compilerOptions, path => compilerHost.readFile(path)) as any as T;
|
||||
synchronizeProgram();
|
||||
|
||||
// Update the wild card directory watch
|
||||
watchConfigFileWildCardDirectories();
|
||||
|
||||
return configFileName ?
|
||||
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } :
|
||||
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames };
|
||||
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close } :
|
||||
{ getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames, close };
|
||||
|
||||
function close() {
|
||||
resolutionCache.clear();
|
||||
clearMap(sourceFilesCache, value => {
|
||||
if (value && value.fileWatcher) {
|
||||
value.fileWatcher.close();
|
||||
value.fileWatcher = undefined;
|
||||
}
|
||||
});
|
||||
if (configFileWatcher) {
|
||||
configFileWatcher.close();
|
||||
configFileWatcher = undefined;
|
||||
}
|
||||
if (watchedWildcardDirectories) {
|
||||
clearMap(watchedWildcardDirectories, closeFileWatcherOf);
|
||||
watchedWildcardDirectories = undefined!;
|
||||
}
|
||||
if (missingFilesMap) {
|
||||
clearMap(missingFilesMap, closeFileWatcher);
|
||||
missingFilesMap = undefined!;
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentBuilderProgram() {
|
||||
return builderProgram;
|
||||
}
|
||||
|
||||
function getCurrentProgram() {
|
||||
return builderProgram && builderProgram.getProgram();
|
||||
return builderProgram && builderProgram.getProgramOrUndefined();
|
||||
}
|
||||
|
||||
function synchronizeProgram() {
|
||||
writeLog(`Synchronizing program`);
|
||||
|
||||
const program = getCurrentProgram();
|
||||
const program = getCurrentBuilderProgram();
|
||||
if (hasChangedCompilerOptions) {
|
||||
newLine = updateNewLine();
|
||||
if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
|
||||
@@ -618,7 +717,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
else {
|
||||
createNewProgram(program, hasInvalidatedResolution);
|
||||
createNewProgram(hasInvalidatedResolution);
|
||||
}
|
||||
|
||||
if (host.afterProgramCreate) {
|
||||
@@ -628,15 +727,13 @@ namespace ts {
|
||||
return builderProgram;
|
||||
}
|
||||
|
||||
function createNewProgram(program: Program, hasInvalidatedResolution: HasInvalidatedResolution) {
|
||||
function createNewProgram(hasInvalidatedResolution: HasInvalidatedResolution) {
|
||||
// Compile the program
|
||||
if (watchLogLevel !== WatchLogLevel.None) {
|
||||
writeLog("CreatingProgramWith::");
|
||||
writeLog(` roots: ${JSON.stringify(rootFileNames)}`);
|
||||
writeLog(` options: ${JSON.stringify(compilerOptions)}`);
|
||||
}
|
||||
writeLog("CreatingProgramWith::");
|
||||
writeLog(` roots: ${JSON.stringify(rootFileNames)}`);
|
||||
writeLog(` options: ${JSON.stringify(compilerOptions)}`);
|
||||
|
||||
const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program;
|
||||
const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
|
||||
hasChangedCompilerOptions = false;
|
||||
hasChangedConfigFileParsingErrors = false;
|
||||
resolutionCache.startCachingPerDirectoryResolution();
|
||||
@@ -680,19 +777,19 @@ namespace ts {
|
||||
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
|
||||
}
|
||||
|
||||
function isFileMissingOnHost(hostSourceFile: HostFileInfo): hostSourceFile is FileMissingOnHost {
|
||||
return typeof hostSourceFile === "number";
|
||||
function isFileMissingOnHost(hostSourceFile: HostFileInfo | undefined): hostSourceFile is FileMissingOnHost {
|
||||
return typeof hostSourceFile === "boolean";
|
||||
}
|
||||
|
||||
function isFilePresentOnHost(hostSourceFile: FileMayBePresentOnHost): hostSourceFile is FilePresentOnHost {
|
||||
return !!(hostSourceFile as FilePresentOnHost).sourceFile;
|
||||
function isFilePresenceUnknownOnHost(hostSourceFile: FileMayBePresentOnHost): hostSourceFile is FilePresenceUnknownOnHost {
|
||||
return typeof (hostSourceFile as FilePresenceUnknownOnHost).version === "boolean";
|
||||
}
|
||||
|
||||
function fileExists(fileName: string) {
|
||||
const path = toPath(fileName);
|
||||
// If file is missing on host from cache, we can definitely say file doesnt exist
|
||||
// otherwise we need to ensure from the disk
|
||||
if (isFileMissingOnHost(sourceFilesCache.get(path)!)) {
|
||||
if (isFileMissingOnHost(sourceFilesCache.get(path))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -700,66 +797,44 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getVersionedSourceFileByPath(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined {
|
||||
const hostSourceFile = sourceFilesCache.get(path)!;
|
||||
const hostSourceFile = sourceFilesCache.get(path);
|
||||
// No source file on the host
|
||||
if (isFileMissingOnHost(hostSourceFile)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Create new source file if requested or the versions dont match
|
||||
if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) {
|
||||
const sourceFile = getNewSourceFile();
|
||||
if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
|
||||
const sourceFile = getNewSourceFile(fileName, languageVersion, onError);
|
||||
if (hostSourceFile) {
|
||||
if (shouldCreateNewSourceFile) {
|
||||
hostSourceFile.version++;
|
||||
}
|
||||
|
||||
if (sourceFile) {
|
||||
// Set the source file and create file watcher now that file was present on the disk
|
||||
(hostSourceFile as FilePresentOnHost).sourceFile = sourceFile;
|
||||
sourceFile.version = hostSourceFile.version.toString();
|
||||
if (!(hostSourceFile as FilePresentOnHost).fileWatcher) {
|
||||
(hostSourceFile as FilePresentOnHost).fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, "Source file");
|
||||
hostSourceFile.version = sourceFile.version;
|
||||
if (!hostSourceFile.fileWatcher) {
|
||||
hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// There is no source file on host any more, close the watch, missing file paths will track it
|
||||
if (isFilePresentOnHost(hostSourceFile)) {
|
||||
if (hostSourceFile.fileWatcher) {
|
||||
hostSourceFile.fileWatcher.close();
|
||||
}
|
||||
sourceFilesCache.set(path, hostSourceFile.version);
|
||||
sourceFilesCache.set(path, false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (sourceFile) {
|
||||
sourceFile.version = initialVersion.toString();
|
||||
const fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, "Source file");
|
||||
sourceFilesCache.set(path, { sourceFile, version: initialVersion, fileWatcher });
|
||||
const fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile);
|
||||
sourceFilesCache.set(path, { sourceFile, version: sourceFile.version, fileWatcher });
|
||||
}
|
||||
else {
|
||||
sourceFilesCache.set(path, initialVersion);
|
||||
sourceFilesCache.set(path, false);
|
||||
}
|
||||
}
|
||||
return sourceFile;
|
||||
}
|
||||
return hostSourceFile.sourceFile;
|
||||
|
||||
function getNewSourceFile() {
|
||||
let text: string | undefined;
|
||||
try {
|
||||
performance.mark("beforeIORead");
|
||||
text = host.readFile(fileName, compilerOptions.charset);
|
||||
performance.mark("afterIORead");
|
||||
performance.measure("I/O Read", "beforeIORead", "afterIORead");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
onError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
return text !== undefined ? createSourceFile(fileName, text, languageVersion) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function nextSourceFileVersion(path: Path) {
|
||||
@@ -767,17 +842,17 @@ namespace ts {
|
||||
if (hostSourceFile !== undefined) {
|
||||
if (isFileMissingOnHost(hostSourceFile)) {
|
||||
// The next version, lets set it as presence unknown file
|
||||
sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 });
|
||||
sourceFilesCache.set(path, { version: false });
|
||||
}
|
||||
else {
|
||||
hostSourceFile.version++;
|
||||
(hostSourceFile as FilePresenceUnknownOnHost).version = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getSourceVersion(path: Path): string | undefined {
|
||||
const hostSourceFile = sourceFilesCache.get(path);
|
||||
return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString();
|
||||
return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
|
||||
}
|
||||
|
||||
function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions, hasSourceFileByPath: boolean) {
|
||||
@@ -786,14 +861,14 @@ namespace ts {
|
||||
// remove the cached entry.
|
||||
// Note we arent deleting entry if file became missing in new program or
|
||||
// there was version update and new source file was created.
|
||||
if (hostSourceFileInfo) {
|
||||
if (hostSourceFileInfo !== undefined) {
|
||||
// record the missing file paths so they can be removed later if watchers arent tracking them
|
||||
if (isFileMissingOnHost(hostSourceFileInfo)) {
|
||||
(missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
|
||||
}
|
||||
else if ((hostSourceFileInfo as FilePresentOnHost).sourceFile === oldSourceFile) {
|
||||
if ((hostSourceFileInfo as FilePresentOnHost).fileWatcher) {
|
||||
(hostSourceFileInfo as FilePresentOnHost).fileWatcher.close();
|
||||
if (hostSourceFileInfo.fileWatcher) {
|
||||
hostSourceFileInfo.fileWatcher.close();
|
||||
}
|
||||
sourceFilesCache.delete(oldSourceFile.resolvedPath);
|
||||
if (!hasSourceFileByPath) {
|
||||
@@ -890,7 +965,7 @@ namespace ts {
|
||||
updateCachedSystemWithFile(fileName, path, eventKind);
|
||||
|
||||
// Update the source file cache
|
||||
if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) {
|
||||
if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
|
||||
resolutionCache.invalidateResolutionOfFile(path);
|
||||
}
|
||||
resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
|
||||
@@ -907,7 +982,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function watchMissingFilePath(missingFilePath: Path) {
|
||||
return watchFilePath(host, missingFilePath, onMissingFileChange, PollingInterval.Medium, missingFilePath, "Missing file");
|
||||
return watchFilePath(host, missingFilePath, onMissingFileChange, PollingInterval.Medium, missingFilePath, WatchType.MissingFile);
|
||||
}
|
||||
|
||||
function onMissingFileChange(fileName: string, eventKind: FileWatcherEventKind, missingFilePath: Path) {
|
||||
@@ -953,7 +1028,7 @@ namespace ts {
|
||||
}
|
||||
nextSourceFileVersion(fileOrDirectoryPath);
|
||||
|
||||
if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return;
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return;
|
||||
|
||||
// If the the added or created file or directory is not supported file name, ignore the file
|
||||
// But when watched directory is added/removed, we need to reload the file list
|
||||
@@ -971,33 +1046,8 @@ namespace ts {
|
||||
}
|
||||
},
|
||||
flags,
|
||||
"Wild card directories"
|
||||
WatchType.WildcardDirectory
|
||||
);
|
||||
}
|
||||
|
||||
function ensureDirectoriesExist(directoryPath: string) {
|
||||
if (directoryPath.length > getRootLength(directoryPath) && !host.directoryExists!(directoryPath)) {
|
||||
const parentDirectory = getDirectoryPath(directoryPath);
|
||||
ensureDirectoriesExist(parentDirectory);
|
||||
host.createDirectory!(directoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) {
|
||||
try {
|
||||
performance.mark("beforeIOWrite");
|
||||
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
|
||||
|
||||
host.writeFile!(fileName, text, writeByteOrderMark);
|
||||
|
||||
performance.mark("afterIOWrite");
|
||||
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
|
||||
}
|
||||
catch (e) {
|
||||
if (onError) {
|
||||
onError(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace ts {
|
||||
directoryExists?(path: string): boolean;
|
||||
getDirectories?(path: string): string[];
|
||||
readDirectory?(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[];
|
||||
realpath?(path: string): string;
|
||||
|
||||
createDirectory?(path: string): void;
|
||||
writeFile?(path: string, data: string, writeByteOrderMark?: boolean): void;
|
||||
@@ -56,7 +57,8 @@ namespace ts {
|
||||
writeFile: host.writeFile && writeFile,
|
||||
addOrDeleteFileOrDirectory,
|
||||
addOrDeleteFile,
|
||||
clearCache
|
||||
clearCache,
|
||||
realpath: host.realpath && realpath
|
||||
};
|
||||
|
||||
function toPath(fileName: string) {
|
||||
@@ -170,7 +172,7 @@ namespace ts {
|
||||
const rootDirPath = toPath(rootDir);
|
||||
const result = tryReadDirectory(rootDir, rootDirPath);
|
||||
if (result) {
|
||||
return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries);
|
||||
return matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
|
||||
}
|
||||
return host.readDirectory!(rootDir, extensions, excludes, includes, depth);
|
||||
|
||||
@@ -183,6 +185,10 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function realpath(s: string) {
|
||||
return host.realpath ? host.realpath(s) : s;
|
||||
}
|
||||
|
||||
function addOrDeleteFileOrDirectory(fileOrDirectory: string, fileOrDirectoryPath: Path) {
|
||||
const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
|
||||
if (existingResult) {
|
||||
@@ -343,10 +349,10 @@ namespace ts {
|
||||
export interface WatchDirectoryHost {
|
||||
watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
|
||||
}
|
||||
export type WatchFile<X, Y> = (host: WatchFileHost, file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, detailInfo1?: X, detailInfo2?: Y) => FileWatcher;
|
||||
export type WatchFile<X, Y> = (host: WatchFileHost, file: string, callback: FileWatcherCallback, pollingInterval: PollingInterval, detailInfo1: X, detailInfo2?: Y) => FileWatcher;
|
||||
export type FilePathWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind, filePath: Path) => void;
|
||||
export type WatchFilePath<X, Y> = (host: WatchFileHost, file: string, callback: FilePathWatcherCallback, pollingInterval: PollingInterval, path: Path, detailInfo1?: X, detailInfo2?: Y) => FileWatcher;
|
||||
export type WatchDirectory<X, Y> = (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, detailInfo1?: X, detailInfo2?: Y) => FileWatcher;
|
||||
export type WatchFilePath<X, Y> = (host: WatchFileHost, file: string, callback: FilePathWatcherCallback, pollingInterval: PollingInterval, path: Path, detailInfo1: X, detailInfo2?: Y) => FileWatcher;
|
||||
export type WatchDirectory<X, Y> = (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags, detailInfo1: X, detailInfo2?: Y) => FileWatcher;
|
||||
|
||||
export interface WatchFactory<X, Y> {
|
||||
watchFile: WatchFile<X, Y>;
|
||||
@@ -361,9 +367,9 @@ namespace ts {
|
||||
function getWatchFactoryWith<X, Y = undefined>(watchLogLevel: WatchLogLevel, log: (s: string) => void, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined,
|
||||
watchFile: (host: WatchFileHost, file: string, callback: FileWatcherCallback, watchPriority: PollingInterval) => FileWatcher,
|
||||
watchDirectory: (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags) => FileWatcher): WatchFactory<X, Y> {
|
||||
const createFileWatcher: CreateFileWatcher<WatchFileHost, PollingInterval, FileWatcherEventKind, undefined, X, Y> = getCreateFileWatcher(watchLogLevel, watchFile);
|
||||
const createFileWatcher: CreateFileWatcher<WatchFileHost, PollingInterval, FileWatcherEventKind, never, X, Y> = getCreateFileWatcher(watchLogLevel, watchFile);
|
||||
const createFilePathWatcher: CreateFileWatcher<WatchFileHost, PollingInterval, FileWatcherEventKind, Path, X, Y> = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
|
||||
const createDirectoryWatcher: CreateFileWatcher<WatchDirectoryHost, WatchDirectoryFlags, undefined, undefined, X, Y> = getCreateFileWatcher(watchLogLevel, watchDirectory);
|
||||
const createDirectoryWatcher: CreateFileWatcher<WatchDirectoryHost, WatchDirectoryFlags, undefined, never, X, Y> = getCreateFileWatcher(watchLogLevel, watchDirectory);
|
||||
return {
|
||||
watchFile: (host, file, callback, pollingInterval, detailInfo1, detailInfo2) =>
|
||||
createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo),
|
||||
@@ -402,7 +408,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function createFileWatcherWithLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, undefined>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
function createFileWatcherWithLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, V>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
log(`${watchCaption}:: Added:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`);
|
||||
const watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
|
||||
return {
|
||||
@@ -413,7 +419,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function createDirectoryWatcherWithLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, undefined>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
function createDirectoryWatcherWithLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, V>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
const watchInfo = `${watchCaption}:: Added:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`;
|
||||
log(watchInfo);
|
||||
const start = timestamp();
|
||||
@@ -432,7 +438,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function createFileWatcherWithTriggerLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, undefined>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
function createFileWatcherWithTriggerLogging<H, T, U, V, X, Y>(host: H, file: string, cb: WatchCallback<U, V>, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch<H, T, U, V>, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined): FileWatcher {
|
||||
return addWatch(host, file, (fileName, cbOptional) => {
|
||||
const triggerredInfo = `${watchCaption}:: Triggered with ${fileName} ${cbOptional !== undefined ? cbOptional : ""}:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`;
|
||||
log(triggerredInfo);
|
||||
@@ -444,7 +450,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getWatchInfo<T, X, Y>(file: string, flags: T, detailInfo1: X, detailInfo2: Y | undefined, getDetailWatchInfo: GetDetailWatchInfo<X, Y> | undefined) {
|
||||
return `WatchInfo: ${file} ${flags} ${getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1}`;
|
||||
return `WatchInfo: ${file} ${flags} ${getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`;
|
||||
}
|
||||
|
||||
export function closeFileWatcherOf<T extends { watcher: FileWatcher; }>(objWithWatcher: T) {
|
||||
|
||||
@@ -384,7 +384,8 @@ namespace ts.server {
|
||||
return notImplemented();
|
||||
}
|
||||
|
||||
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
|
||||
getRenameInfo(fileName: string, position: number, _options?: RenameInfoOptions, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
|
||||
// Not passing along 'options' because server should already have those from the 'configure' command
|
||||
const args: protocol.RenameRequestArgs = { ...this.createFileLocationRequestArgs(fileName, position), findInStrings, findInComments };
|
||||
|
||||
const request = this.processRequest<protocol.RenameRequest>(CommandNames.Rename, args);
|
||||
@@ -428,7 +429,7 @@ namespace ts.server {
|
||||
this.lastRenameEntry.inputs.position !== position ||
|
||||
this.lastRenameEntry.inputs.findInStrings !== findInStrings ||
|
||||
this.lastRenameEntry.inputs.findInComments !== findInComments) {
|
||||
this.getRenameInfo(fileName, position, findInStrings, findInComments);
|
||||
this.getRenameInfo(fileName, position, { allowRenameOfImportPath: true }, findInStrings, findInComments);
|
||||
}
|
||||
|
||||
return this.lastRenameEntry!.locations;
|
||||
|
||||
@@ -183,8 +183,9 @@ namespace compiler {
|
||||
}
|
||||
|
||||
public getSourceMapRecord(): string | undefined {
|
||||
if (this.result!.sourceMaps && this.result!.sourceMaps!.length > 0) {
|
||||
return Harness.SourceMapRecorder.getSourceMapRecord(this.result!.sourceMaps!, this.program!, Array.from(this.js.values()).filter(d => !ts.fileExtensionIs(d.file, ts.Extension.Json)), Array.from(this.dts.values()));
|
||||
const maps = this.result!.sourceMaps;
|
||||
if (maps && maps.length > 0) {
|
||||
return Harness.SourceMapRecorder.getSourceMapRecord(maps, this.program!, Array.from(this.js.values()).filter(d => !ts.fileExtensionIs(d.file, ts.Extension.Json)), Array.from(this.dts.values()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ namespace evaluator {
|
||||
}
|
||||
|
||||
const evaluateText = `(function (module, exports, require, __dirname, __filename, ${globalNames.join(", ")}) { ${output.text} })`;
|
||||
// tslint:disable-next-line:no-eval
|
||||
const evaluateThunk = eval(evaluateText) as (module: any, exports: any, require: (id: string) => any, dirname: string, filename: string, ...globalArgs: any[]) => void;
|
||||
const module: { exports: any; } = { exports: {} };
|
||||
evaluateThunk.call(globals, module, module.exports, noRequire, vpath.dirname(output.file), output.file, FakeSymbol, ...globalArgs);
|
||||
|
||||
+91
-12
@@ -87,7 +87,7 @@ namespace fakes {
|
||||
}
|
||||
|
||||
public readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[] {
|
||||
return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, path => this.getAccessibleFileSystemEntries(path));
|
||||
return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, path => this.getAccessibleFileSystemEntries(path), path => this.realpath(path));
|
||||
}
|
||||
|
||||
public getAccessibleFileSystemEntries(path: string): ts.FileSystemEntries {
|
||||
@@ -375,7 +375,90 @@ namespace fakes {
|
||||
}
|
||||
}
|
||||
|
||||
export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuilderHost {
|
||||
export type ExpectedDiagnostic = [ts.DiagnosticMessage, ...(string | number)[]];
|
||||
function expectedDiagnosticToText([message, ...args]: ExpectedDiagnostic) {
|
||||
let text = ts.getLocaleSpecificMessage(message);
|
||||
if (args.length) {
|
||||
text = ts.formatStringFromArgs(text, args);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function compareProgramBuildInfoDiagnostic(a: ts.ProgramBuildInfoDiagnostic, b: ts.ProgramBuildInfoDiagnostic) {
|
||||
return ts.compareStringsCaseSensitive(ts.isString(a) ? a : a[0], ts.isString(b) ? b : b[0]);
|
||||
}
|
||||
|
||||
export const version = "FakeTSVersion";
|
||||
|
||||
export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuilderHost<ts.BuilderProgram> {
|
||||
createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
|
||||
|
||||
readFile(path: string) {
|
||||
const value = super.readFile(path);
|
||||
if (!value || !ts.isBuildInfoFile(path)) return value;
|
||||
const buildInfo = ts.getBuildInfo(value);
|
||||
if (buildInfo.program) {
|
||||
// Fix lib signatures
|
||||
for (const path of ts.getOwnKeys(buildInfo.program.fileInfos)) {
|
||||
if (ts.startsWith(path, "/lib/")) {
|
||||
const currentValue = buildInfo.program.fileInfos[path];
|
||||
ts.Debug.assert(currentValue.signature === path);
|
||||
ts.Debug.assert(currentValue.signature === currentValue.version);
|
||||
const text = super.readFile(path)!;
|
||||
const signature = ts.generateDjb2Hash(text);
|
||||
buildInfo.program.fileInfos[path] = { version: signature, signature };
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.Debug.assert(buildInfo.version === version);
|
||||
buildInfo.version = ts.version;
|
||||
return ts.getBuildInfoText(buildInfo);
|
||||
}
|
||||
|
||||
public writeFile(fileName: string, content: string, writeByteOrderMark: boolean) {
|
||||
if (!ts.isBuildInfoFile(fileName)) return super.writeFile(fileName, content, writeByteOrderMark);
|
||||
const buildInfo = ts.getBuildInfo(content);
|
||||
if (buildInfo.program) {
|
||||
// Fix lib signatures
|
||||
for (const path of ts.getOwnKeys(buildInfo.program.fileInfos)) {
|
||||
if (ts.startsWith(path, "/lib/")) {
|
||||
const currentValue = buildInfo.program.fileInfos[path];
|
||||
ts.Debug.assert(currentValue.signature === currentValue.version);
|
||||
buildInfo.program.fileInfos[path] = { version: path, signature: path };
|
||||
}
|
||||
}
|
||||
|
||||
// reference Map
|
||||
if (buildInfo.program.referencedMap) {
|
||||
const referencedMap: ts.MapLike<string[]> = {};
|
||||
for (const path of ts.getOwnKeys(buildInfo.program.referencedMap).sort()) {
|
||||
referencedMap[path] = buildInfo.program.referencedMap[path].sort();
|
||||
}
|
||||
buildInfo.program.referencedMap = referencedMap;
|
||||
}
|
||||
|
||||
// exportedModulesMap
|
||||
if (buildInfo.program.exportedModulesMap) {
|
||||
const exportedModulesMap: ts.MapLike<string[]> = {};
|
||||
for (const path of ts.getOwnKeys(buildInfo.program.exportedModulesMap).sort()) {
|
||||
exportedModulesMap[path] = buildInfo.program.exportedModulesMap[path].sort();
|
||||
}
|
||||
buildInfo.program.exportedModulesMap = exportedModulesMap;
|
||||
}
|
||||
|
||||
// semanticDiagnosticsPerFile
|
||||
if (buildInfo.program.semanticDiagnosticsPerFile) {
|
||||
buildInfo.program.semanticDiagnosticsPerFile.sort(compareProgramBuildInfoDiagnostic);
|
||||
}
|
||||
}
|
||||
buildInfo.version = version;
|
||||
super.writeFile(fileName, ts.getBuildInfoText(buildInfo), writeByteOrderMark);
|
||||
}
|
||||
|
||||
now() {
|
||||
return new Date(this.sys.vfs.time());
|
||||
}
|
||||
|
||||
diagnostics: ts.Diagnostic[] = [];
|
||||
|
||||
reportDiagnostic(diagnostic: ts.Diagnostic) {
|
||||
@@ -390,16 +473,12 @@ namespace fakes {
|
||||
this.diagnostics.length = 0;
|
||||
}
|
||||
|
||||
assertDiagnosticMessages(...expected: ts.DiagnosticMessage[]) {
|
||||
const actual = this.diagnostics.slice();
|
||||
if (actual.length !== expected.length) {
|
||||
assert.fail<any>(actual, expected, `Diagnostic arrays did not match - got\r\n${actual.map(a => " " + a.messageText).join("\r\n")}\r\nexpected\r\n${expected.map(e => " " + e.message).join("\r\n")}`);
|
||||
}
|
||||
for (let i = 0; i < actual.length; i++) {
|
||||
if (actual[i].code !== expected[i].code) {
|
||||
assert.fail(actual[i].messageText, expected[i].message, `Mismatched error code - expected diagnostic ${i} "${actual[i].messageText}" to match ${expected[i].message}`);
|
||||
}
|
||||
}
|
||||
assertDiagnosticMessages(...expectedDiagnostics: ExpectedDiagnostic[]) {
|
||||
const actual = this.diagnostics.slice().map(d => d.messageText as string);
|
||||
const expected = expectedDiagnostics.map(expectedDiagnosticToText);
|
||||
assert.deepEqual(actual, expected, `Diagnostic arrays did not match:
|
||||
Actual: ${JSON.stringify(actual, /*replacer*/ undefined, " ")}
|
||||
Expected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`);
|
||||
}
|
||||
|
||||
printDiagnostics(header = "== Diagnostics ==") {
|
||||
|
||||
+100
-17
@@ -774,7 +774,7 @@ namespace FourSlash {
|
||||
if ("exact" in options) {
|
||||
ts.Debug.assert(!("includes" in options) && !("excludes" in options));
|
||||
if (options.exact === undefined) throw this.raiseError("Expected no completions");
|
||||
this.verifyCompletionsAreExactly(actualCompletions.entries, toArray(options.exact));
|
||||
this.verifyCompletionsAreExactly(actualCompletions.entries, toArray(options.exact), options.marker);
|
||||
}
|
||||
else {
|
||||
if (options.includes) {
|
||||
@@ -841,14 +841,14 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
private verifyCompletionsAreExactly(actual: ReadonlyArray<ts.CompletionEntry>, expected: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntry>) {
|
||||
private verifyCompletionsAreExactly(actual: ReadonlyArray<ts.CompletionEntry>, expected: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntry>, marker?: ArrayOrSingle<string | Marker>) {
|
||||
// First pass: test that names are right. Then we'll test details.
|
||||
assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name));
|
||||
assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name), marker ? "At marker " + JSON.stringify(marker) : undefined);
|
||||
|
||||
ts.zipWith(actual, expected, (completion, expectedCompletion, index) => {
|
||||
const name = typeof expectedCompletion === "string" ? expectedCompletion : expectedCompletion.name;
|
||||
if (completion.name !== name) {
|
||||
this.raiseError(`Expected completion at index ${index} to be ${name}, got ${completion.name}`);
|
||||
this.raiseError(`${marker ? JSON.stringify(marker) : "" } Expected completion at index ${index} to be ${name}, got ${completion.name}`);
|
||||
}
|
||||
this.verifyCompletionEntry(completion, expectedCompletion);
|
||||
});
|
||||
@@ -939,8 +939,8 @@ namespace FourSlash {
|
||||
const startFile = this.activeFile.fileName;
|
||||
for (const fileName of files) {
|
||||
const searchFileNames = startFile === fileName ? [startFile] : [startFile, fileName];
|
||||
const highlights = this.getDocumentHighlightsAtCurrentPosition(searchFileNames)!;
|
||||
if (!highlights.every(dh => ts.contains(searchFileNames, dh.fileName))) {
|
||||
const highlights = this.getDocumentHighlightsAtCurrentPosition(searchFileNames);
|
||||
if (highlights && !highlights.every(dh => ts.contains(searchFileNames, dh.fileName))) {
|
||||
this.raiseError(`When asking for document highlights only in files ${searchFileNames}, got document highlights in ${unique(highlights, dh => dh.fileName)}`);
|
||||
}
|
||||
}
|
||||
@@ -1170,7 +1170,7 @@ Actual: ${stringify(fullActual)}`);
|
||||
}
|
||||
|
||||
public verifyRenameLocations(startRanges: ArrayOrSingle<Range>, options: FourSlashInterface.RenameLocationsOptions) {
|
||||
const { findInStrings = false, findInComments = false, ranges = this.getRanges() } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options } : options;
|
||||
const { findInStrings = false, findInComments = false, ranges = this.getRanges(), providePrefixAndSuffixTextForRename = true } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options, providePrefixAndSuffixTextForRename: true } : options;
|
||||
|
||||
for (const startRange of toArray(startRanges)) {
|
||||
this.goToRangeStart(startRange);
|
||||
@@ -1182,7 +1182,7 @@ Actual: ${stringify(fullActual)}`);
|
||||
}
|
||||
|
||||
const references = this.languageService.findRenameLocations(
|
||||
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
|
||||
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments, providePrefixAndSuffixTextForRename);
|
||||
|
||||
const sort = (locations: ReadonlyArray<ts.RenameLocation> | undefined) =>
|
||||
locations && ts.sort(locations, (r1, r2) => ts.compareStringsCaseSensitive(r1.fileName, r2.fileName) || r1.textSpan.start - r2.textSpan.start);
|
||||
@@ -1308,8 +1308,8 @@ Actual: ${stringify(fullActual)}`);
|
||||
}
|
||||
}
|
||||
|
||||
public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined): void {
|
||||
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
|
||||
public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined, renameInfoOptions: ts.RenameInfoOptions | undefined): void {
|
||||
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, renameInfoOptions || { allowRenameOfImportPath: true });
|
||||
if (!renameInfo.canRename) {
|
||||
throw this.raiseError("Rename did not succeed");
|
||||
}
|
||||
@@ -1334,8 +1334,9 @@ Actual: ${stringify(fullActual)}`);
|
||||
}
|
||||
}
|
||||
|
||||
public verifyRenameInfoFailed(message?: string) {
|
||||
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
|
||||
public verifyRenameInfoFailed(message?: string, allowRenameOfImportPath?: boolean) {
|
||||
allowRenameOfImportPath = allowRenameOfImportPath === undefined ? true : allowRenameOfImportPath;
|
||||
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition, { allowRenameOfImportPath });
|
||||
if (renameInfo.canRename) {
|
||||
throw this.raiseError("Rename was expected to fail");
|
||||
}
|
||||
@@ -3158,6 +3159,7 @@ ${code}
|
||||
const debug = new FourSlashInterface.Debug(state);
|
||||
const format = new FourSlashInterface.Format(state);
|
||||
const cancellation = new FourSlashInterface.Cancellation(state);
|
||||
// tslint:disable-next-line:no-eval
|
||||
const f = eval(wrappedCode);
|
||||
f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled);
|
||||
}
|
||||
@@ -4091,12 +4093,12 @@ namespace FourSlashInterface {
|
||||
this.state.verifySemanticClassifications(classifications);
|
||||
}
|
||||
|
||||
public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range) {
|
||||
this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange);
|
||||
public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range, options?: ts.RenameInfoOptions) {
|
||||
this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange, options);
|
||||
}
|
||||
|
||||
public renameInfoFailed(message?: string) {
|
||||
this.state.verifyRenameInfoFailed(message);
|
||||
public renameInfoFailed(message?: string, allowRenameOfImportPath?: boolean) {
|
||||
this.state.verifyRenameInfoFailed(message, allowRenameOfImportPath);
|
||||
}
|
||||
|
||||
public renameLocations(startRanges: ArrayOrSingle<FourSlash.Range>, options: RenameLocationsOptions) {
|
||||
@@ -4543,15 +4545,54 @@ namespace FourSlashInterface {
|
||||
|
||||
export function globalTypesPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
|
||||
return [
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalTypeDecls,
|
||||
...plus,
|
||||
...typeKeywords,
|
||||
];
|
||||
}
|
||||
|
||||
function getInJsKeywords(keywords: ReadonlyArray<ExpectedCompletionEntryObject>): ReadonlyArray<ExpectedCompletionEntryObject> {
|
||||
return keywords.filter(keyword => {
|
||||
switch (keyword.name) {
|
||||
case "enum":
|
||||
case "interface":
|
||||
case "implements":
|
||||
case "private":
|
||||
case "protected":
|
||||
case "public":
|
||||
case "abstract":
|
||||
case "any":
|
||||
case "boolean":
|
||||
case "declare":
|
||||
case "infer":
|
||||
case "is":
|
||||
case "keyof":
|
||||
case "module":
|
||||
case "namespace":
|
||||
case "never":
|
||||
case "readonly":
|
||||
case "number":
|
||||
case "object":
|
||||
case "string":
|
||||
case "symbol":
|
||||
case "type":
|
||||
case "unique":
|
||||
case "unknown":
|
||||
case "global":
|
||||
case "bigint":
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const classElementKeywords: ReadonlyArray<ExpectedCompletionEntryObject> =
|
||||
["private", "protected", "public", "static", "abstract", "async", "constructor", "get", "readonly", "set"].map(keywordEntry);
|
||||
|
||||
export const classElementInJsKeywords = getInJsKeywords(classElementKeywords);
|
||||
|
||||
export const constructorParameterKeywords: ReadonlyArray<ExpectedCompletionEntryObject> =
|
||||
["private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({ name, kind: "keyword" }));
|
||||
|
||||
@@ -4689,6 +4730,8 @@ namespace FourSlashInterface {
|
||||
}
|
||||
});
|
||||
|
||||
export const statementInJsKeywords = getInJsKeywords(statementKeywords);
|
||||
|
||||
export const globalsVars: ReadonlyArray<ExpectedCompletionEntryObject> = [
|
||||
functionEntry("eval"),
|
||||
functionEntry("parseInt"),
|
||||
@@ -4784,11 +4827,24 @@ namespace FourSlashInterface {
|
||||
export const globalsInsideFunction = (plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> => [
|
||||
{ name: "arguments", kind: "local var" },
|
||||
...plus,
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalKeywordsInsideFunction,
|
||||
];
|
||||
|
||||
const globalInJsKeywordsInsideFunction = getInJsKeywords(globalKeywordsInsideFunction);
|
||||
|
||||
// TODO: many of these are inappropriate to always provide
|
||||
export const globalsInJsInsideFunction = (plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> => [
|
||||
{ name: "arguments", kind: "local var" },
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
...plus,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalInJsKeywordsInsideFunction,
|
||||
];
|
||||
|
||||
// TODO: many of these are inappropriate to always provide
|
||||
export const globalKeywords: ReadonlyArray<ExpectedCompletionEntryObject> = [
|
||||
"break",
|
||||
@@ -4867,6 +4923,8 @@ namespace FourSlashInterface {
|
||||
"of",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const globalInJsKeywords = getInJsKeywords(globalKeywords);
|
||||
|
||||
export const insideMethodKeywords: ReadonlyArray<ExpectedCompletionEntryObject> = [
|
||||
"break",
|
||||
"case",
|
||||
@@ -4913,19 +4971,43 @@ namespace FourSlashInterface {
|
||||
"await",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const insideMethodInJsKeywords = getInJsKeywords(insideMethodKeywords);
|
||||
|
||||
export const globalKeywordsPlusUndefined: ReadonlyArray<ExpectedCompletionEntryObject> = (() => {
|
||||
const i = ts.findIndex(globalKeywords, x => x.name === "unique");
|
||||
return [...globalKeywords.slice(0, i), keywordEntry("undefined"), ...globalKeywords.slice(i)];
|
||||
})();
|
||||
|
||||
export const globals: ReadonlyArray<ExpectedCompletionEntryObject> = [
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalKeywords
|
||||
];
|
||||
|
||||
export const globalsInJs: ReadonlyArray<ExpectedCompletionEntryObject> = [
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalInJsKeywords
|
||||
];
|
||||
|
||||
export function globalsPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
|
||||
return [...globalsVars, ...plus, { name: "undefined", kind: "var" }, ...globalKeywords];
|
||||
return [
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
...plus,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalKeywords];
|
||||
}
|
||||
|
||||
export function globalsInJsPlus(plus: ReadonlyArray<ExpectedCompletionEntry>): ReadonlyArray<ExpectedCompletionEntry> {
|
||||
return [
|
||||
{ name: "globalThis", kind: "module" },
|
||||
...globalsVars,
|
||||
...plus,
|
||||
{ name: "undefined", kind: "var" },
|
||||
...globalInJsKeywords];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5086,6 +5168,7 @@ namespace FourSlashInterface {
|
||||
readonly findInStrings?: boolean;
|
||||
readonly findInComments?: boolean;
|
||||
readonly ranges: ReadonlyArray<RenameLocationOptions>;
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
};
|
||||
export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string };
|
||||
}
|
||||
|
||||
+9
-371
@@ -47,23 +47,6 @@ interface XMLHttpRequest {
|
||||
/* tslint:enable:no-var-keyword prefer-const */
|
||||
|
||||
namespace Utils {
|
||||
// Setup some globals based on the current environment
|
||||
export const enum ExecutionEnvironment {
|
||||
Node,
|
||||
Browser,
|
||||
}
|
||||
|
||||
export function getExecutionEnvironment() {
|
||||
if (typeof window !== "undefined") {
|
||||
return ExecutionEnvironment.Browser;
|
||||
}
|
||||
else {
|
||||
return ExecutionEnvironment.Node;
|
||||
}
|
||||
}
|
||||
|
||||
export let currentExecutionEnvironment = getExecutionEnvironment();
|
||||
|
||||
export function encodeString(s: string): string {
|
||||
return ts.sys.bufferFrom!(s).toString("utf8");
|
||||
}
|
||||
@@ -74,22 +57,12 @@ namespace Utils {
|
||||
}
|
||||
|
||||
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
|
||||
const environment = getExecutionEnvironment();
|
||||
switch (environment) {
|
||||
case ExecutionEnvironment.Browser:
|
||||
eval(fileContents);
|
||||
break;
|
||||
case ExecutionEnvironment.Node:
|
||||
const vm = require("vm");
|
||||
if (nodeContext) {
|
||||
vm.runInNewContext(fileContents, nodeContext, fileName);
|
||||
}
|
||||
else {
|
||||
vm.runInThisContext(fileContents, fileName);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new Error("Unknown context");
|
||||
const vm = require("vm");
|
||||
if (nodeContext) {
|
||||
vm.runInNewContext(fileContents, nodeContext, fileName);
|
||||
}
|
||||
else {
|
||||
vm.runInThisContext(fileContents, fileName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,344 +596,11 @@ namespace Harness {
|
||||
};
|
||||
}
|
||||
|
||||
interface URL {
|
||||
hash: string;
|
||||
host: string;
|
||||
hostname: string;
|
||||
href: string;
|
||||
password: string;
|
||||
pathname: string;
|
||||
port: string;
|
||||
protocol: string;
|
||||
search: string;
|
||||
username: string;
|
||||
toString(): string;
|
||||
}
|
||||
|
||||
declare var URL: {
|
||||
prototype: URL;
|
||||
new(url: string, base?: string | URL): URL;
|
||||
};
|
||||
|
||||
function createBrowserIO(): IO {
|
||||
const serverRoot = new URL("http://localhost:8888/");
|
||||
|
||||
class HttpHeaders extends collections.SortedMap<string, string | string[]> {
|
||||
constructor(template?: Record<string, string | string[]>) {
|
||||
super(ts.compareStringsCaseInsensitive);
|
||||
if (template) {
|
||||
for (const key in template) {
|
||||
if (ts.hasProperty(template, key)) {
|
||||
this.set(key, template[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static combine(left: HttpHeaders | undefined, right: HttpHeaders | undefined): HttpHeaders | undefined {
|
||||
if (!left && !right) return undefined;
|
||||
const headers = new HttpHeaders();
|
||||
if (left) left.forEach((value, key) => { headers.set(key, value); });
|
||||
if (right) right.forEach((value, key) => { headers.set(key, value); });
|
||||
return headers;
|
||||
}
|
||||
|
||||
public has(key: string) {
|
||||
return super.has(key.toLowerCase());
|
||||
}
|
||||
|
||||
public get(key: string) {
|
||||
return super.get(key.toLowerCase());
|
||||
}
|
||||
|
||||
public set(key: string, value: string | string[]) {
|
||||
return super.set(key.toLowerCase(), value);
|
||||
}
|
||||
|
||||
public delete(key: string) {
|
||||
return super.delete(key.toLowerCase());
|
||||
}
|
||||
|
||||
public writeRequestHeaders(xhr: XMLHttpRequest) {
|
||||
this.forEach((values, key) => {
|
||||
if (key === "access-control-allow-origin" || key === "content-length") return;
|
||||
const value = Array.isArray(values) ? values.join(",") : values;
|
||||
if (key === "content-type") {
|
||||
xhr.overrideMimeType(value);
|
||||
return;
|
||||
}
|
||||
xhr.setRequestHeader(key, value);
|
||||
});
|
||||
}
|
||||
|
||||
public static readResponseHeaders(xhr: XMLHttpRequest): HttpHeaders {
|
||||
const allHeaders = xhr.getAllResponseHeaders();
|
||||
const headers = new HttpHeaders();
|
||||
for (const header of allHeaders.split(/\r\n/g)) {
|
||||
const colonIndex = header.indexOf(":");
|
||||
if (colonIndex >= 0) {
|
||||
const key = header.slice(0, colonIndex).trim();
|
||||
const value = header.slice(colonIndex + 1).trim();
|
||||
const values = value.split(",");
|
||||
headers.set(key, values.length > 1 ? values : value);
|
||||
}
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
}
|
||||
|
||||
class HttpContent {
|
||||
public headers: HttpHeaders;
|
||||
public content: string;
|
||||
|
||||
constructor(headers: HttpHeaders | Record<string, string | string[]>, content: string) {
|
||||
this.headers = headers instanceof HttpHeaders ? headers : new HttpHeaders(headers);
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public static fromMediaType(mediaType: string, content: string) {
|
||||
return new HttpContent({ "Content-Type": mediaType }, content);
|
||||
}
|
||||
|
||||
public static text(content: string) {
|
||||
return HttpContent.fromMediaType("text/plain", content);
|
||||
}
|
||||
|
||||
public static json(content: object) {
|
||||
return HttpContent.fromMediaType("application/json", JSON.stringify(content));
|
||||
}
|
||||
|
||||
public static readResponseContent(xhr: XMLHttpRequest) {
|
||||
if (typeof xhr.responseText === "string") {
|
||||
return new HttpContent({
|
||||
"Content-Type": xhr.getResponseHeader("Content-Type") || undefined!, // TODO: GH#18217
|
||||
"Content-Length": xhr.getResponseHeader("Content-Length") || undefined!, // TODO: GH#18217
|
||||
}, xhr.responseText);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public writeRequestHeaders(xhr: XMLHttpRequest) {
|
||||
this.headers.writeRequestHeaders(xhr);
|
||||
}
|
||||
}
|
||||
|
||||
class HttpRequestMessage {
|
||||
public method: string;
|
||||
public url: URL;
|
||||
public headers: HttpHeaders;
|
||||
public content?: HttpContent;
|
||||
|
||||
constructor(method: string, url: string | URL, headers?: HttpHeaders | Record<string, string | string[]>, content?: HttpContent) {
|
||||
this.method = method;
|
||||
this.url = typeof url === "string" ? new URL(url) : url;
|
||||
this.headers = headers instanceof HttpHeaders ? headers : new HttpHeaders(headers);
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public static options(url: string | URL) {
|
||||
return new HttpRequestMessage("OPTIONS", url);
|
||||
}
|
||||
|
||||
public static head(url: string | URL) {
|
||||
return new HttpRequestMessage("HEAD", url);
|
||||
}
|
||||
|
||||
public static get(url: string | URL) {
|
||||
return new HttpRequestMessage("GET", url);
|
||||
}
|
||||
|
||||
public static delete(url: string | URL) {
|
||||
return new HttpRequestMessage("DELETE", url);
|
||||
}
|
||||
|
||||
public static put(url: string | URL, content: HttpContent) {
|
||||
return new HttpRequestMessage("PUT", url, /*headers*/ undefined, content);
|
||||
}
|
||||
|
||||
public static post(url: string | URL, content: HttpContent) {
|
||||
return new HttpRequestMessage("POST", url, /*headers*/ undefined, content);
|
||||
}
|
||||
|
||||
public writeRequestHeaders(xhr: XMLHttpRequest) {
|
||||
this.headers.writeRequestHeaders(xhr);
|
||||
if (this.content) {
|
||||
this.content.writeRequestHeaders(xhr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class HttpResponseMessage {
|
||||
public statusCode: number;
|
||||
public statusMessage: string;
|
||||
public headers: HttpHeaders;
|
||||
public content?: HttpContent;
|
||||
|
||||
constructor(statusCode: number, statusMessage: string, headers?: HttpHeaders | Record<string, string | string[]>, content?: HttpContent) {
|
||||
this.statusCode = statusCode;
|
||||
this.statusMessage = statusMessage;
|
||||
this.headers = headers instanceof HttpHeaders ? headers : new HttpHeaders(headers);
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public static notFound(): HttpResponseMessage {
|
||||
return new HttpResponseMessage(404, "Not Found");
|
||||
}
|
||||
|
||||
public static hasSuccessStatusCode(response: HttpResponseMessage) {
|
||||
return response.statusCode === 304 || (response.statusCode >= 200 && response.statusCode < 300);
|
||||
}
|
||||
|
||||
public static readResponseMessage(xhr: XMLHttpRequest) {
|
||||
return new HttpResponseMessage(
|
||||
xhr.status,
|
||||
xhr.statusText,
|
||||
HttpHeaders.readResponseHeaders(xhr),
|
||||
HttpContent.readResponseContent(xhr));
|
||||
}
|
||||
}
|
||||
|
||||
function send(request: HttpRequestMessage): HttpResponseMessage {
|
||||
const xhr = new XMLHttpRequest();
|
||||
try {
|
||||
xhr.open(request.method, request.url.toString(), /*async*/ false);
|
||||
request.writeRequestHeaders(xhr);
|
||||
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
|
||||
xhr.send(request.content && request.content.content);
|
||||
while (xhr.readyState !== 4); // block until ready
|
||||
return HttpResponseMessage.readResponseMessage(xhr);
|
||||
}
|
||||
catch (e) {
|
||||
return HttpResponseMessage.notFound();
|
||||
}
|
||||
}
|
||||
|
||||
let caseSensitivity: "CI" | "CS" | undefined;
|
||||
|
||||
function useCaseSensitiveFileNames() {
|
||||
if (!caseSensitivity) {
|
||||
const response = send(HttpRequestMessage.options(new URL("*", serverRoot)));
|
||||
const xCaseSensitivity = response.headers.get("X-Case-Sensitivity");
|
||||
caseSensitivity = xCaseSensitivity === "CS" ? "CS" : "CI";
|
||||
}
|
||||
return caseSensitivity === "CS";
|
||||
}
|
||||
|
||||
function resolvePath(path: string) {
|
||||
const response = send(HttpRequestMessage.post(new URL("/api/resolve", serverRoot), HttpContent.text(path)));
|
||||
return HttpResponseMessage.hasSuccessStatusCode(response) && response.content ? response.content.content : undefined;
|
||||
}
|
||||
|
||||
function getFileSize(path: string): number {
|
||||
const response = send(HttpRequestMessage.head(new URL(path, serverRoot)));
|
||||
return HttpResponseMessage.hasSuccessStatusCode(response) ? +response.headers.get("Content-Length")!.toString() : 0;
|
||||
}
|
||||
|
||||
function readFile(path: string): string | undefined {
|
||||
const response = send(HttpRequestMessage.get(new URL(path, serverRoot)));
|
||||
return HttpResponseMessage.hasSuccessStatusCode(response) && response.content ? response.content.content : undefined;
|
||||
}
|
||||
|
||||
function writeFile(path: string, contents: string) {
|
||||
send(HttpRequestMessage.put(new URL(path, serverRoot), HttpContent.text(contents)));
|
||||
}
|
||||
|
||||
function fileExists(path: string): boolean {
|
||||
const response = send(HttpRequestMessage.head(new URL(path, serverRoot)));
|
||||
return HttpResponseMessage.hasSuccessStatusCode(response);
|
||||
}
|
||||
|
||||
function directoryExists(path: string): boolean {
|
||||
const response = send(HttpRequestMessage.post(new URL("/api/directoryExists", serverRoot), HttpContent.text(path)));
|
||||
return hasJsonContent(response) && JSON.parse(response.content.content) as boolean;
|
||||
}
|
||||
|
||||
function deleteFile(path: string) {
|
||||
send(HttpRequestMessage.delete(new URL(path, serverRoot)));
|
||||
}
|
||||
|
||||
function directoryName(path: string) {
|
||||
const url = new URL(path, serverRoot);
|
||||
return ts.getDirectoryPath(ts.normalizeSlashes(url.pathname || "/"));
|
||||
}
|
||||
|
||||
function enumerateTestFiles(runner: RunnerBase): (string | FileBasedTest)[] {
|
||||
const response = send(HttpRequestMessage.post(new URL("/api/enumerateTestFiles", serverRoot), HttpContent.text(runner.kind())));
|
||||
return hasJsonContent(response) ? JSON.parse(response.content.content) : [];
|
||||
}
|
||||
|
||||
function listFiles(dirname: string, spec?: RegExp, options?: { recursive?: boolean }): string[] {
|
||||
if (spec || (options && !options.recursive)) {
|
||||
let results = IO.listFiles(dirname);
|
||||
if (spec) {
|
||||
results = results.filter(file => spec.test(file));
|
||||
}
|
||||
if (options && !options.recursive) {
|
||||
results = results.filter(file => ts.getDirectoryPath(ts.normalizeSlashes(file)) === dirname);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
const response = send(HttpRequestMessage.post(new URL("/api/listFiles", serverRoot), HttpContent.text(dirname)));
|
||||
return hasJsonContent(response) ? JSON.parse(response.content.content) : [];
|
||||
}
|
||||
|
||||
function readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[], depth?: number) {
|
||||
return ts.matchFiles(path, extension, exclude, include, useCaseSensitiveFileNames(), "", depth, getAccessibleFileSystemEntries);
|
||||
}
|
||||
|
||||
function getAccessibleFileSystemEntries(dirname: string): ts.FileSystemEntries {
|
||||
const response = send(HttpRequestMessage.post(new URL("/api/getAccessibleFileSystemEntries", serverRoot), HttpContent.text(dirname)));
|
||||
return hasJsonContent(response) ? JSON.parse(response.content.content) : { files: [], directories: [] };
|
||||
}
|
||||
|
||||
function hasJsonContent(response: HttpResponseMessage): response is HttpResponseMessage & { content: HttpContent } {
|
||||
return HttpResponseMessage.hasSuccessStatusCode(response)
|
||||
&& !!response.content
|
||||
&& /^application\/json(;.*)$/.test("" + response.content.headers.get("Content-Type"));
|
||||
}
|
||||
|
||||
return {
|
||||
newLine: () => harnessNewLine,
|
||||
getCurrentDirectory: () => "",
|
||||
useCaseSensitiveFileNames,
|
||||
resolvePath,
|
||||
getFileSize,
|
||||
readFile,
|
||||
writeFile,
|
||||
directoryName: Utils.memoize(directoryName, path => path),
|
||||
getDirectories: () => [],
|
||||
createDirectory: () => {}, // tslint:disable-line no-empty
|
||||
fileExists,
|
||||
directoryExists,
|
||||
deleteFile,
|
||||
listFiles: Utils.memoize(listFiles, (path, spec, options) => `${path}|${spec}|${options ? options.recursive === true : true}`),
|
||||
enumerateTestFiles: Utils.memoize(enumerateTestFiles, runner => runner.kind()),
|
||||
log: s => console.log(s),
|
||||
args: () => [],
|
||||
getExecutingFilePath: () => "",
|
||||
exit: () => {}, // tslint:disable-line no-empty
|
||||
readDirectory,
|
||||
getAccessibleFileSystemEntries,
|
||||
getWorkspaceRoot: () => "/"
|
||||
};
|
||||
}
|
||||
|
||||
export function mockHash(s: string): string {
|
||||
return `hash-${s}`;
|
||||
}
|
||||
|
||||
const environment = Utils.getExecutionEnvironment();
|
||||
switch (environment) {
|
||||
case Utils.ExecutionEnvironment.Node:
|
||||
IO = createNodeIO();
|
||||
break;
|
||||
case Utils.ExecutionEnvironment.Browser:
|
||||
IO = createBrowserIO();
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown value '${environment}' for ExecutionEnvironment.`);
|
||||
}
|
||||
IO = createNodeIO();
|
||||
}
|
||||
|
||||
if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.getEnvironmentVariable!("NODE_ENV"))) {
|
||||
@@ -969,10 +609,8 @@ if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.ge
|
||||
|
||||
namespace Harness {
|
||||
export const libFolder = "built/local/";
|
||||
const tcServicesFileName = ts.combinePaths(libFolder, Utils.getExecutionEnvironment() === Utils.ExecutionEnvironment.Browser ? "typescriptServicesInBrowserTest.js" : "typescriptServices.js");
|
||||
export const tcServicesFile = IO.readFile(tcServicesFileName) + (Utils.getExecutionEnvironment() !== Utils.ExecutionEnvironment.Browser
|
||||
? IO.newLine() + `//# sourceURL=${IO.resolvePath(tcServicesFileName)}`
|
||||
: "");
|
||||
const tcServicesFileName = ts.combinePaths(libFolder, "typescriptServices.js");
|
||||
export const tcServicesFile = IO.readFile(tcServicesFileName) + IO.newLine() + `//# sourceURL=${IO.resolvePath(tcServicesFileName)}`;
|
||||
|
||||
export type SourceMapEmitterCallback = (
|
||||
emittedFile: string,
|
||||
|
||||
@@ -469,11 +469,11 @@ namespace Harness.LanguageService {
|
||||
getSignatureHelpItems(fileName: string, position: number, options: ts.SignatureHelpItemsOptions | undefined): ts.SignatureHelpItems {
|
||||
return unwrapJSONCallResult(this.shim.getSignatureHelpItems(fileName, position, options));
|
||||
}
|
||||
getRenameInfo(fileName: string, position: number): ts.RenameInfo {
|
||||
return unwrapJSONCallResult(this.shim.getRenameInfo(fileName, position));
|
||||
getRenameInfo(fileName: string, position: number, options?: ts.RenameInfoOptions): ts.RenameInfo {
|
||||
return unwrapJSONCallResult(this.shim.getRenameInfo(fileName, position, options));
|
||||
}
|
||||
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ts.RenameLocation[] {
|
||||
return unwrapJSONCallResult(this.shim.findRenameLocations(fileName, position, findInStrings, findInComments));
|
||||
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ts.RenameLocation[] {
|
||||
return unwrapJSONCallResult(this.shim.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename));
|
||||
}
|
||||
getDefinitionAtPosition(fileName: string, position: number): ts.DefinitionInfo[] {
|
||||
return unwrapJSONCallResult(this.shim.getDefinitionAtPosition(fileName, position));
|
||||
@@ -766,6 +766,7 @@ namespace Harness.LanguageService {
|
||||
}
|
||||
|
||||
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any {
|
||||
// tslint:disable-next-line:ban
|
||||
return setTimeout(callback, ms, args);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,10 +15,10 @@ namespace Harness.SourceMapRecorder {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapEmitResult) {
|
||||
export function initializeSourceMapDecoding(sourceMap: ts.RawSourceMap) {
|
||||
decodingIndex = 0;
|
||||
sourceMapMappings = sourceMapData.sourceMap.mappings;
|
||||
mappings = ts.decodeMappings(sourceMapData.sourceMap.mappings);
|
||||
sourceMapMappings = sourceMap.mappings;
|
||||
mappings = ts.decodeMappings(sourceMap.mappings);
|
||||
}
|
||||
|
||||
export function decodeNextEncodedSourceMapSpan(): DecodedMapping {
|
||||
@@ -53,10 +53,10 @@ namespace Harness.SourceMapRecorder {
|
||||
let nextJsLineToWrite: number;
|
||||
let spanMarkerContinues: boolean;
|
||||
|
||||
export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapEmitResult, currentJsFile: documents.TextDocument) {
|
||||
export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMap: ts.RawSourceMap, currentJsFile: documents.TextDocument) {
|
||||
sourceMapRecorder = sourceMapRecordWriter;
|
||||
sourceMapSources = sourceMapData.sourceMap.sources;
|
||||
sourceMapNames = sourceMapData.sourceMap.names;
|
||||
sourceMapSources = sourceMap.sources;
|
||||
sourceMapNames = sourceMap.names;
|
||||
|
||||
jsFile = currentJsFile;
|
||||
jsLineMap = jsFile.lineStarts;
|
||||
@@ -66,14 +66,14 @@ namespace Harness.SourceMapRecorder {
|
||||
nextJsLineToWrite = 0;
|
||||
spanMarkerContinues = false;
|
||||
|
||||
SourceMapDecoder.initializeSourceMapDecoding(sourceMapData);
|
||||
SourceMapDecoder.initializeSourceMapDecoding(sourceMap);
|
||||
sourceMapRecorder.WriteLine("===================================================================");
|
||||
sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMap.file);
|
||||
sourceMapRecorder.WriteLine("JsFile: " + sourceMap.file);
|
||||
sourceMapRecorder.WriteLine("mapUrl: " + ts.tryGetSourceMappingURL(ts.getLineInfo(jsFile.text, jsLineMap)));
|
||||
sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMap.sourceRoot);
|
||||
sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMap.sources);
|
||||
if (sourceMapData.sourceMap.sourcesContent) {
|
||||
sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMap.sourcesContent));
|
||||
sourceMapRecorder.WriteLine("sourceRoot: " + sourceMap.sourceRoot);
|
||||
sourceMapRecorder.WriteLine("sources: " + sourceMap.sources);
|
||||
if (sourceMap.sourcesContent) {
|
||||
sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMap.sourcesContent));
|
||||
}
|
||||
sourceMapRecorder.WriteLine("===================================================================");
|
||||
}
|
||||
@@ -299,7 +299,7 @@ namespace Harness.SourceMapRecorder {
|
||||
}
|
||||
}
|
||||
|
||||
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData, currentFile);
|
||||
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData.sourceMap, currentFile);
|
||||
const mapper = ts.decodeMappings(sourceMapData.sourceMap.mappings);
|
||||
for (let { value: decodedSourceMapping, done } = mapper.next(); !done; { value: decodedSourceMapping, done } = mapper.next()) {
|
||||
const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
|
||||
@@ -320,4 +320,46 @@ namespace Harness.SourceMapRecorder {
|
||||
sourceMapRecorder.Close();
|
||||
return sourceMapRecorder.lines.join("\r\n");
|
||||
}
|
||||
|
||||
export function getSourceMapRecordWithVFS(fs: vfs.FileSystem, sourceMapFile: string) {
|
||||
const sourceMapRecorder = new Compiler.WriterAggregator();
|
||||
let prevSourceFile: documents.TextDocument | undefined;
|
||||
const files = ts.createMap<documents.TextDocument>();
|
||||
const sourceMap = ts.tryParseRawSourceMap(fs.readFileSync(sourceMapFile, "utf8"));
|
||||
if (sourceMap) {
|
||||
const mapDirectory = ts.getDirectoryPath(sourceMapFile);
|
||||
const sourceRoot = sourceMap.sourceRoot ? ts.getNormalizedAbsolutePath(sourceMap.sourceRoot, mapDirectory) : mapDirectory;
|
||||
const generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(sourceMap.file, mapDirectory);
|
||||
const sourceFileAbsolutePaths = sourceMap.sources.map(source => ts.getNormalizedAbsolutePath(source, sourceRoot));
|
||||
const currentFile = getFile(generatedAbsoluteFilePath);
|
||||
|
||||
SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMap, currentFile);
|
||||
const mapper = ts.decodeMappings(sourceMap.mappings);
|
||||
for (let { value: decodedSourceMapping, done } = mapper.next(); !done; { value: decodedSourceMapping, done } = mapper.next()) {
|
||||
const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
|
||||
? getFile(sourceFileAbsolutePaths[decodedSourceMapping.sourceIndex])
|
||||
: undefined;
|
||||
if (currentSourceFile !== prevSourceFile) {
|
||||
if (currentSourceFile) {
|
||||
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
|
||||
}
|
||||
prevSourceFile = currentSourceFile;
|
||||
}
|
||||
else {
|
||||
SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
|
||||
}
|
||||
}
|
||||
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
|
||||
}
|
||||
sourceMapRecorder.Close();
|
||||
return sourceMapRecorder.lines.join("\r\n");
|
||||
|
||||
function getFile(path: string) {
|
||||
const existing = files.get(path);
|
||||
if (existing) return existing;
|
||||
const value = new documents.TextDocument(path, fs.readFileSync(path, "utf8"));
|
||||
files.set(path, value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -826,7 +826,7 @@ interface Array<T> {}`
|
||||
});
|
||||
}
|
||||
return { directories, files };
|
||||
});
|
||||
}, path => this.realpath(path));
|
||||
}
|
||||
|
||||
watchDirectory(directoryName: string, cb: DirectoryWatcherCallback, recursive: boolean): FileWatcher {
|
||||
|
||||
+1
-1
@@ -4,5 +4,5 @@ The files within this directory are used to generate `lib.d.ts` and `lib.es6.d.t
|
||||
|
||||
## Generated files
|
||||
|
||||
Any files ending in `.generated.d.ts` aren't mean to be edited by hand.
|
||||
Any files ending in `.generated.d.ts` aren't meant to be edited by hand.
|
||||
If you need to make changes to such files, make a change to the input files for [**our library generator**](https://github.com/Microsoft/TSJS-lib-generator).
|
||||
|
||||
Vendored
+658
-214
File diff suppressed because it is too large
Load Diff
Vendored
+7
@@ -96,6 +96,13 @@ interface Headers {
|
||||
values(): IterableIterator<string>;
|
||||
}
|
||||
|
||||
interface MediaKeyStatusMap {
|
||||
[Symbol.iterator](): IterableIterator<[BufferSource, MediaKeyStatus]>;
|
||||
entries(): IterableIterator<[BufferSource, MediaKeyStatus]>;
|
||||
keys(): IterableIterator<BufferSource>;
|
||||
values(): IterableIterator<MediaKeyStatus>;
|
||||
}
|
||||
|
||||
interface MediaList {
|
||||
[Symbol.iterator](): IterableIterator<string>;
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -10,7 +10,7 @@ interface Map<K, V> {
|
||||
|
||||
interface MapConstructor {
|
||||
new(): Map<any, any>;
|
||||
new<K, V>(entries?: ReadonlyArray<[K, V]> | null): Map<K, V>;
|
||||
new<K, V>(entries?: ReadonlyArray<readonly [K, V]> | null): Map<K, V>;
|
||||
readonly prototype: Map<any, any>;
|
||||
}
|
||||
declare var Map: MapConstructor;
|
||||
|
||||
Vendored
+1
-1
@@ -129,7 +129,7 @@ interface ReadonlyMap<K, V> {
|
||||
}
|
||||
|
||||
interface MapConstructor {
|
||||
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
|
||||
new <K, V>(iterable: Iterable<readonly [K, V]>): Map<K, V>;
|
||||
}
|
||||
|
||||
interface WeakMap<K extends object, V> { }
|
||||
|
||||
Vendored
+2
-2
@@ -103,7 +103,7 @@ interface Atomics {
|
||||
* Wakes up sleeping agents that are waiting on the given index of the array, returning the
|
||||
* number of agents that were awoken.
|
||||
*/
|
||||
wake(typedArray: Int32Array, index: number, count: number): number;
|
||||
notify(typedArray: Int32Array, index: number, count: number): number;
|
||||
|
||||
/**
|
||||
* Stores the bitwise XOR of a value with the value at the given position in the array,
|
||||
@@ -115,4 +115,4 @@ interface Atomics {
|
||||
readonly [Symbol.toStringTag]: "Atomics";
|
||||
}
|
||||
|
||||
declare var Atomics: Atomics;
|
||||
declare var Atomics: Atomics;
|
||||
|
||||
Vendored
+1
@@ -1,4 +1,5 @@
|
||||
/// <reference lib="es2017" />
|
||||
/// <reference lib="es2018.asynciterable" />
|
||||
/// <reference lib="es2018.promise" />
|
||||
/// <reference lib="es2018.regexp" />
|
||||
/// <reference lib="es2018.intl" />
|
||||
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
/// <reference lib="es2018" />
|
||||
/// <reference lib="es2019.array" />
|
||||
/// <reference lib="es2019.string" />
|
||||
/// <reference lib="es2019.symbol" />
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/// <reference lib="es2019" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="webworker.importscripts" />
|
||||
/// <reference lib="scripthost" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
interface String {
|
||||
/** Removes the trailing white space and line terminator characters from a string. */
|
||||
trimEnd(): string;
|
||||
|
||||
/** Removes the leading white space and line terminator characters from a string. */
|
||||
trimStart(): string;
|
||||
|
||||
/** Removes the trailing white space and line terminator characters from a string. */
|
||||
trimLeft(): string;
|
||||
|
||||
/** Removes the leading white space and line terminator characters from a string. */
|
||||
trimRight(): string;
|
||||
}
|
||||
Vendored
+73
-19
@@ -587,7 +587,7 @@ interface TemplateStringsArray extends ReadonlyArray<string> {
|
||||
|
||||
/**
|
||||
* The type of `import.meta`.
|
||||
*
|
||||
*
|
||||
* If you need to declare that a given property exists on `import.meta`,
|
||||
* this type may be augmented via interface merging.
|
||||
*/
|
||||
@@ -1036,14 +1036,14 @@ interface JSON {
|
||||
* @param reviver A function that transforms the results. This function is called for each member of the object.
|
||||
* If a member contains nested objects, the nested objects are transformed before the parent object is.
|
||||
*/
|
||||
parse(text: string, reviver?: (key: any, value: any) => any): any;
|
||||
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
|
||||
/**
|
||||
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
|
||||
* @param value A JavaScript value, usually an object or array, to be converted.
|
||||
* @param replacer A function that transforms the results.
|
||||
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
|
||||
*/
|
||||
stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
|
||||
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
|
||||
/**
|
||||
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
|
||||
* @param value A JavaScript value, usually an object or array, to be converted.
|
||||
@@ -1114,13 +1114,13 @@ interface ReadonlyArray<T> {
|
||||
* @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean;
|
||||
every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): boolean;
|
||||
/**
|
||||
* Determines whether the specified callback function returns true for any element of an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean;
|
||||
some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): boolean;
|
||||
/**
|
||||
* Performs the specified action for each element in an array.
|
||||
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
|
||||
@@ -1144,7 +1144,7 @@ interface ReadonlyArray<T> {
|
||||
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
|
||||
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
|
||||
*/
|
||||
filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[];
|
||||
filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => unknown, thisArg?: any): T[];
|
||||
/**
|
||||
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
|
||||
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
|
||||
@@ -1451,22 +1451,22 @@ type NonNullable<T> = T extends null | undefined ? never : T;
|
||||
/**
|
||||
* Obtain the parameters of a function type in a tuple
|
||||
*/
|
||||
type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
|
||||
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
|
||||
|
||||
/**
|
||||
* Obtain the parameters of a constructor function type in a tuple
|
||||
*/
|
||||
type ConstructorParameters<T extends new (...args: any[]) => any> = T extends new (...args: infer P) => any ? P : never;
|
||||
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;
|
||||
|
||||
/**
|
||||
* Obtain the return type of a function type
|
||||
*/
|
||||
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;
|
||||
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
|
||||
|
||||
/**
|
||||
* Obtain the return type of a constructor function type
|
||||
*/
|
||||
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;
|
||||
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
|
||||
|
||||
/**
|
||||
* Marker for contextual 'this' type
|
||||
@@ -1913,13 +1913,19 @@ interface Int8ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Int8Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Int8Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array;
|
||||
|
||||
|
||||
}
|
||||
@@ -2183,13 +2189,19 @@ interface Uint8ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Uint8Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Uint8Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array;
|
||||
|
||||
}
|
||||
declare const Uint8Array: Uint8ArrayConstructor;
|
||||
@@ -2452,13 +2464,19 @@ interface Uint8ClampedArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Uint8ClampedArray;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Uint8ClampedArray;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray;
|
||||
}
|
||||
declare const Uint8ClampedArray: Uint8ClampedArrayConstructor;
|
||||
|
||||
@@ -2719,13 +2737,19 @@ interface Int16ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Int16Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Int16Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array;
|
||||
|
||||
|
||||
}
|
||||
@@ -2989,13 +3013,19 @@ interface Uint16ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Uint16Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Uint16Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array;
|
||||
|
||||
|
||||
}
|
||||
@@ -3258,13 +3288,19 @@ interface Int32ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Int32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Int32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array;
|
||||
|
||||
}
|
||||
declare const Int32Array: Int32ArrayConstructor;
|
||||
@@ -3526,13 +3562,19 @@ interface Uint32ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Uint32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Uint32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array;
|
||||
|
||||
}
|
||||
declare const Uint32Array: Uint32ArrayConstructor;
|
||||
@@ -3795,13 +3837,19 @@ interface Float32ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Float32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Float32Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array;
|
||||
|
||||
|
||||
}
|
||||
@@ -4065,13 +4113,19 @@ interface Float64ArrayConstructor {
|
||||
*/
|
||||
of(...items: number[]): Float64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>): Float64Array;
|
||||
|
||||
/**
|
||||
* Creates an array from an array-like or iterable object.
|
||||
* @param arrayLike An array-like or iterable object to convert to an array.
|
||||
* @param mapfn A mapping function to call on every element of the array.
|
||||
* @param thisArg Value of 'this' used to invoke the mapfn.
|
||||
*/
|
||||
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
|
||||
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array;
|
||||
|
||||
}
|
||||
declare const Float64Array: Float64ArrayConstructor;
|
||||
|
||||
Vendored
+1
-4
@@ -1,6 +1,3 @@
|
||||
/// <reference lib="es2018" />
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
/// <reference lib="esnext.array" />
|
||||
/// <reference lib="es2019" />
|
||||
/// <reference lib="esnext.bigint" />
|
||||
/// <reference lib="esnext.symbol" />
|
||||
/// <reference lib="esnext.intl" />
|
||||
|
||||
+6
-3
@@ -6,6 +6,7 @@
|
||||
"es2016",
|
||||
"es2017",
|
||||
"es2018",
|
||||
"es2019",
|
||||
"esnext",
|
||||
// Host only
|
||||
"dom.generated",
|
||||
@@ -29,13 +30,14 @@
|
||||
"es2017.string",
|
||||
"es2017.intl",
|
||||
"es2017.typedarrays",
|
||||
"es2018.asynciterable",
|
||||
"es2018.regexp",
|
||||
"es2018.promise",
|
||||
"es2018.intl",
|
||||
"esnext.asynciterable",
|
||||
"esnext.array",
|
||||
"es2019.array",
|
||||
"es2019.string",
|
||||
"es2019.symbol",
|
||||
"esnext.bigint",
|
||||
"esnext.symbol",
|
||||
"esnext.intl",
|
||||
// Default libraries
|
||||
"es5.full",
|
||||
@@ -43,6 +45,7 @@
|
||||
"es2016.full",
|
||||
"es2017.full",
|
||||
"es2018.full",
|
||||
"es2019.full",
|
||||
"esnext.full"
|
||||
],
|
||||
"paths": {
|
||||
|
||||
Vendored
+159
-25
@@ -154,6 +154,10 @@ interface EventListenerOptions {
|
||||
capture?: boolean;
|
||||
}
|
||||
|
||||
interface EventSourceInit {
|
||||
withCredentials?: boolean;
|
||||
}
|
||||
|
||||
interface ExtendableEventInit extends EventInit {
|
||||
}
|
||||
|
||||
@@ -455,6 +459,7 @@ interface EventListener {
|
||||
(evt: Event): void;
|
||||
}
|
||||
|
||||
/** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */
|
||||
interface ANGLE_instanced_arrays {
|
||||
drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void;
|
||||
drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void;
|
||||
@@ -462,6 +467,7 @@ interface ANGLE_instanced_arrays {
|
||||
readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum;
|
||||
}
|
||||
|
||||
/** The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. */
|
||||
interface AbortController {
|
||||
/**
|
||||
* Returns the AbortSignal object associated with this object.
|
||||
@@ -480,16 +486,17 @@ declare var AbortController: {
|
||||
};
|
||||
|
||||
interface AbortSignalEventMap {
|
||||
"abort": ProgressEvent;
|
||||
"abort": Event;
|
||||
}
|
||||
|
||||
/** The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
|
||||
interface AbortSignal extends EventTarget {
|
||||
/**
|
||||
* Returns true if this AbortSignal's AbortController has signaled to abort, and false
|
||||
* otherwise.
|
||||
*/
|
||||
readonly aborted: boolean;
|
||||
onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null;
|
||||
onabort: ((this: AbortSignal, ev: Event) => any) | null;
|
||||
addEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
|
||||
removeEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
|
||||
@@ -521,6 +528,7 @@ interface AesCmacParams extends Algorithm {
|
||||
length: number;
|
||||
}
|
||||
|
||||
/** A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
|
||||
interface Blob {
|
||||
readonly size: number;
|
||||
readonly type: string;
|
||||
@@ -578,6 +586,7 @@ interface BroadcastChannelEventMap {
|
||||
messageerror: MessageEvent;
|
||||
}
|
||||
|
||||
/** The ByteLengthQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
|
||||
interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
|
||||
highWaterMark: number;
|
||||
size(chunk: ArrayBufferView): number;
|
||||
@@ -588,6 +597,7 @@ declare var ByteLengthQueuingStrategy: {
|
||||
new(options: { highWaterMark: number }): ByteLengthQueuingStrategy;
|
||||
};
|
||||
|
||||
/** The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec. */
|
||||
interface Cache {
|
||||
add(request: RequestInfo): Promise<void>;
|
||||
addAll(requests: RequestInfo[]): Promise<void>;
|
||||
@@ -603,6 +613,7 @@ declare var Cache: {
|
||||
new(): Cache;
|
||||
};
|
||||
|
||||
/** The CacheStorage interface represents the storage for Cache objects. */
|
||||
interface CacheStorage {
|
||||
delete(cacheName: string): Promise<boolean>;
|
||||
has(cacheName: string): Promise<boolean>;
|
||||
@@ -616,6 +627,7 @@ declare var CacheStorage: {
|
||||
new(): CacheStorage;
|
||||
};
|
||||
|
||||
/** The CanvasGradient interface represents an opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */
|
||||
interface CanvasGradient {
|
||||
/**
|
||||
* Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset
|
||||
@@ -644,6 +656,7 @@ interface CanvasPath {
|
||||
rect(x: number, y: number, w: number, h: number): void;
|
||||
}
|
||||
|
||||
/** The CanvasPattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */
|
||||
interface CanvasPattern {
|
||||
/**
|
||||
* Sets the transformation matrix that will be used when rendering the pattern during a fill or
|
||||
@@ -657,6 +670,7 @@ declare var CanvasPattern: {
|
||||
new(): CanvasPattern;
|
||||
};
|
||||
|
||||
/** The Client interface represents an executable context such as a Worker, or a SharedWorker. Window clients are represented by the more-specific WindowClient. You can get Client/WindowClient objects from methods such as Clients.matchAll() and Clients.get(). */
|
||||
interface Client {
|
||||
readonly id: string;
|
||||
readonly type: ClientTypes;
|
||||
@@ -669,6 +683,7 @@ declare var Client: {
|
||||
new(): Client;
|
||||
};
|
||||
|
||||
/** The Clients interface provides access to Client objects. Access it via self.clients within a service worker. */
|
||||
interface Clients {
|
||||
claim(): Promise<void>;
|
||||
get(id: string): Promise<any>;
|
||||
@@ -681,6 +696,7 @@ declare var Clients: {
|
||||
new(): Clients;
|
||||
};
|
||||
|
||||
/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
|
||||
interface CloseEvent extends Event {
|
||||
readonly code: number;
|
||||
readonly reason: string;
|
||||
@@ -703,6 +719,7 @@ interface ConcatParams extends Algorithm {
|
||||
publicInfo?: Uint8Array;
|
||||
}
|
||||
|
||||
/** The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided. */
|
||||
interface Console {
|
||||
memory: any;
|
||||
assert(condition?: boolean, message?: string, ...data: any[]): void;
|
||||
@@ -736,6 +753,7 @@ declare var Console: {
|
||||
new(): Console;
|
||||
};
|
||||
|
||||
/** The CountQueuingStrategy interface of the the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. */
|
||||
interface CountQueuingStrategy extends QueuingStrategy {
|
||||
highWaterMark: number;
|
||||
size(chunk: any): 1;
|
||||
@@ -746,6 +764,7 @@ declare var CountQueuingStrategy: {
|
||||
new(options: { highWaterMark: number }): CountQueuingStrategy;
|
||||
};
|
||||
|
||||
/** The Crypto interface represents basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. */
|
||||
interface Crypto {
|
||||
readonly subtle: SubtleCrypto;
|
||||
getRandomValues<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null>(array: T): T;
|
||||
@@ -756,6 +775,7 @@ declare var Crypto: {
|
||||
new(): Crypto;
|
||||
};
|
||||
|
||||
/** The CryptoKey interface represents a cryptographic key derived from a specific key algorithm. */
|
||||
interface CryptoKey {
|
||||
readonly algorithm: KeyAlgorithm;
|
||||
readonly extractable: boolean;
|
||||
@@ -782,6 +802,7 @@ declare var CustomEvent: {
|
||||
new<T>(typeArg: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
|
||||
};
|
||||
|
||||
/** The DOMException interface represents an abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. */
|
||||
interface DOMException {
|
||||
readonly code: number;
|
||||
readonly message: string;
|
||||
@@ -921,6 +942,8 @@ interface DOMMatrixReadOnly {
|
||||
rotateFromVector(x?: number, y?: number): DOMMatrix;
|
||||
scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
|
||||
scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
|
||||
/** @deprecated */
|
||||
scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix;
|
||||
skewX(sx?: number): DOMMatrix;
|
||||
skewY(sy?: number): DOMMatrix;
|
||||
toFloat32Array(): Float32Array;
|
||||
@@ -1013,6 +1036,7 @@ declare var DOMRectReadOnly: {
|
||||
fromRect(other?: DOMRectInit): DOMRectReadOnly;
|
||||
};
|
||||
|
||||
/** A type returned by some APIs which contains a list of DOMString (strings). */
|
||||
interface DOMStringList {
|
||||
/**
|
||||
* Returns the number of strings in strings.
|
||||
@@ -1039,6 +1063,7 @@ interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
|
||||
"message": MessageEvent;
|
||||
}
|
||||
|
||||
/** The DedicatedWorkerGlobalScope object (the Worker global scope) is accessible through the self keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the JavaScript Reference. See also: Functions available to workers. */
|
||||
interface DedicatedWorkerGlobalScope extends WorkerGlobalScope {
|
||||
onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
|
||||
close(): void;
|
||||
@@ -1078,6 +1103,7 @@ interface EXT_blend_minmax {
|
||||
readonly MIN_EXT: GLenum;
|
||||
}
|
||||
|
||||
/** The EXT_frag_depth extension is part of the WebGL API and enables to set a depth value of a fragment from within the fragment shader. */
|
||||
interface EXT_frag_depth {
|
||||
}
|
||||
|
||||
@@ -1091,11 +1117,13 @@ interface EXT_sRGB {
|
||||
interface EXT_shader_texture_lod {
|
||||
}
|
||||
|
||||
/** The EXT_texture_filter_anisotropic extension is part of the WebGL API and exposes two constants for anisotropic filtering (AF). */
|
||||
interface EXT_texture_filter_anisotropic {
|
||||
readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
|
||||
readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum;
|
||||
}
|
||||
|
||||
/** The ErrorEvent interface represents events providing information related to errors in scripts or in files. */
|
||||
interface ErrorEvent extends Event {
|
||||
readonly colno: number;
|
||||
readonly error: any;
|
||||
@@ -1109,6 +1137,7 @@ declare var ErrorEvent: {
|
||||
new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent;
|
||||
};
|
||||
|
||||
/** The Event interface represents any event which takes place in the DOM; some are user-generated (such as mouse or keyboard events), while others are generated by APIs (such as events that indicate an animation has finished running, a video has been paused, and so forth). While events are usually triggered by such "external" sources, they can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent(). There are many types of events, some of which use other interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. */
|
||||
interface Event {
|
||||
/**
|
||||
* Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
|
||||
@@ -1133,6 +1162,8 @@ interface Event {
|
||||
*/
|
||||
readonly isTrusted: boolean;
|
||||
returnValue: boolean;
|
||||
/** @deprecated */
|
||||
readonly srcElement: EventTarget | null;
|
||||
/**
|
||||
* Returns the object to which event is dispatched (its target).
|
||||
*/
|
||||
@@ -1180,28 +1211,50 @@ interface EventListenerObject {
|
||||
handleEvent(evt: Event): void;
|
||||
}
|
||||
|
||||
interface EventSourceEventMap {
|
||||
"error": Event;
|
||||
"message": MessageEvent;
|
||||
"open": Event;
|
||||
}
|
||||
|
||||
interface EventSource extends EventTarget {
|
||||
onerror: ((this: EventSource, ev: Event) => any) | null;
|
||||
onmessage: ((this: EventSource, ev: MessageEvent) => any) | null;
|
||||
onopen: ((this: EventSource, ev: Event) => any) | null;
|
||||
/**
|
||||
* Returns the state of this EventSource object's connection. It can have the
|
||||
* values described below.
|
||||
*/
|
||||
readonly readyState: number;
|
||||
/**
|
||||
* Returns the URL providing the event stream.
|
||||
*/
|
||||
readonly url: string;
|
||||
/**
|
||||
* Returns true if the credentials mode
|
||||
* for connection requests to the URL providing the
|
||||
* event stream is set to "include", and false otherwise.
|
||||
*/
|
||||
readonly withCredentials: boolean;
|
||||
close(): void;
|
||||
readonly CLOSED: number;
|
||||
readonly CONNECTING: number;
|
||||
readonly OPEN: number;
|
||||
onerror: (evt: MessageEvent) => any;
|
||||
onmessage: (evt: MessageEvent) => any;
|
||||
onopen: (evt: MessageEvent) => any;
|
||||
readonly readyState: number;
|
||||
readonly url: string;
|
||||
readonly withCredentials: boolean;
|
||||
close(): void;
|
||||
addEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
|
||||
removeEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
|
||||
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
|
||||
}
|
||||
|
||||
declare var EventSource: {
|
||||
prototype: EventSource;
|
||||
new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;
|
||||
readonly CLOSED: number;
|
||||
readonly CONNECTING: number;
|
||||
readonly OPEN: number;
|
||||
};
|
||||
|
||||
interface EventSourceInit {
|
||||
readonly withCredentials: boolean;
|
||||
}
|
||||
|
||||
/** EventTarget is an interface implemented by objects that can receive events and may have listeners for them. */
|
||||
interface EventTarget {
|
||||
/**
|
||||
* Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
|
||||
@@ -1230,8 +1283,9 @@ declare var EventTarget: {
|
||||
new(): EventTarget;
|
||||
};
|
||||
|
||||
/** The ExtendableEvent interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. */
|
||||
interface ExtendableEvent extends Event {
|
||||
waitUntil(f: Promise<any>): void;
|
||||
waitUntil(f: any): void;
|
||||
}
|
||||
|
||||
declare var ExtendableEvent: {
|
||||
@@ -1239,6 +1293,7 @@ declare var ExtendableEvent: {
|
||||
new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent;
|
||||
};
|
||||
|
||||
/** The ExtendableMessageEvent interface of the ServiceWorker API represents the event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events. */
|
||||
interface ExtendableMessageEvent extends ExtendableEvent {
|
||||
readonly data: any;
|
||||
readonly lastEventId: string;
|
||||
@@ -1252,13 +1307,14 @@ declare var ExtendableMessageEvent: {
|
||||
new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent;
|
||||
};
|
||||
|
||||
/** This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. */
|
||||
interface FetchEvent extends ExtendableEvent {
|
||||
readonly clientId: string;
|
||||
readonly preloadResponse: Promise<any>;
|
||||
readonly request: Request;
|
||||
readonly resultingClientId: string;
|
||||
readonly targetClientId: string;
|
||||
respondWith(r: Promise<Response>): void;
|
||||
respondWith(r: Response | Promise<Response>): void;
|
||||
}
|
||||
|
||||
declare var FetchEvent: {
|
||||
@@ -1266,6 +1322,7 @@ declare var FetchEvent: {
|
||||
new(type: string, eventInitDict: FetchEventInit): FetchEvent;
|
||||
};
|
||||
|
||||
/** The File interface provides information about files and allows JavaScript in a web page to access their content. */
|
||||
interface File extends Blob {
|
||||
readonly lastModified: number;
|
||||
readonly name: string;
|
||||
@@ -1276,6 +1333,7 @@ declare var File: {
|
||||
new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
|
||||
};
|
||||
|
||||
/** An object of this type is returned by the files property of the HTML <input> element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. */
|
||||
interface FileList {
|
||||
readonly length: number;
|
||||
item(index: number): File | null;
|
||||
@@ -1296,6 +1354,7 @@ interface FileReaderEventMap {
|
||||
"progress": ProgressEvent;
|
||||
}
|
||||
|
||||
/** The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. */
|
||||
interface FileReader extends EventTarget {
|
||||
readonly error: DOMException | null;
|
||||
onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;
|
||||
@@ -1328,6 +1387,7 @@ declare var FileReader: {
|
||||
readonly LOADING: number;
|
||||
};
|
||||
|
||||
/** The FileReaderSync interface allows to read File or Blob objects in a synchronous way. */
|
||||
interface FileReaderSync {
|
||||
readAsArrayBuffer(blob: Blob): ArrayBuffer;
|
||||
readAsBinaryString(blob: Blob): string;
|
||||
@@ -1340,6 +1400,7 @@ declare var FileReaderSync: {
|
||||
new(): FileReaderSync;
|
||||
};
|
||||
|
||||
/** The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". */
|
||||
interface FormData {
|
||||
append(name: string, value: string | Blob, fileName?: string): void;
|
||||
delete(name: string): void;
|
||||
@@ -1359,6 +1420,7 @@ interface GlobalFetch {
|
||||
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
/** The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. */
|
||||
interface Headers {
|
||||
append(name: string, value: string): void;
|
||||
delete(name: string): void;
|
||||
@@ -1382,6 +1444,7 @@ interface HkdfCtrParams extends Algorithm {
|
||||
interface IDBArrayKey extends Array<IDBValidKey> {
|
||||
}
|
||||
|
||||
/** The IDBCursor interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. */
|
||||
interface IDBCursor {
|
||||
/**
|
||||
* Returns the direction ("next", "nextunique", "prev" or "prevunique")
|
||||
@@ -1392,12 +1455,12 @@ interface IDBCursor {
|
||||
* Returns the key of the cursor.
|
||||
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
|
||||
*/
|
||||
readonly key: IDBValidKey | IDBKeyRange;
|
||||
readonly key: IDBValidKey;
|
||||
/**
|
||||
* Returns the effective key of the cursor.
|
||||
* Throws a "InvalidStateError" DOMException if the cursor is advancing or is finished.
|
||||
*/
|
||||
readonly primaryKey: IDBValidKey | IDBKeyRange;
|
||||
readonly primaryKey: IDBValidKey;
|
||||
/**
|
||||
* Returns the IDBObjectStore or IDBIndex the cursor was opened from.
|
||||
*/
|
||||
@@ -1411,12 +1474,12 @@ interface IDBCursor {
|
||||
* Advances the cursor to the next record in range matching or
|
||||
* after key.
|
||||
*/
|
||||
continue(key?: IDBValidKey | IDBKeyRange): void;
|
||||
continue(key?: IDBValidKey): void;
|
||||
/**
|
||||
* Advances the cursor to the next record in range matching
|
||||
* or after key and primaryKey. Throws an "InvalidAccessError" DOMException if the source is not an index.
|
||||
*/
|
||||
continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void;
|
||||
continuePrimaryKey(key: IDBValidKey, primaryKey: IDBValidKey): void;
|
||||
/**
|
||||
* Delete the record pointed at by the cursor with a new value.
|
||||
* If successful, request's result will be undefined.
|
||||
@@ -1435,6 +1498,7 @@ declare var IDBCursor: {
|
||||
new(): IDBCursor;
|
||||
};
|
||||
|
||||
/** The IDBCursorWithValue interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database. It is the same as the IDBCursor, except that it includes the value property. */
|
||||
interface IDBCursorWithValue extends IDBCursor {
|
||||
/**
|
||||
* Returns the cursor's current value.
|
||||
@@ -1454,6 +1518,7 @@ interface IDBDatabaseEventMap {
|
||||
"versionchange": IDBVersionChangeEvent;
|
||||
}
|
||||
|
||||
/** The IDBDatabase interface of the IndexedDB API provides a connection to a database; you can use an IDBDatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database. */
|
||||
interface IDBDatabase extends EventTarget {
|
||||
/**
|
||||
* Returns the name of the database.
|
||||
@@ -1501,6 +1566,7 @@ declare var IDBDatabase: {
|
||||
new(): IDBDatabase;
|
||||
};
|
||||
|
||||
/** In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our To-do Notifications app (view example live.) */
|
||||
interface IDBFactory {
|
||||
/**
|
||||
* Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if
|
||||
@@ -1530,6 +1596,7 @@ declare var IDBFactory: {
|
||||
new(): IDBFactory;
|
||||
};
|
||||
|
||||
/** IDBIndex interface of the IndexedDB API provides asynchronous access to an index in a database. An index is a kind of object store for looking up records in another object store, called the referenced object store. You use this interface to retrieve data. */
|
||||
interface IDBIndex {
|
||||
readonly keyPath: string | string[];
|
||||
readonly multiEntry: boolean;
|
||||
@@ -1590,6 +1657,7 @@ declare var IDBIndex: {
|
||||
new(): IDBIndex;
|
||||
};
|
||||
|
||||
/** A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs: */
|
||||
interface IDBKeyRange {
|
||||
/**
|
||||
* Returns lower bound, or undefined if none.
|
||||
@@ -1638,6 +1706,7 @@ declare var IDBKeyRange: {
|
||||
upperBound(upper: any, open?: boolean): IDBKeyRange;
|
||||
};
|
||||
|
||||
/** This example shows a variety of different uses of object stores, from updating the data structure with IDBObjectStore.createIndex inside an onupgradeneeded function, to adding a new item to our object store with IDBObjectStore.add. For a full working example, see our To-do Notifications app (view example live.) */
|
||||
interface IDBObjectStore {
|
||||
/**
|
||||
* Returns true if the store has a key generator, and false otherwise.
|
||||
@@ -1661,7 +1730,7 @@ interface IDBObjectStore {
|
||||
* Returns the associated transaction.
|
||||
*/
|
||||
readonly transaction: IDBTransaction;
|
||||
add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
|
||||
add(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
|
||||
/**
|
||||
* Deletes all records in store.
|
||||
* If successful, request's result will
|
||||
@@ -1734,7 +1803,7 @@ interface IDBObjectStore {
|
||||
* null if there were no matching records.
|
||||
*/
|
||||
openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest<IDBCursor | null>;
|
||||
put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey>;
|
||||
put(value: any, key?: IDBValidKey): IDBRequest<IDBValidKey>;
|
||||
}
|
||||
|
||||
declare var IDBObjectStore: {
|
||||
@@ -1747,6 +1816,7 @@ interface IDBOpenDBRequestEventMap extends IDBRequestEventMap {
|
||||
"upgradeneeded": IDBVersionChangeEvent;
|
||||
}
|
||||
|
||||
/** Also inherits methods from its parents IDBRequest and EventTarget. */
|
||||
interface IDBOpenDBRequest extends IDBRequest<IDBDatabase> {
|
||||
onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;
|
||||
onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;
|
||||
@@ -1766,6 +1836,7 @@ interface IDBRequestEventMap {
|
||||
"success": Event;
|
||||
}
|
||||
|
||||
/** The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the IDBRequest instance. */
|
||||
interface IDBRequest<T = any> extends EventTarget {
|
||||
/**
|
||||
* When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws
|
||||
@@ -1857,6 +1928,7 @@ declare var IDBTransaction: {
|
||||
new(): IDBTransaction;
|
||||
};
|
||||
|
||||
/** The IDBVersionChangeEvent interface of the IndexedDB API indicates that the version of the database has changed, as the result of an IDBOpenDBRequest.onupgradeneeded event handler function. */
|
||||
interface IDBVersionChangeEvent extends Event {
|
||||
readonly newVersion: number | null;
|
||||
readonly oldVersion: number;
|
||||
@@ -1898,6 +1970,7 @@ interface ImageBitmapOptions {
|
||||
resizeWidth?: number;
|
||||
}
|
||||
|
||||
/** The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData(). It can also be used to set a part of the canvas by using putImageData(). */
|
||||
interface ImageData {
|
||||
/**
|
||||
* Returns the one-dimensional array containing the data in RGBA order, as integers in the
|
||||
@@ -1918,6 +1991,7 @@ declare var ImageData: {
|
||||
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
|
||||
};
|
||||
|
||||
/** The MessageChannel interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. */
|
||||
interface MessageChannel {
|
||||
readonly port1: MessagePort;
|
||||
readonly port2: MessagePort;
|
||||
@@ -1928,6 +2002,7 @@ declare var MessageChannel: {
|
||||
new(): MessageChannel;
|
||||
};
|
||||
|
||||
/** The MessageEvent interface represents a message received by a target object. */
|
||||
interface MessageEvent extends Event {
|
||||
/**
|
||||
* Returns the data of the message.
|
||||
@@ -1966,6 +2041,7 @@ interface MessagePortEventMap {
|
||||
"messageerror": MessageEvent;
|
||||
}
|
||||
|
||||
/** The MessagePort interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. */
|
||||
interface MessagePort extends EventTarget {
|
||||
onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;
|
||||
onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;
|
||||
@@ -2043,6 +2119,7 @@ interface NotificationEventMap {
|
||||
"show": Event;
|
||||
}
|
||||
|
||||
/** The Notification interface of the Notifications API is used to configure and display desktop notifications to the user. */
|
||||
interface Notification extends EventTarget {
|
||||
readonly actions: ReadonlyArray<NotificationAction>;
|
||||
readonly badge: string;
|
||||
@@ -2077,6 +2154,7 @@ declare var Notification: {
|
||||
readonly permission: NotificationPermission;
|
||||
};
|
||||
|
||||
/** The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. */
|
||||
interface NotificationEvent extends ExtendableEvent {
|
||||
readonly action: string;
|
||||
readonly notification: Notification;
|
||||
@@ -2087,23 +2165,29 @@ declare var NotificationEvent: {
|
||||
new(type: string, eventInitDict: NotificationEventInit): NotificationEvent;
|
||||
};
|
||||
|
||||
/** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */
|
||||
interface OES_element_index_uint {
|
||||
}
|
||||
|
||||
/** The OES_standard_derivatives extension is part of the WebGL API and adds the GLSL derivative functions dFdx, dFdy, and fwidth. */
|
||||
interface OES_standard_derivatives {
|
||||
readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: GLenum;
|
||||
}
|
||||
|
||||
/** The OES_texture_float extension is part of the WebGL API and exposes floating-point pixel types for textures. */
|
||||
interface OES_texture_float {
|
||||
}
|
||||
|
||||
/** The OES_texture_float_linear extension is part of the WebGL API and allows linear filtering with floating-point pixel types for textures. */
|
||||
interface OES_texture_float_linear {
|
||||
}
|
||||
|
||||
/** The OES_texture_half_float extension is part of the WebGL API and adds texture formats with 16- (aka half float) and 32-bit floating-point components. */
|
||||
interface OES_texture_half_float {
|
||||
readonly HALF_FLOAT_OES: GLenum;
|
||||
}
|
||||
|
||||
/** The OES_texture_half_float_linear extension is part of the WebGL API and allows linear filtering with half floating-point pixel types for textures. */
|
||||
interface OES_texture_half_float_linear {
|
||||
}
|
||||
|
||||
@@ -2115,6 +2199,7 @@ interface OES_vertex_array_object {
|
||||
readonly VERTEX_ARRAY_BINDING_OES: GLenum;
|
||||
}
|
||||
|
||||
/** The Path2D interface of the Canvas 2D API is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. */
|
||||
interface Path2D extends CanvasPath {
|
||||
addPath(path: Path2D, transform?: DOMMatrix2DInit): void;
|
||||
}
|
||||
@@ -2128,6 +2213,7 @@ interface PerformanceEventMap {
|
||||
"resourcetimingbufferfull": Event;
|
||||
}
|
||||
|
||||
/** The Performance interface provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */
|
||||
interface Performance extends EventTarget {
|
||||
onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null;
|
||||
readonly timeOrigin: number;
|
||||
@@ -2153,6 +2239,7 @@ declare var Performance: {
|
||||
new(): Performance;
|
||||
};
|
||||
|
||||
/** The PerformanceEntry object encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image). */
|
||||
interface PerformanceEntry {
|
||||
readonly duration: number;
|
||||
readonly entryType: string;
|
||||
@@ -2166,6 +2253,7 @@ declare var PerformanceEntry: {
|
||||
new(): PerformanceEntry;
|
||||
};
|
||||
|
||||
/** PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. */
|
||||
interface PerformanceMark extends PerformanceEntry {
|
||||
}
|
||||
|
||||
@@ -2174,6 +2262,7 @@ declare var PerformanceMark: {
|
||||
new(): PerformanceMark;
|
||||
};
|
||||
|
||||
/** PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. */
|
||||
interface PerformanceMeasure extends PerformanceEntry {
|
||||
}
|
||||
|
||||
@@ -2204,6 +2293,7 @@ declare var PerformanceObserverEntryList: {
|
||||
new(): PerformanceObserverEntryList;
|
||||
};
|
||||
|
||||
/** The PerformanceResourceTiming interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, <SVG>, image, or script. */
|
||||
interface PerformanceResourceTiming extends PerformanceEntry {
|
||||
readonly connectEnd: number;
|
||||
readonly connectStart: number;
|
||||
@@ -2230,6 +2320,7 @@ declare var PerformanceResourceTiming: {
|
||||
new(): PerformanceResourceTiming;
|
||||
};
|
||||
|
||||
/** The ProgressEvent interface represents events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). */
|
||||
interface ProgressEvent extends Event {
|
||||
readonly lengthComputable: boolean;
|
||||
readonly loaded: number;
|
||||
@@ -2251,6 +2342,7 @@ declare var PromiseRejectionEvent: {
|
||||
new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;
|
||||
};
|
||||
|
||||
/** The PushEvent interface of the Push API represents a push message that has been received. This event is sent to the global scope of a ServiceWorker. It contains the information sent from an application server to a PushSubscription. */
|
||||
interface PushEvent extends ExtendableEvent {
|
||||
readonly data: PushMessageData | null;
|
||||
}
|
||||
@@ -2260,6 +2352,7 @@ declare var PushEvent: {
|
||||
new(type: string, eventInitDict?: PushEventInit): PushEvent;
|
||||
};
|
||||
|
||||
/** The PushManager interface of the Push API provides a way to receive notifications from third-party servers as well as request URLs for push notifications. */
|
||||
interface PushManager {
|
||||
getSubscription(): Promise<PushSubscription | null>;
|
||||
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
|
||||
@@ -2272,6 +2365,7 @@ declare var PushManager: {
|
||||
readonly supportedContentEncodings: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
/** The PushMessageData interface of the Push API provides methods which let you retrieve the push data sent by a server in various formats. */
|
||||
interface PushMessageData {
|
||||
arrayBuffer(): ArrayBuffer;
|
||||
blob(): Blob;
|
||||
@@ -2284,6 +2378,7 @@ declare var PushMessageData: {
|
||||
new(): PushMessageData;
|
||||
};
|
||||
|
||||
/** The PushSubscription interface of the Push API provides a subcription's URL endpoint and allows unsubscription from a push service. */
|
||||
interface PushSubscription {
|
||||
readonly endpoint: string;
|
||||
readonly expirationTime: number | null;
|
||||
@@ -2326,6 +2421,7 @@ interface ReadableByteStreamController {
|
||||
error(error?: any): void;
|
||||
}
|
||||
|
||||
/** The ReadableStream interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */
|
||||
interface ReadableStream<R = any> {
|
||||
readonly locked: boolean;
|
||||
cancel(reason?: any): Promise<void>;
|
||||
@@ -2390,6 +2486,7 @@ declare var ReadableStreamReader: {
|
||||
new(): ReadableStreamReader;
|
||||
};
|
||||
|
||||
/** The Request interface of the Fetch API represents a resource request. */
|
||||
interface Request extends Body {
|
||||
/**
|
||||
* Returns the cache mode associated with request, which is a string indicating
|
||||
@@ -2475,6 +2572,7 @@ declare var Request: {
|
||||
new(input: RequestInfo, init?: RequestInit): Request;
|
||||
};
|
||||
|
||||
/** The Response interface of the Fetch API represents the response to a request. */
|
||||
interface Response extends Body {
|
||||
readonly headers: Headers;
|
||||
readonly ok: boolean;
|
||||
@@ -2498,6 +2596,7 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
|
||||
"statechange": Event;
|
||||
}
|
||||
|
||||
/** The ServiceWorker interface of the ServiceWorker API provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object. */
|
||||
interface ServiceWorker extends EventTarget, AbstractWorker {
|
||||
onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;
|
||||
readonly scriptURL: string;
|
||||
@@ -2520,6 +2619,7 @@ interface ServiceWorkerContainerEventMap {
|
||||
"messageerror": MessageEvent;
|
||||
}
|
||||
|
||||
/** The ServiceWorkerContainer interface of the ServiceWorker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. */
|
||||
interface ServiceWorkerContainer extends EventTarget {
|
||||
readonly controller: ServiceWorker | null;
|
||||
oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;
|
||||
@@ -2554,6 +2654,7 @@ interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap {
|
||||
"sync": SyncEvent;
|
||||
}
|
||||
|
||||
/** The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker. */
|
||||
interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
|
||||
readonly clients: Clients;
|
||||
onactivate: ((this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any) | null;
|
||||
@@ -2583,6 +2684,7 @@ interface ServiceWorkerRegistrationEventMap {
|
||||
"updatefound": Event;
|
||||
}
|
||||
|
||||
/** The ServiceWorkerRegistration interface of the ServiceWorker API represents the service worker registration. You register a service worker to control one or more pages that share the same origin. */
|
||||
interface ServiceWorkerRegistration extends EventTarget {
|
||||
readonly active: ServiceWorker | null;
|
||||
readonly installing: ServiceWorker | null;
|
||||
@@ -2618,6 +2720,7 @@ declare var StorageManager: {
|
||||
new(): StorageManager;
|
||||
};
|
||||
|
||||
/** The SubtleCrypto interface represents a set of cryptographic primitives. It is available via the Crypto.subtle properties available in a window context (via Window.crypto). */
|
||||
interface SubtleCrypto {
|
||||
decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike<ArrayBuffer>;
|
||||
deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike<ArrayBuffer>;
|
||||
@@ -2644,6 +2747,7 @@ declare var SubtleCrypto: {
|
||||
new(): SubtleCrypto;
|
||||
};
|
||||
|
||||
/** The SyncEvent interface represents a sync action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. */
|
||||
interface SyncEvent extends ExtendableEvent {
|
||||
readonly lastChance: boolean;
|
||||
readonly tag: string;
|
||||
@@ -2654,6 +2758,7 @@ declare var SyncEvent: {
|
||||
new(type: string, init: SyncEventInit): SyncEvent;
|
||||
};
|
||||
|
||||
/** The SyncManager interface of the the ServiceWorker API provides an interface for registering and listing sync registrations. */
|
||||
interface SyncManager {
|
||||
getTags(): Promise<string[]>;
|
||||
register(tag: string): Promise<void>;
|
||||
@@ -2664,6 +2769,7 @@ declare var SyncManager: {
|
||||
new(): SyncManager;
|
||||
};
|
||||
|
||||
/** The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
|
||||
interface TextDecoder {
|
||||
/**
|
||||
* Returns encoding's name, lowercased.
|
||||
@@ -2699,6 +2805,7 @@ declare var TextDecoder: {
|
||||
new(label?: string, options?: TextDecoderOptions): TextDecoder;
|
||||
};
|
||||
|
||||
/** TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */
|
||||
interface TextEncoder {
|
||||
/**
|
||||
* Returns "utf-8".
|
||||
@@ -2715,6 +2822,7 @@ declare var TextEncoder: {
|
||||
new(): TextEncoder;
|
||||
};
|
||||
|
||||
/** The TextMetrics interface represents the dimension of a text in the canvas, as created by the CanvasRenderingContext2D.measureText() method. */
|
||||
interface TextMetrics {
|
||||
readonly actualBoundingBoxAscent: number;
|
||||
readonly actualBoundingBoxDescent: number;
|
||||
@@ -2755,6 +2863,7 @@ interface TransformStreamDefaultController<O = any> {
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** The URL interface represents an object providing static methods used for creating object URLs. */
|
||||
interface URL {
|
||||
hash: string;
|
||||
host: string;
|
||||
@@ -2850,6 +2959,7 @@ interface WEBGL_compressed_texture_astc {
|
||||
readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum;
|
||||
}
|
||||
|
||||
/** The WEBGL_compressed_texture_s3tc extension is part of the WebGL API and exposes four S3TC compressed texture formats. */
|
||||
interface WEBGL_compressed_texture_s3tc {
|
||||
readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum;
|
||||
readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum;
|
||||
@@ -2864,6 +2974,7 @@ interface WEBGL_compressed_texture_s3tc_srgb {
|
||||
readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum;
|
||||
}
|
||||
|
||||
/** The WEBGL_debug_renderer_info extension is part of the WebGL API and exposes two constants with information about the graphics driver for debugging purposes. */
|
||||
interface WEBGL_debug_renderer_info {
|
||||
readonly UNMASKED_RENDERER_WEBGL: GLenum;
|
||||
readonly UNMASKED_VENDOR_WEBGL: GLenum;
|
||||
@@ -2873,6 +2984,7 @@ interface WEBGL_debug_shaders {
|
||||
getTranslatedShaderSource(shader: WebGLShader): string;
|
||||
}
|
||||
|
||||
/** The WEBGL_depth_texture extension is part of the WebGL API and defines 2D depth and depth-stencil textures. */
|
||||
interface WEBGL_depth_texture {
|
||||
readonly UNSIGNED_INT_24_8_WEBGL: GLenum;
|
||||
}
|
||||
@@ -2920,6 +3032,7 @@ interface WEBGL_lose_context {
|
||||
restoreContext(): void;
|
||||
}
|
||||
|
||||
/** The WebGLActiveInfo interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getActiveAttrib() and WebGLRenderingContext.getActiveUniform() methods. */
|
||||
interface WebGLActiveInfo {
|
||||
readonly name: string;
|
||||
readonly size: GLint;
|
||||
@@ -2931,6 +3044,7 @@ declare var WebGLActiveInfo: {
|
||||
new(): WebGLActiveInfo;
|
||||
};
|
||||
|
||||
/** The WebGLBuffer interface is part of the WebGL API and represents an opaque buffer object storing data such as vertices or colors. */
|
||||
interface WebGLBuffer extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -2939,6 +3053,7 @@ declare var WebGLBuffer: {
|
||||
new(): WebGLBuffer;
|
||||
};
|
||||
|
||||
/** The WebContextEvent interface is part of the WebGL API and is an interface for an event that is generated in response to a status change to the WebGL rendering context. */
|
||||
interface WebGLContextEvent extends Event {
|
||||
readonly statusMessage: string;
|
||||
}
|
||||
@@ -2948,6 +3063,7 @@ declare var WebGLContextEvent: {
|
||||
new(type: string, eventInit?: WebGLContextEventInit): WebGLContextEvent;
|
||||
};
|
||||
|
||||
/** The WebGLFramebuffer interface is part of the WebGL API and represents a collection of buffers that serve as a rendering destination. */
|
||||
interface WebGLFramebuffer extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -2964,6 +3080,7 @@ declare var WebGLObject: {
|
||||
new(): WebGLObject;
|
||||
};
|
||||
|
||||
/** The WebGLProgram is part of the WebGL API and is a combination of two compiled WebGLShaders consisting of a vertex shader and a fragment shader (both written in GLSL). */
|
||||
interface WebGLProgram extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -2972,6 +3089,7 @@ declare var WebGLProgram: {
|
||||
new(): WebGLProgram;
|
||||
};
|
||||
|
||||
/** The WebGLRenderbuffer interface is part of the WebGL API and represents a buffer that can contain an image, or can be source or target of an rendering operation. */
|
||||
interface WebGLRenderbuffer extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -2980,6 +3098,7 @@ declare var WebGLRenderbuffer: {
|
||||
new(): WebGLRenderbuffer;
|
||||
};
|
||||
|
||||
/** The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. */
|
||||
interface WebGLRenderingContext extends WebGLRenderingContextBase {
|
||||
}
|
||||
|
||||
@@ -3398,7 +3517,7 @@ interface WebGLRenderingContextBase {
|
||||
isTexture(texture: WebGLTexture | null): GLboolean;
|
||||
lineWidth(width: GLfloat): void;
|
||||
linkProgram(program: WebGLProgram): void;
|
||||
pixelStorei(pname: GLenum, param: GLint): void;
|
||||
pixelStorei(pname: GLenum, param: GLint | GLboolean): void;
|
||||
polygonOffset(factor: GLfloat, units: GLfloat): void;
|
||||
readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView | null): void;
|
||||
renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei): void;
|
||||
@@ -3746,6 +3865,7 @@ interface WebGLRenderingContextBase {
|
||||
readonly ZERO: GLenum;
|
||||
}
|
||||
|
||||
/** The WebGLShader is part of the WebGL API and can either be a vertex or a fragment shader. A WebGLProgram requires both types of shaders. */
|
||||
interface WebGLShader extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -3754,6 +3874,7 @@ declare var WebGLShader: {
|
||||
new(): WebGLShader;
|
||||
};
|
||||
|
||||
/** The WebGLShaderPrecisionFormat interface is part of the WebGL API and represents the information returned by calling the WebGLRenderingContext.getShaderPrecisionFormat() method. */
|
||||
interface WebGLShaderPrecisionFormat {
|
||||
readonly precision: GLint;
|
||||
readonly rangeMax: GLint;
|
||||
@@ -3765,6 +3886,7 @@ declare var WebGLShaderPrecisionFormat: {
|
||||
new(): WebGLShaderPrecisionFormat;
|
||||
};
|
||||
|
||||
/** The WebGLTexture interface is part of the WebGL API and represents an opaque texture object providing storage and state for texturing operations. */
|
||||
interface WebGLTexture extends WebGLObject {
|
||||
}
|
||||
|
||||
@@ -3773,6 +3895,7 @@ declare var WebGLTexture: {
|
||||
new(): WebGLTexture;
|
||||
};
|
||||
|
||||
/** The WebGLUniformLocation interface is part of the WebGL API and represents the location of a uniform variable in a shader program. */
|
||||
interface WebGLUniformLocation {
|
||||
}
|
||||
|
||||
@@ -3791,6 +3914,7 @@ interface WebSocketEventMap {
|
||||
"open": Event;
|
||||
}
|
||||
|
||||
/** The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */
|
||||
interface WebSocket extends EventTarget {
|
||||
binaryType: BinaryType;
|
||||
readonly bufferedAmount: number;
|
||||
@@ -3828,6 +3952,7 @@ interface WindowBase64 {
|
||||
btoa(rawString: string): string;
|
||||
}
|
||||
|
||||
/** The WindowClient interface of the ServiceWorker API represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources. */
|
||||
interface WindowClient extends Client {
|
||||
readonly ancestorOrigins: ReadonlyArray<string>;
|
||||
readonly focused: boolean;
|
||||
@@ -3867,6 +3992,7 @@ interface WorkerEventMap extends AbstractWorkerEventMap {
|
||||
"message": MessageEvent;
|
||||
}
|
||||
|
||||
/** The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread. */
|
||||
interface Worker extends EventTarget, AbstractWorker {
|
||||
onmessage: ((this: Worker, ev: MessageEvent) => any) | null;
|
||||
postMessage(message: any, transfer?: Transferable[]): void;
|
||||
@@ -3879,13 +4005,14 @@ interface Worker extends EventTarget, AbstractWorker {
|
||||
|
||||
declare var Worker: {
|
||||
prototype: Worker;
|
||||
new(stringUrl: string, options?: WorkerOptions): Worker;
|
||||
new(stringUrl: string | URL, options?: WorkerOptions): Worker;
|
||||
};
|
||||
|
||||
interface WorkerGlobalScopeEventMap {
|
||||
"error": ErrorEvent;
|
||||
}
|
||||
|
||||
/** The WorkerGlobalScope interface of the Web Workers API is an interface representing the scope of any worker. Workers have no browsing context; this scope contains the information usually conveyed by Window objects — in this case event handlers, the console or the associated WorkerNavigator object. Each WorkerGlobalScope has its own event loop. */
|
||||
interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, GlobalFetch, WindowOrWorkerGlobalScope {
|
||||
readonly caches: CacheStorage;
|
||||
readonly isSecureContext: boolean;
|
||||
@@ -3905,6 +4032,7 @@ declare var WorkerGlobalScope: {
|
||||
new(): WorkerGlobalScope;
|
||||
};
|
||||
|
||||
/** The WorkerLocation interface defines the absolute location of the script executed by the Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.location property obtained by calling self.location. */
|
||||
interface WorkerLocation {
|
||||
readonly hash: string;
|
||||
readonly host: string;
|
||||
@@ -3923,6 +4051,7 @@ declare var WorkerLocation: {
|
||||
new(): WorkerLocation;
|
||||
};
|
||||
|
||||
/** The WorkerNavigator interface represents a subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator. */
|
||||
interface WorkerNavigator extends NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorStorage {
|
||||
readonly serviceWorker: ServiceWorkerContainer;
|
||||
}
|
||||
@@ -3939,6 +4068,7 @@ interface WorkerUtils extends WindowBase64 {
|
||||
importScripts(...urls: string[]): void;
|
||||
}
|
||||
|
||||
/** The WritableStream interface of the the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. */
|
||||
interface WritableStream<W = any> {
|
||||
readonly locked: boolean;
|
||||
abort(reason?: any): Promise<void>;
|
||||
@@ -3950,10 +4080,12 @@ declare var WritableStream: {
|
||||
new<W = any>(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
|
||||
};
|
||||
|
||||
/** The WritableStreamDefaultController interface of the the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */
|
||||
interface WritableStreamDefaultController {
|
||||
error(error?: any): void;
|
||||
}
|
||||
|
||||
/** The WritableStreamDefaultWriter interface of the the Streams API is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */
|
||||
interface WritableStreamDefaultWriter<W = any> {
|
||||
readonly closed: Promise<void>;
|
||||
readonly desiredSize: number | null;
|
||||
@@ -3968,6 +4100,7 @@ interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {
|
||||
"readystatechange": Event;
|
||||
}
|
||||
|
||||
/** Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. */
|
||||
interface XMLHttpRequest extends XMLHttpRequestEventTarget {
|
||||
onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;
|
||||
/**
|
||||
@@ -4042,7 +4175,8 @@ interface XMLHttpRequest extends XMLHttpRequestEventTarget {
|
||||
*/
|
||||
overrideMimeType(mime: string): void;
|
||||
/**
|
||||
* Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.
|
||||
* Initiates the request. The body argument provides the request body, if any,
|
||||
* and is ignored if the request method is GET or HEAD.
|
||||
* Throws an "InvalidStateError" DOMException if either state is not opened or the send() flag is set.
|
||||
*/
|
||||
send(body?: BodyInit | null): void;
|
||||
@@ -4259,7 +4393,7 @@ type NotificationDirection = "auto" | "ltr" | "rtl";
|
||||
type NotificationPermission = "default" | "denied" | "granted";
|
||||
type PushEncryptionKeyName = "p256dh" | "auth";
|
||||
type PushPermissionState = "denied" | "granted" | "prompt";
|
||||
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url";
|
||||
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
|
||||
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached";
|
||||
type RequestCredentials = "omit" | "same-origin" | "include";
|
||||
type RequestDestination = "" | "audio" | "audioworklet" | "document" | "embed" | "font" | "image" | "manifest" | "object" | "paintworklet" | "report" | "script" | "sharedworker" | "style" | "track" | "video" | "worker" | "xslt";
|
||||
|
||||
@@ -2083,7 +2083,7 @@
|
||||
<Str Cat="Text">
|
||||
<Val><![CDATA[Cannot find the common subdirectory path for the input files.]]></Val>
|
||||
<Tgt Cat="Text" Stat="Loc" Orig="New">
|
||||
<Val><![CDATA[找不到輸入檔案的一般子目錄路徑。]]></Val>
|
||||
<Val><![CDATA[找不到輸入檔的一般子目錄路徑。]]></Val>
|
||||
</Tgt>
|
||||
</Str>
|
||||
<Disp Icon="Str" />
|
||||
@@ -7567,7 +7567,7 @@
|
||||
<Str Cat="Text">
|
||||
<Val><![CDATA[Specify the root directory of input files. Use to control the output directory structure with --outDir.]]></Val>
|
||||
<Tgt Cat="Text" Stat="Loc" Orig="New">
|
||||
<Val><![CDATA[指定輸入檔案的根目錄。用以控制具有 --outDir 的輸出目錄結構。]]></Val>
|
||||
<Val><![CDATA[指定輸入檔的根目錄。用以控制具有 --outDir 的輸出目錄結構。]]></Val>
|
||||
</Tgt>
|
||||
</Str>
|
||||
<Disp Icon="Str" />
|
||||
@@ -9172,7 +9172,7 @@
|
||||
<Str Cat="Text">
|
||||
<Val><![CDATA[Watch input files.]]></Val>
|
||||
<Tgt Cat="Text" Stat="Loc" Orig="New">
|
||||
<Val><![CDATA[監看輸入檔案。]]></Val>
|
||||
<Val><![CDATA[監看輸入檔。]]></Val>
|
||||
</Tgt>
|
||||
</Str>
|
||||
<Disp Icon="Str" />
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+117
-87
@@ -7,7 +7,6 @@ namespace ts.server {
|
||||
export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
|
||||
export const ProjectLoadingStartEvent = "projectLoadingStart";
|
||||
export const ProjectLoadingFinishEvent = "projectLoadingFinish";
|
||||
export const SurveyReady = "surveyReady";
|
||||
export const LargeFileReferencedEvent = "largeFileReferenced";
|
||||
export const ConfigFileDiagEvent = "configFileDiag";
|
||||
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
|
||||
@@ -30,11 +29,6 @@ namespace ts.server {
|
||||
data: { project: Project; };
|
||||
}
|
||||
|
||||
export interface SurveyReady {
|
||||
eventName: typeof SurveyReady;
|
||||
data: { surveyId: string; };
|
||||
}
|
||||
|
||||
export interface LargeFileReferencedEvent {
|
||||
eventName: typeof LargeFileReferencedEvent;
|
||||
data: { file: string; fileSize: number; maxFileSize: number; };
|
||||
@@ -146,7 +140,6 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
export type ProjectServiceEvent = LargeFileReferencedEvent |
|
||||
SurveyReady |
|
||||
ProjectsUpdatedInBackgroundEvent |
|
||||
ProjectLoadingStartEvent |
|
||||
ProjectLoadingFinishEvent |
|
||||
@@ -332,19 +325,6 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum WatchType {
|
||||
ConfigFilePath = "Config file for the program",
|
||||
MissingFilePath = "Missing file from program",
|
||||
WildcardDirectories = "Wild card directory",
|
||||
ClosedScriptInfo = "Closed Script info",
|
||||
ConfigFileForInferredRoot = "Config file for the inferred project root",
|
||||
FailedLookupLocation = "Directory of Failed lookup locations in module resolution",
|
||||
TypeRoots = "Type root directory",
|
||||
NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them",
|
||||
MissingSourceMapFile = "Missing source map file"
|
||||
}
|
||||
|
||||
const enum ConfigFileWatcherStatus {
|
||||
ReloadingFiles = "Reloading configured projects for files",
|
||||
ReloadingInferredRootFiles = "Reloading configured projects for only inferred root files",
|
||||
@@ -355,6 +335,7 @@ namespace ts.server {
|
||||
RootOfInferredProjectFalse = "Open file was set as not inferred root",
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
interface ConfigFileExistenceInfo {
|
||||
/**
|
||||
* Cached value of existence of config file
|
||||
@@ -427,6 +408,21 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface OpenFileArguments {
|
||||
fileName: string;
|
||||
content?: string;
|
||||
scriptKind?: protocol.ScriptKindName | ScriptKind;
|
||||
hasMixedContent?: boolean;
|
||||
projectRootPath?: string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface ChangeFileArguments {
|
||||
fileName: string;
|
||||
changes: Iterator<TextChange>;
|
||||
}
|
||||
|
||||
export class ProjectService {
|
||||
|
||||
/*@internal*/
|
||||
@@ -531,9 +527,6 @@ namespace ts.server {
|
||||
/** Tracks projects that we have already sent telemetry for. */
|
||||
private readonly seenProjects = createMap<true>();
|
||||
|
||||
/** Tracks projects that we have already sent survey events for. */
|
||||
private readonly seenSurveyProjects = createMap<true>();
|
||||
|
||||
/*@internal*/
|
||||
readonly watchFactory: WatchFactory<WatchType, Project>;
|
||||
|
||||
@@ -735,14 +728,6 @@ namespace ts.server {
|
||||
this.eventHandler(event);
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
sendSurveyReadyEvent(surveyId: string) {
|
||||
if (!this.eventHandler) {
|
||||
return;
|
||||
}
|
||||
this.eventHandler({ eventName: SurveyReady, data: { surveyId } });
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
sendLargeFileReferencedEvent(file: string, fileSize: number) {
|
||||
if (!this.eventHandler) {
|
||||
@@ -917,7 +902,7 @@ namespace ts.server {
|
||||
|
||||
getPreferences(file: NormalizedPath): protocol.UserPreferences {
|
||||
const info = this.getScriptInfoForNormalizedPath(file);
|
||||
return info && info.getPreferences() || this.hostConfiguration.preferences;
|
||||
return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() };
|
||||
}
|
||||
|
||||
getHostFormatCodeOptions(): FormatCodeSettings {
|
||||
@@ -1018,7 +1003,7 @@ namespace ts.server {
|
||||
fileOrDirectory => {
|
||||
const fileOrDirectoryPath = this.toPath(fileOrDirectory);
|
||||
project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
|
||||
if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return;
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return;
|
||||
const configFilename = project.getConfigFilePath();
|
||||
|
||||
// If the the added or created file or directory is not supported file name, ignore the file
|
||||
@@ -1035,7 +1020,7 @@ namespace ts.server {
|
||||
}
|
||||
},
|
||||
flags,
|
||||
WatchType.WildcardDirectories,
|
||||
WatchType.WildcardDirectory,
|
||||
project
|
||||
);
|
||||
}
|
||||
@@ -1159,11 +1144,22 @@ namespace ts.server {
|
||||
return project;
|
||||
}
|
||||
|
||||
private assignOrphanScriptInfosToInferredProject() {
|
||||
// collect orphaned files and assign them to inferred project just like we treat open of a file
|
||||
this.openFiles.forEach((projectRootPath, path) => {
|
||||
const info = this.getScriptInfoForPath(path as Path)!;
|
||||
// collect all orphaned script infos from open files
|
||||
if (info.isOrphan()) {
|
||||
this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove this file from the set of open, non-configured files.
|
||||
* @param info The file that has been closed or newly configured
|
||||
*/
|
||||
private closeOpenFile(info: ScriptInfo): void {
|
||||
private closeOpenFile(info: ScriptInfo, skipAssignOrphanScriptInfosToInferredProject?: true) {
|
||||
// Closing file should trigger re-reading the file content from disk. This is
|
||||
// because the user may chose to discard the buffer content before saving
|
||||
// to the disk, and the server's version of the file can be out of sync.
|
||||
@@ -1207,15 +1203,8 @@ namespace ts.server {
|
||||
|
||||
this.openFiles.delete(info.path);
|
||||
|
||||
if (ensureProjectsForOpenFiles) {
|
||||
// collect orphaned files and assign them to inferred project just like we treat open of a file
|
||||
this.openFiles.forEach((projectRootPath, path) => {
|
||||
const info = this.getScriptInfoForPath(path as Path)!;
|
||||
// collect all orphaned script infos from open files
|
||||
if (info.isOrphan()) {
|
||||
this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
|
||||
}
|
||||
});
|
||||
if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
|
||||
this.assignOrphanScriptInfosToInferredProject();
|
||||
}
|
||||
|
||||
// Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project)
|
||||
@@ -1230,6 +1219,8 @@ namespace ts.server {
|
||||
else {
|
||||
this.handleDeletedFile(info);
|
||||
}
|
||||
|
||||
return ensureProjectsForOpenFiles;
|
||||
}
|
||||
|
||||
private deleteScriptInfo(info: ScriptInfo) {
|
||||
@@ -1277,7 +1268,8 @@ namespace ts.server {
|
||||
private setConfigFileExistenceByNewConfiguredProject(project: ConfiguredProject) {
|
||||
const configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
|
||||
if (configFileExistenceInfo) {
|
||||
Debug.assert(configFileExistenceInfo.exists);
|
||||
// The existance might not be set if the file watcher is not invoked by the time config project is created by external project
|
||||
configFileExistenceInfo.exists = true;
|
||||
// close existing watcher
|
||||
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
|
||||
const configFileName = project.getConfigFilePath();
|
||||
@@ -1338,7 +1330,7 @@ namespace ts.server {
|
||||
watches.push(WatchType.ConfigFileForInferredRoot);
|
||||
}
|
||||
if (this.configuredProjects.has(canonicalConfigFilePath)) {
|
||||
watches.push(WatchType.ConfigFilePath);
|
||||
watches.push(WatchType.ConfigFile);
|
||||
}
|
||||
this.logger.info(`ConfigFilePresence:: Current Watches: ${watches}:: File: ${configFileName} Currently impacted open files: RootsOfInferredProjects: ${inferredRoots} OtherOpenFiles: ${otherFiles} Status: ${status}`);
|
||||
}
|
||||
@@ -1623,20 +1615,6 @@ namespace ts.server {
|
||||
return project;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
sendSurveyReady(project: ExternalProject | ConfiguredProject): void {
|
||||
if (this.seenSurveyProjects.has(project.projectName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (project.getCompilerOptions().checkJs !== undefined) {
|
||||
const name = "checkJs";
|
||||
this.logger.info(`Survey ${name} is ready`);
|
||||
this.sendSurveyReadyEvent(name);
|
||||
this.seenSurveyProjects.set(project.projectName, true);
|
||||
}
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
sendProjectTelemetry(project: ExternalProject | ConfiguredProject): void {
|
||||
if (this.seenProjects.has(project.projectName)) {
|
||||
@@ -1705,7 +1683,7 @@ namespace ts.server {
|
||||
configFileName,
|
||||
(_fileName, eventKind) => this.onConfigChangedForConfiguredProject(project, eventKind),
|
||||
PollingInterval.High,
|
||||
WatchType.ConfigFilePath,
|
||||
WatchType.ConfigFile,
|
||||
project
|
||||
);
|
||||
this.configuredProjects.set(project.canonicalConfigFilePath, project);
|
||||
@@ -2007,7 +1985,7 @@ namespace ts.server {
|
||||
const path = toNormalizedPath(uncheckedFileName);
|
||||
const info = this.getScriptInfoForNormalizedPath(path);
|
||||
if (info) return info;
|
||||
const configProject = this.configuredProjects.get(uncheckedFileName);
|
||||
const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
|
||||
return configProject && configProject.getCompilerOptions().configFile;
|
||||
}
|
||||
|
||||
@@ -2094,7 +2072,7 @@ namespace ts.server {
|
||||
watchDir,
|
||||
(fileOrDirectory) => {
|
||||
const fileOrDirectoryPath = this.toPath(fileOrDirectory);
|
||||
if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) return;
|
||||
if (isPathIgnored(fileOrDirectoryPath)) return;
|
||||
|
||||
// Has extension
|
||||
Debug.assert(result.refCount > 0);
|
||||
@@ -2614,20 +2592,22 @@ namespace ts.server {
|
||||
});
|
||||
}
|
||||
|
||||
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult {
|
||||
private getOrCreateOpenScriptInfo(fileName: NormalizedPath, fileContent: string | undefined, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined, projectRootPath: NormalizedPath | undefined) {
|
||||
const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent)!; // TODO: GH#18217
|
||||
this.openFiles.set(info.path, projectRootPath);
|
||||
return info;
|
||||
}
|
||||
|
||||
private assignProjectToOpenedScriptInfo(info: ScriptInfo): OpenConfiguredProjectResult {
|
||||
let configFileName: NormalizedPath | undefined;
|
||||
let configFileErrors: ReadonlyArray<Diagnostic> | undefined;
|
||||
|
||||
const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent)!; // TODO: GH#18217
|
||||
|
||||
this.openFiles.set(info.path, projectRootPath);
|
||||
let project: ConfiguredProject | ExternalProject | undefined = this.findExternalProjectContainingOpenScriptInfo(info);
|
||||
if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
|
||||
configFileName = this.getConfigFileNameForFile(info);
|
||||
if (configFileName) {
|
||||
project = this.findConfiguredProjectByProjectName(configFileName);
|
||||
if (!project) {
|
||||
project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${fileName} to open`);
|
||||
project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${info.fileName} to open`);
|
||||
// Send the event only if the project got created as part of this open request and info is part of the project
|
||||
if (info.isOrphan()) {
|
||||
// Since the file isnt part of configured project, do not send config file info
|
||||
@@ -2635,7 +2615,7 @@ namespace ts.server {
|
||||
}
|
||||
else {
|
||||
configFileErrors = project.getAllProjectErrors();
|
||||
this.sendConfigFileDiagEvent(project, fileName);
|
||||
this.sendConfigFileDiagEvent(project, info.fileName);
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -2657,10 +2637,14 @@ namespace ts.server {
|
||||
// At this point if file is part of any any configured or external project, then it would be present in the containing projects
|
||||
// So if it still doesnt have any containing projects, it needs to be part of inferred project
|
||||
if (info.isOrphan()) {
|
||||
this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
|
||||
Debug.assert(this.openFiles.has(info.path));
|
||||
this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
|
||||
}
|
||||
Debug.assert(!info.isOrphan());
|
||||
return { configFileName, configFileErrors };
|
||||
}
|
||||
|
||||
private cleanupAfterOpeningFile() {
|
||||
// This was postponed from closeOpenFile to after opening next file,
|
||||
// so that we can reuse the project if we need to right away
|
||||
this.removeOrphanConfiguredProjects();
|
||||
@@ -2680,9 +2664,14 @@ namespace ts.server {
|
||||
this.removeOrphanScriptInfos();
|
||||
|
||||
this.printProjects();
|
||||
}
|
||||
|
||||
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult {
|
||||
const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
|
||||
const result = this.assignProjectToOpenedScriptInfo(info);
|
||||
this.cleanupAfterOpeningFile();
|
||||
this.telemetryOnOpenFile(info);
|
||||
return { configFileName, configFileErrors };
|
||||
return result;
|
||||
}
|
||||
|
||||
private removeOrphanConfiguredProjects() {
|
||||
@@ -2776,7 +2765,12 @@ namespace ts.server {
|
||||
return;
|
||||
}
|
||||
|
||||
const info: OpenFileInfo = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path)!.checkJsDirective };
|
||||
const project = scriptInfo.getDefaultProject();
|
||||
if (!project.languageServiceEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const info: OpenFileInfo = { checkJs: !!project.getSourceFile(scriptInfo.path)!.checkJsDirective };
|
||||
this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info } });
|
||||
}
|
||||
|
||||
@@ -2784,12 +2778,16 @@ namespace ts.server {
|
||||
* Close file whose contents is managed by the client
|
||||
* @param filename is absolute pathname
|
||||
*/
|
||||
closeClientFile(uncheckedFileName: string) {
|
||||
closeClientFile(uncheckedFileName: string): void;
|
||||
/*@internal*/
|
||||
closeClientFile(uncheckedFileName: string, skipAssignOrphanScriptInfosToInferredProject: true): boolean;
|
||||
closeClientFile(uncheckedFileName: string, skipAssignOrphanScriptInfosToInferredProject?: true) {
|
||||
const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName));
|
||||
if (info) {
|
||||
this.closeOpenFile(info);
|
||||
const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
|
||||
if (!skipAssignOrphanScriptInfosToInferredProject) {
|
||||
this.printProjects();
|
||||
}
|
||||
this.printProjects();
|
||||
return result;
|
||||
}
|
||||
|
||||
private collectChanges(lastKnownProjectVersions: protocol.ProjectVersionInfo[], currentProjects: Project[], result: ProjectFilesWithTSDiagnostics[]): void {
|
||||
@@ -2809,36 +2807,68 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
applyChangesInOpenFiles(openFiles: protocol.ExternalFile[] | undefined, changedFiles: protocol.ChangedOpenFile[] | undefined, closedFiles: string[] | undefined): void {
|
||||
applyChangesInOpenFiles(openFiles: Iterator<OpenFileArguments> | undefined, changedFiles?: Iterator<ChangeFileArguments>, closedFiles?: string[]): void {
|
||||
let openScriptInfos: ScriptInfo[] | undefined;
|
||||
let assignOrphanScriptInfosToInferredProject = false;
|
||||
if (openFiles) {
|
||||
for (const file of openFiles) {
|
||||
while (true) {
|
||||
const { value: file, done } = openFiles.next();
|
||||
if (done) break;
|
||||
const scriptInfo = this.getScriptInfo(file.fileName);
|
||||
Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already");
|
||||
const normalizedPath = scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName);
|
||||
this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind!), file.hasMixedContent); // TODO: GH#18217
|
||||
// Create script infos so we have the new content for all the open files before we do any updates to projects
|
||||
const info = this.getOrCreateOpenScriptInfo(
|
||||
scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName),
|
||||
file.content,
|
||||
tryConvertScriptKindName(file.scriptKind!),
|
||||
file.hasMixedContent,
|
||||
file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined
|
||||
);
|
||||
(openScriptInfos || (openScriptInfos = [])).push(info);
|
||||
}
|
||||
}
|
||||
|
||||
if (changedFiles) {
|
||||
for (const file of changedFiles) {
|
||||
while (true) {
|
||||
const { value: file, done } = changedFiles.next();
|
||||
if (done) break;
|
||||
const scriptInfo = this.getScriptInfo(file.fileName)!;
|
||||
Debug.assert(!!scriptInfo);
|
||||
// Make edits to script infos and marks containing project as dirty
|
||||
this.applyChangesToFile(scriptInfo, file.changes);
|
||||
}
|
||||
}
|
||||
|
||||
if (closedFiles) {
|
||||
for (const file of closedFiles) {
|
||||
this.closeClientFile(file);
|
||||
// Close files, but dont assign projects to orphan open script infos, that part comes later
|
||||
assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
|
||||
}
|
||||
}
|
||||
|
||||
// All the script infos now exist, so ok to go update projects for open files
|
||||
if (openScriptInfos) {
|
||||
openScriptInfos.forEach(info => this.assignProjectToOpenedScriptInfo(info));
|
||||
}
|
||||
|
||||
// While closing files there could be open files that needed assigning new inferred projects, do it now
|
||||
if (assignOrphanScriptInfosToInferredProject) {
|
||||
this.assignOrphanScriptInfosToInferredProject();
|
||||
}
|
||||
|
||||
// Cleanup projects
|
||||
this.cleanupAfterOpeningFile();
|
||||
|
||||
// Telemetry
|
||||
forEach(openScriptInfos, info => this.telemetryOnOpenFile(info));
|
||||
this.printProjects();
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
applyChangesToFile(scriptInfo: ScriptInfo, changes: TextChange[]) {
|
||||
// apply changes in reverse order
|
||||
for (let i = changes.length - 1; i >= 0; i--) {
|
||||
const change = changes[i];
|
||||
applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterator<TextChange>) {
|
||||
while (true) {
|
||||
const { value: change, done } = changes.next();
|
||||
if (done) break;
|
||||
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ namespace ts.server {
|
||||
|
||||
/*@internal*/
|
||||
constructor(
|
||||
readonly projectName: string,
|
||||
/*@internal*/ readonly projectName: string,
|
||||
readonly projectKind: ProjectKind,
|
||||
readonly projectService: ProjectService,
|
||||
private documentRegistry: DocumentRegistry,
|
||||
@@ -428,7 +428,7 @@ namespace ts.server {
|
||||
directory,
|
||||
cb,
|
||||
flags,
|
||||
WatchType.FailedLookupLocation,
|
||||
WatchType.FailedLookupLocations,
|
||||
this
|
||||
);
|
||||
}
|
||||
@@ -989,7 +989,7 @@ namespace ts.server {
|
||||
}
|
||||
},
|
||||
PollingInterval.Medium,
|
||||
WatchType.MissingFilePath,
|
||||
WatchType.MissingFile,
|
||||
this
|
||||
);
|
||||
return fileWatcher;
|
||||
@@ -1431,7 +1431,6 @@ namespace ts.server {
|
||||
}
|
||||
this.projectService.sendProjectLoadingFinishEvent(this);
|
||||
this.projectService.sendProjectTelemetry(this);
|
||||
this.projectService.sendSurveyReady(this);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1627,7 +1626,6 @@ namespace ts.server {
|
||||
updateGraph() {
|
||||
const result = super.updateGraph();
|
||||
this.projectService.sendProjectTelemetry(this);
|
||||
this.projectService.sendSurveyReady(this);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
+30
-1
@@ -92,6 +92,7 @@ namespace ts.server.protocol {
|
||||
SynchronizeProjectList = "synchronizeProjectList",
|
||||
/* @internal */
|
||||
ApplyChangedToOpenFiles = "applyChangedToOpenFiles",
|
||||
UpdateOpen = "updateOpen",
|
||||
/* @internal */
|
||||
EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full",
|
||||
/* @internal */
|
||||
@@ -1543,6 +1544,32 @@ namespace ts.server.protocol {
|
||||
closedFiles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Request to synchronize list of open files with the client
|
||||
*/
|
||||
export interface UpdateOpenRequest extends Request {
|
||||
command: CommandTypes.UpdateOpen;
|
||||
arguments: UpdateOpenRequestArgs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Arguments to UpdateOpenRequest
|
||||
*/
|
||||
export interface UpdateOpenRequestArgs {
|
||||
/**
|
||||
* List of newly open files
|
||||
*/
|
||||
openFiles?: OpenRequestArgs[];
|
||||
/**
|
||||
* List of open files files that were changes
|
||||
*/
|
||||
changedFiles?: FileCodeEdits[];
|
||||
/**
|
||||
* List of files that were closed
|
||||
*/
|
||||
closedFiles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Request to set compiler options for inferred projects.
|
||||
* External projects are opened / closed explicitly.
|
||||
@@ -2891,7 +2918,7 @@ namespace ts.server.protocol {
|
||||
|
||||
export interface UserPreferences {
|
||||
readonly disableSuggestions?: boolean;
|
||||
readonly quotePreference?: "double" | "single";
|
||||
readonly quotePreference?: "auto" | "double" | "single";
|
||||
/**
|
||||
* If enabled, TypeScript will search through all external modules' exports and add them to the completions list.
|
||||
* This affects lone identifier completions but not completions on the right hand side of `obj.`.
|
||||
@@ -2905,6 +2932,8 @@ namespace ts.server.protocol {
|
||||
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
|
||||
readonly allowTextChangesInNewFiles?: boolean;
|
||||
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
readonly allowRenameOfImportPath?: boolean;
|
||||
}
|
||||
|
||||
export interface CompilerOptions {
|
||||
|
||||
+64
-20
@@ -314,7 +314,8 @@ namespace ts.server {
|
||||
defaultProject: Project,
|
||||
initialLocation: DocumentPosition,
|
||||
findInStrings: boolean,
|
||||
findInComments: boolean
|
||||
findInComments: boolean,
|
||||
hostPreferences: UserPreferences
|
||||
): ReadonlyArray<RenameLocation> {
|
||||
const outputs: RenameLocation[] = [];
|
||||
|
||||
@@ -323,7 +324,7 @@ namespace ts.server {
|
||||
defaultProject,
|
||||
initialLocation,
|
||||
({ project, location }, tryAddToTodo) => {
|
||||
for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || emptyArray) {
|
||||
for (const output of project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || emptyArray) {
|
||||
if (!contains(outputs, output, documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) {
|
||||
outputs.push(output);
|
||||
}
|
||||
@@ -609,10 +610,6 @@ namespace ts.server {
|
||||
diagnostics: bakedDiags
|
||||
}, ConfigFileDiagEvent);
|
||||
break;
|
||||
case SurveyReady:
|
||||
const { surveyId } = event.data;
|
||||
this.event<protocol.SurveyReadyEventBody>({ surveyId }, SurveyReady);
|
||||
break;
|
||||
case ProjectLanguageServiceStateEvent: {
|
||||
const eventName: protocol.ProjectLanguageServiceStateEventName = ProjectLanguageServiceStateEvent;
|
||||
this.event<protocol.ProjectLanguageServiceStateEventBody>({
|
||||
@@ -662,16 +659,32 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
if (fileRequest && this.logger.hasLevel(LogLevel.verbose)) {
|
||||
try {
|
||||
const { file, project } = this.getFileAndProject(fileRequest);
|
||||
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
|
||||
if (scriptInfo) {
|
||||
const text = getSnapshotText(scriptInfo.getSnapshot());
|
||||
msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`;
|
||||
if (this.logger.hasLevel(LogLevel.verbose)) {
|
||||
if (fileRequest) {
|
||||
try {
|
||||
const { file, project } = this.getFileAndProject(fileRequest);
|
||||
const scriptInfo = project.getScriptInfoForNormalizedPath(file);
|
||||
if (scriptInfo) {
|
||||
const text = getSnapshotText(scriptInfo.getSnapshot());
|
||||
msg += `\n\nFile text of ${fileRequest.file}:${indent(text)}\n`;
|
||||
}
|
||||
}
|
||||
catch { } // tslint:disable-line no-empty
|
||||
}
|
||||
|
||||
if (err.message && err.message.indexOf(`Could not find sourceFile:`) !== -1) {
|
||||
msg += `\n\nProjects::\n`;
|
||||
let counter = 0;
|
||||
const addProjectInfo = (project: Project) => {
|
||||
msg += `\nProject '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter}\n`;
|
||||
msg += project.filesToString(/*writeProjectFileNames*/ true);
|
||||
msg += "\n-----------------------------------------------\n";
|
||||
counter++;
|
||||
};
|
||||
this.projectService.externalProjects.forEach(addProjectInfo);
|
||||
this.projectService.configuredProjects.forEach(addProjectInfo);
|
||||
this.projectService.inferredProjects.forEach(addProjectInfo);
|
||||
}
|
||||
catch {} // tslint:disable-line no-empty
|
||||
}
|
||||
|
||||
this.logger.msg(msg, Msg.Err);
|
||||
@@ -1177,7 +1190,7 @@ namespace ts.server {
|
||||
private getRenameInfo(args: protocol.FileLocationRequestArgs): RenameInfo {
|
||||
const { file, project } = this.getFileAndProject(args);
|
||||
const position = this.getPositionInFile(args, file);
|
||||
return project.getLanguageService().getRenameInfo(file, position);
|
||||
return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath });
|
||||
}
|
||||
|
||||
private getProjects(args: protocol.FileRequestArgs, getScriptInfoEnsuringProjectsUptoDate?: boolean, ignoreNoProjectError?: boolean): Projects {
|
||||
@@ -1231,12 +1244,13 @@ namespace ts.server {
|
||||
this.getDefaultProject(args),
|
||||
{ fileName: args.file, pos: position },
|
||||
!!args.findInStrings,
|
||||
!!args.findInComments
|
||||
!!args.findInComments,
|
||||
this.getPreferences(file)
|
||||
);
|
||||
if (!simplifiedResult) return locations;
|
||||
|
||||
const defaultProject = this.getDefaultProject(args);
|
||||
const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), Debug.assertDefined(this.projectService.getScriptInfo(file)));
|
||||
const renameInfo: protocol.RenameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getPreferences(file).allowRenameOfImportPath }), Debug.assertDefined(this.projectService.getScriptInfo(file)));
|
||||
return { info: renameInfo, locs: this.toSpanGroups(locations) };
|
||||
}
|
||||
|
||||
@@ -1656,10 +1670,10 @@ namespace ts.server {
|
||||
const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
|
||||
if (start >= 0) {
|
||||
this.changeSeq++;
|
||||
this.projectService.applyChangesToFile(scriptInfo, [{
|
||||
this.projectService.applyChangesToFile(scriptInfo, singleIterator({
|
||||
span: { start, length: end - start },
|
||||
newText: args.insertString! // TODO: GH#18217
|
||||
}]);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2098,9 +2112,39 @@ namespace ts.server {
|
||||
});
|
||||
return this.requiredResponse(converted);
|
||||
},
|
||||
[CommandNames.UpdateOpen]: (request: protocol.UpdateOpenRequest) => {
|
||||
this.changeSeq++;
|
||||
this.projectService.applyChangesInOpenFiles(
|
||||
request.arguments.openFiles && mapIterator(arrayIterator(request.arguments.openFiles), file => ({
|
||||
fileName: file.file,
|
||||
content: file.fileContent,
|
||||
scriptKind: file.scriptKindName,
|
||||
projectRootPath: file.projectRootPath
|
||||
})),
|
||||
request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({
|
||||
fileName: file.fileName,
|
||||
changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), change => {
|
||||
const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(file.fileName));
|
||||
const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
|
||||
const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
|
||||
return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : undefined;
|
||||
})
|
||||
})),
|
||||
request.arguments.closedFiles
|
||||
);
|
||||
return this.requiredResponse(/*response*/ true);
|
||||
},
|
||||
[CommandNames.ApplyChangedToOpenFiles]: (request: protocol.ApplyChangedToOpenFilesRequest) => {
|
||||
this.changeSeq++;
|
||||
this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles!, request.arguments.closedFiles!); // TODO: GH#18217
|
||||
this.projectService.applyChangesInOpenFiles(
|
||||
request.arguments.openFiles && arrayIterator(request.arguments.openFiles),
|
||||
request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({
|
||||
fileName: file.fileName,
|
||||
// apply changes in reverse order
|
||||
changes: arrayReverseIterator(file.changes)
|
||||
})),
|
||||
request.arguments.closedFiles
|
||||
);
|
||||
// TODO: report errors
|
||||
return this.requiredResponse(/*response*/ true);
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"extends": "../tsconfig-base",
|
||||
"compilerOptions": {
|
||||
"removeComments": true,
|
||||
"removeComments": false,
|
||||
"outFile": "../../built/local/server.js",
|
||||
"preserveConstEnums": true,
|
||||
"types": [
|
||||
|
||||
@@ -217,3 +217,14 @@ namespace ts.server {
|
||||
return indentStr + JSON.stringify(json);
|
||||
}
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
// Additional tsserver specific watch information
|
||||
export const enum WatchType {
|
||||
ClosedScriptInfo = "Closed Script info",
|
||||
ConfigFileForInferredRoot = "Config file for the inferred project root",
|
||||
NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them",
|
||||
MissingSourceMapFile = "Missing source map file",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ namespace ts.codefix {
|
||||
precedingNode = ctorDeclaration.parent.parent;
|
||||
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration as VariableDeclaration);
|
||||
if ((<VariableDeclarationList>ctorDeclaration.parent).declarations.length === 1) {
|
||||
copyComments(precedingNode, newClassDeclaration!, sourceFile); // TODO: GH#18217
|
||||
copyLeadingComments(precedingNode, newClassDeclaration!, sourceFile); // TODO: GH#18217
|
||||
changes.delete(sourceFile, precedingNode);
|
||||
}
|
||||
else {
|
||||
@@ -48,7 +48,7 @@ namespace ts.codefix {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
|
||||
copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
|
||||
|
||||
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
|
||||
changes.insertNodeAfter(sourceFile, precedingNode!, newClassDeclaration);
|
||||
@@ -112,7 +112,7 @@ namespace ts.codefix {
|
||||
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword));
|
||||
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
|
||||
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
|
||||
copyComments(assignmentBinaryExpression, method, sourceFile);
|
||||
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
|
||||
return method;
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ namespace ts.codefix {
|
||||
const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword));
|
||||
const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
|
||||
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
|
||||
copyComments(assignmentBinaryExpression, method, sourceFile);
|
||||
copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
|
||||
return method;
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ namespace ts.codefix {
|
||||
}
|
||||
const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
|
||||
/*type*/ undefined, assignmentBinaryExpression.right);
|
||||
copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
|
||||
copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
|
||||
return prop;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,7 +275,7 @@ namespace ts.codefix {
|
||||
inJs: boolean,
|
||||
preferences: UserPreferences,
|
||||
): void {
|
||||
const methodDeclaration = createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !isInterfaceDeclaration(typeDecl));
|
||||
const methodDeclaration = createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl);
|
||||
const containingMethodDeclaration = getAncestor(callExpression, SyntaxKind.MethodDeclaration);
|
||||
|
||||
if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) {
|
||||
|
||||
@@ -74,7 +74,7 @@ namespace ts.codefix {
|
||||
const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
|
||||
if (!tsconfigObjectLiteral) return undefined;
|
||||
|
||||
const compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions");
|
||||
const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
|
||||
if (!compilerOptionsProperty) {
|
||||
const newCompilerOptions = createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]);
|
||||
changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions));
|
||||
@@ -94,7 +94,7 @@ namespace ts.codefix {
|
||||
return createJsonPropertyAssignment("baseUrl", createStringLiteral(defaultBaseUrl));
|
||||
}
|
||||
function getOrAddBaseUrl(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression): string {
|
||||
const baseUrlProp = findProperty(compilerOptions, "baseUrl");
|
||||
const baseUrlProp = findJsonProperty(compilerOptions, "baseUrl");
|
||||
if (baseUrlProp) {
|
||||
return isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl;
|
||||
}
|
||||
@@ -112,7 +112,7 @@ namespace ts.codefix {
|
||||
return createJsonPropertyAssignment("paths", createObjectLiteral([makeDefaultPathMapping()]));
|
||||
}
|
||||
function getOrAddPathMapping(changes: textChanges.ChangeTracker, tsconfig: TsConfigSourceFile, compilerOptions: ObjectLiteralExpression) {
|
||||
const paths = findProperty(compilerOptions, "paths");
|
||||
const paths = findJsonProperty(compilerOptions, "paths");
|
||||
if (!paths || !isObjectLiteralExpression(paths.initializer)) {
|
||||
changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths());
|
||||
return defaultTypesDirectoryName;
|
||||
@@ -129,14 +129,6 @@ namespace ts.codefix {
|
||||
return defaultTypesDirectoryName;
|
||||
}
|
||||
|
||||
function createJsonPropertyAssignment(name: string, initializer: Expression) {
|
||||
return createPropertyAssignment(createStringLiteral(name), initializer);
|
||||
}
|
||||
|
||||
function findProperty(obj: ObjectLiteralExpression, name: string): PropertyAssignment | undefined {
|
||||
return find(obj.properties, (p): p is PropertyAssignment => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name);
|
||||
}
|
||||
|
||||
function getInstallCommand(fileName: string, packageName: string): InstallPackageAction {
|
||||
return { type: "install package", file: fileName, packageName };
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ namespace ts.codefix {
|
||||
registerCodeFix({
|
||||
errorCodes,
|
||||
getCodeActions(context) {
|
||||
const { program, sourceFile, span } = context;
|
||||
const { sourceFile, span } = context;
|
||||
const changes = textChanges.ChangeTracker.with(context, t =>
|
||||
addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences));
|
||||
addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences));
|
||||
return changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, Diagnostics.Implement_inherited_abstract_class, fixId, Diagnostics.Implement_all_inherited_abstract_classes)];
|
||||
},
|
||||
fixIds: [fixId],
|
||||
@@ -19,7 +19,7 @@ namespace ts.codefix {
|
||||
return codeFixAll(context, errorCodes, (changes, diag) => {
|
||||
const classDeclaration = getClass(diag.file, diag.start);
|
||||
if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
|
||||
addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences);
|
||||
addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -32,15 +32,16 @@ namespace ts.codefix {
|
||||
return cast(token.parent, isClassLike);
|
||||
}
|
||||
|
||||
function addMissingMembers(classDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, checker: TypeChecker, changeTracker: textChanges.ChangeTracker, preferences: UserPreferences): void {
|
||||
function addMissingMembers(classDeclaration: ClassLikeDeclaration, sourceFile: SourceFile, context: TypeConstructionContext, changeTracker: textChanges.ChangeTracker, preferences: UserPreferences): void {
|
||||
const extendsNode = getEffectiveBaseTypeNode(classDeclaration)!;
|
||||
const checker = context.program.getTypeChecker();
|
||||
const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode);
|
||||
|
||||
// Note that this is ultimately derived from a map indexed by symbol names,
|
||||
// so duplicates cannot occur.
|
||||
const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);
|
||||
|
||||
createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
|
||||
createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
|
||||
}
|
||||
|
||||
function symbolPointsToNonPrivateAndAbstractMember(symbol: Symbol): boolean {
|
||||
|
||||
@@ -6,11 +6,10 @@ namespace ts.codefix {
|
||||
registerCodeFix({
|
||||
errorCodes,
|
||||
getCodeActions(context) {
|
||||
const { program, sourceFile, span } = context;
|
||||
const { sourceFile, span } = context;
|
||||
const classDeclaration = getClass(sourceFile, span.start);
|
||||
const checker = program.getTypeChecker();
|
||||
return mapDefined<ExpressionWithTypeArguments, CodeFixAction>(getClassImplementsHeritageClauseElements(classDeclaration), implementedTypeNode => {
|
||||
const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences));
|
||||
const changes = textChanges.ChangeTracker.with(context, t => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences));
|
||||
return changes.length === 0 ? undefined : createCodeFixAction(fixId, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, Diagnostics.Implement_all_unimplemented_interfaces);
|
||||
});
|
||||
},
|
||||
@@ -21,7 +20,7 @@ namespace ts.codefix {
|
||||
const classDeclaration = getClass(diag.file, diag.start);
|
||||
if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) {
|
||||
for (const implementedTypeNode of getClassImplementsHeritageClauseElements(classDeclaration)!) {
|
||||
addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
|
||||
addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -37,13 +36,14 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
function addMissingDeclarations(
|
||||
checker: TypeChecker,
|
||||
context: TypeConstructionContext,
|
||||
implementedTypeNode: ExpressionWithTypeArguments,
|
||||
sourceFile: SourceFile,
|
||||
classDeclaration: ClassLikeDeclaration,
|
||||
changeTracker: textChanges.ChangeTracker,
|
||||
preferences: UserPreferences,
|
||||
): void {
|
||||
const checker = context.program.getTypeChecker();
|
||||
const maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker);
|
||||
// Note that this is ultimately derived from a map indexed by symbol names,
|
||||
// so duplicates cannot occur.
|
||||
@@ -60,12 +60,12 @@ namespace ts.codefix {
|
||||
createMissingIndexSignatureDeclaration(implementedType, IndexKind.String);
|
||||
}
|
||||
|
||||
createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
|
||||
createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
|
||||
|
||||
function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void {
|
||||
const indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
|
||||
if (indexInfoOfKind) {
|
||||
changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)!);
|
||||
changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context))!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/* @internal */
|
||||
namespace ts.codefix {
|
||||
const fixId = "enableExperimentalDecorators";
|
||||
const errorCodes = [
|
||||
Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning.code
|
||||
];
|
||||
registerCodeFix({
|
||||
errorCodes,
|
||||
getCodeActions: (context) => {
|
||||
const { configFile } = context.program.getCompilerOptions();
|
||||
if (configFile === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const changes = textChanges.ChangeTracker.with(context, changeTracker => makeChange(changeTracker, configFile));
|
||||
return [createCodeFixActionNoFixId(fixId, changes, Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)];
|
||||
},
|
||||
fixIds: [fixId],
|
||||
});
|
||||
|
||||
function makeChange(changeTracker: textChanges.ChangeTracker, configFile: TsConfigSourceFile) {
|
||||
setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", createTrue());
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ namespace ts {
|
||||
return textChanges.getNewFileText(toStatements(valueInfo, outputKind), ScriptKind.TS, formatSettings.newLineCharacter || "\n", formatting.getFormatContext(formatSettings));
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
const enum OutputKind { ExportEquals, NamedExport, NamespaceMember, Global }
|
||||
function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray<Statement> {
|
||||
return toStatements(info, OutputKind.NamespaceMember);
|
||||
|
||||
@@ -6,23 +6,48 @@ namespace ts.codefix {
|
||||
* @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
|
||||
* @returns Empty string iff there are no member insertions.
|
||||
*/
|
||||
export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray<Symbol>, checker: TypeChecker, preferences: UserPreferences, out: (node: ClassElement) => void): void {
|
||||
export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray<Symbol>, context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void): void {
|
||||
const classMembers = classDeclaration.symbol.members!;
|
||||
for (const symbol of possiblyMissingSymbols) {
|
||||
if (!classMembers.has(symbol.escapedName)) {
|
||||
addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out);
|
||||
addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getModuleSpecifierResolverHost(context: TypeConstructionContext): SymbolTracker["moduleResolverHost"] {
|
||||
return {
|
||||
directoryExists: context.host.directoryExists ? d => context.host.directoryExists!(d) : undefined,
|
||||
fileExists: context.host.fileExists ? f => context.host.fileExists!(f) : undefined,
|
||||
getCurrentDirectory: context.host.getCurrentDirectory ? () => context.host.getCurrentDirectory!() : undefined,
|
||||
readFile: context.host.readFile ? f => context.host.readFile!(f) : undefined,
|
||||
useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? () => context.host.useCaseSensitiveFileNames!() : undefined,
|
||||
getSourceFiles: () => context.program.getSourceFiles(),
|
||||
getCommonSourceDirectory: () => context.program.getCommonSourceDirectory(),
|
||||
};
|
||||
}
|
||||
|
||||
export function getNoopSymbolTrackerWithResolver(context: TypeConstructionContext): SymbolTracker {
|
||||
return {
|
||||
trackSymbol: noop,
|
||||
moduleResolverHost: getModuleSpecifierResolverHost(context),
|
||||
};
|
||||
}
|
||||
|
||||
export interface TypeConstructionContext {
|
||||
program: Program;
|
||||
host: ModuleSpecifierResolutionHost;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
|
||||
*/
|
||||
function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, checker: TypeChecker, preferences: UserPreferences, out: (node: Node) => void): void {
|
||||
function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, context: TypeConstructionContext, preferences: UserPreferences, out: (node: Node) => void): void {
|
||||
const declarations = symbol.getDeclarations();
|
||||
if (!(declarations && declarations.length)) {
|
||||
return undefined;
|
||||
}
|
||||
const checker = context.program.getTypeChecker();
|
||||
|
||||
const declaration = declarations[0];
|
||||
const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false) as PropertyName;
|
||||
@@ -36,7 +61,7 @@ namespace ts.codefix {
|
||||
case SyntaxKind.SetAccessor:
|
||||
case SyntaxKind.PropertySignature:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
const typeNode = checker.typeToTypeNode(type, enclosingDeclaration);
|
||||
const typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context));
|
||||
out(createProperty(
|
||||
/*decorators*/undefined,
|
||||
modifiers,
|
||||
@@ -83,13 +108,13 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
function outputMethod(signature: Signature, modifiers: NodeArray<Modifier> | undefined, name: PropertyName, body?: Block): void {
|
||||
const method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body);
|
||||
const method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body);
|
||||
if (method) out(method);
|
||||
}
|
||||
}
|
||||
|
||||
function signatureToMethodDeclaration(
|
||||
checker: TypeChecker,
|
||||
context: TypeConstructionContext,
|
||||
signature: Signature,
|
||||
enclosingDeclaration: ClassLikeDeclaration,
|
||||
modifiers: NodeArray<Modifier> | undefined,
|
||||
@@ -97,7 +122,8 @@ namespace ts.codefix {
|
||||
optional: boolean,
|
||||
body: Block | undefined,
|
||||
): MethodDeclaration | undefined {
|
||||
const signatureDeclaration = <MethodDeclaration>checker.signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.NoTruncation | NodeBuilderFlags.SuppressAnyReturnType);
|
||||
const program = context.program;
|
||||
const signatureDeclaration = <MethodDeclaration>program.getTypeChecker().signatureToSignatureDeclaration(signature, SyntaxKind.MethodDeclaration, enclosingDeclaration, NodeBuilderFlags.NoTruncation | NodeBuilderFlags.SuppressAnyReturnType, getNoopSymbolTrackerWithResolver(context));
|
||||
if (!signatureDeclaration) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -117,18 +143,20 @@ namespace ts.codefix {
|
||||
inJs: boolean,
|
||||
makeStatic: boolean,
|
||||
preferences: UserPreferences,
|
||||
body: boolean,
|
||||
contextNode: Node,
|
||||
): MethodDeclaration {
|
||||
const body = !isInterfaceDeclaration(contextNode);
|
||||
const { typeArguments, arguments: args, parent } = call;
|
||||
const checker = context.program.getTypeChecker();
|
||||
const tracker = getNoopSymbolTrackerWithResolver(context);
|
||||
const types = map(args, arg =>
|
||||
// Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {"
|
||||
checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))));
|
||||
checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker));
|
||||
const names = map(args, arg =>
|
||||
isIdentifier(arg) ? arg.text :
|
||||
isPropertyAccessExpression(arg) ? arg.name.text : undefined);
|
||||
const contextualType = checker.getContextualType(call);
|
||||
const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || createKeywordTypeNode(SyntaxKind.AnyKeyword);
|
||||
const returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker);
|
||||
return createMethod(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined,
|
||||
@@ -236,6 +264,7 @@ namespace ts.codefix {
|
||||
createNew(
|
||||
createIdentifier("Error"),
|
||||
/*typeArguments*/ undefined,
|
||||
// TODO Handle auto quote preference.
|
||||
[createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))],
|
||||
/*multiline*/ true);
|
||||
}
|
||||
@@ -249,4 +278,46 @@ namespace ts.codefix {
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function setJsonCompilerOptionValue(
|
||||
changeTracker: textChanges.ChangeTracker,
|
||||
configFile: TsConfigSourceFile,
|
||||
optionName: string,
|
||||
optionValue: Expression,
|
||||
) {
|
||||
const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile);
|
||||
if (!tsconfigObjectLiteral) return undefined;
|
||||
|
||||
const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions");
|
||||
if (compilerOptionsProperty === undefined) {
|
||||
changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment(
|
||||
"compilerOptions",
|
||||
createObjectLiteral([
|
||||
createJsonPropertyAssignment(optionName, optionValue),
|
||||
])));
|
||||
return;
|
||||
}
|
||||
|
||||
const compilerOptions = compilerOptionsProperty.initializer;
|
||||
if (!isObjectLiteralExpression(compilerOptions)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const optionProperty = findJsonProperty(compilerOptions, optionName);
|
||||
|
||||
if (optionProperty === undefined) {
|
||||
changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue));
|
||||
}
|
||||
else {
|
||||
changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue);
|
||||
}
|
||||
}
|
||||
|
||||
export function createJsonPropertyAssignment(name: string, initializer: Expression) {
|
||||
return createPropertyAssignment(createStringLiteral(name), initializer);
|
||||
}
|
||||
|
||||
export function findJsonProperty(obj: ObjectLiteralExpression, name: string): PropertyAssignment | undefined {
|
||||
return find(obj.properties, (p): p is PropertyAssignment => isPropertyAssignment(p) && !!p.name && isStringLiteral(p.name) && p.name.text === name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,7 +375,7 @@ namespace ts.codefix {
|
||||
const symbolName = isJsxOpeningLikeElement(symbolToken.parent)
|
||||
&& symbolToken.parent.tagName === symbolToken
|
||||
&& (isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, SymbolFlags.All, /*excludeGlobals*/ false))
|
||||
? checker.getJsxNamespace()
|
||||
? checker.getJsxNamespace(sourceFile)
|
||||
: symbolToken.text;
|
||||
// "default" is a keyword and not a legal identifier for the import, so we don't expect it here
|
||||
Debug.assert(symbolName !== InternalSymbolName.Default);
|
||||
|
||||
@@ -274,7 +274,17 @@ namespace ts.codefix {
|
||||
return !!merged;
|
||||
}));
|
||||
const tag = createJSDocComment(comments.join("\n"), createNodeArray([...(oldTags || emptyArray), ...unmergedNewTags]));
|
||||
changes.insertJsdocCommentBefore(sourceFile, parent, tag);
|
||||
const jsDocNode = parent.kind === SyntaxKind.ArrowFunction ? getJsDocNodeForArrowFunction(parent) : parent;
|
||||
jsDocNode.jsDoc = parent.jsDoc;
|
||||
jsDocNode.jsDocCache = parent.jsDocCache;
|
||||
changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag);
|
||||
}
|
||||
|
||||
function getJsDocNodeForArrowFunction(signature: ArrowFunction): HasJSDoc {
|
||||
if (signature.parent.kind === SyntaxKind.PropertyDeclaration) {
|
||||
return <HasJSDoc>signature.parent;
|
||||
}
|
||||
return <HasJSDoc>signature.parent.parent;
|
||||
}
|
||||
|
||||
function tryMergeJsdocTags(oldTag: JSDocTag, newTag: JSDocTag): JSDocTag | undefined {
|
||||
@@ -294,30 +304,6 @@ namespace ts.codefix {
|
||||
}
|
||||
}
|
||||
|
||||
function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined {
|
||||
const checker = program.getTypeChecker();
|
||||
let typeIsAccessible = true;
|
||||
const notAccessible = () => { typeIsAccessible = false; };
|
||||
const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
|
||||
trackSymbol: (symbol, declaration, meaning) => {
|
||||
// TODO: GH#18217
|
||||
typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning!, /*shouldComputeAliasToMarkVisible*/ false).accessibility === SymbolAccessibility.Accessible;
|
||||
},
|
||||
reportInaccessibleThisError: notAccessible,
|
||||
reportPrivateInBaseOfClassExpression: notAccessible,
|
||||
reportInaccessibleUniqueSymbolError: notAccessible,
|
||||
moduleResolverHost: {
|
||||
readFile: host.readFile,
|
||||
fileExists: host.fileExists,
|
||||
directoryExists: host.directoryExists,
|
||||
getSourceFiles: program.getSourceFiles,
|
||||
getCurrentDirectory: program.getCurrentDirectory,
|
||||
getCommonSourceDirectory: program.getCommonSourceDirectory,
|
||||
}
|
||||
});
|
||||
return typeIsAccessible ? res : undefined;
|
||||
}
|
||||
|
||||
function getReferences(token: PropertyName | Token<SyntaxKind.ConstructorKeyword>, program: Program, cancellationToken: CancellationToken): ReadonlyArray<Identifier> {
|
||||
// Position shouldn't matter since token is not a SourceFile.
|
||||
return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry =>
|
||||
|
||||
@@ -30,6 +30,7 @@ namespace ts.Completions {
|
||||
ConstructorParameterKeywords, // Keywords at constructor parameter
|
||||
FunctionLikeBodyKeywords, // Keywords at function like body
|
||||
TypeKeywords,
|
||||
Last = TypeKeywords
|
||||
}
|
||||
|
||||
const enum GlobalsSearch { Continue, Success, Fail }
|
||||
@@ -77,7 +78,7 @@ namespace ts.Completions {
|
||||
}
|
||||
|
||||
function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, preferences: UserPreferences): CompletionInfo | undefined {
|
||||
const { symbols, completionKind, isInSnippetScope, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, literals, symbolToOriginInfoMap, recommendedCompletion, isJsxInitializer } = completionData;
|
||||
const { symbols, completionKind, isInSnippetScope, isNewIdentifierLocation, location, propertyAccessToConvert, keywordFilters, literals, symbolToOriginInfoMap, recommendedCompletion, isJsxInitializer, insideJsDocTagTypeExpression } = completionData;
|
||||
|
||||
if (location && location.parent && isJsxClosingElement(location.parent)) {
|
||||
// In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag,
|
||||
@@ -104,7 +105,7 @@ namespace ts.Completions {
|
||||
getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217
|
||||
}
|
||||
else {
|
||||
if ((!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) {
|
||||
if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -113,7 +114,7 @@ namespace ts.Completions {
|
||||
|
||||
if (keywordFilters !== KeywordCompletionFilters.None) {
|
||||
const entryNames = arrayToSet(entries, e => e.name);
|
||||
for (const keywordEntry of getKeywordCompletions(keywordFilters)) {
|
||||
for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) {
|
||||
if (!entryNames.has(keywordEntry.name)) {
|
||||
entries.push(keywordEntry);
|
||||
}
|
||||
@@ -367,7 +368,9 @@ namespace ts.Completions {
|
||||
}
|
||||
|
||||
function getSymbolName(symbol: Symbol, origin: SymbolOriginInfo | undefined, target: ScriptTarget): string {
|
||||
return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === InternalSymbolName.Default
|
||||
return origin && originIsExport(origin) && (
|
||||
(origin.isDefaultExport && symbol.escapedName === InternalSymbolName.Default) ||
|
||||
(symbol.escapedName === InternalSymbolName.ExportEquals))
|
||||
// Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase.
|
||||
? firstDefined(symbol.declarations, d => isExportAssignment(d) && isIdentifier(d.expression) ? d.expression.text : undefined)
|
||||
|| codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target)
|
||||
@@ -508,6 +511,7 @@ namespace ts.Completions {
|
||||
readonly recommendedCompletion: Symbol | undefined;
|
||||
readonly previousToken: Node | undefined;
|
||||
readonly isJsxInitializer: IsJsxInitializer;
|
||||
readonly insideJsDocTagTypeExpression: boolean;
|
||||
}
|
||||
type Request = { readonly kind: CompletionDataKind.JsDocTagName | CompletionDataKind.JsDocTag } | { readonly kind: CompletionDataKind.JsDocParameterName, tag: JSDocParameterTag };
|
||||
|
||||
@@ -701,6 +705,14 @@ namespace ts.Completions {
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
propertyAccessToConvert = parent as PropertyAccessExpression;
|
||||
node = propertyAccessToConvert.expression;
|
||||
if (node.end === contextToken.pos &&
|
||||
isCallExpression(node) &&
|
||||
node.getChildCount(sourceFile) &&
|
||||
last(node.getChildren(sourceFile)).kind !== SyntaxKind.CloseParenToken) {
|
||||
// This is likely dot from incorrectly parsed call expression and user is starting to write spread
|
||||
// eg: Math.min(./**/)
|
||||
return undefined;
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.QualifiedName:
|
||||
node = (parent as QualifiedName).left;
|
||||
@@ -827,7 +839,22 @@ namespace ts.Completions {
|
||||
const literals = mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), t => t.isLiteral() ? t.value : undefined);
|
||||
|
||||
const recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker);
|
||||
return { kind: CompletionDataKind.Data, symbols, completionKind, isInSnippetScope, propertyAccessToConvert, isNewIdentifierLocation, location, keywordFilters, literals, symbolToOriginInfoMap, recommendedCompletion, previousToken, isJsxInitializer };
|
||||
return {
|
||||
kind: CompletionDataKind.Data,
|
||||
symbols,
|
||||
completionKind,
|
||||
isInSnippetScope,
|
||||
propertyAccessToConvert,
|
||||
isNewIdentifierLocation,
|
||||
location,
|
||||
keywordFilters,
|
||||
literals,
|
||||
symbolToOriginInfoMap,
|
||||
recommendedCompletion,
|
||||
previousToken,
|
||||
isJsxInitializer,
|
||||
insideJsDocTagTypeExpression
|
||||
};
|
||||
|
||||
type JSDocTagWithTypeExpression = JSDocParameterTag | JSDocPropertyTag | JSDocReturnTag | JSDocTypeTag | JSDocTypedefTag;
|
||||
|
||||
@@ -880,7 +907,9 @@ namespace ts.Completions {
|
||||
}
|
||||
|
||||
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
|
||||
if (!isTypeLocation && symbol.declarations.some(d => d.kind !== SyntaxKind.SourceFile && d.kind !== SyntaxKind.ModuleDeclaration && d.kind !== SyntaxKind.EnumDeclaration)) {
|
||||
if (!isTypeLocation &&
|
||||
symbol.declarations &&
|
||||
symbol.declarations.some(d => d.kind !== SyntaxKind.SourceFile && d.kind !== SyntaxKind.ModuleDeclaration && d.kind !== SyntaxKind.EnumDeclaration)) {
|
||||
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
|
||||
}
|
||||
|
||||
@@ -1028,7 +1057,7 @@ namespace ts.Completions {
|
||||
|
||||
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
|
||||
if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== SyntaxKind.SourceFile) {
|
||||
const thisType = typeChecker.tryGetThisTypeAt(scopeNode);
|
||||
const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
|
||||
if (thisType) {
|
||||
for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) {
|
||||
symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: SymbolOriginInfoKind.ThisType };
|
||||
@@ -1127,6 +1156,9 @@ namespace ts.Completions {
|
||||
|
||||
case SyntaxKind.AsKeyword:
|
||||
return parentKind === SyntaxKind.AsExpression;
|
||||
|
||||
case SyntaxKind.ExtendsKeyword:
|
||||
return parentKind === SyntaxKind.TypeParameter;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
@@ -1914,7 +1946,18 @@ namespace ts.Completions {
|
||||
}
|
||||
return res;
|
||||
});
|
||||
function getKeywordCompletions(keywordFilter: KeywordCompletionFilters): ReadonlyArray<CompletionEntry> {
|
||||
|
||||
function getKeywordCompletions(keywordFilter: KeywordCompletionFilters, filterOutTsOnlyKeywords: boolean): ReadonlyArray<CompletionEntry> {
|
||||
if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter);
|
||||
|
||||
const index = keywordFilter + KeywordCompletionFilters.Last + 1;
|
||||
return _keywordCompletions[index] ||
|
||||
(_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter)
|
||||
.filter(entry => !isTypeScriptOnlyKeyword(stringToToken(entry.name)!))
|
||||
);
|
||||
}
|
||||
|
||||
function getTypescriptKeywordCompletions(keywordFilter: KeywordCompletionFilters): ReadonlyArray<CompletionEntry> {
|
||||
return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(entry => {
|
||||
const kind = stringToToken(entry.name)!;
|
||||
switch (keywordFilter) {
|
||||
@@ -1939,6 +1982,40 @@ namespace ts.Completions {
|
||||
}));
|
||||
}
|
||||
|
||||
function isTypeScriptOnlyKeyword(kind: SyntaxKind) {
|
||||
switch (kind) {
|
||||
case SyntaxKind.AbstractKeyword:
|
||||
case SyntaxKind.AnyKeyword:
|
||||
case SyntaxKind.BigIntKeyword:
|
||||
case SyntaxKind.BooleanKeyword:
|
||||
case SyntaxKind.DeclareKeyword:
|
||||
case SyntaxKind.EnumKeyword:
|
||||
case SyntaxKind.GlobalKeyword:
|
||||
case SyntaxKind.ImplementsKeyword:
|
||||
case SyntaxKind.InferKeyword:
|
||||
case SyntaxKind.InterfaceKeyword:
|
||||
case SyntaxKind.IsKeyword:
|
||||
case SyntaxKind.KeyOfKeyword:
|
||||
case SyntaxKind.ModuleKeyword:
|
||||
case SyntaxKind.NamespaceKeyword:
|
||||
case SyntaxKind.NeverKeyword:
|
||||
case SyntaxKind.NumberKeyword:
|
||||
case SyntaxKind.ObjectKeyword:
|
||||
case SyntaxKind.PrivateKeyword:
|
||||
case SyntaxKind.ProtectedKeyword:
|
||||
case SyntaxKind.PublicKeyword:
|
||||
case SyntaxKind.ReadonlyKeyword:
|
||||
case SyntaxKind.StringKeyword:
|
||||
case SyntaxKind.SymbolKeyword:
|
||||
case SyntaxKind.TypeKeyword:
|
||||
case SyntaxKind.UniqueKeyword:
|
||||
case SyntaxKind.UnknownKeyword:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isInterfaceOrTypeLiteralCompletionKeyword(kind: SyntaxKind): boolean {
|
||||
return kind === SyntaxKind.ReadonlyKeyword;
|
||||
}
|
||||
|
||||
@@ -39,6 +39,12 @@ namespace ts.FindAllReferences {
|
||||
readonly isForRename?: boolean;
|
||||
/** True if we are searching for implementations. We will have a different method of adding references if so. */
|
||||
readonly implementations?: boolean;
|
||||
/**
|
||||
* True to opt in for enhanced renaming of shorthand properties and import/export specifiers.
|
||||
* The options controls the behavior for the whole rename operation; it cannot be changed on a per-file basis.
|
||||
* Default is false for backwards compatibility.
|
||||
*/
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
}
|
||||
|
||||
export function findReferencedSymbols(program: Program, cancellationToken: CancellationToken, sourceFiles: ReadonlyArray<SourceFile>, sourceFile: SourceFile, position: number): ReferencedSymbol[] | undefined {
|
||||
@@ -106,7 +112,7 @@ namespace ts.FindAllReferences {
|
||||
return flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet));
|
||||
}
|
||||
|
||||
function flattenEntries(referenceSymbols: SymbolAndEntries[] | undefined): ReadonlyArray<Entry> | undefined {
|
||||
function flattenEntries(referenceSymbols: ReadonlyArray<SymbolAndEntries> | undefined): ReadonlyArray<Entry> | undefined {
|
||||
return referenceSymbols && flatMap(referenceSymbols, r => r.references);
|
||||
}
|
||||
|
||||
@@ -157,8 +163,8 @@ namespace ts.FindAllReferences {
|
||||
return { displayParts, kind: symbolKind };
|
||||
}
|
||||
|
||||
export function toRenameLocation(entry: Entry, originalNode: Node, checker: TypeChecker): RenameLocation {
|
||||
return { ...entryToDocumentSpan(entry), ...getPrefixAndSuffixText(entry, originalNode, checker) };
|
||||
export function toRenameLocation(entry: Entry, originalNode: Node, checker: TypeChecker, providePrefixAndSuffixText: boolean): RenameLocation {
|
||||
return { ...entryToDocumentSpan(entry), ...(providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)) };
|
||||
}
|
||||
|
||||
export function toReferenceEntry(entry: Entry): ReferenceEntry {
|
||||
@@ -277,6 +283,11 @@ namespace ts.FindAllReferences {
|
||||
return createTextSpanFromBounds(start, end);
|
||||
}
|
||||
|
||||
export function getTextSpanOfEntry(entry: Entry) {
|
||||
return entry.kind === EntryKind.Span ? entry.textSpan :
|
||||
getTextSpan(entry.node, entry.node.getSourceFile());
|
||||
}
|
||||
|
||||
/** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */
|
||||
function isWriteAccessForReference(node: Node): boolean {
|
||||
const decl = getDeclarationFromName(node);
|
||||
@@ -348,7 +359,7 @@ namespace ts.FindAllReferences {
|
||||
/* @internal */
|
||||
namespace ts.FindAllReferences.Core {
|
||||
/** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */
|
||||
export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap<true> = arrayToSet(sourceFiles, f => f.fileName)): SymbolAndEntries[] | undefined {
|
||||
export function getReferencedSymbolsForNode(position: number, node: Node, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options = {}, sourceFilesSet: ReadonlyMap<true> = arrayToSet(sourceFiles, f => f.fileName)): ReadonlyArray<SymbolAndEntries> | undefined {
|
||||
if (isSourceFile(node)) {
|
||||
const reference = GoToDefinition.getReferenceAtPosition(node, position, program);
|
||||
const moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol);
|
||||
@@ -363,7 +374,7 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
const checker = program.getTypeChecker();
|
||||
let symbol = checker.getSymbolAtLocation(node);
|
||||
const symbol = checker.getSymbolAtLocation(node);
|
||||
|
||||
// Could not find a symbol e.g. unknown identifier
|
||||
if (!symbol) {
|
||||
@@ -375,23 +386,95 @@ namespace ts.FindAllReferences.Core {
|
||||
return getReferencedSymbolsForModule(program, symbol.parent!, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet);
|
||||
}
|
||||
|
||||
let moduleReferences: SymbolAndEntries[] = emptyArray;
|
||||
const moduleSourceFile = isModuleSymbol(symbol);
|
||||
let referencedNode: Node | undefined = node;
|
||||
if (moduleSourceFile) {
|
||||
const exportEquals = symbol.exports!.get(InternalSymbolName.ExportEquals);
|
||||
// If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
|
||||
moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
|
||||
if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences;
|
||||
// Continue to get references to 'export ='.
|
||||
symbol = skipAlias(exportEquals, checker);
|
||||
referencedNode = undefined;
|
||||
const moduleReferences = getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
|
||||
if (moduleReferences && !(symbol.flags & SymbolFlags.Transient)) {
|
||||
return moduleReferences;
|
||||
}
|
||||
return concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
|
||||
|
||||
const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(node, symbol, checker);
|
||||
const moduleReferencesOfExportTarget = aliasedSymbol &&
|
||||
getReferencedSymbolsForModuleIfDeclaredBySourceFile(aliasedSymbol, program, sourceFiles, cancellationToken, options, sourceFilesSet);
|
||||
|
||||
const references = getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options);
|
||||
return mergeReferences(program, moduleReferences, references, moduleReferencesOfExportTarget);
|
||||
}
|
||||
|
||||
function isModuleSymbol(symbol: Symbol): SourceFile | undefined {
|
||||
return symbol.flags & SymbolFlags.Module ? find(symbol.declarations, isSourceFile) : undefined;
|
||||
function getMergedAliasedSymbolOfNamespaceExportDeclaration(node: Node, symbol: Symbol, checker: TypeChecker) {
|
||||
if (node.parent && isNamespaceExportDeclaration(node.parent)) {
|
||||
const aliasedSymbol = checker.getAliasedSymbol(symbol);
|
||||
const targetSymbol = checker.getMergedSymbol(aliasedSymbol);
|
||||
if (aliasedSymbol !== targetSymbol) {
|
||||
return targetSymbol;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol: Symbol, program: Program, sourceFiles: ReadonlyArray<SourceFile>, cancellationToken: CancellationToken, options: Options, sourceFilesSet: ReadonlyMap<true>) {
|
||||
const moduleSourceFile = symbol.flags & SymbolFlags.Module ? find(symbol.declarations, isSourceFile) : undefined;
|
||||
if (!moduleSourceFile) return undefined;
|
||||
const exportEquals = symbol.exports!.get(InternalSymbolName.ExportEquals);
|
||||
// If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them.
|
||||
const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet);
|
||||
if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences;
|
||||
// Continue to get references to 'export ='.
|
||||
const checker = program.getTypeChecker();
|
||||
symbol = skipAlias(exportEquals, checker);
|
||||
return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol(symbol, /*node*/ undefined, sourceFiles, sourceFilesSet, checker, cancellationToken, options));
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the references by sorting them (by file index in sourceFiles and their location in it) that point to same definition symbol
|
||||
*/
|
||||
function mergeReferences(program: Program, ...referencesToMerge: (SymbolAndEntries[] | undefined)[]): SymbolAndEntries[] | undefined {
|
||||
let result: SymbolAndEntries[] | undefined;
|
||||
for (const references of referencesToMerge) {
|
||||
if (!references || !references.length) continue;
|
||||
if (!result) {
|
||||
result = references;
|
||||
continue;
|
||||
}
|
||||
for (const entry of references) {
|
||||
if (!entry.definition || entry.definition.type !== DefinitionKind.Symbol) {
|
||||
result.push(entry);
|
||||
continue;
|
||||
}
|
||||
const symbol = entry.definition.symbol;
|
||||
const refIndex = findIndex(result, ref => !!ref.definition &&
|
||||
ref.definition.type === DefinitionKind.Symbol &&
|
||||
ref.definition.symbol === symbol);
|
||||
if (refIndex === -1) {
|
||||
result.push(entry);
|
||||
continue;
|
||||
}
|
||||
|
||||
const reference = result[refIndex];
|
||||
result[refIndex] = {
|
||||
definition: reference.definition,
|
||||
references: reference.references.concat(entry.references).sort((entry1, entry2) => {
|
||||
const entry1File = getSourceFileIndexOfEntry(program, entry1);
|
||||
const entry2File = getSourceFileIndexOfEntry(program, entry2);
|
||||
if (entry1File !== entry2File) {
|
||||
return compareValues(entry1File, entry2File);
|
||||
}
|
||||
|
||||
const entry1Span = getTextSpanOfEntry(entry1);
|
||||
const entry2Span = getTextSpanOfEntry(entry2);
|
||||
return entry1Span.start !== entry2Span.start ?
|
||||
compareValues(entry1Span.start, entry2Span.start) :
|
||||
compareValues(entry1Span.length, entry2Span.length);
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function getSourceFileIndexOfEntry(program: Program, entry: Entry) {
|
||||
const sourceFile = entry.kind === EntryKind.Span ?
|
||||
program.getSourceFile(entry.fileName)! :
|
||||
entry.node.getSourceFile();
|
||||
return program.getSourceFiles().indexOf(sourceFile);
|
||||
}
|
||||
|
||||
function getReferencedSymbolsForModule(program: Program, symbol: Symbol, excludeImportTypeOfExportEquals: boolean, sourceFiles: ReadonlyArray<SourceFile>, sourceFilesSet: ReadonlyMap<true>): SymbolAndEntries[] {
|
||||
@@ -430,7 +513,7 @@ namespace ts.FindAllReferences.Core {
|
||||
break;
|
||||
default:
|
||||
// This may be merged with something.
|
||||
Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
|
||||
Debug.assert(!!(symbol.flags & SymbolFlags.Transient), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,7 +567,7 @@ namespace ts.FindAllReferences.Core {
|
||||
|
||||
/** Core find-all-references algorithm for a normal symbol. */
|
||||
function getReferencedSymbolsForSymbol(originalSymbol: Symbol, node: Node | undefined, sourceFiles: ReadonlyArray<SourceFile>, sourceFilesSet: ReadonlyMap<true>, checker: TypeChecker, cancellationToken: CancellationToken, options: Options): SymbolAndEntries[] {
|
||||
const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol;
|
||||
const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol;
|
||||
|
||||
// Compute the meaning from the location and the symbol it references
|
||||
const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All;
|
||||
@@ -492,7 +575,7 @@ namespace ts.FindAllReferences.Core {
|
||||
const result: SymbolAndEntries[] = [];
|
||||
const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result);
|
||||
|
||||
const exportSpecifier = !options.isForRename ? undefined : find(symbol.declarations, isExportSpecifier);
|
||||
const exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : find(symbol.declarations, isExportSpecifier);
|
||||
if (exportSpecifier) {
|
||||
// When renaming at an export specifier, rename the export and not the thing being exported.
|
||||
getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true);
|
||||
@@ -502,7 +585,7 @@ namespace ts.FindAllReferences.Core {
|
||||
searchForImportsOfExport(node, symbol, { exportingModuleSymbol: Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: ExportKind.Default }, state);
|
||||
}
|
||||
else {
|
||||
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] });
|
||||
const search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] });
|
||||
|
||||
// Try to get the smallest valid scope that we can limit our search to;
|
||||
// otherwise we'll need to search globally (i.e. include each file).
|
||||
@@ -538,14 +621,16 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
/** Handle a few special cases relating to export/import specifiers. */
|
||||
function skipPastExportOrImportSpecifierOrUnion(symbol: Symbol, node: Node, checker: TypeChecker, isForRename: boolean): Symbol | undefined {
|
||||
function skipPastExportOrImportSpecifierOrUnion(symbol: Symbol, node: Node, checker: TypeChecker, useLocalSymbolForExportSpecifier: boolean): Symbol | undefined {
|
||||
const { parent } = node;
|
||||
if (isExportSpecifier(parent) && !isForRename) {
|
||||
if (isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) {
|
||||
return getLocalSymbolForExportSpecifier(node as Identifier, symbol, parent, checker);
|
||||
}
|
||||
// If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references.
|
||||
return firstDefined(symbol.declarations, decl => {
|
||||
if (!decl.parent) {
|
||||
// Ignore UMD module and global merge
|
||||
if (symbol.flags & SymbolFlags.Transient) return undefined;
|
||||
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
|
||||
Debug.fail(`Unexpected symbol at ${Debug.showSyntaxKind(node)}: ${Debug.showSymbol(symbol)}`);
|
||||
}
|
||||
@@ -583,6 +668,12 @@ namespace ts.FindAllReferences.Core {
|
||||
Class,
|
||||
}
|
||||
|
||||
function getNonModuleSymbolOfMergedModuleSymbol(symbol: Symbol) {
|
||||
if (!(symbol.flags & (SymbolFlags.Module | SymbolFlags.Transient))) return undefined;
|
||||
const decl = symbol.declarations && find(symbol.declarations, d => !isSourceFile(d) && !isModuleDeclaration(d));
|
||||
return decl && decl.symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds all state needed for the finding references.
|
||||
* Unlike `Search`, there is only one `State`.
|
||||
@@ -643,7 +734,7 @@ namespace ts.FindAllReferences.Core {
|
||||
// The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form
|
||||
// here appears to be intentional).
|
||||
const {
|
||||
text = stripQuotes(unescapeLeadingUnderscores((getLocalSymbolForExportDefault(symbol) || symbol).escapedName)),
|
||||
text = stripQuotes(unescapeLeadingUnderscores((getLocalSymbolForExportDefault(symbol) || getNonModuleSymbolOfMergedModuleSymbol(symbol) || symbol).escapedName)),
|
||||
allSearchSymbols = [symbol],
|
||||
} = searchOptions;
|
||||
const escapedText = escapeLeadingUnderscores(text);
|
||||
@@ -1071,6 +1162,8 @@ namespace ts.FindAllReferences.Core {
|
||||
addReferencesHere: boolean,
|
||||
alwaysGetReferences?: boolean,
|
||||
): void {
|
||||
Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled");
|
||||
|
||||
const { parent, propertyName, name } = exportSpecifier;
|
||||
const exportDeclaration = parent.parent;
|
||||
const localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker);
|
||||
@@ -1102,15 +1195,17 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
// For `export { foo as bar }`, rename `foo`, but not `bar`.
|
||||
if (!state.options.isForRename || alwaysGetReferences) {
|
||||
const exportKind = referenceLocation.originalKeywordKind === SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named;
|
||||
if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) {
|
||||
const isDefaultExport = referenceLocation.originalKeywordKind === SyntaxKind.DefaultKeyword
|
||||
|| exportSpecifier.name.originalKeywordKind === SyntaxKind.DefaultKeyword;
|
||||
const exportKind = isDefaultExport ? ExportKind.Default : ExportKind.Named;
|
||||
const exportSymbol = Debug.assertDefined(exportSpecifier.symbol);
|
||||
const exportInfo = Debug.assertDefined(getExportInfo(exportSymbol, exportKind, state.checker));
|
||||
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
|
||||
}
|
||||
|
||||
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
|
||||
if (search.comingFrom !== ImportExport.Export && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) {
|
||||
if (search.comingFrom !== ImportExport.Export && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) {
|
||||
const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier);
|
||||
if (imported) searchForImportedSymbol(imported, state);
|
||||
}
|
||||
@@ -1145,7 +1240,7 @@ namespace ts.FindAllReferences.Core {
|
||||
const { symbol } = importOrExport;
|
||||
|
||||
if (importOrExport.kind === ImportExport.Import) {
|
||||
if (!state.options.isForRename) {
|
||||
if (!(isForRenameWithPrefixAndSuffixText(state.options))) {
|
||||
searchForImportedSymbol(symbol, state);
|
||||
}
|
||||
}
|
||||
@@ -1514,16 +1609,16 @@ namespace ts.FindAllReferences.Core {
|
||||
|
||||
// For certain symbol kinds, we need to include other symbols in the search set.
|
||||
// This is not needed when searching for re-exports.
|
||||
function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, isForRename: boolean, implementations: boolean): Symbol[] {
|
||||
function populateSearchSymbolSet(symbol: Symbol, location: Node, checker: TypeChecker, isForRename: boolean, providePrefixAndSuffixText: boolean, implementations: boolean): Symbol[] {
|
||||
const result: Symbol[] = [];
|
||||
forEachRelatedSymbol<void>(symbol, location, checker, isForRename,
|
||||
forEachRelatedSymbol<void>(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText),
|
||||
(sym, root, base) => { result.push(base || root || sym); },
|
||||
/*allowBaseTypes*/ () => !implementations);
|
||||
return result;
|
||||
}
|
||||
|
||||
function forEachRelatedSymbol<T>(
|
||||
symbol: Symbol, location: Node, checker: TypeChecker, isForRenamePopulateSearchSymbolSet: boolean,
|
||||
symbol: Symbol, location: Node, checker: TypeChecker, isForRenamePopulateSearchSymbolSet: boolean, onlyIncludeBindingElementAtReferenceLocation: boolean,
|
||||
cbSymbol: (symbol: Symbol, rootSymbol?: Symbol, baseSymbol?: Symbol, kind?: NodeEntryKind) => T | undefined,
|
||||
allowBaseTypes: (rootSymbol: Symbol) => boolean,
|
||||
): T | undefined {
|
||||
@@ -1566,6 +1661,13 @@ namespace ts.FindAllReferences.Core {
|
||||
if (res2) return res2;
|
||||
}
|
||||
|
||||
const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker);
|
||||
if (aliasedSymbol) {
|
||||
// In case of UMD module and global merging, search for global as well
|
||||
const res = cbSymbol(aliasedSymbol, /*rootSymbol*/ undefined, /*baseSymbol*/ undefined, EntryKind.Node);
|
||||
if (res) return res;
|
||||
}
|
||||
|
||||
const res = fromRoot(symbol);
|
||||
if (res) return res;
|
||||
|
||||
@@ -1577,9 +1679,25 @@ namespace ts.FindAllReferences.Core {
|
||||
}
|
||||
|
||||
// symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property.
|
||||
// Don't do this when populating search set for a rename -- just rename the local.
|
||||
// Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local.
|
||||
if (!isForRenamePopulateSearchSymbolSet) {
|
||||
const bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : undefined;
|
||||
let bindingElementPropertySymbol: Symbol | undefined;
|
||||
if (onlyIncludeBindingElementAtReferenceLocation) {
|
||||
bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : undefined;
|
||||
}
|
||||
else {
|
||||
bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
|
||||
}
|
||||
return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal);
|
||||
}
|
||||
|
||||
Debug.assert(isForRenamePopulateSearchSymbolSet);
|
||||
// due to the above assert and the arguments at the uses of this function,
|
||||
// (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds
|
||||
const includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation;
|
||||
|
||||
if (includeOriginalSymbolOfBindingElement) {
|
||||
const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker);
|
||||
return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal);
|
||||
}
|
||||
|
||||
@@ -1597,6 +1715,13 @@ namespace ts.FindAllReferences.Core {
|
||||
? getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, base => cbSymbol(sym, rootSymbol, base, kind))
|
||||
: undefined));
|
||||
}
|
||||
|
||||
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined {
|
||||
const bindingElement = getDeclarationOfKind<BindingElement>(symbol, SyntaxKind.BindingElement);
|
||||
if (bindingElement && isObjectBindingElementWithoutPropertyName(bindingElement)) {
|
||||
return getPropertySymbolFromBindingElement(checker, bindingElement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface RelatedSymbol {
|
||||
@@ -1606,6 +1731,7 @@ namespace ts.FindAllReferences.Core {
|
||||
function getRelatedSymbol(search: Search, referenceSymbol: Symbol, referenceLocation: Node, state: State): RelatedSymbol | undefined {
|
||||
const { checker } = state;
|
||||
return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false,
|
||||
/*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename,
|
||||
(sym, rootSymbol, baseSymbol, kind): RelatedSymbol | undefined => search.includes(baseSymbol || rootSymbol || sym)
|
||||
// For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol.
|
||||
? { symbol: rootSymbol && !(getCheckFlags(sym) & CheckFlags.Synthetic) ? rootSymbol : sym, kind }
|
||||
@@ -1651,7 +1777,8 @@ namespace ts.FindAllReferences.Core {
|
||||
|
||||
function isImplementation(node: Node): boolean {
|
||||
return !!(node.flags & NodeFlags.Ambient)
|
||||
|| (isVariableLike(node) ? hasInitializer(node)
|
||||
? !(isInterfaceDeclaration(node) || isTypeAliasDeclaration(node))
|
||||
: (isVariableLike(node) ? hasInitializer(node)
|
||||
: isFunctionLikeDeclaration(node) ? !!node.body
|
||||
: isClassLike(node) || isModuleOrEnumDeclaration(node));
|
||||
}
|
||||
@@ -1696,4 +1823,8 @@ namespace ts.FindAllReferences.Core {
|
||||
t.symbol && t.symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? t.symbol : undefined);
|
||||
return res.length === 0 ? undefined : res;
|
||||
}
|
||||
|
||||
function isForRenameWithPrefixAndSuffixText(options: Options) {
|
||||
return options.isForRename && options.providePrefixAndSuffixTextForRename;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,7 +442,7 @@ namespace ts.formatting {
|
||||
case SyntaxKind.ForInStatement:
|
||||
// "in" keyword in [P in keyof T]: T[P]
|
||||
case SyntaxKind.TypeParameter:
|
||||
return context.currentTokenSpan.kind === SyntaxKind.InKeyword || context.nextTokenSpan.kind === SyntaxKind.InKeyword;
|
||||
return context.currentTokenSpan.kind === SyntaxKind.InKeyword || context.nextTokenSpan.kind === SyntaxKind.InKeyword || context.currentTokenSpan.kind === SyntaxKind.EqualsToken || context.nextTokenSpan.kind === SyntaxKind.EqualsToken;
|
||||
// Technically, "of" is not a binary operator, but format it the same way as "in"
|
||||
case SyntaxKind.ForOfStatement:
|
||||
return context.currentTokenSpan.kind === SyntaxKind.OfKeyword || context.nextTokenSpan.kind === SyntaxKind.OfKeyword;
|
||||
|
||||
@@ -151,7 +151,7 @@ namespace ts {
|
||||
const toImport = oldFromNew !== undefined
|
||||
// If we're at the new location (file was already renamed), need to redo module resolution starting from the old location.
|
||||
// TODO:GH#18217
|
||||
? getSourceFileToImportFromResolved(resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), oldToNew, host)
|
||||
? getSourceFileToImportFromResolved(resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host as ModuleResolutionHost), oldToNew)
|
||||
: getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew);
|
||||
|
||||
// Need an update if the imported file moved, or the importing file moved and was using a relative path.
|
||||
@@ -192,28 +192,35 @@ namespace ts {
|
||||
const resolved = host.resolveModuleNames
|
||||
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName)
|
||||
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName);
|
||||
return getSourceFileToImportFromResolved(resolved, oldToNew, host);
|
||||
return getSourceFileToImportFromResolved(resolved, oldToNew);
|
||||
}
|
||||
}
|
||||
|
||||
function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined {
|
||||
function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater): ToImport | undefined {
|
||||
// Search through all locations looking for a moved file, and only then test already existing files.
|
||||
// This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location.
|
||||
return tryEach(tryGetNewFile) || tryEach(tryGetOldFile);
|
||||
if (!resolved) return undefined;
|
||||
|
||||
function tryEach(cb: (oldFileName: string) => ToImport | undefined): ToImport | undefined {
|
||||
return resolved && (
|
||||
(resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, cb));
|
||||
// First try resolved module
|
||||
if (resolved.resolvedModule) {
|
||||
const result = tryChange(resolved.resolvedModule.resolvedFileName);
|
||||
if (result) return result;
|
||||
}
|
||||
|
||||
function tryGetNewFile(oldFileName: string): ToImport | undefined {
|
||||
const newFileName = oldToNew(oldFileName);
|
||||
return newFileName !== undefined && host.fileExists!(newFileName) ? { newFileName, updated: true } : undefined; // TODO: GH#18217
|
||||
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
|
||||
const result = forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
|
||||
if (result) return result;
|
||||
|
||||
// If nothing changed, then result is resolved module file thats not updated
|
||||
return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false };
|
||||
|
||||
function tryChangeWithIgnoringPackageJson(oldFileName: string) {
|
||||
return !endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined;
|
||||
}
|
||||
|
||||
function tryGetOldFile(oldFileName: string): ToImport | undefined {
|
||||
function tryChange(oldFileName: string) {
|
||||
const newFileName = oldToNew(oldFileName);
|
||||
return host.fileExists!(oldFileName) ? newFileName !== undefined ? { newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217
|
||||
return newFileName && { newFileName, updated: true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ namespace ts.FindAllReferences {
|
||||
}
|
||||
|
||||
/**
|
||||
* `import x = require("./x") or `import * as x from "./x"`.
|
||||
* `import x = require("./x")` or `import * as x from "./x"`.
|
||||
* An `export =` may be imported by this syntax, so it may be a direct import.
|
||||
* If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here.
|
||||
*/
|
||||
|
||||
@@ -28,12 +28,12 @@ namespace ts.OrganizeImports {
|
||||
organizeImportsWorker(topLevelExportDecls, coalesceExports);
|
||||
|
||||
for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
|
||||
const ambientModuleBody = getModuleBlock(ambientModule as ModuleDeclaration)!; // TODO: GH#18217
|
||||
if (!ambientModule.body) { continue; }
|
||||
|
||||
const ambientModuleImportDecls = ambientModuleBody.statements.filter(isImportDeclaration);
|
||||
const ambientModuleImportDecls = ambientModule.body.statements.filter(isImportDeclaration);
|
||||
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
|
||||
|
||||
const ambientModuleExportDecls = ambientModuleBody.statements.filter(isExportDeclaration);
|
||||
const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
|
||||
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
|
||||
}
|
||||
|
||||
@@ -68,8 +68,8 @@ namespace ts.OrganizeImports {
|
||||
else {
|
||||
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
|
||||
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
|
||||
useNonAdjustedStartPosition: true, // Leave header comment in place
|
||||
useNonAdjustedEndPosition: false,
|
||||
leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place
|
||||
trailingTriviaOption: textChanges.TrailingTriviaOption.Include,
|
||||
suffix: getNewLineOrDefaultFromHost(host, formatContext.options),
|
||||
});
|
||||
}
|
||||
@@ -81,14 +81,9 @@ namespace ts.OrganizeImports {
|
||||
}
|
||||
}
|
||||
|
||||
function getModuleBlock(moduleDecl: ModuleDeclaration): ModuleBlock | undefined {
|
||||
const body = moduleDecl.body;
|
||||
return body && !isIdentifier(body) ? (isModuleBlock(body) ? body : getModuleBlock(body)) : undefined;
|
||||
}
|
||||
|
||||
function removeUnusedImports(oldImports: ReadonlyArray<ImportDeclaration>, sourceFile: SourceFile, program: Program) {
|
||||
const typeChecker = program.getTypeChecker();
|
||||
const jsxNamespace = typeChecker.getJsxNamespace();
|
||||
const jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
|
||||
const jsxElementsPresent = !!(sourceFile.transformFlags & TransformFlags.ContainsJsx);
|
||||
|
||||
const usedImports: ImportDeclaration[] = [];
|
||||
|
||||
@@ -48,13 +48,13 @@ namespace ts.refactor.addOrRemoveBracesToArrowFunction {
|
||||
const returnStatement = createReturn(expression);
|
||||
body = createBlock([returnStatement], /* multiLine */ true);
|
||||
suppressLeadingAndTrailingTrivia(body);
|
||||
copyComments(expression!, returnStatement, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ true);
|
||||
copyLeadingComments(expression!, returnStatement, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ true);
|
||||
}
|
||||
else if (actionName === removeBracesActionName && returnStatement) {
|
||||
const actualExpression = expression || createVoidZero();
|
||||
body = needsParentheses(actualExpression) ? createParen(actualExpression) : actualExpression;
|
||||
suppressLeadingAndTrailingTrivia(body);
|
||||
copyComments(returnStatement, body, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ false);
|
||||
copyLeadingComments(returnStatement, body, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ false);
|
||||
}
|
||||
else {
|
||||
Debug.fail("invalid action");
|
||||
|
||||
@@ -0,0 +1,567 @@
|
||||
/* @internal */
|
||||
namespace ts.refactor.convertParamsToDestructuredObject {
|
||||
const refactorName = "Convert parameters to destructured object";
|
||||
const minimumParameterLength = 2;
|
||||
registerRefactor(refactorName, { getEditsForAction, getAvailableActions });
|
||||
|
||||
|
||||
function getAvailableActions(context: RefactorContext): ReadonlyArray<ApplicableRefactorInfo> {
|
||||
const { file, startPosition } = context;
|
||||
const isJSFile = isSourceFileJS(file);
|
||||
if (isJSFile) return emptyArray; // TODO: GH#30113
|
||||
const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
|
||||
if (!functionDeclaration) return emptyArray;
|
||||
|
||||
const description = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object);
|
||||
return [{
|
||||
name: refactorName,
|
||||
description,
|
||||
actions: [{
|
||||
name: refactorName,
|
||||
description
|
||||
}]
|
||||
}];
|
||||
}
|
||||
|
||||
function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined {
|
||||
Debug.assert(actionName === refactorName);
|
||||
const { file, startPosition, program, cancellationToken, host } = context;
|
||||
const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
|
||||
if (!functionDeclaration || !cancellationToken) return undefined;
|
||||
|
||||
const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
|
||||
if (groupedReferences.valid) {
|
||||
const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, host, t, functionDeclaration, groupedReferences));
|
||||
return { renameFilename: undefined, renameLocation: undefined, edits };
|
||||
}
|
||||
|
||||
return { edits: [] }; // TODO: GH#30113
|
||||
}
|
||||
|
||||
function doChange(
|
||||
sourceFile: SourceFile,
|
||||
program: Program,
|
||||
host: LanguageServiceHost,
|
||||
changes: textChanges.ChangeTracker,
|
||||
functionDeclaration: ValidFunctionDeclaration,
|
||||
groupedReferences: GroupedReferences): void {
|
||||
const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param));
|
||||
changes.replaceNodeRangeWithNodes(
|
||||
sourceFile,
|
||||
first(functionDeclaration.parameters),
|
||||
last(functionDeclaration.parameters),
|
||||
newParamDeclaration,
|
||||
{ joiner: ", ",
|
||||
// indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
|
||||
indentation: 0,
|
||||
leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll,
|
||||
trailingTriviaOption: textChanges.TrailingTriviaOption.Include
|
||||
});
|
||||
|
||||
const functionCalls = sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ (a, b) => compareValues(a.pos, b.pos));
|
||||
for (const call of functionCalls) {
|
||||
if (call.arguments && call.arguments.length) {
|
||||
const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
|
||||
changes.replaceNodeRange(
|
||||
getSourceFileOfNode(call),
|
||||
first(call.arguments),
|
||||
last(call.arguments),
|
||||
newArgument,
|
||||
{ leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: textChanges.TrailingTriviaOption.Include });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getGroupedReferences(functionDeclaration: ValidFunctionDeclaration, program: Program, cancellationToken: CancellationToken): GroupedReferences {
|
||||
const functionNames = getFunctionNames(functionDeclaration);
|
||||
const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
|
||||
const names = deduplicate([...functionNames, ...classNames], equateValues);
|
||||
const checker = program.getTypeChecker();
|
||||
|
||||
const references = flatMap(names, /*mapfn*/ name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken));
|
||||
const groupedReferences = groupReferences(references);
|
||||
|
||||
if (!every(groupedReferences.declarations, /*callback*/ decl => contains(names, decl))) {
|
||||
groupedReferences.valid = false;
|
||||
}
|
||||
|
||||
return groupedReferences;
|
||||
|
||||
function groupReferences(referenceEntries: ReadonlyArray<FindAllReferences.Entry>): GroupedReferences {
|
||||
const classReferences: ClassReferences = { accessExpressions: [], typeUsages: [] };
|
||||
const groupedReferences: GroupedReferences = { functionCalls: [], declarations: [], classReferences, valid: true };
|
||||
const functionSymbols = map(functionNames, checker.getSymbolAtLocation);
|
||||
const classSymbols = map(classNames, checker.getSymbolAtLocation);
|
||||
const isConstructor = isConstructorDeclaration(functionDeclaration);
|
||||
|
||||
for (const entry of referenceEntries) {
|
||||
if (entry.kind !== FindAllReferences.EntryKind.Node) {
|
||||
groupedReferences.valid = false;
|
||||
continue;
|
||||
}
|
||||
if (contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
|
||||
const decl = entryToDeclaration(entry);
|
||||
if (decl) {
|
||||
groupedReferences.declarations.push(decl);
|
||||
continue;
|
||||
}
|
||||
|
||||
const call = entryToFunctionCall(entry);
|
||||
if (call) {
|
||||
groupedReferences.functionCalls.push(call);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// if the refactored function is a constructor, we must also check if the references to its class are valid
|
||||
if (isConstructor && contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
|
||||
const decl = entryToDeclaration(entry);
|
||||
if (decl) {
|
||||
groupedReferences.declarations.push(decl);
|
||||
continue;
|
||||
}
|
||||
|
||||
const accessExpression = entryToAccessExpression(entry);
|
||||
if (accessExpression) {
|
||||
classReferences.accessExpressions.push(accessExpression);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only class declarations are allowed to be used as a type (in a heritage clause),
|
||||
// otherwise `findAllReferences` might not be able to track constructor calls.
|
||||
if (isClassDeclaration(functionDeclaration.parent)) {
|
||||
const type = entryToType(entry);
|
||||
if (type) {
|
||||
classReferences.typeUsages.push(type);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
groupedReferences.valid = false;
|
||||
}
|
||||
|
||||
return groupedReferences;
|
||||
}
|
||||
}
|
||||
|
||||
function symbolComparer(a: Symbol, b: Symbol): boolean {
|
||||
return getSymbolTarget(a) === getSymbolTarget(b);
|
||||
}
|
||||
|
||||
function entryToDeclaration(entry: FindAllReferences.NodeEntry): Node | undefined {
|
||||
if (isDeclaration(entry.node.parent)) {
|
||||
return entry.node;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function entryToFunctionCall(entry: FindAllReferences.NodeEntry): CallExpression | NewExpression | undefined {
|
||||
if (entry.node.parent) {
|
||||
const functionReference = entry.node;
|
||||
const parent = functionReference.parent;
|
||||
switch (parent.kind) {
|
||||
// Function call (foo(...) or super(...))
|
||||
case SyntaxKind.CallExpression:
|
||||
const callExpression = tryCast(parent, isCallExpression);
|
||||
if (callExpression && callExpression.expression === functionReference) {
|
||||
return callExpression;
|
||||
}
|
||||
break;
|
||||
// Constructor call (new Foo(...))
|
||||
case SyntaxKind.NewExpression:
|
||||
const newExpression = tryCast(parent, isNewExpression);
|
||||
if (newExpression && newExpression.expression === functionReference) {
|
||||
return newExpression;
|
||||
}
|
||||
break;
|
||||
// Method call (x.foo(...))
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression);
|
||||
if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
|
||||
const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression);
|
||||
if (callExpression && callExpression.expression === propertyAccessExpression) {
|
||||
return callExpression;
|
||||
}
|
||||
}
|
||||
break;
|
||||
// Method call (x["foo"](...))
|
||||
case SyntaxKind.ElementAccessExpression:
|
||||
const elementAccessExpression = tryCast(parent, isElementAccessExpression);
|
||||
if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
|
||||
const callExpression = tryCast(elementAccessExpression.parent, isCallExpression);
|
||||
if (callExpression && callExpression.expression === elementAccessExpression) {
|
||||
return callExpression;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function entryToAccessExpression(entry: FindAllReferences.NodeEntry): ElementAccessExpression | PropertyAccessExpression | undefined {
|
||||
if (entry.node.parent) {
|
||||
const reference = entry.node;
|
||||
const parent = reference.parent;
|
||||
switch (parent.kind) {
|
||||
// `C.foo`
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression);
|
||||
if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
|
||||
return propertyAccessExpression;
|
||||
}
|
||||
break;
|
||||
// `C["foo"]`
|
||||
case SyntaxKind.ElementAccessExpression:
|
||||
const elementAccessExpression = tryCast(parent, isElementAccessExpression);
|
||||
if (elementAccessExpression && elementAccessExpression.expression === reference) {
|
||||
return elementAccessExpression;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function entryToType(entry: FindAllReferences.NodeEntry): Node | undefined {
|
||||
const reference = entry.node;
|
||||
if (getMeaningFromLocation(reference) === SemanticMeaning.Type || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
|
||||
return reference;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined {
|
||||
const node = getTouchingToken(file, startPosition);
|
||||
const functionDeclaration = getContainingFunction(node);
|
||||
|
||||
// don't offer refactor on top-level JSDoc
|
||||
if (isTopLevelJSDoc(node)) return undefined;
|
||||
|
||||
if (functionDeclaration
|
||||
&& isValidFunctionDeclaration(functionDeclaration, checker)
|
||||
&& rangeContainsRange(functionDeclaration, node)
|
||||
&& !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration;
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isTopLevelJSDoc(node: Node): boolean {
|
||||
const containingJSDoc = findAncestor(node, isJSDocNode);
|
||||
if (containingJSDoc) {
|
||||
const containingNonJSDoc = findAncestor(containingJSDoc, n => !isJSDocNode(n));
|
||||
return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isValidFunctionDeclaration(
|
||||
functionDeclaration: SignatureDeclaration,
|
||||
checker: TypeChecker): functionDeclaration is ValidFunctionDeclaration {
|
||||
if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false;
|
||||
switch (functionDeclaration.kind) {
|
||||
case SyntaxKind.FunctionDeclaration:
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
return !!functionDeclaration.name
|
||||
&& !!functionDeclaration.body
|
||||
&& !checker.isImplementationOfOverload(functionDeclaration);
|
||||
case SyntaxKind.Constructor:
|
||||
if (isClassDeclaration(functionDeclaration.parent)) {
|
||||
return !!functionDeclaration.body
|
||||
&& !!functionDeclaration.parent.name
|
||||
&& !checker.isImplementationOfOverload(functionDeclaration);
|
||||
}
|
||||
else {
|
||||
return isValidVariableDeclaration(functionDeclaration.parent.parent)
|
||||
&& !!functionDeclaration.body
|
||||
&& !checker.isImplementationOfOverload(functionDeclaration);
|
||||
}
|
||||
case SyntaxKind.FunctionExpression:
|
||||
case SyntaxKind.ArrowFunction:
|
||||
return isValidVariableDeclaration(functionDeclaration.parent);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isValidParameterNodeArray(
|
||||
parameters: NodeArray<ParameterDeclaration>,
|
||||
checker: TypeChecker): parameters is ValidParameterNodeArray {
|
||||
return getRefactorableParametersLength(parameters) >= minimumParameterLength
|
||||
&& every(parameters, /*callback*/ paramDecl => isValidParameterDeclaration(paramDecl, checker));
|
||||
}
|
||||
|
||||
function isValidParameterDeclaration(
|
||||
parameterDeclaration: ParameterDeclaration,
|
||||
checker: TypeChecker): parameterDeclaration is ValidParameterDeclaration {
|
||||
if (isRestParameter(parameterDeclaration)) {
|
||||
const type = checker.getTypeAtLocation(parameterDeclaration);
|
||||
if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false;
|
||||
}
|
||||
return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && isIdentifier(parameterDeclaration.name);
|
||||
}
|
||||
|
||||
function isValidVariableDeclaration(node: Node): node is ValidVariableDeclaration {
|
||||
return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; // TODO: GH#30113
|
||||
}
|
||||
|
||||
function hasThisParameter(parameters: NodeArray<ParameterDeclaration>): boolean {
|
||||
return parameters.length > 0 && isThis(parameters[0].name);
|
||||
}
|
||||
|
||||
function getRefactorableParametersLength(parameters: NodeArray<ParameterDeclaration>): number {
|
||||
if (hasThisParameter(parameters)) {
|
||||
return parameters.length - 1;
|
||||
}
|
||||
return parameters.length;
|
||||
}
|
||||
|
||||
function getRefactorableParameters(parameters: NodeArray<ValidParameterDeclaration>): NodeArray<ValidParameterDeclaration> {
|
||||
if (hasThisParameter(parameters)) {
|
||||
parameters = createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
function createPropertyOrShorthandAssignment(name: string, initializer: Expression): PropertyAssignment | ShorthandPropertyAssignment {
|
||||
if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) {
|
||||
return createShorthandPropertyAssignment(name);
|
||||
}
|
||||
return createPropertyAssignment(name, initializer);
|
||||
}
|
||||
|
||||
function createNewArgument(functionDeclaration: ValidFunctionDeclaration, functionArguments: NodeArray<Expression>): ObjectLiteralExpression {
|
||||
const parameters = getRefactorableParameters(functionDeclaration.parameters);
|
||||
const hasRestParameter = isRestParameter(last(parameters));
|
||||
const nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
|
||||
const properties = map(nonRestArguments, (arg, i) => {
|
||||
const parameterName = getParameterName(parameters[i]);
|
||||
const property = createPropertyOrShorthandAssignment(parameterName, arg);
|
||||
|
||||
suppressLeadingAndTrailingTrivia(property.name);
|
||||
if (isPropertyAssignment(property)) suppressLeadingAndTrailingTrivia(property.initializer);
|
||||
copyComments(arg, property);
|
||||
return property;
|
||||
});
|
||||
|
||||
if (hasRestParameter && functionArguments.length >= parameters.length) {
|
||||
const restArguments = functionArguments.slice(parameters.length - 1);
|
||||
const restProperty = createPropertyAssignment(getParameterName(last(parameters)), createArrayLiteral(restArguments));
|
||||
properties.push(restProperty);
|
||||
}
|
||||
|
||||
const objectLiteral = createObjectLiteral(properties, /*multiLine*/ false);
|
||||
return objectLiteral;
|
||||
}
|
||||
|
||||
function createNewParameters(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray<ParameterDeclaration> {
|
||||
const checker = program.getTypeChecker();
|
||||
const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
|
||||
const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration);
|
||||
const objectParameterName = createObjectBindingPattern(bindingElements);
|
||||
const objectParameterType = createParameterTypeNode(refactorableParameters);
|
||||
|
||||
let objectInitializer: Expression | undefined;
|
||||
// If every parameter in the original function was optional, add an empty object initializer to the new object parameter
|
||||
if (every(refactorableParameters, isOptionalParameter)) {
|
||||
objectInitializer = createObjectLiteral();
|
||||
}
|
||||
|
||||
const objectParameter = createParameter(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
objectParameterName,
|
||||
/*questionToken*/ undefined,
|
||||
objectParameterType,
|
||||
objectInitializer);
|
||||
|
||||
if (hasThisParameter(functionDeclaration.parameters)) {
|
||||
const thisParameter = functionDeclaration.parameters[0];
|
||||
const newThisParameter = createParameter(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
thisParameter.name,
|
||||
/*questionToken*/ undefined,
|
||||
thisParameter.type);
|
||||
|
||||
suppressLeadingAndTrailingTrivia(newThisParameter.name);
|
||||
copyComments(thisParameter.name, newThisParameter.name);
|
||||
if (thisParameter.type) {
|
||||
suppressLeadingAndTrailingTrivia(newThisParameter.type!);
|
||||
copyComments(thisParameter.type, newThisParameter.type!);
|
||||
}
|
||||
|
||||
return createNodeArray([newThisParameter, objectParameter]);
|
||||
}
|
||||
return createNodeArray([objectParameter]);
|
||||
|
||||
function createBindingElementFromParameterDeclaration(parameterDeclaration: ValidParameterDeclaration): BindingElement {
|
||||
const element = createBindingElement(
|
||||
/*dotDotDotToken*/ undefined,
|
||||
/*propertyName*/ undefined,
|
||||
getParameterName(parameterDeclaration),
|
||||
isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? createArrayLiteral() : parameterDeclaration.initializer);
|
||||
|
||||
suppressLeadingAndTrailingTrivia(element);
|
||||
if (parameterDeclaration.initializer && element.initializer) {
|
||||
copyComments(parameterDeclaration.initializer, element.initializer);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
function createParameterTypeNode(parameters: NodeArray<ValidParameterDeclaration>): TypeLiteralNode {
|
||||
const members = map(parameters, createPropertySignatureFromParameterDeclaration);
|
||||
const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine);
|
||||
return typeNode;
|
||||
}
|
||||
|
||||
function createPropertySignatureFromParameterDeclaration(parameterDeclaration: ValidParameterDeclaration): PropertySignature {
|
||||
let parameterType = parameterDeclaration.type;
|
||||
if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) {
|
||||
parameterType = getTypeNode(parameterDeclaration);
|
||||
}
|
||||
|
||||
const propertySignature = createPropertySignature(
|
||||
/*modifiers*/ undefined,
|
||||
getParameterName(parameterDeclaration),
|
||||
isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : parameterDeclaration.questionToken,
|
||||
parameterType,
|
||||
/*initializer*/ undefined);
|
||||
|
||||
suppressLeadingAndTrailingTrivia(propertySignature);
|
||||
copyComments(parameterDeclaration.name, propertySignature.name);
|
||||
if (parameterDeclaration.type && propertySignature.type) {
|
||||
copyComments(parameterDeclaration.type, propertySignature.type);
|
||||
}
|
||||
|
||||
return propertySignature;
|
||||
}
|
||||
|
||||
function getTypeNode(node: Node): TypeNode | undefined {
|
||||
const type = checker.getTypeAtLocation(node);
|
||||
return getTypeNodeIfAccessible(type, node, program, host);
|
||||
}
|
||||
|
||||
function isOptionalParameter(parameterDeclaration: ValidParameterDeclaration): boolean {
|
||||
if (isRestParameter(parameterDeclaration)) {
|
||||
const type = checker.getTypeAtLocation(parameterDeclaration);
|
||||
return !checker.isTupleType(type);
|
||||
}
|
||||
return checker.isOptionalParameter(parameterDeclaration);
|
||||
}
|
||||
}
|
||||
|
||||
function copyComments(sourceNode: Node, targetNode: Node) {
|
||||
const sourceFile = sourceNode.getSourceFile();
|
||||
const text = sourceFile.text;
|
||||
if (hasLeadingLineBreak(sourceNode, text)) {
|
||||
copyLeadingComments(sourceNode, targetNode, sourceFile);
|
||||
}
|
||||
else {
|
||||
copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
|
||||
}
|
||||
copyTrailingComments(sourceNode, targetNode, sourceFile);
|
||||
}
|
||||
|
||||
function hasLeadingLineBreak(node: Node, text: string) {
|
||||
const start = node.getFullStart();
|
||||
const end = node.getStart();
|
||||
for (let i = start; i < end; i++) {
|
||||
if (text.charCodeAt(i) === CharacterCodes.lineFeed) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getParameterName(paramDeclaration: ValidParameterDeclaration) {
|
||||
return getTextOfIdentifierOrLiteral(paramDeclaration.name);
|
||||
}
|
||||
|
||||
function getClassNames(constructorDeclaration: ValidConstructor): Identifier[] {
|
||||
switch (constructorDeclaration.parent.kind) {
|
||||
case SyntaxKind.ClassDeclaration:
|
||||
const classDeclaration = constructorDeclaration.parent;
|
||||
return [classDeclaration.name];
|
||||
case SyntaxKind.ClassExpression:
|
||||
const classExpression = constructorDeclaration.parent;
|
||||
const variableDeclaration = constructorDeclaration.parent.parent;
|
||||
const className = classExpression.name;
|
||||
if (className) return [className, variableDeclaration.name];
|
||||
return [variableDeclaration.name];
|
||||
}
|
||||
}
|
||||
|
||||
function getFunctionNames(functionDeclaration: ValidFunctionDeclaration): Node[] {
|
||||
switch (functionDeclaration.kind) {
|
||||
case SyntaxKind.FunctionDeclaration:
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
return [functionDeclaration.name];
|
||||
case SyntaxKind.Constructor:
|
||||
const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile())!;
|
||||
if (functionDeclaration.parent.kind === SyntaxKind.ClassExpression) {
|
||||
const variableDeclaration = functionDeclaration.parent.parent;
|
||||
return [variableDeclaration.name, ctrKeyword];
|
||||
}
|
||||
return [ctrKeyword];
|
||||
case SyntaxKind.ArrowFunction:
|
||||
return [functionDeclaration.parent.name];
|
||||
case SyntaxKind.FunctionExpression:
|
||||
if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name];
|
||||
return [functionDeclaration.parent.name];
|
||||
default:
|
||||
return Debug.assertNever(functionDeclaration);
|
||||
}
|
||||
}
|
||||
|
||||
type ValidParameterNodeArray = NodeArray<ValidParameterDeclaration>;
|
||||
|
||||
interface ValidVariableDeclaration extends VariableDeclaration {
|
||||
name: Identifier;
|
||||
type: undefined;
|
||||
}
|
||||
|
||||
interface ValidConstructor extends ConstructorDeclaration {
|
||||
parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: ValidVariableDeclaration });
|
||||
parameters: NodeArray<ValidParameterDeclaration>;
|
||||
body: FunctionBody;
|
||||
}
|
||||
|
||||
interface ValidFunction extends FunctionDeclaration {
|
||||
name: Identifier;
|
||||
parameters: NodeArray<ValidParameterDeclaration>;
|
||||
body: FunctionBody;
|
||||
}
|
||||
|
||||
interface ValidMethod extends MethodDeclaration {
|
||||
parameters: NodeArray<ValidParameterDeclaration>;
|
||||
body: FunctionBody;
|
||||
}
|
||||
|
||||
interface ValidFunctionExpression extends FunctionExpression {
|
||||
parent: ValidVariableDeclaration;
|
||||
parameters: NodeArray<ValidParameterDeclaration>;
|
||||
}
|
||||
|
||||
interface ValidArrowFunction extends ArrowFunction {
|
||||
parent: ValidVariableDeclaration;
|
||||
parameters: NodeArray<ValidParameterDeclaration>;
|
||||
}
|
||||
|
||||
type ValidFunctionDeclaration = ValidConstructor | ValidFunction | ValidMethod | ValidArrowFunction | ValidFunctionExpression;
|
||||
|
||||
interface ValidParameterDeclaration extends ParameterDeclaration {
|
||||
name: Identifier;
|
||||
modifiers: undefined;
|
||||
decorators: undefined;
|
||||
}
|
||||
|
||||
interface GroupedReferences {
|
||||
functionCalls: (CallExpression | NewExpression)[];
|
||||
declarations: Node[];
|
||||
classReferences?: ClassReferences;
|
||||
valid: boolean;
|
||||
}
|
||||
interface ClassReferences {
|
||||
accessExpressions: Node[];
|
||||
typeUsages: Node[];
|
||||
}
|
||||
}
|
||||
@@ -460,6 +460,12 @@ namespace ts.refactor {
|
||||
const oldImportsNeededByNewFile = new SymbolSet();
|
||||
const newFileImportsFromOldFile = new SymbolSet();
|
||||
|
||||
const containsJsx = find(toMove, statement => !!(statement.transformFlags & TransformFlags.ContainsJsx));
|
||||
const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx);
|
||||
if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code)
|
||||
oldImportsNeededByNewFile.add(jsxNamespaceSymbol);
|
||||
}
|
||||
|
||||
for (const statement of toMove) {
|
||||
forEachTopLevelDeclaration(statement, decl => {
|
||||
movedSymbols.add(Debug.assertDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
|
||||
@@ -485,6 +491,11 @@ namespace ts.refactor {
|
||||
for (const statement of oldFile.statements) {
|
||||
if (contains(toMove, statement)) continue;
|
||||
|
||||
// jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile.
|
||||
if (jsxNamespaceSymbol && !!(statement.transformFlags & TransformFlags.ContainsJsx)) {
|
||||
unusedImportsFromOldFile.delete(jsxNamespaceSymbol);
|
||||
}
|
||||
|
||||
forEachReference(statement, checker, symbol => {
|
||||
if (movedSymbols.has(symbol)) oldFileImportsFromNewFile.add(symbol);
|
||||
unusedImportsFromOldFile.delete(symbol);
|
||||
@@ -492,6 +503,23 @@ namespace ts.refactor {
|
||||
}
|
||||
|
||||
return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile };
|
||||
|
||||
function getJsxNamespaceSymbol(containsJsx: Node | undefined) {
|
||||
if (containsJsx === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const jsxNamespace = checker.getJsxNamespace(containsJsx);
|
||||
|
||||
// Strictly speaking, this could resolve to a symbol other than the JSX namespace.
|
||||
// This will produce erroneous output (probably, an incorrectly copied import) but
|
||||
// is expected to be very rare and easily reversible.
|
||||
const jsxNamespaceSymbol = checker.resolveName(jsxNamespace, containsJsx, SymbolFlags.Namespace, /*excludeGlobals*/ true);
|
||||
|
||||
return !!jsxNamespaceSymbol && some(jsxNamespaceSymbol.declarations, isInImport)
|
||||
? jsxNamespaceSymbol
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Below should all be utilities
|
||||
@@ -512,7 +540,7 @@ namespace ts.refactor {
|
||||
}
|
||||
function isVariableDeclarationInImport(decl: VariableDeclaration) {
|
||||
return isSourceFile(decl.parent.parent.parent) &&
|
||||
decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
|
||||
!!decl.initializer && isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
|
||||
}
|
||||
|
||||
function filterImport(i: SupportedImport, moduleSpecifier: StringLiteralLike, keep: (name: Identifier) => boolean): SupportedImportStatement | undefined {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/* @internal */
|
||||
namespace ts.Rename {
|
||||
export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number): RenameInfo {
|
||||
export function getRenameInfo(program: Program, sourceFile: SourceFile, position: number, options?: RenameInfoOptions): RenameInfo {
|
||||
const node = getTouchingPropertyName(sourceFile, position);
|
||||
const renameInfo = node && nodeIsEligibleForRename(node)
|
||||
? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))
|
||||
? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()), options)
|
||||
: undefined;
|
||||
return renameInfo || getRenameInfoError(Diagnostics.You_cannot_rename_this_element);
|
||||
}
|
||||
|
||||
function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean): RenameInfo | undefined {
|
||||
function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean, options?: RenameInfoOptions): RenameInfo | undefined {
|
||||
const symbol = typeChecker.getSymbolAtLocation(node);
|
||||
if (!symbol) return;
|
||||
// Only allow a symbol to be renamed if it actually has at least one declaration.
|
||||
@@ -26,7 +26,7 @@ namespace ts.Rename {
|
||||
}
|
||||
|
||||
if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) {
|
||||
return getRenameInfoForModule(node, sourceFile, symbol);
|
||||
return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined;
|
||||
}
|
||||
|
||||
const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node);
|
||||
|
||||
@@ -16,18 +16,20 @@ namespace ts {
|
||||
public pos: number;
|
||||
public end: number;
|
||||
public flags: NodeFlags;
|
||||
public modifierFlagsCache: ModifierFlags;
|
||||
public transformFlags: TransformFlags;
|
||||
public parent: Node;
|
||||
public symbol!: Symbol; // Actually optional, but it was too annoying to access `node.symbol!` everywhere since in many cases we know it must be defined
|
||||
public jsDoc?: JSDoc[];
|
||||
public original?: Node;
|
||||
public transformFlags: TransformFlags;
|
||||
private _children: Node[] | undefined;
|
||||
|
||||
constructor(kind: SyntaxKind, pos: number, end: number) {
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = NodeFlags.None;
|
||||
this.transformFlags = undefined!; // TODO: GH#18217
|
||||
this.modifierFlagsCache = ModifierFlags.None;
|
||||
this.transformFlags = TransformFlags.None;
|
||||
this.parent = undefined!;
|
||||
this.kind = kind;
|
||||
}
|
||||
@@ -200,16 +202,19 @@ namespace ts {
|
||||
public pos: number;
|
||||
public end: number;
|
||||
public flags: NodeFlags;
|
||||
public modifierFlagsCache: ModifierFlags;
|
||||
public transformFlags: TransformFlags;
|
||||
public parent: Node;
|
||||
public symbol!: Symbol;
|
||||
public jsDocComments?: JSDoc[];
|
||||
public transformFlags!: TransformFlags;
|
||||
|
||||
constructor(pos: number, end: number) {
|
||||
// Set properties in same order as NodeObject
|
||||
this.pos = pos;
|
||||
this.end = end;
|
||||
this.flags = NodeFlags.None;
|
||||
this.modifierFlagsCache = ModifierFlags.None;
|
||||
this.transformFlags = TransformFlags.None;
|
||||
this.parent = undefined!;
|
||||
}
|
||||
|
||||
@@ -1153,7 +1158,7 @@ namespace ts {
|
||||
function getValidSourceFile(fileName: string): SourceFile {
|
||||
const sourceFile = program.getSourceFile(fileName);
|
||||
if (!sourceFile) {
|
||||
throw new Error("Could not find file: '" + fileName + "'.");
|
||||
throw new Error(`Could not find sourceFile: '${fileName}' in ${program && JSON.stringify(program.getSourceFiles().map(f => f.fileName))}.`);
|
||||
}
|
||||
return sourceFile;
|
||||
}
|
||||
@@ -1549,7 +1554,7 @@ namespace ts {
|
||||
return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch);
|
||||
}
|
||||
|
||||
function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined {
|
||||
function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): RenameLocation[] | undefined {
|
||||
synchronizeHostData();
|
||||
const sourceFile = getValidSourceFile(fileName);
|
||||
const node = getTouchingPropertyName(sourceFile, position);
|
||||
@@ -1559,7 +1564,8 @@ namespace ts {
|
||||
({ fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(node.tagName, sourceFile) }));
|
||||
}
|
||||
else {
|
||||
return getReferencesWorker(node, position, { findInStrings, findInComments, isForRename: true }, FindAllReferences.toRenameLocation);
|
||||
return getReferencesWorker(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, isForRename: true },
|
||||
(entry, originalNode, checker) => FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1792,7 +1798,7 @@ namespace ts {
|
||||
const span = createTextSpanFromBounds(start, end);
|
||||
const formatContext = formatting.getFormatContext(formatOptions);
|
||||
|
||||
return flatMap(deduplicate(errorCodes, equateValues, compareValues), errorCode => {
|
||||
return flatMap(deduplicate<number>(errorCodes, equateValues, compareValues), errorCode => {
|
||||
cancellationToken.throwIfCancellationRequested();
|
||||
return codefix.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences });
|
||||
});
|
||||
@@ -2062,9 +2068,9 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function getRenameInfo(fileName: string, position: number): RenameInfo {
|
||||
function getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo {
|
||||
synchronizeHostData();
|
||||
return Rename.getRenameInfo(program, getValidSourceFile(fileName), position);
|
||||
return Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options);
|
||||
}
|
||||
|
||||
function getRefactorContext(file: SourceFile, positionOrRange: number | TextRange, preferences: UserPreferences, formatOptions?: FormatCodeSettings): RefactorContext {
|
||||
|
||||
@@ -164,13 +164,13 @@ namespace ts {
|
||||
* Returns a JSON-encoded value of the type:
|
||||
* { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } }
|
||||
*/
|
||||
getRenameInfo(fileName: string, position: number): string;
|
||||
getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): string;
|
||||
|
||||
/**
|
||||
* Returns a JSON-encoded value of the type:
|
||||
* { fileName: string, textSpan: { start: number, length: number } }[]
|
||||
*/
|
||||
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string;
|
||||
findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string;
|
||||
|
||||
/**
|
||||
* Returns a JSON-encoded value of the type:
|
||||
@@ -831,17 +831,17 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
public getRenameInfo(fileName: string, position: number): string {
|
||||
public getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): string {
|
||||
return this.forwardJSONCall(
|
||||
`getRenameInfo('${fileName}', ${position})`,
|
||||
() => this.languageService.getRenameInfo(fileName, position)
|
||||
() => this.languageService.getRenameInfo(fileName, position, options)
|
||||
);
|
||||
}
|
||||
|
||||
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string {
|
||||
public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): string {
|
||||
return this.forwardJSONCall(
|
||||
`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`,
|
||||
() => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments)
|
||||
`findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`,
|
||||
() => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -452,7 +452,7 @@ namespace ts.SignatureHelp {
|
||||
}
|
||||
|
||||
function getContainingArgumentInfo(node: Node, position: number, sourceFile: SourceFile, checker: TypeChecker, isManuallyInvoked: boolean): ArgumentListInfo | undefined {
|
||||
for (let n = node; isManuallyInvoked || (!isBlock(n) && !isSourceFile(n)); n = n.parent) {
|
||||
for (let n = node; !isSourceFile(n) && (isManuallyInvoked || !isBlock(n)); n = n.parent) {
|
||||
// If the node is not a subspan of its parent, this is a big problem.
|
||||
// There have been crashes that might be caused by this violation.
|
||||
Debug.assert(rangeContainsRange(n.parent, n), "Not a subspan", () => `Child: ${Debug.showSyntaxKind(n)}, parent: ${Debug.showSyntaxKind(n.parent)}`);
|
||||
@@ -559,14 +559,14 @@ namespace ts.SignatureHelp {
|
||||
const parameters = (typeParameters || emptyArray).map(t => createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer));
|
||||
const parameterParts = mapToDisplayParts(writer => {
|
||||
const thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)!] : [];
|
||||
const params = createNodeArray([...thisParameter, ...candidateSignature.parameters.map(param => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags)!)]);
|
||||
const params = createNodeArray([...thisParameter, ...checker.getExpandedParameters(candidateSignature).map(param => checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags)!)]);
|
||||
printer.writeList(ListFormat.CallExpressionArguments, params, sourceFile, writer);
|
||||
});
|
||||
return { isVariadic: false, parameters, prefix: [punctuationPart(SyntaxKind.LessThanToken)], suffix: [punctuationPart(SyntaxKind.GreaterThanToken), ...parameterParts] };
|
||||
}
|
||||
|
||||
function itemInfoForParameters(candidateSignature: Signature, checker: TypeChecker, enclosingDeclaration: Node, sourceFile: SourceFile): SignatureHelpItemInfo {
|
||||
const isVariadic = candidateSignature.hasRestParameter;
|
||||
const isVariadic = checker.hasEffectiveRestParameter(candidateSignature);
|
||||
const printer = createPrinter({ removeComments: true });
|
||||
const typeParameterParts = mapToDisplayParts(writer => {
|
||||
if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) {
|
||||
@@ -574,7 +574,7 @@ namespace ts.SignatureHelp {
|
||||
printer.writeList(ListFormat.TypeParameters, args, sourceFile, writer);
|
||||
}
|
||||
});
|
||||
const parameters = candidateSignature.parameters.map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer));
|
||||
const parameters = checker.getExpandedParameters(candidateSignature).map(p => createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer));
|
||||
return { isVariadic, parameters, prefix: [...typeParameterParts, punctuationPart(SyntaxKind.OpenParenToken)], suffix: [punctuationPart(SyntaxKind.CloseParenToken)] };
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ namespace ts.Completions.StringCompletions {
|
||||
case Extension.Jsx: return ScriptElementKindModifier.jsxModifier;
|
||||
case Extension.Ts: return ScriptElementKindModifier.tsModifier;
|
||||
case Extension.Tsx: return ScriptElementKindModifier.tsxModifier;
|
||||
case Extension.TsBuildInfo: return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`);
|
||||
case undefined: return ScriptElementKindModifier.none;
|
||||
default:
|
||||
return Debug.assertNever(extension);
|
||||
|
||||
@@ -310,7 +310,7 @@ namespace ts.SymbolDisplay {
|
||||
displayParts.push(spacePart());
|
||||
addFullSymbolName(symbol);
|
||||
}
|
||||
if (symbolFlags & SymbolFlags.Module) {
|
||||
if (symbolFlags & SymbolFlags.Module && !isThisExpression) {
|
||||
prefixNextMeaning();
|
||||
const declaration = getDeclarationOfKind<ModuleDeclaration>(symbol, SyntaxKind.ModuleDeclaration);
|
||||
const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier;
|
||||
|
||||
+42
-29
@@ -28,17 +28,27 @@ namespace ts.textChanges {
|
||||
}
|
||||
|
||||
export interface ConfigurableStart {
|
||||
/** True to use getStart() (NB, not getFullStart()) without adjustment. */
|
||||
useNonAdjustedStartPosition?: boolean;
|
||||
leadingTriviaOption?: LeadingTriviaOption;
|
||||
}
|
||||
export interface ConfigurableEnd {
|
||||
/** True to use getEnd() without adjustment. */
|
||||
useNonAdjustedEndPosition?: boolean;
|
||||
trailingTriviaOption?: TrailingTriviaOption;
|
||||
}
|
||||
|
||||
export enum Position {
|
||||
FullStart,
|
||||
Start
|
||||
export enum LeadingTriviaOption {
|
||||
/** Exclude all leading trivia (use getStart()) */
|
||||
Exclude,
|
||||
/** Include leading trivia and,
|
||||
* if there are no line breaks between the node and the previous token,
|
||||
* include all trivia between the node and the previous token
|
||||
*/
|
||||
IncludeAll,
|
||||
}
|
||||
|
||||
export enum TrailingTriviaOption {
|
||||
/** Exclude all trailing trivia (use getEnd()) */
|
||||
Exclude,
|
||||
/** Include trailing trivia */
|
||||
Include,
|
||||
}
|
||||
|
||||
function skipWhitespacesAndLineBreaks(text: string, start: number) {
|
||||
@@ -68,13 +78,14 @@ namespace ts.textChanges {
|
||||
* Usually leading trivia of the variable declaration 'y' should not include trailing trivia (whitespace, comment 'this is x' and newline) from the preceding
|
||||
* variable declaration and trailing trivia for 'y' should include (whitespace, comment 'this is y', newline).
|
||||
* By default when removing nodes we adjust start and end positions to respect specification of the trivia above.
|
||||
* If pos\end should be interpreted literally 'useNonAdjustedStartPosition' or 'useNonAdjustedEndPosition' should be set to true
|
||||
* If pos\end should be interpreted literally (that is, withouth including leading and trailing trivia), `leadingTriviaOption` should be set to `LeadingTriviaOption.Exclude`
|
||||
* and `trailingTriviaOption` to `TrailingTriviaOption.Exclude`.
|
||||
*/
|
||||
export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {}
|
||||
|
||||
export const useNonAdjustedPositions: ConfigurableStartEnd = {
|
||||
useNonAdjustedStartPosition: true,
|
||||
useNonAdjustedEndPosition: true,
|
||||
const useNonAdjustedPositions: ConfigurableStartEnd = {
|
||||
leadingTriviaOption: LeadingTriviaOption.Exclude,
|
||||
trailingTriviaOption: TrailingTriviaOption.Exclude,
|
||||
};
|
||||
|
||||
export interface InsertNodeOptions {
|
||||
@@ -143,11 +154,12 @@ namespace ts.textChanges {
|
||||
}
|
||||
|
||||
function getAdjustedRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd): TextRange {
|
||||
return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
|
||||
return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
|
||||
}
|
||||
|
||||
function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart, position: Position) {
|
||||
if (options.useNonAdjustedStartPosition) {
|
||||
function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart) {
|
||||
const { leadingTriviaOption } = options;
|
||||
if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
|
||||
return node.getStart(sourceFile);
|
||||
}
|
||||
const fullStart = node.getFullStart();
|
||||
@@ -165,7 +177,7 @@ namespace ts.textChanges {
|
||||
// fullstart
|
||||
// when b is replaced - we usually want to keep the leading trvia
|
||||
// when b is deleted - we delete it
|
||||
return position === Position.Start ? start : fullStart;
|
||||
return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
|
||||
}
|
||||
// get start position of the line following the line that contains fullstart position
|
||||
// (but only if the fullstart isn't the very beginning of the file)
|
||||
@@ -178,11 +190,12 @@ namespace ts.textChanges {
|
||||
|
||||
function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd) {
|
||||
const { end } = node;
|
||||
if (options.useNonAdjustedEndPosition || isExpression(node)) {
|
||||
const { trailingTriviaOption } = options;
|
||||
if (trailingTriviaOption === TrailingTriviaOption.Exclude || (isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
|
||||
return end;
|
||||
}
|
||||
const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
|
||||
return newEnd !== end && isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
|
||||
return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
|
||||
? newEnd
|
||||
: end;
|
||||
}
|
||||
@@ -240,15 +253,15 @@ namespace ts.textChanges {
|
||||
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
|
||||
}
|
||||
|
||||
public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = {}): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
|
||||
public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
|
||||
const endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
|
||||
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
|
||||
}
|
||||
|
||||
public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = {}): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
|
||||
const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
|
||||
public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
|
||||
const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
|
||||
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
|
||||
}
|
||||
|
||||
@@ -307,7 +320,7 @@ namespace ts.textChanges {
|
||||
}
|
||||
|
||||
public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false): void {
|
||||
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
|
||||
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
|
||||
}
|
||||
|
||||
public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void {
|
||||
@@ -427,7 +440,7 @@ namespace ts.textChanges {
|
||||
}
|
||||
|
||||
public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void {
|
||||
const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}, Position.Start);
|
||||
const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {});
|
||||
this.insertNodeAt(sourceFile, pos, newNode, {
|
||||
prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
|
||||
suffix: this.newLineCharacter
|
||||
@@ -736,7 +749,7 @@ namespace ts.textChanges {
|
||||
|
||||
// find first non-whitespace position in the leading trivia of the node
|
||||
function startPositionToDeleteNodeInList(sourceFile: SourceFile, node: Node): number {
|
||||
return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
|
||||
return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
|
||||
}
|
||||
|
||||
function getClassOrObjectBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, sourceFile: SourceFile): [number, number] {
|
||||
@@ -1090,7 +1103,7 @@ namespace ts.textChanges {
|
||||
case SyntaxKind.ImportDeclaration:
|
||||
deleteNode(changes, sourceFile, node,
|
||||
// For first import, leave header comment in place
|
||||
node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
|
||||
node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
|
||||
break;
|
||||
|
||||
case SyntaxKind.BindingElement:
|
||||
@@ -1134,7 +1147,7 @@ namespace ts.textChanges {
|
||||
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
|
||||
}
|
||||
else {
|
||||
deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { useNonAdjustedEndPosition: true } : undefined);
|
||||
deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1213,8 +1226,8 @@ namespace ts.textChanges {
|
||||
|
||||
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
|
||||
// Exported for tests only! (TODO: improve tests to not need this)
|
||||
export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = {}): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
|
||||
export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
|
||||
const startPosition = getAdjustedStartPosition(sourceFile, node, options);
|
||||
const endPosition = getAdjustedEndPosition(sourceFile, node, options);
|
||||
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@
|
||||
"codefixes/fixClassDoesntImplementInheritedAbstractMember.ts",
|
||||
"codefixes/fixClassSuperMustPrecedeThisAccess.ts",
|
||||
"codefixes/fixConstructorForDerivedNeedSuperCall.ts",
|
||||
"codefixes/fixEnableExperimentalDecorators.ts",
|
||||
"codefixes/fixExtendsInterfaceBecomesImplements.ts",
|
||||
"codefixes/fixForgottenThisPropertyAccess.ts",
|
||||
"codefixes/fixUnusedIdentifier.ts",
|
||||
@@ -83,6 +84,7 @@
|
||||
"refactors/generateGetAccessorAndSetAccessor.ts",
|
||||
"refactors/moveToNewFile.ts",
|
||||
"refactors/addOrRemoveBracesToArrowFunction.ts",
|
||||
"refactors/convertParamsToDestructuredObject.ts",
|
||||
"services.ts",
|
||||
"breakpoints.ts",
|
||||
"transform.ts",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user