GithubHelp home page GithubHelp logo

joarwilk / flowgen Goto Github PK

View Code? Open in Web Editor NEW
658.0 11.0 87.0 1.7 MB

Generate flowtype definition files from TypeScript

License: Other

JavaScript 0.90% TypeScript 99.10%
typescript converter flow flowtype cli definition

flowgen's Introduction

Flowgen

The state of the converter

It's surprisingly robust and non-lossy as it stands right now, in big part thanks to how similar flow and typescript definition files are. Please see the output in this flow-typed PR for the state of the output.

Supported? Syntax TypeScript Flow
Void type void void
Undefined type undefined void
Unknown type unknown mixed
Symbol type symbol Symbol
Unique symbol type unique symbol Symbol
Object type object {[key: string]: any}
Never type never empty
Variance interface A { readonly b: B, c: C } interface A { +b: B, c: C }
Functions (a: A, b: B) => C (a: A, b: B) => C
Indexers {[k: string]: string} {[k: string]: string}
This type (this: X, a: A, b: B) => C (a: A, b: B) => C
Type guards (a: X) => a is A (a: X) => boolean
Type parameter bounds function f<A extends string>(a:A){} function f<A: string>(a:A){}
keyof X keyof X $Keys<X>
X[keyof X] X[keyof X] $ElementType<X, $Keys<X>>
Partial Partial<X> $Rest<X, {}>
Readonly Readonly<X> $ReadOnly<X>
ReadonlyArray ReadonlyArray<X> $ReadOnlyArray<X>
ReadonlySet ReadonlySet<X> $ReadOnlySet<X>
ReadonlyMap ReadonlyMap<X, Y> $ReadOnlyMap<X, Y>
Record Record<K, T> { [key: K]: T }
Pick Pick<T, K>
Exclude Exclude<T, U>
Extract Extract<T, U>
NonNullable NonNullable<X> $NonMaybeType<X>
ReturnType ReturnType<F> $Call<<R>((...args: any[]) => R) => R, F>
InstanceType InstanceType<X>
Required Required<X>
ThisType ThisType<X>
T['string'] T['string'] $PropertyType<T, k>
T[k] T[k] $ElementType<T, k>
Mapped types {[K in keyof Obj]: Obj[K]} $ObjMapi<Obj, <K>(K) => $ElementType<Obj, K>>
Conditional types A extends B ? C : D any
typeof operator typeof foo typeof foo
Tuple type [number, string] [number, string]
Type alias type A = string type A = string
type/typeof import import A from 'module' import type A from 'module'

Usage

Install using npm i flowgen --save

import { compiler } from 'flowgen';

// To compile a d.ts file
const flowdef = compiler.compileDefinitionFile(filename);

// To compile a string
const flowdef = compiler.compileDefinitionString(str);

// To compile a typescript test file to JavaScript
// esTarget = ES5/ES6 etc
const testCase = compiler.compileTest(path, esTarget)

Recommended second step:

import { beautify } from 'flowgen';

// Make the definition human readable
const readableDef = beautify(generatedFlowdef);

CLI

Standard usage (will produce export.flow.js):

npm i -g flowgen
flowgen lodash.d.ts

Options

-o / --output-file [outputFile]: Specifies the filename of the exported file, defaults to export.flow.js

Flags for specific cases

--flow-typed-format: Format output so it fits in the flow-typed repo
--compile-tests: Compile any sibling <filename>-tests.ts files found
--no-inexact: Do not mark object types as inexact (using `...`)
--no-module-exports: Convert `export = Type` only to default export, instead of `declare module.exports: Type`
--interface-records: Convert TypeScript interfaces to Exact Objects
--no-jsdoc: Ignore TypeScript JSDoc
--add-flow-header: Add `// @flow` to generated files. Should be used for libs.

The difficult parts

Namespaces

Namespaces have been a big headache. What it does right now is that it splits any namespace out into prefixed global scope declarations instead. It works OK, but its not pretty and there's some drawbacks to it.

External library imports

Definitions in TS and flow are often quite different, and imported types from other libraries don't usually have a one-to-one mapping. Common cases are React.ReactElement, React.CSSPropsetc. This might require manual processing, or we add a set of hardcoded mutations that handle common cases.

Odd TS conventions

Lodash has been one of the reference libraries i've worked with when creating the converter. The definition is mostly just a series of interfaces with the same name being re-declared over and over again for each function, which doesn't translate to flow at all. There's multiple ways of solving this but I don't have a great solution for it in place yet.

Sample of finding all typescript definition files and generate flow file with shell script

If your typescript definition files are built in lib add below shell script and run it.

for i in $(find lib -type f -name "*.d.ts");
  do sh -c "flowgen $i -o ${i%.*.*}.js.flow";
done;

So if you have definition files in different dir, you can rename lib and run the script.

Here’s an example of the above as an npm script in package.json that excludes any typescript definition files found inside node_modules:

  "scripts": {
    "build:flowtypes": "find . -type f -not -path './node_modules/*' -name '*.d.ts' -exec sh -c 'yarn flowgen --add-flow-header $1 -o ${1%.*.*}.js.flow' _ '{}' \\;"
  }

You can then have a build script that generates flow types along the lines of tsc --build && npm run build:flowtypes.

Contributing

All help is appreciated. Please tweet at me if you want some help getting started, or just want to discuss ideas on how to solve the trickier parts.

Distribution

  • git pull origin master
  • yarn compile
  • Change the version in package.json
  • git add .
  • `git commit -m "New release"
  • npm publish
  • git push

flowgen's People

Contributors

0xflotus avatar acusti avatar ajbogh avatar bringking avatar dependabot[bot] avatar erikbrinkman avatar gnprice avatar goodmind avatar hyochan avatar invictusmb avatar joarwilk avatar jt-stripe avatar lgeiger avatar lhchavez avatar moroine avatar namuol avatar orta avatar rattrayalex avatar scimonster avatar sebastiengllmt avatar sibelius avatar swansontec avatar talshani avatar techieshark avatar v-gjy avatar valentinpalkovic avatar vikr01 avatar w01fgang avatar wyozi avatar zxbodya avatar

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flowgen's Issues

transform JSX.Element to React$Node or React.Node

Hi, great work with Flowgen!

I tried to convert some React component definitions yesterday that has JSX.Element types. I think proper way to handle these types is to transform them to React$Node or React.Node automatically instead of global$JSX$Element. I think it's safe assumption in Flow since Flow assumes all the JSX to be React anyways, which means only JSX you can have in Flow codebase is React. Where this kind of logic would belong in the code base if I would want to give it a try?

Here is an example input and output of current behaviour:

Input:

/// <reference types="react" />
import * as React from 'react';
declare class Button extends React.PureComponent<React.ButtonHTMLAttributes<HTMLButtonElement> & {
    active?: boolean;
    children?: string | JSX.Element;
    fullWidth?: boolean;
    icon?: JSX.Element;
    small?: boolean;
    large?: boolean;
    primary?: boolean;
    secondary?: boolean;
    destructive?: boolean;
    linkDefault?: boolean;
    link?: boolean;
    loading?: boolean;
}> {
    render(): JSX.Element;
}
export default Button;

Output:

import * as React from "react";
declare class Button
  mixins React.PureComponent<
      React.ButtonHTMLAttributes<HTMLButtonElement> & {
        active?: boolean,
        children?: string | global$JSX$Element,
        fullWidth?: boolean,
        icon?: global$JSX$Element,
        small?: boolean,
        large?: boolean,
        primary?: boolean,
        secondary?: boolean,
        destructive?: boolean,
        linkDefault?: boolean,
        link?: boolean,
        loading?: boolean
      }
    > 
  render(): global$JSX$Element;
}
declare export default typeof Button;

Typescript version is incorrect

Installing flowgen globally using

yarn global add flowgen

install typescript 2.8.3 as a dependency instead of 2.4.2

This is due to the semver dependency "typescript": "^2.4.2"

I changed it locally to "typescript": "~2.4.2" which only update patch version and it fixed.

note that tests doesn't pass on 2.8.3 so I will address this in a different ticket.

Status of the project?

First of all this project is getting less attention than it suppose.

Even if it is not able to convert all definitions 100% reliably it can serve as a starting point. This tool should be part of flow-typed. If flow-typed can not find original flow definitions it can search DefinetlyTyped for definition, download it and convert to flow with flowgen. If there is no DefinetlyTyped definitions it can generate stubs.

Other questions is how to improve and verify quality of generated code.

There is flow-to-typescript. We can convert from ts to flow and then from flow to ts and compare results. If they are identical it means, that you are lucky one you have definition without ambiguation.

There is type-profile, which can gather runtime type information, which can be used to verify type signatures. For example, we can run tests, gather info about types and compare to what we have. Idea not new, there are similar project for Python - MonkeyType, for Ruby - ruby-type-inference.

There is babel-plugin-transform-flow-to-gen. We can use type signatures to generate property based tests (like QuickCheck in Haskell) and run those.

There is flow definition linting tool.

Related https://github.com/stereobooster/type-o-rama, flow-typed/flow-typed#1494

Replace js-beautify with prettier?

I couldn't find any clues if js-beautify is aware of flow syntax, but I am sure that prettier does.
I think replacing js-beautify with prettier will be more flow compliant.

Using it on the codebase to prettify it and force a common code style is also a good idea.
If you think it is a good idea, I have a branch locally I can PR

No // @flow ?

Hi, I have a quick question.
AFAIK, in order to Flow work, we need // @flow this line on the top.
But it didn't write this line for us?

I used CLI flowgen.
Thanks.

Doesn't create directory structure for output file

flowgen doesn't seem to create non-existent directories when one is provided in the output file. It should create all directories up to the filename, or provide an option to do so.

For instance, I do not yet have a flow-typed folder, so this command fails:

$ flowgen ${file} -o ./flow-typed/test.flow.js;

{ Error: ENOENT: no such file or directory, open './flow-typed/test.flow.js'

undefined inside union type produces NO PRINT IMPLEMENTED

When trying to convert lodash typings

        find<T>(
            collection: List<T>,
            predicate?: ListIterator<T, boolean>,
            thisArg?: any
        ): T | undefined;

produces the following output

            find<T>(
                collection: List<T>,
                predicate?: ListIterator<T, boolean>,
                thisArg?: any): T | NO PRINT IMPLEMENTED: function Object() {
                [native code]
            },

Locally installed flowgen breaks jest

Maybe it's problem on jest side, I'm not sure, but when I installed flowgen yarn add -D flowgen it broke locally installed jest.

TypeError: projects.map is not a function
    at Object.<anonymous> (/Users/.../app-js/node_modules/jest-cli/build/cli/runCLI.js:112:28)
    at Generator.next (<anonymous>)
    at step (/Users/.../app-js/node_modules/jest-cli/build/cli/runCLI.js:1:260)
    at /Users/.../app-js/node_modules/jest-cli/build/cli/runCLI.js:1:490
    at Promise (<anonymous>)
    at Object.<anonymous> (/Users/.../app-js/node_modules/jest-cli/build/cli/runCLI.js:1:171)
    at Object.module.exports [as runCLI] (/Users/.../app-js/node_modules/jest-cli/build/cli/runCLI.js:139:50)
    at Object.run (/Users/.../app-js/node_modules/flowgen/node_modules/jest-cli/build/cli/index.js:41:17)
    at Object.<anonymous> (/Users/.../app-js/node_modules/flowgen/node_modules/jest-cli/bin/jest.js:16:25)
    at Module._compile (module.js:573:30)

winstonjs conversion fails

I've done a lot of digging on this, but I'm afraid I don't know enough about the TS compiler to understand what's going on. Easy repro, as well.

Just run flowgen on any TS definition in winstonjs/winston:

declare module.exports: typeof winston - index.d.ts
declare var winston: winston.Transports; - transports/index.d.ts

Miss some newlines in generated defintions

First of all thank you for this work. This project definitely need more love and maybe it should be transferred to Flow org to get more attention. Even if it can not be used transform everything, it can serve as starting point for handcrafted definitions.

Here is a problem:

✗ flowgen flow-typed/npm/react-router-redux_v4.x.x.d.ts -o flow-typed/npm/react-router-redux_v4.x.x.js

react-router-redux_v4.x.x.d.ts

I get this output

declare export var CALL_HISTORY_METHOD: string;
declare export var LOCATION_CHANGE: string;
declare export interface LocationActionPayload {
    method: string,
        args?: any[]
}
declare export type RouterAction = {
    payload?: LocationActionPayload
} & Action
declare export type LocationAction = (nextLocation: LocationDescriptor) => RouterAction;
declare export type GoAction = (n: number) => RouterAction;
declare export type NavigateAction = () => RouterAction;
declare export var push: LocationAction;
declare export var replace: LocationAction;
declare export var go: GoAction;
declare export var goBack: NavigateAction;
declare export var goForward: NavigateAction;
declare export interface RouteActions {
    push: typeof push,
        replace: typeof replace,
        go: typeof go,
        goForward: typeof goForward,
        goBack: typeof goBack
}
declare export var routerActions: RouteActions;
declare export interface RouterState {
    locationBeforeTransitions: Location
}
declare export type DefaultSelectLocationState = (state: any) => RouterState;
declare export interface SyncHistoryWithStoreOptions {
    selectLocationState?: DefaultSelectLocationState,
        adjustUrlOnReplay?: boolean
}
declare export interface HistoryUnsubscribe {
    unsubscribe(): void
}
declare export function routerReducer(state?: RouterState, action?: Action): RouterStatedeclare export function syncHistoryWithStore(
    history: History,
    store: Store<any>,
    options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribedeclare export function routerMiddleware(history: History): Middleware

Pay attention to

declare export function routerReducer(state?: RouterState, action?: Action): RouterStatedeclare export function syncHistoryWithStore(

Should be

declare export function routerReducer(state?: RouterState, action?: Action): RouterState
declare export function syncHistoryWithStore(

and

    options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribedeclare export function routerMiddleware(history: History): Middleware

should be

    options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe
declare export function routerMiddleware(history: History): Middleware

Also I need to add this

import type { Middleware, Store } from "redux";
type Action = any;

import type { Location } from "react-router";
type Path = string;
type LocationDescriptor = Path | Location;

declare module "react-router-redux" {
...
}

And it is working 👌

Suggestion : add @types/flowgen to DefinitlyTyped repo

Here is a suggestion that i created in one of my typescript project :

declare module 'flowgen' {
  const defaultExport: {
    compiler: {
      compileDefinitionFile: (filePath: string) => string;
      compileDefinitionString: (str: string) => string;
      compileTest: (path: string, esTarget: string) => string;
    };
    beautify: (generatedFlowdef: string) => string;
  };
  export default defaultExport;
}

Crash with latest release

When running the danger deploy:

TypeError: Cannot read property 'elements' of undefined
    at Import.print (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/nodes/import.js:45:60)
    at /Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/compiler.js:23:18
    at Array.map (<anonymous>)
    at compile (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/compiler.js:22:39)
    at Object.compileDefinitionFile (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/compiler.js:44:12)
    at /Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/runner.js:56:51
    at Array.forEach (<anonymous>)
    at Object.compile (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/runner.js:35:13)
    at Command.<anonymous> (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/lib/cli/index.js:20:6)
    at Command.listener (/Users/ortatherox/.npm/_npx/23340/lib/node_modules/flowgen/node_modules/commander/index.js:315:8)

nested modules

I'm trying to convert https://github.com/photonstorm/phaser-ce/blob/master/typescript/phaser.d.ts, and rather than using nested namespaces, it's using nested modules. If I convert these to namespace, then flowgen successfully un-nests them, but it leaves nested module declarations as nested.

I suspect that this d.ts should be updated to use namespace instead of module in all but the root case but it would also be nice if flowgen handled this gracefully.

It also seems like classes aren't getting prefixed when pulled out in the namespace flattening process.

Getting 'NO PRINT IMPLEMENTED' for a few scenarios

I was trying to generate a type definition for popsicle.

I grabbed the Typescript definition from typings but there were a few scenarios that seemed to fail. Not sure if I should list them all here, but here were 2 of them.

exec(cb: (error: PopsicleError | null, response?: Response) => void): void;
produced

  exec(
            cb: (
                error: PopsicleError | NO PRINT IMPLEMENTED: NullKeyword,
                response?: Response) => void): void;

on(event: keyof Events, fn: (this: this, ...args: any[]) => void): this;
produced

on(
            event: NO PRINT IMPLEMENTED: function Object() {
                [native code]
            },
            fn: (this: this, ...args: any[]) => void): this;

Silent failure to write

After executing flowgen globals.d.ts on a file which contains minimal contents, there is no written flowtype file.

// globals.d.ts
export type AssayType = 'DNA' | 'cfDNA' | 'RNA' | 'IHC';

My terminal output when executing flowgen globals.d.ts is "Parsing globals", but no other output.

Missing features or transforms

This issue would track what I can find is missing from converter when you typecheck resulting Flow files.

This list will be updated when I find something new

  1. Unexpected use of this type.
    This happens because Flow doesn't understand this outside of class declarations

    Example:

    declare interface A {
      foo(): this;
      bar(): this;
    }
  2. Illegal name. or Unsupported key in object type. when numbers used as keys in interfaces or types.

    type Foo = {
      0: "ACCESS";
    }
    interface IFoo {
      0: "ACCESS";
    }

    Flow PR: facebook/flow#7593

Abstract classes

I just started with flow and I am new to the topic of typed javascript. Among others, I need to convert
this library.

When I run flowgen on it, it seems the whole abstract class abstract class Locator<E, L, V> and its methods are omitted.

Why is this the case? Especially these methods are important and as they appear nowhere in the generated flow definition I think this will cause trouble...

Also I have seen than an enum was omitted:

export const enum State {
    Fulfilled = 0,
    ...
}

Generated files shouldn't claim authorship by flowgen author

I'm very grateful for this module and I appreciate the effort that's gone into it, but I think it's potentially confusing to default to including flowgen's own author an repo details in a doc comment at the top of every file it outputs:

/**
 * Flowtype definitions for index
 * Generated by Flowgen from a Typescript Definition
 * Flowgen v1.8.2
 * Author: [Joar Wilk](http://twitter.com/joarwilk)
 * Repo: http://github.com/joarwilk/flowgen
 */

// ...followed by MY type defs

At a glance it seems to claim authorship of the file, which is not the case. (I am just talking about the 'Author' and 'Repo' lines – the rest of the comment is good.)

Odd TS conventions

Lodash has been one of the reference libraries i've worked with when creating the converter. The definition is mostly just a series of interfaces with the same name being re-declared over and over again for each function, which doesn't translate to flow at all. There's multiple ways of solving this but I dont have a great solution for it in place yet.

As per TS Docs they can all be merged together. I assume that's what TS type checker does internally.
https://www.typescriptlang.org/docs/handbook/declaration-merging.html

Did I understand correctly the issue?

1.5.3 fails on vars parsing

Hi there.

Caught an error on const declaration parsing:

Input index.d.ts:

declare module '@qiwi/cyclone/lib/es5/error' {
	export const TRANSITION_VIOLATION: string;
	export const INVALID_UNLOCK_KEY: string;
	export const LOCK_VIOLATION: string;
	export const UNREACHABLE_STATE: string;
	export class MachineError extends Error {
	}
}

Exception:

TypeError: factory.createVariableNode is not a function
    at collectNode (/Users/antongolub/projects/cyclone/node_modules/flowgen/lib/parse.js:119:57)
    at /Users/antongolub/projects/cyclone/node_modules/flowgen/lib/parse.js:152:14
    at Array.forEach (<anonymous>)
    at traverseNode (/Users/antongolub/projects/cyclone/node_modules/flowgen/lib/parse.js:151:21)
    at collectNode (/Users/antongolub/projects/cyclone/node_modules/flowgen/lib/parse.js:98:9)

After refactoring the previous parse.js implementation (which refers to factory.createVariableNode) is still present in package. Once parse.js is deleted, everything works as it should.

screenshot 2019-02-05 at 11 42 50

Could anybody repack / publish a new version?

ExportDeclaration

Trying to use this on apollo-client's index.d.ts I'm getting:

Parsing index
Missing node parse ExportDeclaration

And looking at parser.js this is effectively not supported.
Are you aware of this issue?

Add a GitHub issue template

Ideally this would have instructions on how to get set up to write a test for the bits of definition file that aren't converting, as well as showing what they think it should look like.

Cannot reference type from a value position.

Not sure why I'm getting this issue...happy to post more info if needed.

Cannot reference type myproject$proto$Point [1] from a value position.

[1] 86│ declare interface myproject$proto$Point {
:
104│ * Represents a Point.
105│ /
106│ declare class myproject$proto$Point
107│ mixins myproject$proto$Point {
108│ /
*
109│ * Constructs a new Point.
110│ * @param properties Properties to set

Conversion failure for union types with strings

If you have a d.ts file with this line:
export declare type MediaType = 'Video' | 'Audio' | 'Image' | 'Text' | 'Other';

the conversion yields:
declare export type MediaType = Video |
Audio |
Image |
Text |
Other;

The quotation marks are removed, so the resulting union type declaration is invalid.

Function and namespace declarations are not merged

Assigning a value to a key in a function is a somewhat common pattern, especially in React for setting defaultProps on stateless functional components:

import React from 'react';

interface Props: {
    a: number,
    b: string,
};

function Component({a, b}: Props): React.ReactNode {
    return <div>a is {a} and b is {b}</div>;
}

Component.defaultProps = {
    a: 1,
};

export default Component;

tsc generates something like this as its corresponding .d.ts header:

// this is the callable signature
declare function Component({a, b}: Props): JSX.Element;

// any additional values on the function go here
declare namespace Component {
    var defaultProps: {
        a: number;
    }
}

This is valid because of TypeScript's declaration merging which causes tsc to interpret the function and namespace declarations with the same name to mean "this is a function that also has some values in it". Flow does not have this merging, so the correct way to express this concept in Flow typedefs is this:

declare var Component {
    // this is the callable signature
    (p: Props): React$Node;
    // any additional values on the function go here
    defaultProps: {
        a: number;
    };
}

Flowgen generates this instead, which is a pretty faithful translation of the source .d.ts file given that Flow doesn't support namespaces:

// this is the callable signature
declare function Component(x: Props): React$Node;
declare var Component: typeof npm$namespace$Component;

// any additional values on the function go here
declare var npm$namespace$Component: {
    defaultProps: typeof Component$defaultProps;
};
declare var Component$defaultProps: {
    a: number;
};

However, this is invalid in Flow and it isn't happy:

7: declare function Component(x: Props): React$Node;
                             ^ property `defaultProps` is missing in function type [1] but exists in object type [2].
References:
7: declare function Component(x: Props): React$Node;
                             ^ [1]
8: declare var Component: typeof npm$namespace$Component;
                          ^ [2]
8: declare var Component: typeof npm$namespace$Component;
                          ^ a call signature declaring the expected parameter / return type is missing in object type [1] but exists in function type [2].
References:
8: declare var Component: typeof npm$namespace$Component;
                          ^ [1]
7: declare function Component(x: Props): React$Node;

source tryflow

Flowgen needs to be able to detect when a .d.ts file is declaring a function and namespace with the same name and generate a single Flow var declaration that has a callable signature as well as the types of the properties on the function.

Formatting with prettier breaks

[error] dist/private/js/index.flow.js: SyntaxError: `declare export interface` is not supported. Use `export interface` instead (5:16)
[error]   3 |  * Properties of a CustomMessage.
[error]   4 | */
[error] > 5 | declare export interface ICustomMessage {
[error]     |                ^
[error]   6 |
[error]   7 | /**
[error]   8 |  * CustomMessage payload

--flow-typed-format doesn't work

Running

$ flowgen --flow-typed-format build/focus.d.ts
Parsing focus
Missing node parse ExportDeclaration

Doesn't produce any output file.
However,

$ flowgen build/focus.d.ts
Parsing focus
Missing node parse ExportDeclaration

does.

declare type FakeEventType = {
keyCode: number,
preventDefault(): void
};
export type KeyDownEventType = {
key: number,
target?: HTMLElement,
originalEvent: KeyboardEvent | FakeEventType | MouseEvent
};
declare var focus: (toFocus: string) => void;
declare var fakeKeyDown: (fakeEvent: FakeEventType) => boolean;
declare var fakeEnter: () => boolean;
declare var fakeReturn: () => boolean;

$ flowgen -V
1.3.0

focus.d.ts

declare type FakeEventType = {
keyCode: number;
preventDefault(): void;
};
export declare type KeyDownEventType = {
key: number;
target?: HTMLElement;
originalEvent: KeyboardEvent | FakeEventType | MouseEvent;
};
declare const focus: (toFocus: string) => void;
declare const fakeKeyDown: (fakeEvent: FakeEventType) => boolean;
declare const fakeEnter: () => boolean;
declare const fakeReturn: () => boolean;
export { focus, fakeKeyDown, fakeEnter, fakeReturn };
//# sourceMappingURL=focus.d.ts.map

Object.keys().includes is not a function

I am getting the following error when running from the npm package. Is the npm package working as expected? I might try this from source.

npm WARN [email protected] requires a peer of typescript@>=2.0.0 but none was installed.
λ ~/Developer/hpe/DefinitelyTyped/ master flowgen grommet/index.d.ts 
Parsing index
Parsing index failed
[TypeError: Object.keys(...).includes is not a function]

P.S. thanks for this package!!

Split library and cli

Would be cool to not have index.js being the commander script, but exposing flowgen as a library instead.

I would like to use flowgen in a project, and having the cli exposed as the index of the package makes it harder to integrate flowgen in a build process without having to pass by shell script.

This would not remove the runner from package.json bin.

The ouputFile is overwritten while iterating over multiple .d.ts files

I would like to automatically convert typescript files in-place to flow files. I found that I could include multiple typescript files by using a glob pattern, however the output file option seems to only accept a single filename.

When the single output file is generated it only includes the type information for the last file iterated upon.

flowgen ./dist/**/*.d.ts -o ./dist/example.flow.js

The code should either append all types into this single output file, or it should allow a similar Glob pattern and generate flow files based on the same root name (everything before .d.ts).

# concatenate all types to one file
flowgen ./dist/**/*.d.ts -o ./dist/example.flow.js

# create files with similar names and folder structure
flowgen ./dist/**/*.d.ts -o ./dist/**/*.flow.js

outputFile,

Workaround:

Add the following code to your package.json

"flowgen": "for file in $(find ./dist -name *.d.ts -type f); do flowgen ${file} -o ${file/.d.ts/.flow.js}; done;"

Run the command with npm run flowgen.

Alternatively, if flowgen is installed globally by npm install -g flowgen then you can use the command directly in the terminal:

for file in $(find ./dist -name *.d.ts -type f); do flowgen ${file} -o ${file/.d.ts/.flow.js}; done;

Repeated functions declarations in lodash

Not sure where else to bring this up, but regarding the repeated declarations of the same function in the lodash typedefs that you mentioned in the README: those are probably overloads. I'm just starting out with Flow, but it seems overloading is supported in Flow as well.

TypeScript definition that relies on importing sub-definition doesn't work at all.

For example, this is the index.d.ts of firebase:
https://github.com/firebase/firebase-js-sdk/blob/master/packages/firebase/index.d.ts

And here's what flowgen outputs:

declare module.exports: typeof firebase

Which is obviously unusable.

From the readme, it's stated that "imported types from other libraries dont usually have a one-to-one mapping." However, in this case, it's importing its own sub-definition, albeit from other packages, which is in TS. So, flowgen can't ignore import statement completely.

Import type, missing "type" keyword

Hi,
I have type import in my ts file:
import { HttpRequest } from "./httpRequests"

but the generated flow declaration states:
import { HttpRequest } from './httpRequests'; instead of import type { HttpRequest } from './httpRequests';

Shouldn't be this automatically transpiled? Tried last flowgen from repo. Thanks.

Missing node parse ExportDeclaration

Getting strange errors while trying to generate flow type definitions for bloomer:

npm install bloomer
cd node_modules/bloomer/lib/
flowgen index.d.ts 
Parsing index
Missing node parse ExportDeclaration
Missing node parse ExportDeclaration
Missing node parse ExportDeclaration
Missing node parse ExportDeclaration
Missing node parse ExportDeclaration
Missing node parse ExportDeclaration
...
flowgen bulma.d.ts 
Parsing bulma
"NO PRINT IMPLEMENTED: TypeOperator"
flowgen elements/Box.d.ts 
Parsing Box
NO MEMBERS_ NodeObject {
  pos: 169,
  end: 271,
  flags: 0,
  transformFlags: undefined,
  parent: undefined,
 ...

flowtype format failed

on OSX

https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/uws/index.d.ts

flowgen --flow-typed-format uws.ts
Parsing u
Parsing u failed
{ Error: ENOENT: no such file or directory, mkdir '../exports/u_v1.x.x'
    at Object.fs.mkdirSync (fs.js:887:18)
    at exportForFlowTyped (/Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/lib/cli/flow-typed-exporter.js:21:18)
    at /Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/lib/cli/runner.js:77:40
    at Array.forEach (<anonymous>)
    at Object.compile (/Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/lib/cli/runner.js:50:13)
    at Command.<anonymous> (/Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/lib/cli/index.js:25:6)
    at Command.listener (/Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/node_modules/commander/index.js:301:8)
    at emitOne (events.js:115:13)
    at Command.emit (events.js:210:7)
    at Command.parseArgs (/Users/bradennapier/.nvm/versions/node/v8.8.1/lib/node_modules/flowgen/node_modules/commander/index.js:617:12)
  errno: -2,
  code: 'ENOENT',
  syscall: 'mkdir',
  path: '../exports/u_v1.x.x' }

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.