@khanacademy/graphql-flow 0.2.4 → 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 (57) hide show
  1. package/.flowconfig +1 -0
  2. package/.github/workflows/changeset-release.yml +3 -17
  3. package/.github/workflows/pr-checks.yml +13 -10
  4. package/CHANGELOG.md +35 -0
  5. package/Readme.md +41 -132
  6. package/dist/__test__/example-schema.graphql +67 -0
  7. package/dist/__test__/generateTypeFileContents.test.js +157 -0
  8. package/dist/__test__/graphql-flow.test.js +639 -0
  9. package/dist/__test__/processPragmas.test.js +76 -0
  10. package/dist/cli/__test__/config.test.js +120 -0
  11. package/dist/cli/config.js +51 -26
  12. package/dist/cli/config.js.flow +40 -68
  13. package/dist/cli/config.js.map +1 -1
  14. package/dist/cli/run.js +41 -19
  15. package/dist/cli/run.js.flow +58 -22
  16. package/dist/cli/run.js.map +1 -1
  17. package/dist/cli/schema.json +91 -0
  18. package/dist/enums.js +20 -7
  19. package/dist/enums.js.flow +44 -15
  20. package/dist/enums.js.map +1 -1
  21. package/dist/generateResponseType.js +47 -47
  22. package/dist/generateResponseType.js.flow +55 -57
  23. package/dist/generateResponseType.js.map +1 -1
  24. package/dist/generateTypeFiles.js +41 -22
  25. package/dist/generateTypeFiles.js.flow +86 -78
  26. package/dist/generateTypeFiles.js.map +1 -1
  27. package/dist/generateVariablesType.js +24 -24
  28. package/dist/generateVariablesType.js.flow +25 -28
  29. package/dist/generateVariablesType.js.map +1 -1
  30. package/dist/index.js +18 -20
  31. package/dist/index.js.flow +31 -16
  32. package/dist/index.js.map +1 -1
  33. package/dist/parser/__test__/parse.test.js +247 -0
  34. package/dist/types.js.flow +28 -5
  35. package/flow-typed/npm/@babel/types_vx.x.x.js +17 -3
  36. package/package.json +3 -2
  37. package/src/__test__/generateTypeFileContents.test.js +55 -1
  38. package/src/__test__/graphql-flow.test.js +7 -7
  39. package/src/__test__/processPragmas.test.js +28 -15
  40. package/src/cli/__test__/config.test.js +120 -0
  41. package/src/cli/config.js +40 -68
  42. package/src/cli/run.js +58 -22
  43. package/src/cli/schema.json +91 -0
  44. package/src/enums.js +44 -15
  45. package/src/generateResponseType.js +55 -57
  46. package/src/generateTypeFiles.js +86 -78
  47. package/src/generateVariablesType.js +25 -28
  48. package/src/index.js +31 -16
  49. package/src/types.js +28 -5
  50. package/.github/actions/filter-files/action.yml +0 -37
  51. package/.github/actions/full-or-limited/action.yml +0 -27
  52. package/.github/actions/json-args/action.yml +0 -32
  53. package/.github/actions/setup/action.yml +0 -28
  54. package/dist/jest-mock-graphql-tag.js +0 -88
  55. package/dist/jest-mock-graphql-tag.js.flow +0 -96
  56. package/dist/jest-mock-graphql-tag.js.map +0 -1
  57. package/src/jest-mock-graphql-tag.js +0 -96
package/src/enums.js CHANGED
@@ -3,15 +3,41 @@
3
3
  * Both input & output types can have enums & scalars.
4
4
  */
5
5
  import * as babelTypes from '@babel/types';
6
- import {type BabelNodeFlowType} from '@babel/types';
7
- import type {Config} from './types';
6
+ import type {BabelNodeFlowType} from '@babel/types';
7
+ import type {Context} from './types';
8
8
  import {maybeAddDescriptionComment} from './utils';
9
+ import type {IntrospectionEnumType} from 'graphql/utilities/introspectionQuery';
10
+
11
+ export const experimentalEnumTypeToFlow = (
12
+ ctx: Context,
13
+ enumConfig: IntrospectionEnumType,
14
+ description: string,
15
+ ): BabelNodeFlowType => {
16
+ const enumDeclaration = babelTypes.enumDeclaration(
17
+ // pass id into generic type annotation
18
+ babelTypes.identifier(enumConfig.name),
19
+ babelTypes.enumStringBody(
20
+ enumConfig.enumValues.map((v) =>
21
+ babelTypes.enumDefaultedMember(babelTypes.identifier(v.name)),
22
+ ),
23
+ ),
24
+ );
25
+
26
+ if (ctx.experimentalEnumsMap) {
27
+ ctx.experimentalEnumsMap[enumConfig.name] = enumDeclaration;
28
+ }
29
+
30
+ return maybeAddDescriptionComment(
31
+ description,
32
+ babelTypes.genericTypeAnnotation(enumDeclaration.id),
33
+ );
34
+ };
9
35
 
10
36
  export const enumTypeToFlow = (
11
- config: Config,
37
+ ctx: Context,
12
38
  name: string,
13
39
  ): BabelNodeFlowType => {
14
- const enumConfig = config.schema.enumsByName[name];
40
+ const enumConfig = ctx.schema.enumsByName[name];
15
41
  let combinedDescription = enumConfig.enumValues
16
42
  .map(
17
43
  (n) =>
@@ -25,14 +51,17 @@ export const enumTypeToFlow = (
25
51
  combinedDescription =
26
52
  enumConfig.description + '\n\n' + combinedDescription;
27
53
  }
28
- return maybeAddDescriptionComment(
29
- combinedDescription,
30
- babelTypes.unionTypeAnnotation(
31
- enumConfig.enumValues.map((n) =>
32
- babelTypes.stringLiteralTypeAnnotation(n.name),
33
- ),
34
- ),
35
- );
54
+
55
+ return ctx.experimentalEnumsMap
56
+ ? experimentalEnumTypeToFlow(ctx, enumConfig, combinedDescription)
57
+ : maybeAddDescriptionComment(
58
+ combinedDescription,
59
+ babelTypes.unionTypeAnnotation(
60
+ enumConfig.enumValues.map((n) =>
61
+ babelTypes.stringLiteralTypeAnnotation(n.name),
62
+ ),
63
+ ),
64
+ );
36
65
  };
37
66
 
38
67
  export const builtinScalars: {[key: string]: string} = {
@@ -46,7 +75,7 @@ export const builtinScalars: {[key: string]: string} = {
46
75
  };
47
76
 
48
77
  export const scalarTypeToFlow = (
49
- config: Config,
78
+ ctx: Context,
50
79
  name: string,
51
80
  ): BabelNodeFlowType => {
52
81
  if (builtinScalars[name]) {
@@ -54,13 +83,13 @@ export const scalarTypeToFlow = (
54
83
  babelTypes.identifier(builtinScalars[name]),
55
84
  );
56
85
  }
57
- const underlyingType = config.scalars[name];
86
+ const underlyingType = ctx.scalars[name];
58
87
  if (underlyingType != null) {
59
88
  return babelTypes.genericTypeAnnotation(
60
89
  babelTypes.identifier(underlyingType),
61
90
  );
62
91
  }
63
- config.errors.push(
92
+ ctx.errors.push(
64
93
  `Unexpected scalar '${name}'! Please add it to the "scalars" argument at the callsite of 'generateFlowTypes()'.`,
65
94
  );
66
95
  return babelTypes.genericTypeAnnotation(
@@ -9,7 +9,7 @@ import type {
9
9
  OperationDefinitionNode,
10
10
  FragmentDefinitionNode,
11
11
  } from 'graphql';
12
- import type {Config, Schema, Selections} from './types';
12
+ import type {Context, Schema, Selections} from './types';
13
13
  import {
14
14
  liftLeadingPropertyComments,
15
15
  maybeAddDescriptionComment,
@@ -30,10 +30,10 @@ import {
30
30
  export const generateResponseType = (
31
31
  schema: Schema,
32
32
  query: OperationDefinitionNode,
33
- config: Config,
33
+ ctx: Context,
34
34
  ): string => {
35
35
  const ast = querySelectionToObjectType(
36
- config,
36
+ ctx,
37
37
  query.selectionSet.selections,
38
38
  query.operation === 'mutation'
39
39
  ? schema.typesByName.Mutation
@@ -45,7 +45,7 @@ export const generateResponseType = (
45
45
  };
46
46
 
47
47
  const sortedObjectTypeAnnotation = (
48
- config: Config,
48
+ ctx: Context,
49
49
  properties: Array<
50
50
  BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty,
51
51
  >,
@@ -67,10 +67,10 @@ const sortedObjectTypeAnnotation = (
67
67
  undefined /* internalSlots */,
68
68
  true /* exact */,
69
69
  );
70
- const name = config.path.join('_');
71
- const isTopLevelType = config.path.length <= 1;
72
- if (config.allObjectTypes != null && !isTopLevelType) {
73
- config.allObjectTypes[name] = obj;
70
+ const name = ctx.path.join('_');
71
+ const isTopLevelType = ctx.path.length <= 1;
72
+ if (ctx.allObjectTypes != null && !isTopLevelType) {
73
+ ctx.allObjectTypes[name] = obj;
74
74
  return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));
75
75
  } else {
76
76
  return obj;
@@ -80,16 +80,16 @@ const sortedObjectTypeAnnotation = (
80
80
  export const generateFragmentType = (
81
81
  schema: Schema,
82
82
  fragment: FragmentDefinitionNode,
83
- config: Config,
83
+ ctx: Context,
84
84
  ): string => {
85
85
  const onType = fragment.typeCondition.name.value;
86
86
  let ast;
87
87
 
88
88
  if (schema.typesByName[onType]) {
89
89
  ast = sortedObjectTypeAnnotation(
90
- config,
90
+ ctx,
91
91
  objectPropertiesToFlow(
92
- config,
92
+ ctx,
93
93
  schema.typesByName[onType],
94
94
  onType,
95
95
  fragment.selectionSet.selections,
@@ -97,14 +97,14 @@ export const generateFragmentType = (
97
97
  );
98
98
  } else if (schema.interfacesByName[onType]) {
99
99
  ast = unionOrInterfaceToFlow(
100
- config,
101
- config.schema.interfacesByName[onType],
100
+ ctx,
101
+ ctx.schema.interfacesByName[onType],
102
102
  fragment.selectionSet.selections,
103
103
  );
104
104
  } else if (schema.unionsByName[onType]) {
105
105
  ast = unionOrInterfaceToFlow(
106
- config,
107
- config.schema.unionsByName[onType],
106
+ ctx,
107
+ ctx.schema.unionsByName[onType],
108
108
  fragment.selectionSet.selections,
109
109
  );
110
110
  } else {
@@ -116,31 +116,31 @@ export const generateFragmentType = (
116
116
  };
117
117
 
118
118
  const _typeToFlow = (
119
- config: Config,
119
+ ctx: Context,
120
120
  type,
121
121
  selection,
122
122
  ): babelTypes.BabelNodeFlowType => {
123
123
  if (type.kind === 'SCALAR') {
124
- return scalarTypeToFlow(config, type.name);
124
+ return scalarTypeToFlow(ctx, type.name);
125
125
  }
126
126
  if (type.kind === 'LIST') {
127
127
  return babelTypes.genericTypeAnnotation(
128
- config.readOnlyArray
128
+ ctx.readOnlyArray
129
129
  ? babelTypes.identifier('$ReadOnlyArray')
130
130
  : babelTypes.identifier('Array'),
131
131
  babelTypes.typeParameterInstantiation([
132
- typeToFlow(config, type.ofType, selection),
132
+ typeToFlow(ctx, type.ofType, selection),
133
133
  ]),
134
134
  );
135
135
  }
136
136
  if (type.kind === 'UNION') {
137
- const union = config.schema.unionsByName[type.name];
137
+ const union = ctx.schema.unionsByName[type.name];
138
138
  if (!selection.selectionSet) {
139
139
  console.log('no selection set', selection);
140
140
  return babelTypes.anyTypeAnnotation();
141
141
  }
142
142
  return unionOrInterfaceToFlow(
143
- config,
143
+ ctx,
144
144
  union,
145
145
  selection.selectionSet.selections,
146
146
  );
@@ -152,13 +152,13 @@ const _typeToFlow = (
152
152
  return babelTypes.anyTypeAnnotation();
153
153
  }
154
154
  return unionOrInterfaceToFlow(
155
- config,
156
- config.schema.interfacesByName[type.name],
155
+ ctx,
156
+ ctx.schema.interfacesByName[type.name],
157
157
  selection.selectionSet.selections,
158
158
  );
159
159
  }
160
160
  if (type.kind === 'ENUM') {
161
- return enumTypeToFlow(config, type.name);
161
+ return enumTypeToFlow(ctx, type.name);
162
162
  }
163
163
  if (type.kind !== 'OBJECT') {
164
164
  console.log('not object', type);
@@ -166,11 +166,11 @@ const _typeToFlow = (
166
166
  }
167
167
 
168
168
  const tname = type.name;
169
- if (!config.schema.typesByName[tname]) {
169
+ if (!ctx.schema.typesByName[tname]) {
170
170
  console.log('unknown referenced type', tname);
171
171
  return babelTypes.anyTypeAnnotation();
172
172
  }
173
- const childType = config.schema.typesByName[tname];
173
+ const childType = ctx.schema.typesByName[tname];
174
174
  if (!selection.selectionSet) {
175
175
  console.log('no selection set', selection);
176
176
  return babelTypes.anyTypeAnnotation();
@@ -178,7 +178,7 @@ const _typeToFlow = (
178
178
  return maybeAddDescriptionComment(
179
179
  childType.description,
180
180
  querySelectionToObjectType(
181
- config,
181
+ ctx,
182
182
  selection.selectionSet.selections,
183
183
  childType,
184
184
  tname,
@@ -187,19 +187,19 @@ const _typeToFlow = (
187
187
  };
188
188
 
189
189
  export const typeToFlow = (
190
- config: Config,
190
+ ctx: Context,
191
191
  type: IntrospectionOutputTypeRef,
192
192
  selection: FieldNode,
193
193
  ): babelTypes.BabelNodeFlowType => {
194
194
  // throw new Error('npoe');
195
195
  if (type.kind === 'NON_NULL') {
196
- return _typeToFlow(config, type.ofType, selection);
196
+ return _typeToFlow(ctx, type.ofType, selection);
197
197
  }
198
198
  // If we don'babelTypes care about strict nullability checking, then pretend everything is non-null
199
- if (!config.strictNullability) {
200
- return _typeToFlow(config, type, selection);
199
+ if (!ctx.strictNullability) {
200
+ return _typeToFlow(ctx, type, selection);
201
201
  }
202
- const inner = _typeToFlow(config, type, selection);
202
+ const inner = _typeToFlow(ctx, type, selection);
203
203
  const result = babelTypes.nullableTypeAnnotation(inner);
204
204
  return transferLeadingComments(inner, result);
205
205
  };
@@ -233,21 +233,21 @@ const ensureOnlyOneTypenameProperty = (properties) => {
233
233
  };
234
234
 
235
235
  const querySelectionToObjectType = (
236
- config: Config,
236
+ ctx: Context,
237
237
  selections,
238
238
  type,
239
239
  typeName: string,
240
240
  ): BabelNodeFlowType => {
241
241
  return sortedObjectTypeAnnotation(
242
- config,
242
+ ctx,
243
243
  ensureOnlyOneTypenameProperty(
244
- objectPropertiesToFlow(config, type, typeName, selections),
244
+ objectPropertiesToFlow(ctx, type, typeName, selections),
245
245
  ),
246
246
  );
247
247
  };
248
248
 
249
249
  export const objectPropertiesToFlow = (
250
- config: Config,
250
+ ctx: Context,
251
251
  type: IntrospectionObjectType & {
252
252
  fieldsByName: {[name: string]: IntrospectionField},
253
253
  },
@@ -264,15 +264,15 @@ export const objectPropertiesToFlow = (
264
264
  return [];
265
265
  }
266
266
  return objectPropertiesToFlow(
267
- config,
268
- config.schema.typesByName[newTypeName],
267
+ ctx,
268
+ ctx.schema.typesByName[newTypeName],
269
269
  newTypeName,
270
270
  selection.selectionSet.selections,
271
271
  );
272
272
  }
273
273
  case 'FragmentSpread':
274
- if (!config.fragments[selection.name.value]) {
275
- config.errors.push(
274
+ if (!ctx.fragments[selection.name.value]) {
275
+ ctx.errors.push(
276
276
  `No fragment named '${selection.name.value}'. Did you forget to include it in the template literal?`,
277
277
  );
278
278
  return [
@@ -286,10 +286,10 @@ export const objectPropertiesToFlow = (
286
286
  }
287
287
 
288
288
  return objectPropertiesToFlow(
289
- config,
289
+ ctx,
290
290
  type,
291
291
  typeName,
292
- config.fragments[selection.name.value].selectionSet
292
+ ctx.fragments[selection.name.value].selectionSet
293
293
  .selections,
294
294
  );
295
295
 
@@ -309,7 +309,7 @@ export const objectPropertiesToFlow = (
309
309
  ];
310
310
  }
311
311
  if (!type.fieldsByName[name]) {
312
- config.errors.push(
312
+ ctx.errors.push(
313
313
  `Unknown field '${name}' for type '${typeName}'`,
314
314
  );
315
315
  return babelTypes.objectTypeProperty(
@@ -331,8 +331,8 @@ export const objectPropertiesToFlow = (
331
331
  babelTypes.identifier(alias),
332
332
  typeToFlow(
333
333
  {
334
- ...config,
335
- path: config.path.concat([alias]),
334
+ ...ctx,
335
+ path: ctx.path.concat([alias]),
336
336
  },
337
337
  typeField.type,
338
338
  selection,
@@ -343,7 +343,7 @@ export const objectPropertiesToFlow = (
343
343
  ];
344
344
 
345
345
  default:
346
- config.errors.push(
346
+ ctx.errors.push(
347
347
  // eslint-disable-next-line flowtype-errors/uncovered
348
348
  `Unsupported selection kind '${selection.kind}'`,
349
349
  );
@@ -354,7 +354,7 @@ export const objectPropertiesToFlow = (
354
354
  };
355
355
 
356
356
  export const unionOrInterfaceToFlow = (
357
- config: Config,
357
+ ctx: Context,
358
358
  type:
359
359
  | IntrospectionUnionType
360
360
  | (IntrospectionInterfaceType & {
@@ -377,10 +377,8 @@ export const unionOrInterfaceToFlow = (
377
377
  })
378
378
  .map((possible) => {
379
379
  const configWithUpdatedPath = {
380
- ...config,
381
- path: allFields
382
- ? config.path
383
- : config.path.concat([possible.name]),
380
+ ...ctx,
381
+ path: allFields ? ctx.path : ctx.path.concat([possible.name]),
384
382
  };
385
383
  return {
386
384
  typeName: possible.name,
@@ -421,11 +419,11 @@ export const unionOrInterfaceToFlow = (
421
419
  ),
422
420
  );
423
421
  }
424
- return sortedObjectTypeAnnotation(config, sharedAttributes);
422
+ return sortedObjectTypeAnnotation(ctx, sharedAttributes);
425
423
  }
426
424
  if (selectedAttributes.length === 1) {
427
425
  return sortedObjectTypeAnnotation(
428
- config,
426
+ ctx,
429
427
  selectedAttributes[0].attributes,
430
428
  );
431
429
  }
@@ -462,14 +460,14 @@ export const unionOrInterfaceToFlow = (
462
460
  const result = babelTypes.unionTypeAnnotation(
463
461
  selectedAttributes.map(({typeName, attributes}) =>
464
462
  sortedObjectTypeAnnotation(
465
- {...config, path: config.path.concat([typeName])},
463
+ {...ctx, path: ctx.path.concat([typeName])},
466
464
  attributes,
467
465
  ),
468
466
  ),
469
467
  );
470
- const name = config.path.join('_');
471
- if (config.allObjectTypes && config.path.length > 1) {
472
- config.allObjectTypes[name] = result;
468
+ const name = ctx.path.join('_');
469
+ if (ctx.allObjectTypes && ctx.path.length > 1) {
470
+ ctx.allObjectTypes[name] = result;
473
471
  return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));
474
472
  }
475
473
  return result;
@@ -1,28 +1,10 @@
1
1
  // @flow
2
- // Import this in your jest setup, to mock out graphql-tag!
3
2
  import type {DocumentNode} from 'graphql';
4
- import type {Options, Schema, Scalars} from './types';
3
+ import type {GenerateConfig, CrawlConfig, Schema} from './types';
5
4
  import fs from 'fs';
6
5
  import path from 'path';
7
6
  import {documentToFlowTypes} from '.';
8
7
 
9
- export type ExternalOptions = {
10
- pragma?: string,
11
- loosePragma?: string,
12
- ignorePragma?: string,
13
- scalars?: Scalars,
14
- strictNullability?: boolean,
15
- /**
16
- * The command that users should run to regenerate the types files.
17
- */
18
- regenerateCommand?: string,
19
- readOnlyArray?: boolean,
20
- splitTypes?: boolean,
21
- generatedDirectory?: string,
22
- exportAllObjectTypes?: boolean,
23
- typeFileName?: string,
24
- };
25
-
26
8
  export const indexPrelude = (regenerateCommand?: string): string => `// @flow
27
9
  //
28
10
  // AUTOGENERATED
@@ -37,7 +19,7 @@ export const generateTypeFileContents = (
37
19
  fileName: string,
38
20
  schema: Schema,
39
21
  document: DocumentNode,
40
- options: Options,
22
+ options: GenerateConfig,
41
23
  generatedDir: string,
42
24
  indexContents: string,
43
25
  ): {indexContents: string, files: {[key: string]: string}} => {
@@ -62,54 +44,82 @@ export const generateTypeFileContents = (
62
44
  };
63
45
 
64
46
  const generated = documentToFlowTypes(document, schema, options);
65
- generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
66
- // We write all generated files to a `__generated__` subdir to keep
67
- // things tidy.
68
- const targetFileName = options.typeFileName
69
- ? options.typeFileName.replace('[operationName]', name)
70
- : `${name}.js`;
71
- const targetPath = path.join(generatedDir, targetFileName);
72
-
73
- let fileContents =
74
- '// @' +
75
- `flow\n// AUTOGENERATED -- DO NOT EDIT\n` +
76
- `// Generated for operation '${name}' in file '../${path.basename(
77
- fileName,
78
- )}'\n` +
79
- (options.regenerateCommand
80
- ? `// To regenerate, run '${options.regenerateCommand}'.\n`
81
- : '') +
82
- code;
83
- if (options.splitTypes && !isFragment) {
84
- fileContents +=
85
- `\nexport type ${name} = ${typeName}['response'];\n` +
86
- `export type ${name}Variables = ${typeName}['variables'];\n`;
87
- }
88
- Object.keys(extraTypes).forEach((name) => {
89
- fileContents += `\n\nexport type ${name} = ${extraTypes[name]};`;
90
- });
91
-
92
- addToIndex(targetPath, typeName);
93
- files[targetPath] =
94
- fileContents
95
- // Remove whitespace from the ends of lines; babel's generate sometimes
96
- // leaves them hanging around.
97
- .replace(/\s+$/gm, '') + '\n';
98
- });
47
+ generated.forEach(
48
+ ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {
49
+ // We write all generated files to a `__generated__` subdir to keep
50
+ // things tidy.
51
+ const targetFileName = options.typeFileName
52
+ ? options.typeFileName.replace('[operationName]', name)
53
+ : `${name}.js`;
54
+ const targetPath = path.join(generatedDir, targetFileName);
55
+
56
+ let fileContents =
57
+ '// @' +
58
+ `flow\n// AUTOGENERATED -- DO NOT EDIT\n` +
59
+ `// Generated for operation '${name}' in file '../${path.basename(
60
+ fileName,
61
+ )}'\n` +
62
+ (options.regenerateCommand
63
+ ? `// To regenerate, run '${options.regenerateCommand}'.\n`
64
+ : '') +
65
+ code;
66
+ if (options.splitTypes && !isFragment) {
67
+ fileContents +=
68
+ `\nexport type ${name} = ${typeName}['response'];\n` +
69
+ `export type ${name}Variables = ${typeName}['variables'];\n`;
70
+ }
71
+ Object.keys(extraTypes).forEach(
72
+ (name) =>
73
+ (fileContents += `\n\nexport type ${name} = ${extraTypes[name]};`),
74
+ );
75
+ const enumNames = Object.keys(experimentalEnums);
76
+ if (options.experimentalEnums && enumNames.length) {
77
+ // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype
78
+ // and remove this disable.
79
+ fileContents += `\n\n/* eslint-disable no-undef */`;
80
+ enumNames.forEach(
81
+ (name) =>
82
+ (fileContents += `\nexport ${experimentalEnums[name]};\n`),
83
+ );
84
+ fileContents += `/* eslint-enable no-undef */`;
85
+ }
86
+
87
+ addToIndex(targetPath, typeName);
88
+ files[targetPath] =
89
+ fileContents
90
+ // Remove whitespace from the ends of lines; babel's generate sometimes
91
+ // leaves them hanging around.
92
+ .replace(/\s+$/gm, '') + '\n';
93
+ },
94
+ );
99
95
 
100
96
  return {files, indexContents};
101
97
  };
102
98
 
99
+ const getGeneratedDir = (fileName: string, options: GenerateConfig) => {
100
+ const generatedDirectory = options.generatedDirectory ?? '__generated__';
101
+ if (path.isAbsolute(generatedDirectory)) {
102
+ // fileName is absolute here, so we make it relative to cwd
103
+ // for more reasonable filenames. We convert leading ..'s
104
+ // to `__` so this doesn't escape the output directory.
105
+ return path.join(
106
+ generatedDirectory,
107
+ path
108
+ .relative(process.cwd(), path.dirname(fileName))
109
+ .replace(/\.\.\//g, '__/'),
110
+ );
111
+ } else {
112
+ return path.join(path.dirname(fileName), generatedDirectory);
113
+ }
114
+ };
115
+
103
116
  export const generateTypeFiles = (
104
117
  fileName: string,
105
118
  schema: Schema,
106
119
  document: DocumentNode,
107
- options: Options,
120
+ options: GenerateConfig,
108
121
  ) => {
109
- const generatedDir = path.join(
110
- path.dirname(fileName),
111
- options.generatedDirectory ?? '__generated__',
112
- );
122
+ const generatedDir = getGeneratedDir(fileName, options);
113
123
  const indexFile = path.join(generatedDir, 'index.js');
114
124
 
115
125
  if (!fs.existsSync(generatedDir)) {
@@ -137,35 +147,33 @@ export const generateTypeFiles = (
137
147
  };
138
148
 
139
149
  export const processPragmas = (
140
- options: ExternalOptions,
150
+ generateConfig: GenerateConfig,
151
+ crawlConfig: CrawlConfig,
141
152
  rawSource: string,
142
- ): null | Options => {
143
- if (options.ignorePragma && rawSource.includes(options.ignorePragma)) {
144
- return null;
153
+ ): {generate: boolean, strict?: boolean} => {
154
+ if (
155
+ crawlConfig.ignorePragma &&
156
+ rawSource.includes(crawlConfig.ignorePragma)
157
+ ) {
158
+ return {generate: false};
145
159
  }
146
160
 
147
- const autogen = options.loosePragma
148
- ? rawSource.includes(options.loosePragma)
161
+ const autogen = crawlConfig.loosePragma
162
+ ? rawSource.includes(crawlConfig.loosePragma)
149
163
  : false;
150
- const autogenStrict = options.pragma
151
- ? rawSource.includes(options.pragma)
164
+ const autogenStrict = crawlConfig.pragma
165
+ ? rawSource.includes(crawlConfig.pragma)
152
166
  : false;
153
- const noPragmas = !options.loosePragma && !options.pragma;
167
+ const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;
154
168
 
155
169
  if (autogen || autogenStrict || noPragmas) {
156
170
  return {
157
- regenerateCommand: options.regenerateCommand,
158
- strictNullability: noPragmas
159
- ? options.strictNullability
171
+ generate: true,
172
+ strict: noPragmas
173
+ ? generateConfig.strictNullability
160
174
  : autogenStrict || !autogen,
161
- readOnlyArray: options.readOnlyArray,
162
- scalars: options.scalars,
163
- splitTypes: options.splitTypes,
164
- generatedDirectory: options.generatedDirectory,
165
- exportAllObjectTypes: options.exportAllObjectTypes,
166
- typeFileName: options.typeFileName,
167
175
  };
168
176
  } else {
169
- return null;
177
+ return {generate: false};
170
178
  }
171
179
  };