Giter Site home page Giter Site logo

tsutils's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

tsutils's Issues

Support TypeScript 3.0

With TypeScript 3.0.0-rc, below failures.

Apparently it's now possible for Nodes to not have any tokens, which I'm not sure how to fix.
The other issues look minor, just some adjusted signatures.

test/rules/control-flow/testCfaRule.ts:32:34 - error TS2345: Argument of type 'Node | undefined' is not assignable to parameter of type 'Node'.
  Type 'undefined' is not assignable to type 'Node'.

32             ctx.addFailureAtNode(node.getFirstToken(ctx.sourceFile), 'control flow end');
                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

test/tokenTests.ts:67:45 - error TS2345: Argument of type 'Node | undefined' is not assignable to parameter of type 'Node'.
  Type 'undefined' is not assignable to type 'Node'.

67         assert.isUndefined(getPreviousToken(sourceFile.getFirstToken()), 'Token');
                                               ~~~~~~~~~~~~~~~~~~~~~~~~~~

util/type.ts:87:5 - error TS2322: Type 'ReadonlyArray<Signature>' is not assignable to type 'Signature[]'.
  Property 'push' is missing in type 'ReadonlyArray<Signature>'.

87     return type.getCallSignatures();
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

util/type.ts:97:61 - error TS2345: Argument of type 'Type | undefined' is not assignable to parameter of type 'Type'.
  Type 'undefined' is not assignable to type 'Type'.

97     for (const ty of unionTypeParts(checker.getApparentType(type))) {
                                                               ~~~~

util/util.ts:85:41 - error TS2345: Argument of type 'Node' is not assignable to parameter of type 'Declaration'.
  Property '_declarationBrand' is missing in type 'Node'.

85     return (ts.getCombinedModifierFlags(node) & flag) !== 0;
                                           ~~~~

util/util.ts:953:15 - error TS2339: Property 'unescapeIdentifier' does not exist on type 'typeof ts'.

953     return ts.unescapeIdentifier ? ts.unescapeIdentifier(node.text) : node.text;
                  ~~~~~~~~~~~~~~~~~~

util/util.ts:953:39 - error TS2339: Property 'unescapeIdentifier' does not exist on type 'typeof ts'.

953     return ts.unescapeIdentifier ? ts.unescapeIdentifier(node.text) : node.text;
                                          ~~~~~~~~~~~~~~~~~~

An in-range update of tslib is breaking the build 🚨

Version 1.9.2 of tslib was just published.

Branch Build failing 🚨
Dependency tslib
Current Version 1.9.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

tslib is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Release Notes tslib 1.9.2

Fixes issues in the __generator helper regarding return-ing and throw-ing. Details are available on Microsoft/TypeScript#24463

Commits

The new version differs by 2 commits.

  • a921045 Update version to '1.9.2'.
  • c72f81c Update __generators helper to match TS#24463 (#53)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

API to get variable usage include global var

collectVariableUsage only collect variable with variable declaration.

Can we get global variable usage such as process.env.REACT_APP_HOST's process or window.document's window?

Can't get JsDocs directly from a VariableDeclaration

/**
 * First
 */
const firstVariable = true,
    /**
     * Second
     */
    secondVariable = false;
import { getJsDoc } from "tsutils";

// Edit: not visitVariableStatement(node: VariableStatement)
function visitVariableDeclaration(node: VariableDeclaration) {
    // Blank
    getJsDoc(node);

    // Always ["First"]
    getJsDoc(node.parent);
}

Expected:

Calling getJsDoc on a VariableStatement should retrieve the docs for the node, even if they're also the docs for the containing VariableDeclarationList.

Actual:

Only ever gets the docs for the VariableDeclarationList.

An in-range update of tslib is breaking the build 🚨

Version 1.9.0 of tslib was just published.

Branch Build failing 🚨
Dependency tslib
Current Version 1.8.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

tslib is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Release Notes tslib 1.9.0

This release introduces import helpers that are utilized by TypeScript 2.7's --esModuleInterop flag for interoperability between ECMAScript modules and legacy module formats.

Commits

The new version differs by 4 commits.

  • 3d0f4d4 Update version to '1.9.0'.
  • c380b8d Merge pull request #43 from Microsoft/import-helpers
  • c1cd8e1 Remove erroneous semicolons from import star helper
  • b630cee Add import helpers

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Refactor collectVariableUsage

The current API is somewhat difficult to use and does too much by analyzing the whole source file ahead of time.

The new API should return an object that can be used to:

  • get all declarations of an identifier (also with an identifier of a usage)
  • get all uses of a declaration (allow filtering by domain)
  • check if identifier is in scope
  • get a list of all declarations in the file

optionally:

  • get all identifiers in scope (optionally filtered by kind)
  • get all locations where the identifier is in scope (excluding TDZ)
  • lazily analyze only the scopes necessary to answer requests

Needs a good name:

  • ScopeAnalyzer
  • UsageTracker
  • ReferenceFinder

An in-range update of @types/mocha is breaking the build 🚨

Version 2.2.48 of @types/mocha was just published.

Branch Build failing 🚨
Dependency @types/mocha
Current Version 2.2.47
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

@types/mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

util request - line count

Some recent (and not-so-recent) rule requests hinge on the ability to accurately detect the number of lines spanned by a given piece of code. Something like this would be very helpful:

const lineCount: number = getNewlineCount(node);

Of course, some variations may be needed, specifically the option to ignore lines w/ comments only.

Typescript@next removed/renamed TypeVariable

When using tsutils with the latest Typescript (typescript@next, currently 2.8.0-dev.20180221), they appear to have renamed the TypeVariable interface to InstantiableType. This changed somewhere between commits afc588eb9e6322faf55bc28f26994712e3f02261 and edffb120549536cefd73409cc87f0439dac722cf but I didn't dig deep enough to see where.

If you simply change ts.TypeVariable to ts.InstantiableType in typeguard/type.ts, that fixes the compile error in tsutils, but I don't know if that has other side effects that need investigating, or if you want to rename the checks as a result of the TS renaming.

Feature request: New util to find all imports

tsutils has a function findImports() that finds imports where the argument to the import is a string literal:

const foo = require('foo');

but does not find imports where the argument is dynamically constructed:

const myPath = resolvePathSomehow();
const bar = require(myPath);

It would be handy to have a function that finds this second case for a library like tslint which has a linting rule no-require-imports which should find all occurrences of the require() function, regardless of its argument, but doesn't since it uses the current implementation of findImports(). See this item.

error TS2304: Cannot find name 'Map'.

C:\Users\camer\ts\TsAst [base-class ≑ +0 ~4 -0 !]> tsc
node_modules/tsutils/util/usage.d.ts(30,74): error TS2304: Cannot find name 'Map'.

c:\Users\camer\ts\TsAst\node_modules\tsutils\util\usage.d.ts

export declare function collectVariableUsage(sourceFile: ts.SourceFile): Map<ts.Identifier, VariableInfo>;
  "dependencies": {
    "@types/node": "^8.0.51",
    "tsutils": "^2.12.2",
    "typescript": "^2.6.1"
  },

image

getControlFlowEnd: handle LabeledStatement the same as in endsControlFlow

endsControlFlow applies some special handling to iteration statements (and switch) if they are the child of a LabeledSatement.

This behavior is not quite correct since there may be multiple nested labels.
Either way the result may be surprising.

Decide whether this is a bugfix or a breaking change.

BooleanCompilerOptions uses [email protected] features

See discussion in microsoft/tslint-microsoft-contrib#469 (comment):

Using tsc v2.6.2
node_modules/tsutils/util/util.d.ts(117,73): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(118,1): error TS1128: Declaration or statement expected.
node_modules/tsutils/util/util.d.ts(118,3): error TS1128: Declaration or statement expected.
node_modules/tsutils/util/util.d.ts(119,17): error TS1005: ',' expected.
node_modules/tsutils/util/util.d.ts(119,36): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(119,44): error TS1005: ';' expected.
node_modules/tsutils/util/util.d.ts(120,3): error TS1128: Declaration or statement expected.

tsutils lists its TypeScript dependency as allowing 2.1 and up. Two issues:

  • Either this construct should be simplified or that dependency should be upgraded
  • Can there be builds added that test with TypeScript at the lowest allowed version?

typescript 2.8 problem with 2.27.2

we are still on typescript 2.8 and we are having such error with latest version 2.27.2 :

node_modules/tsutils/typeguard/node.d.ts:67:69 - error TS2694: Namespace 'ts' has no exported member 'ImportTypeNode'.

67 export declare function isImportTypeNode(node: ts.Node): node is ts.ImportTypeNode;

on 2.27.1 it was fine because this line was under // @internal

was this change made by accident, or we just have to stay on 2.27.1 until we upgrade to 2.9 typescript?
2.8 typescript is still supported if I read correctly your package.json

An in-range update of @types/mocha is breaking the build 🚨

Version 5.2.1 of @types/mocha was just published.

Branch Build failing 🚨
Dependency @types/mocha
Current Version 5.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

@types/mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

TypeScript 3 RC? "ts.unescapeIdentifier is not a function"

The 'no-misused-new' rule threw an error in 'D:/Code/WebClient/src/typings/lib.dom.custom.d.ts':
TypeError: ts.unescapeIdentifier is not a function
    at getIdentifierText (D:\Code\WebClient\node_modules\tsutils\util\util.js:872:15)
    at Object.getPropertyName (D:\Code\WebClient\node_modules\tsutils\util\util.js:208:61)
    at cb (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:51:27)
    at visitNodes (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15098:30)
    at Object.forEachChild (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15404:21)
    at cb (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:67:19)
    at visitNodes (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15098:30)
    at Object.forEachChild (D:\Code\WebClient\node_modules\typescript\lib\typescript.js:15324:24)
    at walk (D:\Code\WebClient\node_modules\tslint\lib\rules\noMisusedNewRule.js:49:15)

tslint-eslint-rules failing due to missing type

Currently the project is giving this error:

tslint-eslint-rules/node_modules/tsutils/src/typeguard.d.ts(140,70): error TS2694: Namespace 'ts' has no exported member 'EnumLiteralType'.

Updated all the packages to try to fix it, i noticed that this project has ts ^2.4.0 which is making wonder if their 2.4.1 broke it. I also installed ts 2.4.0 and the error still remains.

is*ScopeBoundary

  • add new function isTypeScopeBoundary
  • isFunctionScopeBoundary
    • add boolean parameter to always consider SourceFile a boundary
    • remove all type-only boundaries
  • introduce ScopeBoundarySelector
export const enum ScopeBoundary {
    None = 0,
    Function = 1,
    Block = 2,
    Type = 4,
}
export const enum ScopeBoundarySelector {
    Function = ScopeBoundary.Function,
    Block = Function | ScopeBounary.Block,
    Type = Block | ScopeBoundary.Type,
}

usage: handle 'const' assertions

1 as const has a TypeReferenceNode where the Identifier is const. This is currently handled as reference to a type named const. This is not a real problem, but needs to be handled eventually.

An in-range update of @types/node is breaking the build 🚨

Version 10.1.4 of @types/node was just published.

Branch Build failing 🚨
Dependency @types/node
Current Version 10.1.3
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

TypeError: Cannot read property 'kind' of undefined

In some projects, I conditionally use longjohn when NODE_ENV !== 'production'. This turns out to break some import/dependency checks I am implementing using tsutils.

Source (yes, that’s it):

require('longjohn');

Result:

TypeError: Cannot read property 'kind' of undefined
    at ImportFinder._findNestedImports (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1070:30)
    at ImportFinder.find (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1016:18)
    at findImportLikeNodes (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:1001:48)
    at Object.findImports (/home/petter/owl/client/devtools/node_modules/tsutils/util/util.js:971:24)
    at p.getSourceFiles.filter.forEach (/home/petter/lint_cmds/depcheck.js:50:6)

The relevant part of the lint command:

const ts = require('typescript');
const p = ts.createProgram(
	tsFiles, // array of paths
	JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'))
);
p.getSourceFiles().forEach((f) => tsutils.findImports(f, 1 | 2 | 16 | 32));

How to I get the moduleName for each SourceFile?

Is there a way to get the moduleNames for a SourceFile? They are all showing up as uknown when I do this?
http://www.typescriptlang.org/docs/handbook/module-resolution.html

import * as ts from "typescript";
import * as fs from "fs";
// import {isTypeReference, isClassDeclaration} from "tsutils";

const tsPath = "node_modules/@types/mocha/index.d.ts"
const options: ts.CompilerOptions = { target: ts.ScriptTarget.ES2015 }
const host = ts.createCompilerHost(options, true);
const program = ts.createProgram([tsPath], options, host)
const checker = program.getTypeChecker()

for (const sf of program.getSourceFiles()){
    console.log(sf.fileName + ": " + sf.moduleName)
}
C:\Users\camer\ts\TsAst [moduleName +1 ~0 -0 !]> node .\modulename.js
C:/Users/camer/ts/TsAst/node_modules/typescript/lib/lib.es6.d.ts: undefined
node_modules/@types/mocha/index.d.ts: undefined
C:/Users/camer/ts/TsAst/node_modules/@types/node/inspector.d.ts: undefined
C:/Users/camer/ts/TsAst/node_modules/@types/node/index.d.ts: undefined

Get the text of a comment??

Would be nice to see a really good example of getting comments from TS using your package. I found out about tsutils from this post but could not quite get it to work like I want.

I also tried an official example from Typescript but ran into problems as well.
Typescript Compiler Example for Type Checker
Issue I posted about the problem

Basically I can only ever get an object with the position of comments but not the text itself or anything else out of it.

Here is my code below:

import * as utils from 'tsutils';
import * as ts from 'typescript';
import {SourceFile} from 'typescript';

function generateDocumentation(
  fileNames: string[],
  options: ts.CompilerOptions
): void {

    // Build a program using the set of root file names in fileNames
    let program = ts.createProgram(fileNames, options);

    // Visit every sourceFile in the program
    for (const sourceFile of program.getSourceFiles()) {
        if (!sourceFile.isDeclarationFile) {
            
            // Walk the tree to search for classes
            //ts.forEachChild(sourceFile, visit);
            visit(sourceFile,sourceFile);
        }
    }

    return;

    /** visit nodes finding exported classes */
    function visit(node: ts.Node, src: SourceFile) {

        utils.forEachComment(node, (fullText: string, comment: ts.CommentRange) => {
            console.log('--- The comment object looks like below ---');
            console.dir(comment);
            //this line definitely does not get the text of the comment, but what does????
            var commentStr: ts.CommentRange = utils.getCommentAtPosition(src,comment.pos);
            console.log('The comment text is ', commentStr);
            console.log('--- --- --- --- ---');
        });

    }

}

generateDocumentation(
    ['src/controllers/testController.ts'], 
    {
        target: ts.ScriptTarget.Latest,
        module: ts.ModuleKind.CommonJS
    }
);

Any chance of some more docs on how to use this package? A good example of getting and displaying comments would be sooooo useful.

endsControlFlow and TryStatement

  • control flow statements inside finally override everything from try and catch if exhaustive.
  • ThrowStatement inside try needs to be filtered if there is a catch clause
  • TryStatements with catch only end control flow if try AND catch definitely end control flow

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.