add ability to call self-signed or invalid certificate clients

This commit is contained in:
Joel Male
2021-02-26 13:58:33 +10:00
parent 528d756289
commit 9380ee26ff
3852 changed files with 253796 additions and 137756 deletions
+24 -8
View File
@@ -1,8 +1,24 @@
import * as ts from 'typescript';
export declare function endsControlFlow(statement: ts.Statement | ts.BlockLike): boolean;
export declare type ControlFlowStatement = ts.BreakStatement | ts.ContinueStatement | ts.ReturnStatement | ts.ThrowStatement;
export interface ControlFlowEnd {
readonly statements: ReadonlyArray<ControlFlowStatement>;
readonly end: boolean;
}
export declare function getControlFlowEnd(statement: ts.Statement | ts.BlockLike): ControlFlowEnd;
import * as ts from 'typescript';
export declare function endsControlFlow(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): boolean;
export declare type ControlFlowStatement = ts.BreakStatement | ts.ContinueStatement | ts.ReturnStatement | ts.ThrowStatement | ts.ExpressionStatement & {
expression: ts.CallExpression;
};
export interface ControlFlowEnd {
/**
* Statements that may end control flow at this statement.
* Does not contain control flow statements that jump only inside the statement, for example a `continue` inside a nested for loop.
*/
readonly statements: ReadonlyArray<ControlFlowStatement>;
/** `true` if control flow definitely ends. */
readonly end: boolean;
}
export declare function getControlFlowEnd(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): ControlFlowEnd;
export declare enum SignatureEffect {
Never = 1,
Asserts = 2
}
/**
* Dermines whether a top level CallExpression has a control flow effect according to TypeScript's rules.
* This handles functions returning `never` and `asserts`.
*/
export declare function callExpressionAffectsControlFlow(node: ts.CallExpression, checker: ts.TypeChecker): SignatureEffect | undefined;
+296 -171
View File
@@ -1,171 +1,296 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const node_1 = require("../typeguard/node");
function endsControlFlow(statement) {
return getControlFlowEnd(statement).end;
}
exports.endsControlFlow = endsControlFlow;
const defaultControlFlowEnd = { statements: [], end: false };
function getControlFlowEnd(statement) {
return node_1.isBlockLike(statement) ? handleBlock(statement) : getControlFlowEndWorker(statement);
}
exports.getControlFlowEnd = getControlFlowEnd;
function getControlFlowEndWorker(statement) {
switch (statement.kind) {
case ts.SyntaxKind.ReturnStatement:
case ts.SyntaxKind.ThrowStatement:
case ts.SyntaxKind.ContinueStatement:
case ts.SyntaxKind.BreakStatement:
return { statements: [statement], end: true };
case ts.SyntaxKind.Block:
return handleBlock(statement);
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.WhileStatement:
return handleForAndWhileStatement(statement);
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.ForInStatement:
return handleForInOrOfStatement(statement);
case ts.SyntaxKind.DoStatement:
return matchBreakOrContinue(getControlFlowEndWorker(statement.statement), node_1.isBreakOrContinueStatement);
case ts.SyntaxKind.IfStatement:
return handleIfStatement(statement);
case ts.SyntaxKind.SwitchStatement:
return matchBreakOrContinue(handleSwitchStatement(statement), node_1.isBreakStatement);
case ts.SyntaxKind.TryStatement:
return handleTryStatement(statement);
case ts.SyntaxKind.LabeledStatement:
return matchLabel(getControlFlowEndWorker(statement.statement), statement.label);
case ts.SyntaxKind.WithStatement:
return getControlFlowEndWorker(statement.statement);
default:
return defaultControlFlowEnd;
}
}
function handleBlock(statement) {
const result = { statements: [], end: false };
for (const s of statement.statements) {
const current = getControlFlowEndWorker(s);
result.statements.push(...current.statements);
if (current.end) {
result.end = true;
break;
}
}
return result;
}
function handleForInOrOfStatement(statement) {
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement), node_1.isBreakOrContinueStatement);
end.end = false;
return end;
}
function handleForAndWhileStatement(statement) {
const constantCondition = statement.kind === ts.SyntaxKind.WhileStatement
? getConstantCondition(statement.expression)
: statement.condition === undefined || getConstantCondition(statement.condition);
if (constantCondition === false)
return defaultControlFlowEnd;
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement), node_1.isBreakOrContinueStatement);
if (constantCondition === undefined)
end.end = false;
return end;
}
function getConstantCondition(node) {
switch (node.kind) {
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
default:
return;
}
}
function handleIfStatement(node) {
switch (getConstantCondition(node.expression)) {
case true:
return getControlFlowEndWorker(node.thenStatement);
case false:
return node.elseStatement === undefined
? defaultControlFlowEnd
: getControlFlowEndWorker(node.elseStatement);
}
const then = getControlFlowEndWorker(node.thenStatement);
if (node.elseStatement === undefined)
return {
statements: then.statements,
end: false,
};
const elze = getControlFlowEndWorker(node.elseStatement);
return {
statements: [...then.statements, ...elze.statements],
end: then.end && elze.end,
};
}
function handleSwitchStatement(node) {
let hasDefault = false;
const result = {
statements: [],
end: false,
};
for (const clause of node.caseBlock.clauses) {
if (clause.kind === ts.SyntaxKind.DefaultClause)
hasDefault = true;
const current = handleBlock(clause);
result.end = current.end;
result.statements.push(...current.statements);
}
if (!hasDefault)
result.end = false;
return result;
}
function handleTryStatement(node) {
let finallyResult;
if (node.finallyBlock !== undefined) {
finallyResult = handleBlock(node.finallyBlock);
if (finallyResult.end)
return finallyResult;
}
const tryResult = handleBlock(node.tryBlock);
if (node.catchClause === undefined)
return { statements: finallyResult.statements.concat(tryResult.statements), end: tryResult.end };
const catchResult = handleBlock(node.catchClause.block);
return {
statements: tryResult.statements
.filter((s) => s.kind !== ts.SyntaxKind.ThrowStatement)
.concat(catchResult.statements, finallyResult === undefined ? [] : finallyResult.statements),
end: tryResult.end && catchResult.end,
};
}
function matchBreakOrContinue(current, pred) {
const result = {
statements: [],
end: current.end,
};
for (const statement of current.statements) {
if (pred(statement) && statement.label === undefined) {
result.end = false;
continue;
}
result.statements.push(statement);
}
return result;
}
function matchLabel(current, label) {
const result = {
statements: [],
end: current.end,
};
const labelText = label.text;
for (const statement of current.statements) {
switch (statement.kind) {
case ts.SyntaxKind.BreakStatement:
case ts.SyntaxKind.ContinueStatement:
if (statement.label !== undefined && statement.label.text === labelText) {
result.end = false;
continue;
}
}
result.statements.push(statement);
}
return result;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callExpressionAffectsControlFlow = exports.SignatureEffect = exports.getControlFlowEnd = exports.endsControlFlow = void 0;
const ts = require("typescript");
const node_1 = require("../typeguard/node");
const util_1 = require("./util");
function endsControlFlow(statement, checker) {
return getControlFlowEnd(statement, checker).end;
}
exports.endsControlFlow = endsControlFlow;
const defaultControlFlowEnd = { statements: [], end: false };
function getControlFlowEnd(statement, checker) {
return node_1.isBlockLike(statement) ? handleBlock(statement, checker) : getControlFlowEndWorker(statement, checker);
}
exports.getControlFlowEnd = getControlFlowEnd;
function getControlFlowEndWorker(statement, checker) {
switch (statement.kind) {
case ts.SyntaxKind.ReturnStatement:
case ts.SyntaxKind.ThrowStatement:
case ts.SyntaxKind.ContinueStatement:
case ts.SyntaxKind.BreakStatement:
return { statements: [statement], end: true };
case ts.SyntaxKind.Block:
return handleBlock(statement, checker);
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.WhileStatement:
return handleForAndWhileStatement(statement, checker);
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.ForInStatement:
return handleForInOrOfStatement(statement, checker);
case ts.SyntaxKind.DoStatement:
return matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
case ts.SyntaxKind.IfStatement:
return handleIfStatement(statement, checker);
case ts.SyntaxKind.SwitchStatement:
return matchBreakOrContinue(handleSwitchStatement(statement, checker), node_1.isBreakStatement);
case ts.SyntaxKind.TryStatement:
return handleTryStatement(statement, checker);
case ts.SyntaxKind.LabeledStatement:
return matchLabel(getControlFlowEndWorker(statement.statement, checker), statement.label);
case ts.SyntaxKind.WithStatement:
return getControlFlowEndWorker(statement.statement, checker);
case ts.SyntaxKind.ExpressionStatement:
if (checker === undefined)
return defaultControlFlowEnd;
return handleExpressionStatement(statement, checker);
default:
return defaultControlFlowEnd;
}
}
function handleBlock(statement, checker) {
const result = { statements: [], end: false };
for (const s of statement.statements) {
const current = getControlFlowEndWorker(s, checker);
result.statements.push(...current.statements);
if (current.end) {
result.end = true;
break;
}
}
return result;
}
function handleForInOrOfStatement(statement, checker) {
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
end.end = false; // loop body is guaranteed to be executed
return end;
}
function handleForAndWhileStatement(statement, checker) {
const constantCondition = statement.kind === ts.SyntaxKind.WhileStatement
? getConstantCondition(statement.expression)
: statement.condition === undefined || getConstantCondition(statement.condition);
if (constantCondition === false)
return defaultControlFlowEnd; // loop body is never executed
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
if (constantCondition === undefined)
end.end = false; // can't be sure that loop body is executed at all
return end;
}
/** Simply detects `true` and `false` in conditions. That matches TypeScript's behavior. */
function getConstantCondition(node) {
switch (node.kind) {
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
default:
return;
}
}
function handleIfStatement(node, checker) {
switch (getConstantCondition(node.expression)) {
case true:
// else branch is never executed
return getControlFlowEndWorker(node.thenStatement, checker);
case false:
// then branch is never executed
return node.elseStatement === undefined
? defaultControlFlowEnd
: getControlFlowEndWorker(node.elseStatement, checker);
}
const then = getControlFlowEndWorker(node.thenStatement, checker);
if (node.elseStatement === undefined)
return {
statements: then.statements,
end: false,
};
const elze = getControlFlowEndWorker(node.elseStatement, checker);
return {
statements: [...then.statements, ...elze.statements],
end: then.end && elze.end,
};
}
function handleSwitchStatement(node, checker) {
let hasDefault = false;
const result = {
statements: [],
end: false,
};
for (const clause of node.caseBlock.clauses) {
if (clause.kind === ts.SyntaxKind.DefaultClause)
hasDefault = true;
const current = handleBlock(clause, checker);
result.end = current.end;
result.statements.push(...current.statements);
}
result.end && (result.end = hasDefault || checker !== undefined && util_1.hasExhaustiveCaseClauses(node, checker));
return result;
}
function handleTryStatement(node, checker) {
let finallyResult;
if (node.finallyBlock !== undefined) {
finallyResult = handleBlock(node.finallyBlock, checker);
// if 'finally' always ends control flow, we are not interested in any jump statements from 'try' or 'catch'
if (finallyResult.end)
return finallyResult;
}
const tryResult = handleBlock(node.tryBlock, checker);
if (node.catchClause === undefined)
return { statements: finallyResult.statements.concat(tryResult.statements), end: tryResult.end };
const catchResult = handleBlock(node.catchClause.block, checker);
return {
statements: tryResult.statements
// remove all throw statements and throwing function calls from the list of control flow statements inside tryBlock
.filter((s) => s.kind !== ts.SyntaxKind.ThrowStatement && s.kind !== ts.SyntaxKind.ExpressionStatement)
.concat(catchResult.statements, finallyResult === undefined ? [] : finallyResult.statements),
end: tryResult.end && catchResult.end, // only ends control flow if try AND catch definitely end control flow
};
}
/** Dotted name as TypeScript requires it for assertion signatures to affect control flow. */
function isDottedNameWithExplicitTypeAnnotation(node, checker) {
while (true) {
switch (node.kind) {
case ts.SyntaxKind.Identifier: {
const symbol = checker.getExportSymbolOfSymbol(checker.getSymbolAtLocation(node));
return isExplicitlyTypedSymbol(util_1.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : symbol, checker);
}
case ts.SyntaxKind.ThisKeyword:
return isExplicitlyTypedThis(node);
case ts.SyntaxKind.SuperKeyword:
return true;
case ts.SyntaxKind.PropertyAccessExpression:
if (!isExplicitlyTypedSymbol(checker.getSymbolAtLocation(node), checker))
return false;
// falls through
case ts.SyntaxKind.ParenthesizedExpression:
node = node.expression;
continue;
default:
return false;
}
}
}
function isExplicitlyTypedSymbol(symbol, checker) {
if (symbol === undefined)
return false;
if (util_1.isSymbolFlagSet(symbol, ts.SymbolFlags.Function | ts.SymbolFlags.Method | ts.SymbolFlags.Class | ts.SymbolFlags.ValueModule))
return true;
if (!util_1.isSymbolFlagSet(symbol, ts.SymbolFlags.Variable | ts.SymbolFlags.Property))
return false;
if (symbol.valueDeclaration === undefined)
return false;
if (declarationHasExplicitTypeAnnotation(symbol.valueDeclaration))
return true;
return node_1.isVariableDeclaration(symbol.valueDeclaration) &&
symbol.valueDeclaration.parent.parent.kind === ts.SyntaxKind.ForOfStatement &&
isDottedNameWithExplicitTypeAnnotation(symbol.valueDeclaration.parent.parent.expression, checker);
}
function declarationHasExplicitTypeAnnotation(node) {
if (ts.isJSDocPropertyLikeTag(node))
return node.typeExpression !== undefined;
return (node_1.isVariableDeclaration(node) ||
node_1.isParameterDeclaration(node) ||
node_1.isPropertyDeclaration(node) ||
node_1.isPropertySignature(node)) && (util_1.isNodeFlagSet(node, ts.NodeFlags.JavaScriptFile)
? ts.getJSDocType(node)
: node.type) !== undefined;
}
function isExplicitlyTypedThis(node) {
var _a;
do {
node = node.parent;
if (node_1.isDecorator(node)) {
// `this` in decorators always resolves outside of the containing class
if (node.parent.kind === ts.SyntaxKind.Parameter && node_1.isClassLikeDeclaration(node.parent.parent.parent)) {
node = node.parent.parent.parent.parent;
}
else if (node_1.isClassLikeDeclaration(node.parent.parent)) {
node = node.parent.parent.parent;
}
else if (node_1.isClassLikeDeclaration(node.parent)) {
node = node.parent.parent;
}
}
} while (util_1.isFunctionScopeBoundary(node) !== 1 /* Function */ || node.kind === ts.SyntaxKind.ArrowFunction);
return util_1.isFunctionWithBody(node) &&
(util_1.isNodeFlagSet(node, ts.NodeFlags.JavaScriptFile)
? ((_a = ts.getJSDocThisTag(node)) === null || _a === void 0 ? void 0 : _a.typeExpression) !== undefined
: node.parameters.length !== 0 && util_1.isThisParameter(node.parameters[0]) && node.parameters[0].type !== undefined) ||
node_1.isClassLikeDeclaration(node.parent);
}
var SignatureEffect;
(function (SignatureEffect) {
SignatureEffect[SignatureEffect["Never"] = 1] = "Never";
SignatureEffect[SignatureEffect["Asserts"] = 2] = "Asserts";
})(SignatureEffect = exports.SignatureEffect || (exports.SignatureEffect = {}));
/**
* Dermines whether a top level CallExpression has a control flow effect according to TypeScript's rules.
* This handles functions returning `never` and `asserts`.
*/
function callExpressionAffectsControlFlow(node, checker) {
var _a, _b, _c;
if (!node_1.isExpressionStatement(node.parent) ||
ts.isOptionalChain(node) ||
!isDottedNameWithExplicitTypeAnnotation(node.expression, checker))
return;
const signature = checker.getResolvedSignature(node);
if ((signature === null || signature === void 0 ? void 0 : signature.declaration) === undefined)
return;
const typeNode = ts.isJSDocSignature(signature.declaration)
? (_b = (_a = signature.declaration.type) === null || _a === void 0 ? void 0 : _a.typeExpression) === null || _b === void 0 ? void 0 : _b.type
: (_c = signature.declaration.type) !== null && _c !== void 0 ? _c : (util_1.isNodeFlagSet(signature.declaration, ts.NodeFlags.JavaScriptFile)
? ts.getJSDocReturnType(signature.declaration)
: undefined);
if (typeNode === undefined)
return;
if (node_1.isTypePredicateNode(typeNode) && typeNode.assertsModifier !== undefined)
return 2 /* Asserts */;
return util_1.isTypeFlagSet(checker.getTypeFromTypeNode(typeNode), ts.TypeFlags.Never) ? 1 /* Never */ : undefined;
}
exports.callExpressionAffectsControlFlow = callExpressionAffectsControlFlow;
function handleExpressionStatement(node, checker) {
if (!node_1.isCallExpression(node.expression))
return defaultControlFlowEnd;
switch (callExpressionAffectsControlFlow(node.expression, checker)) {
case 2 /* Asserts */:
return { statements: [node], end: false };
case 1 /* Never */:
return { statements: [node], end: true };
case undefined:
return defaultControlFlowEnd;
}
}
function matchBreakOrContinue(current, pred) {
const result = {
statements: [],
end: current.end,
};
for (const statement of current.statements) {
if (pred(statement) && statement.label === undefined) {
result.end = false;
continue;
}
result.statements.push(statement);
}
return result;
}
function matchLabel(current, label) {
const result = {
statements: [],
end: current.end,
};
const labelText = label.text;
for (const statement of current.statements) {
switch (statement.kind) {
case ts.SyntaxKind.BreakStatement:
case ts.SyntaxKind.ContinueStatement:
if (statement.label !== undefined && statement.label.text === labelText) {
result.end = false;
continue;
}
}
result.statements.push(statement);
}
return result;
}
//# sourceMappingURL=control-flow.js.map
File diff suppressed because one or more lines are too long
+33 -20
View File
@@ -1,20 +1,33 @@
import * as ts from 'typescript';
export interface NodeWrap {
node: ts.Node;
kind: ts.SyntaxKind;
children: NodeWrap[];
next?: NodeWrap;
skip?: NodeWrap;
parent?: NodeWrap;
}
export interface WrappedAst extends NodeWrap {
node: ts.SourceFile;
next: NodeWrap;
skip: undefined;
parent: undefined;
}
export interface ConvertedAst {
wrapped: WrappedAst;
flat: ReadonlyArray<ts.Node>;
}
export declare function convertAst(sourceFile: ts.SourceFile): ConvertedAst;
import * as ts from 'typescript';
/** Wraps an AST node. Can be used as a tree using `children` or a linked list using `next` and `skip`. */
export interface NodeWrap {
/** The real AST node. */
node: ts.Node;
/** The SyntaxKind of `node`. */
kind: ts.SyntaxKind;
/** All immediate children of `node` that would be visited by `ts.forEachChild(node, cb)`. */
children: NodeWrap[];
/** Link to the next NodeWrap, depth-first. */
next?: NodeWrap;
/** Link to the next NodeWrap skipping all children of the current node. */
skip?: NodeWrap;
/** Link to the parent NodeWrap */
parent?: NodeWrap;
}
export interface WrappedAst extends NodeWrap {
node: ts.SourceFile;
next: NodeWrap;
skip: undefined;
parent: undefined;
}
export interface ConvertedAst {
/** nodes wrapped in a data structure with useful links */
wrapped: WrappedAst;
/** depth-first array of all nodes excluding SourceFile */
flat: ReadonlyArray<ts.Node>;
}
/**
* Takes a `ts.SourceFile` and creates data structures that are easier (or more performant) to traverse.
* Note that there is only a performance gain if you can reuse these structures. It's not recommended for one-time AST walks.
*/
export declare function convertAst(sourceFile: ts.SourceFile): ConvertedAst;
+79 -47
View File
@@ -1,47 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const util_1 = require("./util");
function convertAst(sourceFile) {
const wrapped = {
node: sourceFile,
parent: undefined,
kind: ts.SyntaxKind.SourceFile,
children: [],
next: undefined,
skip: undefined,
};
const flat = [];
let current = wrapped;
let previous = current;
ts.forEachChild(sourceFile, function wrap(node) {
flat.push(node);
const parent = current;
previous.next = current = {
node,
parent,
kind: node.kind,
children: [],
next: undefined,
skip: undefined,
};
if (previous !== parent)
setSkip(previous, current);
previous = current;
parent.children.push(current);
if (util_1.isNodeKind(node.kind))
ts.forEachChild(node, wrap);
current = parent;
});
return {
wrapped,
flat,
};
}
exports.convertAst = convertAst;
function setSkip(node, skip) {
do {
node.skip = skip;
node = node.parent;
} while (node !== skip.parent);
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertAst = void 0;
const ts = require("typescript");
const util_1 = require("./util");
/**
* Takes a `ts.SourceFile` and creates data structures that are easier (or more performant) to traverse.
* Note that there is only a performance gain if you can reuse these structures. It's not recommended for one-time AST walks.
*/
function convertAst(sourceFile) {
const wrapped = {
node: sourceFile,
parent: undefined,
kind: ts.SyntaxKind.SourceFile,
children: [],
next: undefined,
skip: undefined,
};
const flat = [];
let current = wrapped;
function collectChildren(node) {
current.children.push({
node,
parent: current,
kind: node.kind,
children: [],
next: undefined,
skip: undefined,
});
}
const stack = [];
while (true) {
if (current.children.length === 0) {
ts.forEachChild(current.node, collectChildren);
if (current.children.length === 0) {
current = current.parent; // nothing to do here, go back to parent
}
else {
// recurse into first child
const firstChild = current.children[0];
current.next = firstChild;
flat.push(firstChild.node);
if (util_1.isNodeKind(firstChild.kind))
current = firstChild;
stack.push(1); // set index in stack so we know where to continue processing children
}
}
else {
const index = stack[stack.length - 1];
if (index < current.children.length) { // handles 2nd child to the last
const currentChild = current.children[index];
flat.push(currentChild.node);
let previous = current.children[index - 1];
while (previous.children.length !== 0) {
previous.skip = currentChild;
previous = previous.children[previous.children.length - 1];
}
previous.skip = previous.next = currentChild;
++stack[stack.length - 1];
if (util_1.isNodeKind(currentChild.kind))
current = currentChild; // recurse into child
}
else {
// done on this node
if (stack.length === 1)
break;
// remove index from stack and go back to parent
stack.pop();
current = current.parent;
}
}
}
return {
wrapped,
flat,
};
}
exports.convertAst = convertAst;
//# sourceMappingURL=convert-ast.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"convert-ast.js","sourceRoot":"","sources":["convert-ast.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,iCAAoC;AAgCpC;;;GAGG;AACH,SAAgB,UAAU,CAAC,UAAyB;IAChD,MAAM,OAAO,GAAe;QACxB,IAAI,EAAE,UAAU;QAChB,MAAM,EAAE,SAAS;QACjB,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU;QAC9B,QAAQ,EAAE,EAAE;QACZ,IAAI,EAAO,SAAS;QACpB,IAAI,EAAE,SAAS;KAClB,CAAC;IACF,MAAM,IAAI,GAAc,EAAE,CAAC;IAC3B,IAAI,OAAO,GAAa,OAAO,CAAC;IAEhC,SAAS,eAAe,CAAC,IAAa;QAClC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;YAClB,IAAI;YACJ,MAAM,EAAE,OAAO;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,QAAQ,EAAE,EAAE;YACZ,IAAI,EAAE,SAAS;YACf,IAAI,EAAE,SAAS;SAClB,CAAC,CAAC;IACP,CAAC;IACD,MAAM,KAAK,GAAG,EAAE,CAAC;IACjB,OAAO,IAAI,EAAE;QACT,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;YAC/B,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;YAC/C,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC/B,OAAO,GAAG,OAAO,CAAC,MAAO,CAAC,CAAC,wCAAwC;aACtE;iBAAM;gBACH,2BAA2B;gBAC3B,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,GAAG,UAAU,CAAC;gBAC1B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBAC3B,IAAI,iBAAU,CAAC,UAAU,CAAC,IAAI,CAAC;oBAC3B,OAAO,GAAG,UAAU,CAAC;gBACzB,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,sEAAsE;aACxF;SACJ;aAAM;YACH,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACtC,IAAI,KAAK,GAAG,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,gCAAgC;gBACnE,MAAM,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;gBAC7C,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC7B,IAAI,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;gBAC3C,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;oBACnC,QAAQ,CAAC,IAAI,GAAG,YAAY,CAAC;oBAC7B,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;iBAC9D;gBACD,QAAQ,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,GAAG,YAAY,CAAC;gBAC7C,EAAE,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBAC1B,IAAI,iBAAU,CAAC,YAAY,CAAC,IAAI,CAAC;oBAC7B,OAAO,GAAG,YAAY,CAAC,CAAC,qBAAqB;aACpD;iBAAM;gBACH,oBAAoB;gBACpB,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;oBAClB,MAAM;gBACV,gDAAgD;gBAChD,KAAK,CAAC,GAAG,EAAE,CAAC;gBACZ,OAAO,GAAG,OAAO,CAAC,MAAO,CAAC;aAC7B;SACJ;KACJ;IAED,OAAO;QACH,OAAO;QACP,IAAI;KACP,CAAC;AACN,CAAC;AAlED,gCAkEC"}
+5 -5
View File
@@ -1,5 +1,5 @@
export * from './util';
export * from './usage';
export * from './control-flow';
export * from './type';
export * from './convert-ast';
export * from './util';
export * from './usage';
export * from './control-flow';
export * from './type';
export * from './convert-ast';
+9 -8
View File
@@ -1,8 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./util"), exports);
tslib_1.__exportStar(require("./usage"), exports);
tslib_1.__exportStar(require("./control-flow"), exports);
tslib_1.__exportStar(require("./type"), exports);
tslib_1.__exportStar(require("./convert-ast"), exports);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./util"), exports);
tslib_1.__exportStar(require("./usage"), exports);
tslib_1.__exportStar(require("./control-flow"), exports);
tslib_1.__exportStar(require("./type"), exports);
tslib_1.__exportStar(require("./convert-ast"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;;AAAA,iDAAuB;AACvB,kDAAwB;AACxB,yDAA+B;AAC/B,iDAAuB;AACvB,wDAA8B"}
+34 -21
View File
@@ -1,21 +1,34 @@
import * as ts from 'typescript';
import { PropertyName } from './util';
export declare function isEmptyObjectType(type: ts.Type): type is ts.ObjectType;
export declare function removeOptionalityFromType(checker: ts.TypeChecker, type: ts.Type): ts.Type;
export declare function isTypeAssignableToNumber(checker: ts.TypeChecker, type: ts.Type): boolean;
export declare function isTypeAssignableToString(checker: ts.TypeChecker, type: ts.Type): boolean;
export declare function getCallSignaturesOfType(type: ts.Type): ReadonlyArray<ts.Signature>;
export declare function unionTypeParts(type: ts.Type): ts.Type[];
export declare function intersectionTypeParts(type: ts.Type): ts.Type[];
export declare function someTypePart(type: ts.Type, predicate: (t: ts.Type) => t is ts.UnionOrIntersectionType, cb: (t: ts.Type) => boolean): boolean;
export declare function isThenableType(checker: ts.TypeChecker, node: ts.Node, type: ts.Type): boolean;
export declare function isThenableType(checker: ts.TypeChecker, node: ts.Expression, type?: ts.Type): boolean;
export declare function isFalsyType(type: ts.Type): boolean;
export declare function isBooleanLiteralType(type: ts.Type, literal: boolean): boolean;
export declare function getPropertyOfType(type: ts.Type, name: ts.__String): ts.Symbol | undefined;
export declare function isPropertyReadonlyInType(type: ts.Type, name: ts.__String, checker: ts.TypeChecker): boolean;
export declare function symbolHasReadonlyDeclaration(symbol: ts.Symbol, checker: ts.TypeChecker): boolean;
export declare function getPropertyNameFromType(type: ts.Type): PropertyName | undefined;
export declare function getConstructorTypeOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Type;
export declare function getInstanceTypeOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Type;
export declare function getIteratorYieldResultFromIteratorResult(type: ts.Type, node: ts.Node, checker: ts.TypeChecker): ts.Type;
import * as ts from 'typescript';
import { PropertyName } from './util';
export declare function isEmptyObjectType(type: ts.Type): type is ts.ObjectType;
export declare function removeOptionalityFromType(checker: ts.TypeChecker, type: ts.Type): ts.Type;
export declare function removeOptionalChainingUndefinedMarkerType(checker: ts.TypeChecker, type: ts.Type): ts.Type;
export declare function isOptionalChainingUndefinedMarkerType(checker: ts.TypeChecker, t: ts.Type): boolean;
export declare function isTypeAssignableToNumber(checker: ts.TypeChecker, type: ts.Type): boolean;
export declare function isTypeAssignableToString(checker: ts.TypeChecker, type: ts.Type): boolean;
export declare function getCallSignaturesOfType(type: ts.Type): ReadonlyArray<ts.Signature>;
/** Returns all types of a union type or an array containing `type` itself if it's no union type. */
export declare function unionTypeParts(type: ts.Type): ts.Type[];
/** Returns all types of a intersection type or an array containing `type` itself if it's no intersection type. */
export declare function intersectionTypeParts(type: ts.Type): ts.Type[];
export declare function someTypePart(type: ts.Type, predicate: (t: ts.Type) => t is ts.UnionOrIntersectionType, cb: (t: ts.Type) => boolean): boolean;
/** Determines if a type thenable and can be used with `await`. */
export declare function isThenableType(checker: ts.TypeChecker, node: ts.Node, type: ts.Type): boolean;
/** Determines if a type thenable and can be used with `await`. */
export declare function isThenableType(checker: ts.TypeChecker, node: ts.Expression, type?: ts.Type): boolean;
/** Determine if a type is definitely falsy. This function doesn't unwrap union types. */
export declare function isFalsyType(type: ts.Type): boolean;
/** Determines whether the given type is a boolean literal type and matches the given boolean literal (true or false). */
export declare function isBooleanLiteralType(type: ts.Type, literal: boolean): boolean;
export declare function getPropertyOfType(type: ts.Type, name: ts.__String): ts.Symbol | undefined;
/** Determines if writing to a certain property of a given type is allowed. */
export declare function isPropertyReadonlyInType(type: ts.Type, name: ts.__String, checker: ts.TypeChecker): boolean;
export declare function symbolHasReadonlyDeclaration(symbol: ts.Symbol, checker: ts.TypeChecker): boolean;
/** Returns the the literal name or unique symbol name from a given type. Doesn't unwrap union types. */
export declare function getPropertyNameFromType(type: ts.Type): PropertyName | undefined;
export declare function getSymbolOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Symbol;
export declare function getConstructorTypeOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Type;
export declare function getInstanceTypeOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Type;
export declare function getIteratorYieldResultFromIteratorResult(type: ts.Type, node: ts.Node, checker: ts.TypeChecker): ts.Type;
/** Lookup the declaration of a class member in the super class. */
export declare function getBaseClassMemberOfClassElement(node: ts.PropertyDeclaration | ts.MethodDeclaration | ts.AccessorDeclaration, checker: ts.TypeChecker): ts.Symbol | undefined;
+299 -238
View File
@@ -1,238 +1,299 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const type_1 = require("../typeguard/type");
const util_1 = require("./util");
const node_1 = require("../typeguard/node");
function isEmptyObjectType(type) {
if (type_1.isObjectType(type) &&
type.objectFlags & ts.ObjectFlags.Anonymous &&
type.getProperties().length === 0 &&
type.getCallSignatures().length === 0 &&
type.getConstructSignatures().length === 0 &&
type.getStringIndexType() === undefined &&
type.getNumberIndexType() === undefined) {
const baseTypes = type.getBaseTypes();
return baseTypes === undefined || baseTypes.every(isEmptyObjectType);
}
return false;
}
exports.isEmptyObjectType = isEmptyObjectType;
function removeOptionalityFromType(checker, type) {
if (!containsTypeWithFlag(type, ts.TypeFlags.Undefined))
return type;
const allowsNull = containsTypeWithFlag(type, ts.TypeFlags.Null);
type = checker.getNonNullableType(type);
return allowsNull ? checker.getNullableType(type, ts.TypeFlags.Null) : type;
}
exports.removeOptionalityFromType = removeOptionalityFromType;
function containsTypeWithFlag(type, flag) {
for (const t of unionTypeParts(type))
if (util_1.isTypeFlagSet(t, flag))
return true;
return false;
}
function isTypeAssignableToNumber(checker, type) {
return isTypeAssignableTo(checker, type, ts.TypeFlags.NumberLike);
}
exports.isTypeAssignableToNumber = isTypeAssignableToNumber;
function isTypeAssignableToString(checker, type) {
return isTypeAssignableTo(checker, type, ts.TypeFlags.StringLike);
}
exports.isTypeAssignableToString = isTypeAssignableToString;
function isTypeAssignableTo(checker, type, flags) {
flags |= ts.TypeFlags.Any;
let typeParametersSeen;
return (function check(t) {
if (type_1.isTypeParameter(t) && t.symbol !== undefined && t.symbol.declarations !== undefined) {
if (typeParametersSeen === undefined) {
typeParametersSeen = new Set([t]);
}
else if (!typeParametersSeen.has(t)) {
typeParametersSeen.add(t);
}
else {
return false;
}
const declaration = t.symbol.declarations[0];
if (declaration.constraint === undefined)
return true;
return check(checker.getTypeFromTypeNode(declaration.constraint));
}
if (type_1.isUnionType(t))
return t.types.every(check);
if (type_1.isIntersectionType(t))
return t.types.some(check);
return util_1.isTypeFlagSet(t, flags);
})(type);
}
function getCallSignaturesOfType(type) {
if (type_1.isUnionType(type)) {
const signatures = [];
for (const t of type.types)
signatures.push(...getCallSignaturesOfType(t));
return signatures;
}
if (type_1.isIntersectionType(type)) {
let signatures;
for (const t of type.types) {
const sig = getCallSignaturesOfType(t);
if (sig.length !== 0) {
if (signatures !== undefined)
return [];
signatures = sig;
}
}
return signatures === undefined ? [] : signatures;
}
return type.getCallSignatures();
}
exports.getCallSignaturesOfType = getCallSignaturesOfType;
function unionTypeParts(type) {
return type_1.isUnionType(type) ? type.types : [type];
}
exports.unionTypeParts = unionTypeParts;
function intersectionTypeParts(type) {
return type_1.isIntersectionType(type) ? type.types : [type];
}
exports.intersectionTypeParts = intersectionTypeParts;
function someTypePart(type, predicate, cb) {
return predicate(type) ? type.types.some(cb) : cb(type);
}
exports.someTypePart = someTypePart;
function isThenableType(checker, node, type = checker.getTypeAtLocation(node)) {
for (const ty of unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined)
continue;
const thenType = checker.getTypeOfSymbolAtLocation(then, node);
for (const t of unionTypeParts(thenType))
for (const signature of t.getCallSignatures())
if (signature.parameters.length !== 0 && isCallback(checker, signature.parameters[0], node))
return true;
}
return false;
}
exports.isThenableType = isThenableType;
function isCallback(checker, param, node) {
let type = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node));
if (param.valueDeclaration.dotDotDotToken) {
type = type.getNumberIndexType();
if (type === undefined)
return false;
}
for (const t of unionTypeParts(type))
if (t.getCallSignatures().length !== 0)
return true;
return false;
}
function isFalsyType(type) {
if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void))
return true;
if (type_1.isLiteralType(type))
return !type.value;
return isBooleanLiteralType(type, false);
}
exports.isFalsyType = isFalsyType;
function isBooleanLiteralType(type, literal) {
return util_1.isTypeFlagSet(type, ts.TypeFlags.BooleanLiteral) &&
type.intrinsicName === (literal ? 'true' : 'false');
}
exports.isBooleanLiteralType = isBooleanLiteralType;
function getPropertyOfType(type, name) {
if (!name.startsWith('__'))
return type.getProperty(name);
return type.getProperties().find((s) => s.escapedName === name);
}
exports.getPropertyOfType = getPropertyOfType;
function isPropertyReadonlyInType(type, name, checker) {
let seenProperty = false;
let seenReadonlySignature = false;
for (const t of unionTypeParts(type)) {
if (getPropertyOfType(t, name) === undefined) {
const index = (util_1.isNumericPropertyName(name) ? checker.getIndexInfoOfType(t, ts.IndexKind.Number) : undefined) ||
checker.getIndexInfoOfType(t, ts.IndexKind.String);
if (index !== undefined && index.isReadonly) {
if (seenProperty)
return true;
seenReadonlySignature = true;
}
}
else if (seenReadonlySignature || isReadonlyPropertyIntersection(t, name, checker)) {
return true;
}
else {
seenProperty = true;
}
}
return false;
}
exports.isPropertyReadonlyInType = isPropertyReadonlyInType;
function isReadonlyPropertyIntersection(type, name, checker) {
return someTypePart(type, type_1.isIntersectionType, (t) => {
const prop = getPropertyOfType(t, name);
if (prop === undefined)
return false;
if (prop.flags & ts.SymbolFlags.Transient) {
if (/^(?:[1-9]\d*|0)$/.test(name) && type_1.isTupleTypeReference(t))
return t.target.readonly;
switch (isReadonlyPropertyFromMappedType(t, name, checker)) {
case true:
return true;
case false:
return false;
default:
}
}
return (util_1.isSymbolFlagSet(prop, ts.SymbolFlags.ValueModule) ||
symbolHasReadonlyDeclaration(prop, checker));
});
}
function isReadonlyPropertyFromMappedType(type, name, checker) {
if (!type_1.isObjectType(type) || !util_1.isObjectFlagSet(type, ts.ObjectFlags.Mapped))
return;
const declaration = type.symbol.declarations[0];
if (declaration.readonlyToken !== undefined && !/^__@[^@]+$/.test(name))
return declaration.readonlyToken.kind !== ts.SyntaxKind.MinusToken;
return isPropertyReadonlyInType(type.modifiersType, name, checker);
}
function symbolHasReadonlyDeclaration(symbol, checker) {
return (symbol.flags & ts.SymbolFlags.Accessor) === ts.SymbolFlags.GetAccessor ||
symbol.declarations !== undefined &&
symbol.declarations.some((node) => util_1.isModifierFlagSet(node, ts.ModifierFlags.Readonly) ||
node_1.isVariableDeclaration(node) && util_1.isNodeFlagSet(node.parent, ts.NodeFlags.Const) ||
node_1.isCallExpression(node) && util_1.isReadonlyAssignmentDeclaration(node, checker) ||
node_1.isEnumMember(node) ||
(node_1.isPropertyAssignment(node) || node_1.isShorthandPropertyAssignment(node)) && util_1.isInConstContext(node.parent));
}
exports.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration;
function getPropertyNameFromType(type) {
if (type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) {
const value = String(type.value);
return { displayName: value, symbolName: ts.escapeLeadingUnderscores(value) };
}
if (type_1.isUniqueESSymbolType(type))
return {
displayName: `[${type.symbol ? type.symbol.name : type.escapedName.replace(/^__@|@\d+$/g, '')}]`,
symbolName: type.escapedName,
};
}
exports.getPropertyNameFromType = getPropertyNameFromType;
function getConstructorTypeOfClassLikeDeclaration(node, checker) {
return checker.getDeclaredTypeOfSymbol(node.name !== undefined ? checker.getSymbolAtLocation(node.name) : checker.getTypeAtLocation(node).symbol);
}
exports.getConstructorTypeOfClassLikeDeclaration = getConstructorTypeOfClassLikeDeclaration;
function getInstanceTypeOfClassLikeDeclaration(node, checker) {
return node.kind === ts.SyntaxKind.ClassDeclaration
? checker.getTypeAtLocation(node)
: checker.getTypeOfSymbolAtLocation(checker.getTypeAtLocation(node).getProperty('prototype'), node);
}
exports.getInstanceTypeOfClassLikeDeclaration = getInstanceTypeOfClassLikeDeclaration;
function getIteratorYieldResultFromIteratorResult(type, node, checker) {
return type_1.isUnionType(type) && type.types.find((t) => {
const done = t.getProperty('done');
return done !== undefined &&
isBooleanLiteralType(removeOptionalityFromType(checker, checker.getTypeOfSymbolAtLocation(done, node)), false);
}) || type;
}
exports.getIteratorYieldResultFromIteratorResult = getIteratorYieldResultFromIteratorResult;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBaseClassMemberOfClassElement = exports.getIteratorYieldResultFromIteratorResult = exports.getInstanceTypeOfClassLikeDeclaration = exports.getConstructorTypeOfClassLikeDeclaration = exports.getSymbolOfClassLikeDeclaration = exports.getPropertyNameFromType = exports.symbolHasReadonlyDeclaration = exports.isPropertyReadonlyInType = exports.getPropertyOfType = exports.isBooleanLiteralType = exports.isFalsyType = exports.isThenableType = exports.someTypePart = exports.intersectionTypeParts = exports.unionTypeParts = exports.getCallSignaturesOfType = exports.isTypeAssignableToString = exports.isTypeAssignableToNumber = exports.isOptionalChainingUndefinedMarkerType = exports.removeOptionalChainingUndefinedMarkerType = exports.removeOptionalityFromType = exports.isEmptyObjectType = void 0;
const ts = require("typescript");
const type_1 = require("../typeguard/type");
const util_1 = require("./util");
const node_1 = require("../typeguard/node");
function isEmptyObjectType(type) {
if (type_1.isObjectType(type) &&
type.objectFlags & ts.ObjectFlags.Anonymous &&
type.getProperties().length === 0 &&
type.getCallSignatures().length === 0 &&
type.getConstructSignatures().length === 0 &&
type.getStringIndexType() === undefined &&
type.getNumberIndexType() === undefined) {
const baseTypes = type.getBaseTypes();
return baseTypes === undefined || baseTypes.every(isEmptyObjectType);
}
return false;
}
exports.isEmptyObjectType = isEmptyObjectType;
function removeOptionalityFromType(checker, type) {
if (!containsTypeWithFlag(type, ts.TypeFlags.Undefined))
return type;
const allowsNull = containsTypeWithFlag(type, ts.TypeFlags.Null);
type = checker.getNonNullableType(type);
return allowsNull ? checker.getNullableType(type, ts.TypeFlags.Null) : type;
}
exports.removeOptionalityFromType = removeOptionalityFromType;
function containsTypeWithFlag(type, flag) {
for (const t of unionTypeParts(type))
if (util_1.isTypeFlagSet(t, flag))
return true;
return false;
}
function removeOptionalChainingUndefinedMarkerType(checker, type) {
if (!type_1.isUnionType(type))
return isOptionalChainingUndefinedMarkerType(checker, type) ? type.getNonNullableType() : type;
let flags = 0;
let containsUndefinedMarker = false;
for (const t of type.types) {
if (isOptionalChainingUndefinedMarkerType(checker, t)) {
containsUndefinedMarker = true;
}
else {
flags |= t.flags;
}
}
return containsUndefinedMarker
? checker.getNullableType(type.getNonNullableType(), flags)
: type;
}
exports.removeOptionalChainingUndefinedMarkerType = removeOptionalChainingUndefinedMarkerType;
function isOptionalChainingUndefinedMarkerType(checker, t) {
return util_1.isTypeFlagSet(t, ts.TypeFlags.Undefined) && checker.getNullableType(t.getNonNullableType(), ts.TypeFlags.Undefined) !== t;
}
exports.isOptionalChainingUndefinedMarkerType = isOptionalChainingUndefinedMarkerType;
function isTypeAssignableToNumber(checker, type) {
return isTypeAssignableTo(checker, type, ts.TypeFlags.NumberLike);
}
exports.isTypeAssignableToNumber = isTypeAssignableToNumber;
function isTypeAssignableToString(checker, type) {
return isTypeAssignableTo(checker, type, ts.TypeFlags.StringLike);
}
exports.isTypeAssignableToString = isTypeAssignableToString;
function isTypeAssignableTo(checker, type, flags) {
flags |= ts.TypeFlags.Any;
let typeParametersSeen;
return (function check(t) {
if (type_1.isTypeParameter(t) && t.symbol !== undefined && t.symbol.declarations !== undefined) {
if (typeParametersSeen === undefined) {
typeParametersSeen = new Set([t]);
}
else if (!typeParametersSeen.has(t)) {
typeParametersSeen.add(t);
}
else {
return false;
}
const declaration = t.symbol.declarations[0];
if (declaration.constraint === undefined)
return true; // TODO really?
return check(checker.getTypeFromTypeNode(declaration.constraint));
}
if (type_1.isUnionType(t))
return t.types.every(check);
if (type_1.isIntersectionType(t))
return t.types.some(check);
return util_1.isTypeFlagSet(t, flags);
})(type);
}
function getCallSignaturesOfType(type) {
if (type_1.isUnionType(type)) {
const signatures = [];
for (const t of type.types)
signatures.push(...getCallSignaturesOfType(t));
return signatures;
}
if (type_1.isIntersectionType(type)) {
let signatures;
for (const t of type.types) {
const sig = getCallSignaturesOfType(t);
if (sig.length !== 0) {
if (signatures !== undefined)
return []; // if more than one type of the intersection has call signatures, none of them is useful for inference
signatures = sig;
}
}
return signatures === undefined ? [] : signatures;
}
return type.getCallSignatures();
}
exports.getCallSignaturesOfType = getCallSignaturesOfType;
/** Returns all types of a union type or an array containing `type` itself if it's no union type. */
function unionTypeParts(type) {
return type_1.isUnionType(type) ? type.types : [type];
}
exports.unionTypeParts = unionTypeParts;
/** Returns all types of a intersection type or an array containing `type` itself if it's no intersection type. */
function intersectionTypeParts(type) {
return type_1.isIntersectionType(type) ? type.types : [type];
}
exports.intersectionTypeParts = intersectionTypeParts;
function someTypePart(type, predicate, cb) {
return predicate(type) ? type.types.some(cb) : cb(type);
}
exports.someTypePart = someTypePart;
function isThenableType(checker, node, type = checker.getTypeAtLocation(node)) {
for (const ty of unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined)
continue;
const thenType = checker.getTypeOfSymbolAtLocation(then, node);
for (const t of unionTypeParts(thenType))
for (const signature of t.getCallSignatures())
if (signature.parameters.length !== 0 && isCallback(checker, signature.parameters[0], node))
return true;
}
return false;
}
exports.isThenableType = isThenableType;
function isCallback(checker, param, node) {
let type = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node));
if (param.valueDeclaration.dotDotDotToken) {
// unwrap array type of rest parameter
type = type.getNumberIndexType();
if (type === undefined)
return false;
}
for (const t of unionTypeParts(type))
if (t.getCallSignatures().length !== 0)
return true;
return false;
}
/** Determine if a type is definitely falsy. This function doesn't unwrap union types. */
function isFalsyType(type) {
if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void))
return true;
if (type_1.isLiteralType(type))
return !type.value;
return isBooleanLiteralType(type, false);
}
exports.isFalsyType = isFalsyType;
/** Determines whether the given type is a boolean literal type and matches the given boolean literal (true or false). */
function isBooleanLiteralType(type, literal) {
return util_1.isTypeFlagSet(type, ts.TypeFlags.BooleanLiteral) &&
type.intrinsicName === (literal ? 'true' : 'false');
}
exports.isBooleanLiteralType = isBooleanLiteralType;
function getPropertyOfType(type, name) {
if (!name.startsWith('__'))
return type.getProperty(name);
return type.getProperties().find((s) => s.escapedName === name);
}
exports.getPropertyOfType = getPropertyOfType;
/** Determines if writing to a certain property of a given type is allowed. */
function isPropertyReadonlyInType(type, name, checker) {
let seenProperty = false;
let seenReadonlySignature = false;
for (const t of unionTypeParts(type)) {
if (getPropertyOfType(t, name) === undefined) {
// property is not present in this part of the union -> check for readonly index signature
const index = (util_1.isNumericPropertyName(name) ? checker.getIndexInfoOfType(t, ts.IndexKind.Number) : undefined) ||
checker.getIndexInfoOfType(t, ts.IndexKind.String);
if (index !== undefined && index.isReadonly) {
if (seenProperty)
return true;
seenReadonlySignature = true;
}
}
else if (seenReadonlySignature || isReadonlyPropertyIntersection(t, name, checker)) {
return true;
}
else {
seenProperty = true;
}
}
return false;
}
exports.isPropertyReadonlyInType = isPropertyReadonlyInType;
function isReadonlyPropertyIntersection(type, name, checker) {
return someTypePart(type, type_1.isIntersectionType, (t) => {
const prop = getPropertyOfType(t, name);
if (prop === undefined)
return false;
if (prop.flags & ts.SymbolFlags.Transient) {
if (/^(?:[1-9]\d*|0)$/.test(name) && type_1.isTupleTypeReference(t))
return t.target.readonly;
switch (isReadonlyPropertyFromMappedType(t, name, checker)) {
case true:
return true;
case false:
return false;
default:
// `undefined` falls through
}
}
return (
// members of namespace import
util_1.isSymbolFlagSet(prop, ts.SymbolFlags.ValueModule) ||
// we unwrapped every mapped type, now we can check the actual declarations
symbolHasReadonlyDeclaration(prop, checker));
});
}
function isReadonlyPropertyFromMappedType(type, name, checker) {
if (!type_1.isObjectType(type) || !util_1.isObjectFlagSet(type, ts.ObjectFlags.Mapped))
return;
const declaration = type.symbol.declarations[0];
// well-known symbols are not affected by mapped types
if (declaration.readonlyToken !== undefined && !/^__@[^@]+$/.test(name))
return declaration.readonlyToken.kind !== ts.SyntaxKind.MinusToken;
return isPropertyReadonlyInType(type.modifiersType, name, checker);
}
function symbolHasReadonlyDeclaration(symbol, checker) {
return (symbol.flags & ts.SymbolFlags.Accessor) === ts.SymbolFlags.GetAccessor ||
symbol.declarations !== undefined &&
symbol.declarations.some((node) => util_1.isModifierFlagSet(node, ts.ModifierFlags.Readonly) ||
node_1.isVariableDeclaration(node) && util_1.isNodeFlagSet(node.parent, ts.NodeFlags.Const) ||
node_1.isCallExpression(node) && util_1.isReadonlyAssignmentDeclaration(node, checker) ||
node_1.isEnumMember(node) ||
(node_1.isPropertyAssignment(node) || node_1.isShorthandPropertyAssignment(node)) && util_1.isInConstContext(node.parent));
}
exports.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration;
/** Returns the the literal name or unique symbol name from a given type. Doesn't unwrap union types. */
function getPropertyNameFromType(type) {
// string or number literal. bigint is intentionally excluded
if (type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) {
const value = String(type.value);
return { displayName: value, symbolName: ts.escapeLeadingUnderscores(value) };
}
if (type_1.isUniqueESSymbolType(type))
return {
displayName: `[${type.symbol ? type.symbol.name : type.escapedName.replace(/^__@|@\d+$/g, '')}]`,
symbolName: type.escapedName,
};
}
exports.getPropertyNameFromType = getPropertyNameFromType;
function getSymbolOfClassLikeDeclaration(node, checker) {
var _a;
return checker.getSymbolAtLocation((_a = node.name) !== null && _a !== void 0 ? _a : util_1.getChildOfKind(node, ts.SyntaxKind.ClassKeyword));
}
exports.getSymbolOfClassLikeDeclaration = getSymbolOfClassLikeDeclaration;
function getConstructorTypeOfClassLikeDeclaration(node, checker) {
return node.kind === ts.SyntaxKind.ClassExpression
? checker.getTypeAtLocation(node)
: checker.getTypeOfSymbolAtLocation(getSymbolOfClassLikeDeclaration(node, checker), node);
}
exports.getConstructorTypeOfClassLikeDeclaration = getConstructorTypeOfClassLikeDeclaration;
function getInstanceTypeOfClassLikeDeclaration(node, checker) {
return node.kind === ts.SyntaxKind.ClassDeclaration
? checker.getTypeAtLocation(node)
: checker.getDeclaredTypeOfSymbol(getSymbolOfClassLikeDeclaration(node, checker));
}
exports.getInstanceTypeOfClassLikeDeclaration = getInstanceTypeOfClassLikeDeclaration;
function getIteratorYieldResultFromIteratorResult(type, node, checker) {
return type_1.isUnionType(type) && type.types.find((t) => {
const done = t.getProperty('done');
return done !== undefined &&
isBooleanLiteralType(removeOptionalityFromType(checker, checker.getTypeOfSymbolAtLocation(done, node)), false);
}) || type;
}
exports.getIteratorYieldResultFromIteratorResult = getIteratorYieldResultFromIteratorResult;
/** Lookup the declaration of a class member in the super class. */
function getBaseClassMemberOfClassElement(node, checker) {
if (!node_1.isClassLikeDeclaration(node.parent))
return;
const base = util_1.getBaseOfClassLikeExpression(node.parent);
if (base === undefined)
return;
const name = util_1.getSingleLateBoundPropertyNameOfPropertyName(node.name, checker);
if (name === undefined)
return;
const baseType = checker.getTypeAtLocation(util_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword)
? base.expression
: base);
return getPropertyOfType(baseType, name.symbolName);
}
exports.getBaseClassMemberOfClassElement = getBaseClassMemberOfClassElement;
//# sourceMappingURL=type.js.map
+1
View File
File diff suppressed because one or more lines are too long
+30 -30
View File
@@ -1,30 +1,30 @@
import * as ts from 'typescript';
export interface VariableInfo {
domain: DeclarationDomain;
exported: boolean;
uses: VariableUse[];
inGlobalScope: boolean;
declarations: ts.Identifier[];
}
export interface VariableUse {
domain: UsageDomain;
location: ts.Identifier;
}
export declare enum DeclarationDomain {
Namespace = 1,
Type = 2,
Value = 4,
Import = 8,
Any = 7
}
export declare enum UsageDomain {
Namespace = 1,
Type = 2,
Value = 4,
ValueOrNamespace = 5,
Any = 7,
TypeQuery = 8
}
export declare function getUsageDomain(node: ts.Identifier): UsageDomain | undefined;
export declare function getDeclarationDomain(node: ts.Identifier): DeclarationDomain | undefined;
export declare function collectVariableUsage(sourceFile: ts.SourceFile): Map<ts.Identifier, VariableInfo>;
import * as ts from 'typescript';
export interface VariableInfo {
domain: DeclarationDomain;
exported: boolean;
uses: VariableUse[];
inGlobalScope: boolean;
declarations: ts.Identifier[];
}
export interface VariableUse {
domain: UsageDomain;
location: ts.Identifier;
}
export declare enum DeclarationDomain {
Namespace = 1,
Type = 2,
Value = 4,
Import = 8,
Any = 7
}
export declare enum UsageDomain {
Namespace = 1,
Type = 2,
Value = 4,
ValueOrNamespace = 5,
Any = 7,
TypeQuery = 8
}
export declare function getUsageDomain(node: ts.Identifier): UsageDomain | undefined;
export declare function getDeclarationDomain(node: ts.Identifier): DeclarationDomain | undefined;
export declare function collectVariableUsage(sourceFile: ts.SourceFile): Map<ts.Identifier, VariableInfo>;
+658 -645
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long
+264 -167
View File
@@ -1,167 +1,264 @@
import * as ts from 'typescript';
import { NodeWrap } from './convert-ast';
export declare function getChildOfKind<T extends ts.SyntaxKind>(node: ts.Node, kind: T, sourceFile?: ts.SourceFile): ts.Token<T> | undefined;
export declare function isTokenKind(kind: ts.SyntaxKind): boolean;
export declare function isNodeKind(kind: ts.SyntaxKind): boolean;
export declare function isAssignmentKind(kind: ts.SyntaxKind): boolean;
export declare function isTypeNodeKind(kind: ts.SyntaxKind): boolean;
export declare function isJsDocKind(kind: ts.SyntaxKind): boolean;
export declare function isKeywordKind(kind: ts.SyntaxKind): boolean;
export declare function isThisParameter(parameter: ts.ParameterDeclaration): boolean;
export declare function getModifier(node: ts.Node, kind: ts.Modifier['kind']): ts.Modifier | undefined;
export declare function hasModifier(modifiers: ts.ModifiersArray | undefined, ...kinds: Array<ts.Modifier['kind']>): boolean;
export declare function isParameterProperty(node: ts.ParameterDeclaration): boolean;
export declare function hasAccessModifier(node: ts.ClassElement | ts.ParameterDeclaration): boolean;
export declare const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean;
export declare const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean;
export declare const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean;
export declare function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags): boolean;
export declare function isModifierFlagSet(node: ts.Node, flag: ts.ModifierFlags): boolean;
export declare function getPreviousStatement(statement: ts.Statement): ts.Statement | undefined;
export declare function getNextStatement(statement: ts.Statement): ts.Statement | undefined;
export declare function getPreviousToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
export declare function getNextToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
export declare function getTokenAtPosition(parent: ts.Node, pos: number, sourceFile?: ts.SourceFile, allowJsDoc?: boolean): ts.Node | undefined;
export declare function getCommentAtPosition(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): ts.CommentRange | undefined;
export declare function isPositionInComment(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): boolean;
export declare function commentText(sourceText: string, comment: ts.CommentRange): string;
export declare function getWrappedNodeAtPosition(wrap: NodeWrap, pos: number): NodeWrap | undefined;
export declare function getPropertyName(propertyName: ts.PropertyName): string | undefined;
export declare function forEachDestructuringIdentifier<T>(pattern: ts.BindingPattern, fn: (element: ts.BindingElement & {
name: ts.Identifier;
}) => T): T | undefined;
export declare function forEachDeclaredVariable<T>(declarationList: ts.VariableDeclarationList, cb: (element: (ts.VariableDeclaration | ts.BindingElement) & {
name: ts.Identifier;
}) => T): T | undefined;
export declare enum VariableDeclarationKind {
Var = 0,
Let = 1,
Const = 2
}
export declare function getVariableDeclarationKind(declarationList: ts.VariableDeclarationList): VariableDeclarationKind;
export declare function isBlockScopedVariableDeclarationList(declarationList: ts.VariableDeclarationList): boolean;
export declare function isBlockScopedVariableDeclaration(declaration: ts.VariableDeclaration): boolean;
export declare function isBlockScopedDeclarationStatement(statement: ts.Statement): statement is ts.DeclarationStatement;
export declare function isInSingleStatementContext(statement: ts.Statement): boolean;
export declare enum ScopeBoundary {
None = 0,
Function = 1,
Block = 2,
Type = 4,
ConditionalType = 8
}
export declare enum ScopeBoundarySelector {
Function = 1,
Block = 3,
Type = 7,
InferType = 8
}
export declare function isScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isTypeScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isFunctionScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isBlockScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function hasOwnThisReference(node: ts.Node): boolean;
export declare function isFunctionWithBody(node: ts.Node): node is ts.FunctionLikeDeclaration & {
body: {};
};
export declare function forEachToken(node: ts.Node, cb: (node: ts.Node) => void, sourceFile?: ts.SourceFile): void;
export declare type ForEachTokenCallback = (fullText: string, kind: ts.SyntaxKind, range: ts.TextRange, parent: ts.Node) => void;
export declare function forEachTokenWithTrivia(node: ts.Node, cb: ForEachTokenCallback, sourceFile?: ts.SourceFile): void;
export declare type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void;
export declare function forEachComment(node: ts.Node, cb: ForEachCommentCallback, sourceFile?: ts.SourceFile): void;
export interface LineRange extends ts.TextRange {
contentLength: number;
}
export declare function getLineRanges(sourceFile: ts.SourceFile): LineRange[];
export declare function getLineBreakStyle(sourceFile: ts.SourceFile): "\n" | "\r\n";
export declare function isValidIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isValidPropertyAccess(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isValidPropertyName(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isValidNumericLiteral(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isValidJsxIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isNumericPropertyName(name: string | ts.__String): boolean;
export declare function isSameLine(sourceFile: ts.SourceFile, pos1: number, pos2: number): boolean;
export declare enum SideEffectOptions {
None = 0,
TaggedTemplate = 1,
Constructor = 2,
JsxElement = 4
}
export declare function hasSideEffects(node: ts.Expression, options?: SideEffectOptions): boolean;
export declare function getDeclarationOfBindingElement(node: ts.BindingElement): ts.VariableDeclaration | ts.ParameterDeclaration;
export declare function isExpressionValueUsed(node: ts.Expression): boolean;
export declare enum AccessKind {
None = 0,
Read = 1,
Write = 2,
Delete = 4,
ReadWrite = 3,
Modification = 6
}
export declare function getAccessKind(node: ts.Node): AccessKind;
export declare function isReassignmentTarget(node: ts.Expression): boolean;
export declare function canHaveJsDoc(node: ts.Node): node is ts.HasJSDoc;
export declare function getJsDoc(node: ts.Node, sourceFile?: ts.SourceFile): ts.JSDoc[];
export declare function parseJsDocOfNode(node: ts.Node, considerTrailingComments?: boolean, sourceFile?: ts.SourceFile): ts.JSDoc[];
export declare enum ImportKind {
ImportDeclaration = 1,
ImportEquals = 2,
ExportFrom = 4,
DynamicImport = 8,
Require = 16,
ImportType = 32,
All = 63,
AllImports = 59,
AllStaticImports = 3,
AllImportExpressions = 24,
AllRequireLike = 18
}
export declare function findImports(sourceFile: ts.SourceFile, kinds: ImportKind): (ts.StringLiteral | ts.NoSubstitutionTemplateLiteral)[];
export declare type ImportLike = ts.ImportDeclaration | (ts.ImportEqualsDeclaration & {
moduleReference: ts.ExternalModuleReference;
}) | (ts.ExportDeclaration & {
moduleSpecifier: {};
}) | (ts.CallExpression & {
expression: ts.Token<ts.SyntaxKind.ImportKeyword> | (ts.Identifier & {
text: 'require';
});
arguments: [ts.Expression];
}) | ts.ImportTypeNode;
export declare function findImportLikeNodes(sourceFile: ts.SourceFile, kinds: ImportKind): ImportLike[];
export declare function isStatementInAmbientContext(node: ts.Statement): boolean;
export declare function isAmbientModuleBlock(node: ts.Node): node is ts.ModuleBlock;
export declare function getIIFE(func: ts.FunctionExpression | ts.ArrowFunction): ts.CallExpression | undefined;
export declare type StrictCompilerOption = 'noImplicitAny' | 'noImplicitThis' | 'strictNullChecks' | 'strictFunctionTypes' | 'strictPropertyInitialization' | 'alwaysStrict' | 'strictBindCallApply';
export declare function isStrictCompilerOptionEnabled(options: ts.CompilerOptions, option: StrictCompilerOption): boolean;
export declare type BooleanCompilerOptions = {
[K in keyof ts.CompilerOptions]: NonNullable<ts.CompilerOptions[K]> extends boolean ? K : never;
} extends {
[_ in keyof ts.CompilerOptions]: infer U;
} ? U : never;
export declare function isCompilerOptionEnabled(options: ts.CompilerOptions, option: BooleanCompilerOptions | 'stripInternal'): boolean;
export declare function isAmbientModule(node: ts.ModuleDeclaration): boolean;
export declare function getCheckJsDirective(source: string): ts.CheckJsDirective | undefined;
export declare function isConstAssertion(node: ts.AssertionExpression): boolean;
export declare function isInConstContext(node: ts.Expression): boolean;
export declare function isReadonlyAssignmentDeclaration(node: ts.CallExpression, checker: ts.TypeChecker): boolean;
export declare function isBindableObjectDefinePropertyCall(node: ts.CallExpression): boolean;
export interface WellKnownSymbolLiteral extends ts.PropertyAccessExpression {
expression: ts.Identifier & {
text: 'Symbol';
escapedText: 'symbol';
};
}
export declare function isWellKnownSymbolLiterally(node: ts.Expression): node is WellKnownSymbolLiteral;
export interface PropertyName {
displayName: string;
symbolName: ts.__String;
}
export declare function getPropertyNameOfWellKnownSymbol(node: WellKnownSymbolLiteral): PropertyName;
export interface LateBoundPropertyNames {
known: boolean;
names: PropertyName[];
}
export declare function getLateBoundPropertyNames(node: ts.Expression, checker: ts.TypeChecker): LateBoundPropertyNames;
export declare function getLateBoundPropertyNamesOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): LateBoundPropertyNames;
export declare function getSingleLateBoundPropertyNameOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): PropertyName | undefined;
export declare function unwrapParentheses(node: ts.Expression): ts.Expression;
import * as ts from 'typescript';
import { NodeWrap } from './convert-ast';
export declare function getChildOfKind<T extends ts.SyntaxKind>(node: ts.Node, kind: T, sourceFile?: ts.SourceFile): ts.Token<T> | undefined;
export declare function isTokenKind(kind: ts.SyntaxKind): boolean;
export declare function isNodeKind(kind: ts.SyntaxKind): boolean;
export declare function isAssignmentKind(kind: ts.SyntaxKind): boolean;
export declare function isTypeNodeKind(kind: ts.SyntaxKind): boolean;
export declare function isJsDocKind(kind: ts.SyntaxKind): boolean;
export declare function isKeywordKind(kind: ts.SyntaxKind): boolean;
export declare function isThisParameter(parameter: ts.ParameterDeclaration): boolean;
export declare function getModifier(node: ts.Node, kind: ts.Modifier['kind']): ts.Modifier | undefined;
export declare function hasModifier(modifiers: ts.ModifiersArray | undefined, ...kinds: Array<ts.Modifier['kind']>): boolean;
export declare function isParameterProperty(node: ts.ParameterDeclaration): boolean;
export declare function hasAccessModifier(node: ts.ClassElement | ts.ParameterDeclaration): boolean;
export declare const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean;
export declare const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean;
export declare const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean;
export declare function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags): boolean;
export declare function isModifierFlagSet(node: ts.Node, flag: ts.ModifierFlags): boolean;
export declare function getPreviousStatement(statement: ts.Statement): ts.Statement | undefined;
export declare function getNextStatement(statement: ts.Statement): ts.Statement | undefined;
/** Returns the token before the start of `node` or `undefined` if there is none. */
export declare function getPreviousToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
/** Returns the next token that begins after the end of `node`. Returns `undefined` for SourceFile and EndOfFileToken */
export declare function getNextToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
/** Returns the token at or following the specified position or undefined if none is found inside `parent`. */
export declare function getTokenAtPosition(parent: ts.Node, pos: number, sourceFile?: ts.SourceFile, allowJsDoc?: boolean): ts.Node | undefined;
/**
* Return the comment at the specified position.
* You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
* If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
*/
export declare function getCommentAtPosition(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): ts.CommentRange | undefined;
/**
* Returns whether the specified position is inside a comment.
* You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
* If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
*/
export declare function isPositionInComment(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): boolean;
export declare function commentText(sourceText: string, comment: ts.CommentRange): string;
/** Returns the deepest AST Node at `pos`. Returns undefined if `pos` is outside of the range of `node` */
export declare function getAstNodeAtPosition(node: ts.Node, pos: number): ts.Node | undefined;
/**
* Returns the NodeWrap of deepest AST node that contains `pos` between its `pos` and `end`.
* Only returns undefined if pos is outside of `wrap`
*/
export declare function getWrappedNodeAtPosition(wrap: NodeWrap, pos: number): NodeWrap | undefined;
export declare function getPropertyName(propertyName: ts.PropertyName): string | undefined;
export declare function forEachDestructuringIdentifier<T>(pattern: ts.BindingPattern, fn: (element: ts.BindingElement & {
name: ts.Identifier;
}) => T): T | undefined;
export declare function forEachDeclaredVariable<T>(declarationList: ts.VariableDeclarationList, cb: (element: (ts.VariableDeclaration | ts.BindingElement) & {
name: ts.Identifier;
}) => T): T | undefined;
export declare enum VariableDeclarationKind {
Var = 0,
Let = 1,
Const = 2
}
export declare function getVariableDeclarationKind(declarationList: ts.VariableDeclarationList): VariableDeclarationKind;
export declare function isBlockScopedVariableDeclarationList(declarationList: ts.VariableDeclarationList): boolean;
export declare function isBlockScopedVariableDeclaration(declaration: ts.VariableDeclaration): boolean;
export declare function isBlockScopedDeclarationStatement(statement: ts.Statement): statement is ts.DeclarationStatement;
export declare function isInSingleStatementContext(statement: ts.Statement): boolean;
export declare enum ScopeBoundary {
None = 0,
Function = 1,
Block = 2,
Type = 4,
ConditionalType = 8
}
export declare enum ScopeBoundarySelector {
Function = 1,
Block = 3,
Type = 7,
InferType = 8
}
export declare function isScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isTypeScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isFunctionScopeBoundary(node: ts.Node): ScopeBoundary;
export declare function isBlockScopeBoundary(node: ts.Node): ScopeBoundary;
/** Returns true for scope boundaries that have their own `this` reference instead of inheriting it from the containing scope */
export declare function hasOwnThisReference(node: ts.Node): boolean;
export declare function isFunctionWithBody(node: ts.Node): node is ts.FunctionLikeDeclaration & {
body: {};
};
/**
* Iterate over all tokens of `node`
*
* @param node The node whose tokens should be visited
* @param cb Is called for every token contained in `node`
*/
export declare function forEachToken(node: ts.Node, cb: (node: ts.Node) => void, sourceFile?: ts.SourceFile): void;
export declare type ForEachTokenCallback = (fullText: string, kind: ts.SyntaxKind, range: ts.TextRange, parent: ts.Node) => void;
/**
* Iterate over all tokens and trivia of `node`
*
* @description JsDoc comments are treated like regular comments
*
* @param node The node whose tokens should be visited
* @param cb Is called for every token contained in `node` and trivia before the token
*/
export declare function forEachTokenWithTrivia(node: ts.Node, cb: ForEachTokenCallback, sourceFile?: ts.SourceFile): void;
export declare type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void;
/** Iterate over all comments owned by `node` or its children */
export declare function forEachComment(node: ts.Node, cb: ForEachCommentCallback, sourceFile?: ts.SourceFile): void;
export interface LineRange extends ts.TextRange {
contentLength: number;
}
export declare function getLineRanges(sourceFile: ts.SourceFile): LineRange[];
/** Get the line break style used in sourceFile. This function only looks at the first line break. If there is none, \n is assumed. */
export declare function getLineBreakStyle(sourceFile: ts.SourceFile): "\n" | "\r\n";
/**
* Determines whether the given text parses as a standalone identifier.
* This is not a guarantee that it works in every context. The property name in PropertyAccessExpressions for example allows reserved words.
* Depending on the context it could be parsed as contextual keyword or TypeScript keyword.
*/
export declare function isValidIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
/**
* Determines whether the given text can be used to access a property with a PropertyAccessExpression while preserving the property's name.
*/
export declare function isValidPropertyAccess(text: string, languageVersion?: ts.ScriptTarget): boolean;
/**
* Determines whether the given text can be used as unquoted name of a property declaration while preserving the property's name.
*/
export declare function isValidPropertyName(text: string, languageVersion?: ts.ScriptTarget): boolean;
/**
* Determines whether the given text can be parsed as a numeric literal.
*/
export declare function isValidNumericLiteral(text: string, languageVersion?: ts.ScriptTarget): boolean;
/**
* Determines whether the given text can be used as JSX tag or attribute name while preserving the exact name.
*/
export declare function isValidJsxIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
export declare function isNumericPropertyName(name: string | ts.__String): boolean;
export declare function isSameLine(sourceFile: ts.SourceFile, pos1: number, pos2: number): boolean;
export declare enum SideEffectOptions {
None = 0,
TaggedTemplate = 1,
Constructor = 2,
JsxElement = 4
}
export declare function hasSideEffects(node: ts.Expression, options?: SideEffectOptions): boolean;
/** Returns the VariableDeclaration or ParameterDeclaration that contains the BindingElement */
export declare function getDeclarationOfBindingElement(node: ts.BindingElement): ts.VariableDeclaration | ts.ParameterDeclaration;
export declare function isExpressionValueUsed(node: ts.Expression): boolean;
export declare enum AccessKind {
None = 0,
Read = 1,
Write = 2,
Delete = 4,
ReadWrite = 3,
Modification = 6
}
export declare function getAccessKind(node: ts.Node): AccessKind;
export declare function isReassignmentTarget(node: ts.Expression): boolean;
export declare function canHaveJsDoc(node: ts.Node): node is ts.HasJSDoc;
/** Gets the JSDoc of a node. For performance reasons this function should only be called when `canHaveJsDoc` returns true. */
export declare function getJsDoc(node: ts.Node, sourceFile?: ts.SourceFile): ts.JSDoc[];
/**
* Parses the JsDoc of any node. This function is made for nodes that don't get their JsDoc parsed by the TypeScript parser.
*
* @param considerTrailingComments When set to `true` this function uses the trailing comments if the node starts on the same line
* as the previous node ends.
*/
export declare function parseJsDocOfNode(node: ts.Node, considerTrailingComments?: boolean, sourceFile?: ts.SourceFile): ts.JSDoc[];
export declare enum ImportKind {
ImportDeclaration = 1,
ImportEquals = 2,
ExportFrom = 4,
DynamicImport = 8,
Require = 16,
ImportType = 32,
All = 63,
AllImports = 59,
AllStaticImports = 3,
AllImportExpressions = 24,
AllRequireLike = 18
}
export declare function findImports(sourceFile: ts.SourceFile, kinds: ImportKind, ignoreFileName?: boolean): (ts.StringLiteral | ts.NoSubstitutionTemplateLiteral)[];
export declare type ImportLike = ts.ImportDeclaration | ts.ImportEqualsDeclaration & {
moduleReference: ts.ExternalModuleReference;
} | ts.ExportDeclaration & {
moduleSpecifier: {};
} | ts.CallExpression & {
expression: ts.Token<ts.SyntaxKind.ImportKeyword> | ts.Identifier & {
text: 'require';
};
arguments: [ts.Expression, ...ts.Expression[]];
} | ts.ImportTypeNode;
export declare function findImportLikeNodes(sourceFile: ts.SourceFile, kinds: ImportKind, ignoreFileName?: boolean): ImportLike[];
/**
* Ambient context means the statement itself has the `declare` keyword
* or is inside a `declare namespace`, `delcare module` or `declare global`.
*/
export declare function isStatementInAmbientContext(node: ts.Statement): boolean;
/** Includes `declare namespace`, `declare module` and `declare global` and namespace nested in one of the aforementioned. */
export declare function isAmbientModuleBlock(node: ts.Node): node is ts.ModuleBlock;
export declare function getIIFE(func: ts.FunctionExpression | ts.ArrowFunction): ts.CallExpression | undefined;
export declare type StrictCompilerOption = 'noImplicitAny' | 'noImplicitThis' | 'strictNullChecks' | 'strictFunctionTypes' | 'strictPropertyInitialization' | 'alwaysStrict' | 'strictBindCallApply';
export declare function isStrictCompilerOptionEnabled(options: ts.CompilerOptions, option: StrictCompilerOption): boolean;
export declare type BooleanCompilerOptions = {
[K in keyof ts.CompilerOptions]: NonNullable<ts.CompilerOptions[K]> extends boolean ? K : never;
} extends {
[_ in keyof ts.CompilerOptions]: infer U;
} ? U : never;
/**
* Checks if a given compiler option is enabled.
* It handles dependencies of options, e.g. `declaration` is implicitly enabled by `composite` or `strictNullChecks` is enabled by `strict`.
* However, it does not check dependencies that are already checked and reported as errors, e.g. `checkJs` without `allowJs`.
* This function only handles boolean flags.
*/
export declare function isCompilerOptionEnabled(options: ts.CompilerOptions, option: BooleanCompilerOptions | 'stripInternal'): boolean;
/**
* Has nothing to do with `isAmbientModuleBlock`.
*
* @returns `true` if it's a global augmentation or has a string name.
*/
export declare function isAmbientModule(node: ts.ModuleDeclaration): boolean;
/**
* @deprecated use `getTsCheckDirective` instead since `// @ts-nocheck` is no longer restricted to JS files.
* @returns the last `// @ts-check` or `// @ts-nocheck` directive in the given file.
*/
export declare function getCheckJsDirective(source: string): ts.CheckJsDirective | undefined;
/** @returns the last `// @ts-check` or `// @ts-nocheck` directive in the given file. */
export declare function getTsCheckDirective(source: string): ts.CheckJsDirective | undefined;
export declare function isConstAssertion(node: ts.AssertionExpression): boolean;
/** Detects whether an expression is affected by an enclosing 'as const' assertion and therefore treated literally. */
export declare function isInConstContext(node: ts.Expression): boolean;
/** Returns true for `Object.defineProperty(o, 'prop', {value, writable: false})` and `Object.defineProperty(o, 'prop', {get: () => 1})`*/
export declare function isReadonlyAssignmentDeclaration(node: ts.CallExpression, checker: ts.TypeChecker): boolean;
/** Determines whether a call to `Object.defineProperty` is statically analyzable. */
export declare function isBindableObjectDefinePropertyCall(node: ts.CallExpression): boolean;
export interface WellKnownSymbolLiteral extends ts.PropertyAccessExpression {
expression: ts.Identifier & {
text: 'Symbol';
escapedText: 'symbol';
};
}
export declare function isWellKnownSymbolLiterally(node: ts.Expression): node is WellKnownSymbolLiteral;
export interface PropertyName {
displayName: string;
symbolName: ts.__String;
}
export declare function getPropertyNameOfWellKnownSymbol(node: WellKnownSymbolLiteral): PropertyName;
export interface LateBoundPropertyNames {
/** Whether all constituents are literal names. */
known: boolean;
names: PropertyName[];
}
export declare function getLateBoundPropertyNames(node: ts.Expression, checker: ts.TypeChecker): LateBoundPropertyNames;
export declare function getLateBoundPropertyNamesOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): LateBoundPropertyNames;
/** Most declarations demand there to be only one statically known name, e.g. class members with computed name. */
export declare function getSingleLateBoundPropertyNameOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): PropertyName | undefined;
export declare function unwrapParentheses(node: ts.Expression): ts.Expression;
export declare function formatPseudoBigInt(v: ts.PseudoBigInt): `${string}n` | `-${string}n`;
/**
* Determines whether the given `SwitchStatement`'s `case` clauses cover every possible value of the switched expression.
* The logic is the same as TypeScript's control flow analysis.
* This does **not** check whether all `case` clauses do a certain action like assign a variable or return a value.
* This function ignores the `default` clause if present.
*/
export declare function hasExhaustiveCaseClauses(node: ts.SwitchStatement, checker: ts.TypeChecker): boolean;
export declare function getBaseOfClassLikeExpression(node: ts.ClassLikeDeclaration): ts.ExpressionWithTypeArguments | undefined;
+1684 -1422
View File
File diff suppressed because it is too large Load Diff
+1
View File
File diff suppressed because one or more lines are too long