@khanacademy/graphql-flow 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.github/workflows/pr-checks.yml +4 -6
  2. package/CHANGELOG.md +22 -0
  3. package/Readme.md +41 -167
  4. package/dist/__test__/example-schema.graphql +67 -0
  5. package/dist/__test__/generateTypeFileContents.test.js +157 -0
  6. package/dist/__test__/graphql-flow.test.js +639 -0
  7. package/dist/__test__/processPragmas.test.js +76 -0
  8. package/dist/cli/__test__/config.test.js +120 -0
  9. package/dist/cli/config.js +45 -106
  10. package/dist/cli/config.js.flow +37 -159
  11. package/dist/cli/config.js.map +1 -1
  12. package/dist/cli/run.js +40 -36
  13. package/dist/cli/run.js.flow +56 -42
  14. package/dist/cli/run.js.map +1 -1
  15. package/dist/cli/schema.json +91 -0
  16. package/dist/enums.js +9 -9
  17. package/dist/enums.js.flow +11 -11
  18. package/dist/enums.js.map +1 -1
  19. package/dist/generateResponseType.js +47 -47
  20. package/dist/generateResponseType.js.flow +55 -57
  21. package/dist/generateResponseType.js.map +1 -1
  22. package/dist/generateTypeFiles.js +13 -17
  23. package/dist/generateTypeFiles.js.flow +21 -43
  24. package/dist/generateTypeFiles.js.map +1 -1
  25. package/dist/generateVariablesType.js +24 -24
  26. package/dist/generateVariablesType.js.flow +25 -28
  27. package/dist/generateVariablesType.js.map +1 -1
  28. package/dist/index.js +0 -8
  29. package/dist/index.js.flow +4 -5
  30. package/dist/index.js.map +1 -1
  31. package/dist/parser/__test__/parse.test.js +247 -0
  32. package/dist/types.js.flow +26 -6
  33. package/package.json +3 -2
  34. package/src/__test__/generateTypeFileContents.test.js +3 -1
  35. package/src/__test__/graphql-flow.test.js +7 -7
  36. package/src/__test__/processPragmas.test.js +28 -15
  37. package/src/cli/__test__/config.test.js +110 -84
  38. package/src/cli/config.js +37 -159
  39. package/src/cli/run.js +56 -42
  40. package/src/cli/schema.json +91 -0
  41. package/src/enums.js +11 -11
  42. package/src/generateResponseType.js +55 -57
  43. package/src/generateTypeFiles.js +21 -43
  44. package/src/generateVariablesType.js +25 -28
  45. package/src/index.js +4 -5
  46. package/src/types.js +26 -6
  47. package/dist/cli/utils.js +0 -21
  48. package/dist/cli/utils.js.flow +0 -14
  49. package/dist/cli/utils.js.map +0 -1
  50. package/dist/jest-mock-graphql-tag.js +0 -88
  51. package/dist/jest-mock-graphql-tag.js.flow +0 -96
  52. package/dist/jest-mock-graphql-tag.js.map +0 -1
  53. package/src/cli/__test__/utils.test.js +0 -19
  54. package/src/cli/utils.js +0 -14
  55. package/src/jest-mock-graphql-tag.js +0 -96
@@ -22,16 +22,14 @@ jobs:
22
22
  node-version: ${{ matrix.node-version }}
23
23
 
24
24
  - name: Get All Changed Files
25
- uses: jaredly/get-changed-files@absolute
25
+ uses: Khan/actions@get-changed-files-v1
26
26
  id: changed
27
- with:
28
- format: 'json'
29
27
 
30
28
  - id: js-files
31
29
  name: Find .js changed files
32
30
  uses: Khan/actions@filter-files-v0
33
31
  with:
34
- changed-files: ${{ steps.changed.outputs.added_modified }}
32
+ changed-files: ${{ steps.changed.outputs.files }}
35
33
  extensions: '.js'
36
34
 
37
35
  - name: Run Flow
@@ -42,7 +40,7 @@ jobs:
42
40
  uses: Khan/actions@filter-files-v0
43
41
  name: Files that would trigger a full eslint run
44
42
  with:
45
- changed-files: ${{ steps.changed.outputs.added_modified }}
43
+ changed-files: ${{ steps.changed.outputs.files }}
46
44
  files: '.eslintrc.js,package.json,.eslintignore'
47
45
 
48
46
  - name: Eslint
@@ -57,7 +55,7 @@ jobs:
57
55
  uses: Khan/actions@filter-files-v0
58
56
  name: Files that would trigger a full jest run
59
57
  with:
60
- changed-files: ${{ steps.changed.outputs.added_modified }}
58
+ changed-files: ${{ steps.changed.outputs.files }}
61
59
  files: 'package.json,package-lock.json'
62
60
 
63
61
  - name: Jest
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @khanacademy/graphql-flow
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 1e1de13: BREAKING: Change config file format, split into 'crawl' and 'generate' sections
8
+ See schema.json for new organization.
9
+ - 284be55: [breaking] remove support for running graphql-flow via jest
10
+
11
+ Now the cli tool is the only way to invoke graphql-flow.
12
+
13
+ - 9f7f2d1: Breaking: removed support for multiple config files (to be replaced with override support in the central config file)
14
+
15
+ ### Minor Changes
16
+
17
+ - a99fc38: Support multiple 'generate' configs, allowing projects to have different settings for different directories or files
18
+
19
+ `config.generate` can now be an object or an array of objects, with `match` and `exclude` arrays (either a RegExp or a string that will be passed to `new RegExp()`) to fine-tune which files they apply to.
20
+
21
+ ### Patch Changes
22
+
23
+ - bcc06d0: Use jsonschema for validating the config file
24
+
3
25
  ## 0.3.0
4
26
 
5
27
  ### Minor Changes
package/Readme.md CHANGED
@@ -4,44 +4,7 @@ This is a tool for generating flow types from graphql queries in javascript fron
4
4
 
5
5
  ## Using as a CLI tool
6
6
 
7
- Write a config file, with the following options:
8
-
9
- ```json
10
- {
11
- // Response to the "introspection query" (see below), or a .graphql schema file.
12
- // The file extension indicates the format, .json or .graphql (default .json).
13
- // This path is resolved relative to the config file location.
14
- "schemaFilePath": "../some/schema-file.json",
15
- // List of regexes
16
- "excludes": ["\\bsome-thing", "_test.jsx?$"],
17
- // Options for type generation (see below)
18
- "options": {
19
- "scalars": {
20
- "JSONString": "string"
21
- }
22
- }
23
- }
24
- ```
25
-
26
- Optionally add subconfig files to subdirectories for granular control of behavior, with the following options:
27
-
28
- ```json
29
- {
30
- // Note that this file must be named, or end with, "graphql-flow.config.json"
31
- // I.e., "my-service.graphql.config.json" would also work.
32
- // These files will affect the directory in which they are located and all subdirectories, unless overridden by a deeper subconfig.
33
-
34
- // Optionally add the path of another config file. Can be the root config (provided when running the script) or any other subconfig to merge options.
35
- // If a chain of extends are provided, will resolve in order. Be sure not to extend in a circle-- currently, this will just cause a stack overflow error.
36
- // Cannot currently override `schemaFilePath`.
37
- "extends": "./another/config/from/root.config.json",
38
- // Can extend or override `excludes` and `options`.
39
- "excludes": ["\\bsome-thing", "_test.jsx?$"],
40
- "options": {
41
- ...
42
- }
43
- }
44
- ```
7
+ Write a config file, following the schema defined in [src/cli/schema.json](src/cli/schema.json), either as a `.json` file, or a `.js` file that `module.exports` an object adhering to the schema.
45
8
 
46
9
  Then run from the CLI, like so:
47
10
 
@@ -49,143 +12,54 @@ Then run from the CLI, like so:
49
12
  $ graphql-flow path/to/config.json
50
13
  ```
51
14
 
52
- Files will be discovered relative to the current working directory.
53
-
54
- To specify what file should be checked, pass them in as subsequent cli arguments.
55
-
56
- ## Options (for the cli 'options' config item, or when running from jest):
57
-
58
- ```ts
59
- type Options = {
60
- // These are from the `documentToFlowTypes` options object above
61
- strictNullability: boolean = true,
62
- readOnlyArray: boolean = true,
63
- scalars: {[key: string]: 'string' | 'boolean' | 'number'}
64
-
65
- // Specify the name of the generated types directory. If this
66
- // is a relative path, then this is used to suffix the output
67
- // directory; if it's an absolute path it's used to prefix the
68
- // output directory. For instance, if a gql directive is
69
- // found in /foo/bar/baz/query.js and you run the cli (or
70
- // jest) from directory /foo, then:
71
- // * if `generatedDirectory` is "__generated__", the output will
72
- // be in /foo/bar/baz/__generated__/index.js and sibling files
73
- // * if `generatedDirectory` is "/tmp/__generated__", the output
74
- // will be in /tmp/__generated__/bar/baz/index.js and sibling
75
- // files.
76
- generatedDirectory: string = '__generated__',
77
-
78
- // The default generated type contains both the types of the response
79
- // and the variables, combined as [operatioName]Type. Setting
80
- // `splitTypes = true` adds the additional exports [operationName]
81
- // (for the response) and [operationName]Variables (for the variables).
82
- splitTypes?: boolean,
83
-
84
- // Specify an opt-in pragma that must be present in a graphql string source
85
- // in order for it to be picked up and processed
86
- // e.g. set this to `"# @autogen\n"` to only generate types for queries that
87
- // have the comment `# @autogen` in them.
88
- pragma?: string,
89
- // Specify a pragma that will turn off `strictNullability` for that
90
- // source file. e.g. `"# @autogen-loose\n"`.
91
- loosePragma?: string,
92
- // If neither pragma nor loosePragma are specified, all graphql documents
93
- // that contain a query or mutation will be processed.
94
-
95
- // Any graphql operations containing ignorePragma will be skipped
96
- ignorePragma?: string,
97
-
98
- // Set to true to mirror gqlgen's behavior of exporting all
99
- // nested object types within the response type.
100
- // Names are generated by concatenating the attribute names
101
- // of the path to the object type, separated by underscores.
102
- exportAllObjectTypes?: boolean,
103
-
104
- // A template for the name of generated files
105
- // default: [operationName].js
106
- typeFileName?: string,
107
-
108
- // Generate flow enums to replace literal unions in generated types. Exports
109
- // each set of enums from each file regardless of other options. Designated
110
- // "experimental" because of bug in eslint that requires config comments.
111
- experimentalEnums?: boolean,
112
- }
113
- ```
114
-
115
- ## Using from jest
116
-
117
- You can also use jest to do the heavy lifting, running all of your code and collecting queries
118
- by mocking out the `graphql-tag` function itself. This requires that all graphql operations are
119
- defined at the top level (no queries defined in functions or components, for example), but does
120
- support complicated things like returning a fragment from a function (which is probably
121
- not a great idea code-style-wise anyway).
122
-
123
- ### jest-setup.js
124
-
125
- Add the following snippet to your jest-setup.js
15
+ Files will be discovered relative to the `crawl.root`.
126
16
 
127
- ```js
128
- if (process.env.GRAPHQL_FLOW) {
129
- jest.mock('graphql-tag', () => {
130
- const introspectionData = jest.requireActual(
131
- './server-introspection-response.json',
132
- );
133
-
134
- return jest.requireActual('../tools/graphql-flow/jest-mock-graphql-tag.js')(
135
- introspectionData,
136
- // See "Options" type above
137
- {
138
- pragma: '# @autogen\n',
139
- loosePragma: '# @autogen-loose\n',
140
- }
141
- );
142
- });
143
- }
144
- ```
17
+ ### Multiple generate configs
145
18
 
146
- That will mock out the `graphql-tag` function, so that everywhere you call 'gql`some-query`', we'll pick it up and
147
- generate a type for it! As written, the mocking only happens if the `GRAPHQL_FLOW` env variable is set, so that it won't run every time.
19
+ To customize type generation for certain directories or files, you can provide multiple
20
+ `generate` configs as an array, using `match` and `exclude` to customize behavior.
148
21
 
149
- By default, all queries are processed. To have them 'opt-in', use the `pragma` and `loosePragma` options. Queries with `loosePragma` in the source will have types generated that ignore nullability.
22
+ For a given file containing operations, the first `generate` config that matches that path
23
+ (and doesn't exclude it) will be used to generate types for those operations. If a `generate`
24
+ config doesn't have a `match` attribute, it will match all files (but might exclude some via the
25
+ `exclude` attribute).
150
26
 
151
- ### Ensure all files with queries get processed by jest
27
+ For example:
152
28
 
153
- Then you'll want to make a pseudo-'test' that makes sure to 'require' all of the files that define queries, so that
154
- jest will process them and our mock will see them.
155
29
  ```js
156
- // generate-types.test.js
157
- import {findGraphqlTagReferences} from '../tools/graphql-flow/find-files-with-gql';
158
- import path from 'path';
159
-
160
- if (process.env.GRAPHQL_FLOW) {
161
- findGraphqlTagReferences(path.join(__dirname, '..')).forEach(name => {
162
- require(name);
163
- });
164
-
165
- it('should have found queries', () => {
166
- const gql = require('graphql-tag')
167
- expect(gql.collectedQueries.length).toBeGreaterThan(0)
168
- })
169
- } else {
170
- it(`not generating graphql types because the env flag isn't set`, () => {
171
- // not doing anything because the env flag isn't set.
172
- })
173
- }
174
- ```
175
-
176
- ### Run that test to generate the types!
177
-
178
- You can add a script to package.json, like so:
179
- ```json
180
- "scripts": {
181
- "generate-types": "env GRAPHQL_FLOW=1 jest generate-types.test.js"
182
- }
30
+ // dev/graphql-flow/config.js
31
+
32
+ const options = {
33
+ schemaFilePath: "../../gengraphql/composed-schema.graphql",
34
+ regenerateCommand: "make gqlflow",
35
+ generatedDirectory: "__graphql-types__",
36
+ exclude: [
37
+ /_test.js$/,
38
+ /.fixture.js$/,
39
+ /\b__flowtests__\b/,
40
+ ],
41
+ };
42
+
43
+ module.exports = {
44
+ crawl: {
45
+ root: "../../",
46
+ },
47
+ generate: [
48
+ {
49
+ ...options,
50
+ schemaFilePath: "../../gengraphql/course-editor-schema.graphql",
51
+ match: [/\bcourse-editor-package\b/, /\bcourse-editor\b/],
52
+ },
53
+ {
54
+ ...options,
55
+ match: [/\bdiscussion-package\b/]
56
+ experimentalEnums: true,
57
+ },
58
+ options,
59
+ ],
60
+ };
183
61
  ```
184
62
 
185
- And then `yarn generate-types` or `npm run generate-types` gets your types generated!
186
-
187
- 🚀
188
-
189
63
  ## Introspecting your backend's graphql schema
190
64
  Here's how to get your backend's schema in the way that this tool expects, using the builtin 'graphql introspection query':
191
65
 
@@ -0,0 +1,67 @@
1
+ scalar PositiveNumber
2
+
3
+ enum Episode { NEW_HOPE, EMPIRE, JEDI }
4
+
5
+ """
6
+ A movie character
7
+ """
8
+ interface Character {
9
+ id: String!
10
+ name: String
11
+ friends: [Character]
12
+ appearsIn: [Episode]
13
+ }
14
+
15
+ """
16
+ A human character
17
+ """
18
+ type Human implements Character {
19
+ id: String!
20
+ """The person's name"""
21
+ name: String
22
+ friends: [Character]
23
+ appearsIn: [Episode]
24
+ homePlanet: String
25
+ alive: Boolean
26
+ hands: PositiveNumber
27
+ }
28
+
29
+ """
30
+ A robot character
31
+ """
32
+ type Droid implements Character {
33
+ id: String!
34
+ name: String
35
+ friends: [Character]
36
+ appearsIn: [Episode]
37
+ """The robot's primary function"""
38
+ primaryFunction: String!
39
+ }
40
+
41
+ type Animal {
42
+ name: String
43
+ }
44
+
45
+ union Friendable = Human | Droid | Animal
46
+
47
+ type Query {
48
+ hero(episode: Episode): Character
49
+ human(id: String!): Human
50
+ droid(id: String!): Droid
51
+ friend(id: String!): Friendable
52
+ candies(number: PositiveNumber!): String
53
+ }
54
+
55
+ """A character to add"""
56
+ input CharacterInput {
57
+ """The new character's name"""
58
+ name: String!
59
+ """The character's friends"""
60
+ friends: [ID!]
61
+ appearsIn: [Episode!]
62
+ candies: PositiveNumber!
63
+ }
64
+
65
+ type Mutation {
66
+ addCharacter(character: CharacterInput!): Character
67
+ }
@@ -0,0 +1,157 @@
1
+ // @flow
2
+ // Test the generate the type file contents
3
+
4
+ import {getSchemas} from '../cli/config';
5
+ import {generateTypeFileContents, indexPrelude} from '../generateTypeFiles';
6
+ import gql from 'graphql-tag';
7
+
8
+ const [_, exampleSchema] = getSchemas(__dirname + '/example-schema.graphql');
9
+
10
+ describe('generateTypeFileContents', () => {
11
+ it('split types should export response & variables types', () => {
12
+ const {indexContents, files} = generateTypeFileContents(
13
+ 'hello.js',
14
+ exampleSchema,
15
+ gql`
16
+ query Hello {
17
+ human(id: "Han") {
18
+ id
19
+ }
20
+ }
21
+ `,
22
+ {splitTypes: true, schemaFilePath: ''},
23
+ '__generated__',
24
+ indexPrelude('yarn queries'),
25
+ );
26
+ expect(indexContents).toMatchInlineSnapshot(`
27
+ "// @flow
28
+ //
29
+ // AUTOGENERATED
30
+ // NOTE: New response types are added to this file automatically.
31
+ // Outdated response types can be removed manually as they are deprecated.
32
+ // To regenerate, run yarn queries
33
+ //
34
+
35
+ export type {HelloType} from './Hello.js';
36
+ "
37
+ `);
38
+ expect(
39
+ Object.keys(files)
40
+ .map((k) => `// ${k}\n${files[k]}`)
41
+ .join('\n\n'),
42
+ ).toMatchInlineSnapshot(`
43
+ "// __generated__/Hello.js
44
+ // @flow
45
+ // AUTOGENERATED -- DO NOT EDIT
46
+ // Generated for operation 'Hello' in file '../hello.js'
47
+ export type HelloType = {|
48
+ variables: {||},
49
+ response: {|
50
+ /** A human character*/
51
+ human: ?{|
52
+ id: string
53
+ |}
54
+ |}
55
+ |};
56
+ export type Hello = HelloType['response'];
57
+ export type HelloVariables = HelloType['variables'];
58
+ "
59
+ `);
60
+ });
61
+
62
+ it('should respect the typeFileName option', () => {
63
+ const {files} = generateTypeFileContents(
64
+ 'hello.js',
65
+ exampleSchema,
66
+ gql`
67
+ query Hello {
68
+ human(id: "Han") {
69
+ id
70
+ }
71
+ }
72
+ `,
73
+ {
74
+ splitTypes: true,
75
+ typeFileName: 'prefix-[operationName]-suffix.js',
76
+ schemaFilePath: '',
77
+ },
78
+ '__generated__',
79
+ indexPrelude('yarn queries'),
80
+ );
81
+ expect(
82
+ Object.keys(files)
83
+ .map((k) => `// ${k}\n${files[k]}`)
84
+ .join('\n\n'),
85
+ ).toMatchInlineSnapshot(`
86
+ "// __generated__/prefix-Hello-suffix.js
87
+ // @flow
88
+ // AUTOGENERATED -- DO NOT EDIT
89
+ // Generated for operation 'Hello' in file '../hello.js'
90
+ export type HelloType = {|
91
+ variables: {||},
92
+ response: {|
93
+ /** A human character*/
94
+ human: ?{|
95
+ id: string
96
+ |}
97
+ |}
98
+ |};
99
+ export type Hello = HelloType['response'];
100
+ export type HelloVariables = HelloType['variables'];
101
+ "
102
+ `);
103
+ });
104
+
105
+ describe('experimentalEnums', () => {
106
+ it('should generate the expected values', () => {
107
+ const {files} = generateTypeFileContents(
108
+ 'hello.js',
109
+ exampleSchema,
110
+ gql`
111
+ query Hello {
112
+ human(id: "Han") {
113
+ appearsIn
114
+ }
115
+ }
116
+ `,
117
+ {
118
+ experimentalEnums: true,
119
+ schemaFilePath: '',
120
+ },
121
+ '__generated__',
122
+ indexPrelude('yarn queries'),
123
+ );
124
+ expect(
125
+ Object.keys(files)
126
+ .map((k) => `// ${k}\n${files[k]}`)
127
+ .join('\n\n'),
128
+ ).toMatchInlineSnapshot(`
129
+ "// __generated__/Hello.js
130
+ // @flow
131
+ // AUTOGENERATED -- DO NOT EDIT
132
+ // Generated for operation 'Hello' in file '../hello.js'
133
+ export type HelloType = {|
134
+ variables: {||},
135
+ response: {|
136
+ /** A human character*/
137
+ human: ?{|
138
+ appearsIn: ?$ReadOnlyArray<
139
+ /** - NEW_HOPE
140
+ - EMPIRE
141
+ - JEDI*/
142
+ ?Episode>
143
+ |}
144
+ |}
145
+ |};
146
+ /* eslint-disable no-undef */
147
+ export enum Episode {
148
+ NEW_HOPE,
149
+ EMPIRE,
150
+ JEDI,
151
+ };
152
+ /* eslint-enable no-undef */
153
+ "
154
+ `);
155
+ });
156
+ });
157
+ });