@khanacademy/graphql-flow 1.0.0 → 1.1.1

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.
package/.flowconfig CHANGED
@@ -1,6 +1,8 @@
1
1
  [ignore]
2
2
  ; The 'resolve' package bundles test files that it really shouldn't
3
3
  .*/resolve/test/resolver/malformed_package_json/
4
+ <PROJECT_ROOT>/dist/
5
+
4
6
  [include]
5
7
 
6
8
  [libs]
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @khanacademy/graphql-flow
2
2
 
3
+ ## 1.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - a581359: Fix processing of typescript imports that don't use an extension
8
+
9
+ ## 1.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - c7367a1: Basic TypeScript support!
14
+
3
15
  ## 1.0.0
4
16
 
5
17
  ### Major Changes
@@ -33,11 +33,12 @@ const validateOrThrow = (value, jsonSchema) => {
33
33
  exports.validateOrThrow = validateOrThrow;
34
34
 
35
35
  const loadConfigFile = configFile => {
36
- // $FlowIgnore // eslint-disable-next-line flowtype-errors/uncovered
37
- const data = require(configFile); // eslint-disable-next-line flowtype-errors/uncovered
36
+ // $FlowIgnore
37
+ const data = require(configFile); // eslint-disable-line flowtype-errors/uncovered
38
38
 
39
39
 
40
- validateOrThrow(data, _schema.default);
40
+ validateOrThrow(data, _schema.default); // eslint-disable-line flowtype-errors/uncovered
41
+
41
42
  return data;
42
43
  };
43
44
  /**
@@ -28,10 +28,9 @@ export const validateOrThrow = (value: mixed, jsonSchema: mixed) => {
28
28
  };
29
29
 
30
30
  export const loadConfigFile = (configFile: string): Config => {
31
- // $FlowIgnore // eslint-disable-next-line flowtype-errors/uncovered
32
- const data: Config = require(configFile);
33
- // eslint-disable-next-line flowtype-errors/uncovered
34
- validateOrThrow(data, configSchema);
31
+ // $FlowIgnore
32
+ const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered
33
+ validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered
35
34
  return data;
36
35
  };
37
36
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/config.js"],"names":["validateOrThrow","value","jsonSchema","result","valid","Error","errors","map","error","toString","join","loadConfigFile","configFile","data","require","configSchema","getSchemas","schemaFilePath","raw","fs","readFileSync","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData","JSON","parse","findApplicableConfig","path","configs","Array","isArray","find","config","exclude","some","RegExp","test","match","matcher"],"mappings":";;;;;;;AAIA;;AACA;;AAEA;;AACA;;AAQA;;;;AAX0C;AAWL;AAE9B,MAAMA,eAAe,GAAG,CAACC,KAAD,EAAeC,UAAf,KAAqC;AAChE;AACA,QAAMC,MAAM,GAAG,0BAASF,KAAT,EAAgBC,UAAhB,CAAf;;AACA,MAAI,CAACC,MAAM,CAACC,KAAZ,EAAmB;AACf,UAAM,IAAIC,KAAJ,CACFF,MAAM,CAACG,MAAP,CAAcC,GAAd,CAAmBC,KAAD,IAAWA,KAAK,CAACC,QAAN,EAA7B,EAA+CC,IAA/C,CAAoD,IAApD,CADE,CAAN;AAGH;AACD;;AACH,CATM;;;;AAWA,MAAMC,cAAc,GAAIC,UAAD,IAAgC;AAC1D;AACA,QAAMC,IAAY,GAAGC,OAAO,CAACF,UAAD,CAA5B,CAF0D,CAG1D;;;AACAZ,EAAAA,eAAe,CAACa,IAAD,EAAOE,eAAP,CAAf;AACA,SAAOF,IAAP;AACH,CANM;AAQP;AACA;AACA;;;;;AACO,MAAMG,UAAU,GAAIC,cAAD,IAAqD;AAC3E,QAAMC,GAAG,GAAGC,YAAGC,YAAH,CAAgBH,cAAhB,EAAgC,MAAhC,CAAZ;;AACA,MAAIA,cAAc,CAACI,QAAf,CAAwB,UAAxB,CAAJ,EAAyC;AACrC,UAAMC,mBAAmB,GAAG,0BAAYJ,GAAZ,CAA5B;AACA,UAAMK,aAAa,GAAG,0BAClBD,mBADkB,EAElB,oCAAsB;AAACE,MAAAA,YAAY,EAAE;AAAf,KAAtB,CAFkB,CAAtB;AAIA,UAAMC,uBAAuB,GAAG,+DAC5B;AACEF,IAAAA,aAAa,CAACV,IAFY,CAAhC;AAIA,WAAO,CAACS,mBAAD,EAAsBG,uBAAtB,CAAP;AACH,GAXD,MAWO;AACH;AACA,UAAMC,iBAAqC,GAAGC,IAAI,CAACC,KAAL,CAAWV,GAAX,CAA9C;AACA,UAAMI,mBAAmB,GAAG,gCAAkBI,iBAAlB,CAA5B;AACA,UAAMD,uBAAuB,GACzB,8DAA4BC,iBAA5B,CADJ;AAEA,WAAO,CAACJ,mBAAD,EAAsBG,uBAAtB,CAAP;AACH;AACJ,CArBM;AAuBP;AACA;AACA;AACA;AACA;;;;;AACO,MAAMI,oBAAoB,GAAG,CAChCC,IADgC,EAEhCC,OAFgC,KAGd;AAClB,MAAI,CAACC,KAAK,CAACC,OAAN,CAAcF,OAAd,CAAL,EAA6B;AACzBA,IAAAA,OAAO,GAAG,CAACA,OAAD,CAAV;AACH;;AACD,SAAOA,OAAO,CAACG,IAAR,CAAcC,MAAD,IAAY;AAAA;;AAC5B,2BAAIA,MAAM,CAACC,OAAX,4CAAI,gBAAgBC,IAAhB,CAAsBD,OAAD,IAAa,IAAIE,MAAJ,CAAWF,OAAX,EAAoBG,IAApB,CAAyBT,IAAzB,CAAlC,CAAJ,EAAuE;AACnE,aAAO,KAAP;AACH;;AACD,QAAI,CAACK,MAAM,CAACK,KAAZ,EAAmB;AACf,aAAO,IAAP;AACH;;AACD,WAAOL,MAAM,CAACK,KAAP,CAAaH,IAAb,CAAmBI,OAAD,IAAa,IAAIH,MAAJ,CAAWG,OAAX,EAAoBF,IAApB,CAAyBT,IAAzB,CAA/B,CAAP;AACH,GARM,CAAP;AASH,CAhBM","sourcesContent":["// @flow\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {schemaFromIntrospectionData} from '../schemaFromIntrospectionData';\nimport configSchema from './schema.json'; // eslint-disable-line flowtype-errors/uncovered\n\nimport fs from 'fs';\nimport {\n buildClientSchema,\n buildSchema,\n getIntrospectionQuery,\n graphqlSync,\n type IntrospectionQuery,\n} from 'graphql';\nimport type {Config, GenerateConfig} from '../types';\nimport {validate} from 'jsonschema'; // eslint-disable-line flowtype-errors/uncovered\n\nexport const validateOrThrow = (value: mixed, jsonSchema: mixed) => {\n /* eslint-disable flowtype-errors/uncovered */\n const result = validate(value, jsonSchema);\n if (!result.valid) {\n throw new Error(\n result.errors.map((error) => error.toString()).join('\\n'),\n );\n }\n /* eslint-enable flowtype-errors/uncovered */\n};\n\nexport const loadConfigFile = (configFile: string): Config => {\n // $FlowIgnore // eslint-disable-next-line flowtype-errors/uncovered\n const data: Config = require(configFile);\n // eslint-disable-next-line flowtype-errors/uncovered\n validateOrThrow(data, configSchema);\n return data;\n};\n\n/**\n * Loads a .json 'introspection query response', or a .graphql schema definition.\n */\nexport const getSchemas = (schemaFilePath: string): [GraphQLSchema, Schema] => {\n const raw = fs.readFileSync(schemaFilePath, 'utf8');\n if (schemaFilePath.endsWith('.graphql')) {\n const schemaForValidation = buildSchema(raw);\n const queryResponse = graphqlSync(\n schemaForValidation,\n getIntrospectionQuery({descriptions: true}),\n );\n const schemaForTypeGeneration = schemaFromIntrospectionData(\n // eslint-disable-next-line flowtype-errors/uncovered\n ((queryResponse.data: any): IntrospectionQuery),\n );\n return [schemaForValidation, schemaForTypeGeneration];\n } else {\n // eslint-disable-next-line flowtype-errors/uncovered\n const introspectionData: IntrospectionQuery = JSON.parse(raw);\n const schemaForValidation = buildClientSchema(introspectionData);\n const schemaForTypeGeneration =\n schemaFromIntrospectionData(introspectionData);\n return [schemaForValidation, schemaForTypeGeneration];\n }\n};\n\n/**\n * Find the first item of the `config.generate` array where both:\n * - no item of `exclude` matches\n * - at least one item of `match` matches\n */\nexport const findApplicableConfig = (\n path: string,\n configs: Array<GenerateConfig> | GenerateConfig,\n): ?GenerateConfig => {\n if (!Array.isArray(configs)) {\n configs = [configs];\n }\n return configs.find((config) => {\n if (config.exclude?.some((exclude) => new RegExp(exclude).test(path))) {\n return false;\n }\n if (!config.match) {\n return true;\n }\n return config.match.some((matcher) => new RegExp(matcher).test(path));\n });\n};\n"],"file":"config.js"}
1
+ {"version":3,"sources":["../../src/cli/config.js"],"names":["validateOrThrow","value","jsonSchema","result","valid","Error","errors","map","error","toString","join","loadConfigFile","configFile","data","require","configSchema","getSchemas","schemaFilePath","raw","fs","readFileSync","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData","JSON","parse","findApplicableConfig","path","configs","Array","isArray","find","config","exclude","some","RegExp","test","match","matcher"],"mappings":";;;;;;;AAIA;;AACA;;AAEA;;AACA;;AAQA;;;;AAX0C;AAWL;AAE9B,MAAMA,eAAe,GAAG,CAACC,KAAD,EAAeC,UAAf,KAAqC;AAChE;AACA,QAAMC,MAAM,GAAG,0BAASF,KAAT,EAAgBC,UAAhB,CAAf;;AACA,MAAI,CAACC,MAAM,CAACC,KAAZ,EAAmB;AACf,UAAM,IAAIC,KAAJ,CACFF,MAAM,CAACG,MAAP,CAAcC,GAAd,CAAmBC,KAAD,IAAWA,KAAK,CAACC,QAAN,EAA7B,EAA+CC,IAA/C,CAAoD,IAApD,CADE,CAAN;AAGH;AACD;;AACH,CATM;;;;AAWA,MAAMC,cAAc,GAAIC,UAAD,IAAgC;AAC1D;AACA,QAAMC,IAAY,GAAGC,OAAO,CAACF,UAAD,CAA5B,CAF0D,CAEhB;;;AAC1CZ,EAAAA,eAAe,CAACa,IAAD,EAAOE,eAAP,CAAf,CAH0D,CAGrB;;AACrC,SAAOF,IAAP;AACH,CALM;AAOP;AACA;AACA;;;;;AACO,MAAMG,UAAU,GAAIC,cAAD,IAAqD;AAC3E,QAAMC,GAAG,GAAGC,YAAGC,YAAH,CAAgBH,cAAhB,EAAgC,MAAhC,CAAZ;;AACA,MAAIA,cAAc,CAACI,QAAf,CAAwB,UAAxB,CAAJ,EAAyC;AACrC,U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../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {schemaFromIntrospectionData} from '../schemaFromIntrospectionData';\nimport configSchema from './schema.json'; // eslint-disable-line flowtype-errors/uncovered\n\nimport fs from 'fs';\nimport {\n buildClientSchema,\n buildSchema,\n getIntrospectionQuery,\n graphqlSync,\n type IntrospectionQuery,\n} from 'graphql';\nimport type {Config, GenerateConfig} from '../types';\nimport {validate} from 'jsonschema'; // eslint-disable-line flowtype-errors/uncovered\n\nexport const validateOrThrow = (value: mixed, jsonSchema: mixed) => {\n /* eslint-disable flowtype-errors/uncovered */\n const result = validate(value, jsonSchema);\n if (!result.valid) {\n throw new Error(\n result.errors.map((error) => error.toString()).join('\\n'),\n );\n }\n /* eslint-enable flowtype-errors/uncovered */\n};\n\nexport const loadConfigFile = (configFile: string): Config => {\n // $FlowIgnore\n const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered\n validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered\n return data;\n};\n\n/**\n * Loads a .json 'introspection query response', or a .graphql schema definition.\n */\nexport const getSchemas = (schemaFilePath: string): [GraphQLSchema, Schema] => {\n const raw = fs.readFileSync(schemaFilePath, 'utf8');\n if (schemaFilePath.endsWith('.graphql')) {\n const schemaForValidation = buildSchema(raw);\n const queryResponse = graphqlSync(\n schemaForValidation,\n getIntrospectionQuery({descriptions: true}),\n );\n const schemaForTypeGeneration = schemaFromIntrospectionData(\n // eslint-disable-next-line flowtype-errors/uncovered\n ((queryResponse.data: any): IntrospectionQuery),\n );\n return [schemaForValidation, schemaForTypeGeneration];\n } else {\n // eslint-disable-next-line flowtype-errors/uncovered\n const introspectionData: IntrospectionQuery = JSON.parse(raw);\n const schemaForValidation = buildClientSchema(introspectionData);\n const schemaForTypeGeneration =\n schemaFromIntrospectionData(introspectionData);\n return [schemaForValidation, schemaForTypeGeneration];\n }\n};\n\n/**\n * Find the first item of the `config.generate` array where both:\n * - no item of `exclude` matches\n * - at least one item of `match` matches\n */\nexport const findApplicableConfig = (\n path: string,\n configs: Array<GenerateConfig> | GenerateConfig,\n): ?GenerateConfig => {\n if (!Array.isArray(configs)) {\n configs = [configs];\n }\n return configs.find((config) => {\n if (config.exclude?.some((exclude) => new RegExp(exclude).test(path))) {\n return false;\n }\n if (!config.match) {\n return true;\n }\n return config.match.some((matcher) => new RegExp(matcher).test(path));\n });\n};\n"],"file":"config.js"}
package/dist/cli/run.js CHANGED
@@ -42,7 +42,7 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj &&
42
42
 
43
43
  /** Step (1) */
44
44
  const findGraphqlTagReferences = root => {
45
- const response = (0, _child_process.execSync)("git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx'", {
45
+ const response = (0, _child_process.execSync)("git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'", {
46
46
  encoding: 'utf8',
47
47
  cwd: root
48
48
  });
@@ -73,7 +73,24 @@ const files = (0, _parse.processFiles)(inputFiles, f => {
73
73
  }
74
74
 
75
75
  if ((0, _fs.existsSync)(f + '.js')) {
76
- return (0, _fs.readFileSync)(f + '.js', 'utf8');
76
+ return {
77
+ text: (0, _fs.readFileSync)(f + '.js', 'utf8'),
78
+ resolvedPath: f + '.js'
79
+ };
80
+ }
81
+
82
+ if ((0, _fs.existsSync)(f + '.ts')) {
83
+ return {
84
+ text: (0, _fs.readFileSync)(f + '.ts', 'utf8'),
85
+ resolvedPath: f + '.ts'
86
+ };
87
+ }
88
+
89
+ if ((0, _fs.existsSync)(f + '.tsx')) {
90
+ return {
91
+ text: (0, _fs.readFileSync)(f + '.tsx', 'utf8'),
92
+ resolvedPath: f + '.tsx'
93
+ };
77
94
  }
78
95
 
79
96
  throw new Error(`Unable to find ${f}`);
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // @flow
3
3
  /* eslint-disable no-console */
4
+ import type {Schema} from '../types';
5
+ import type {GraphQLSchema} from 'graphql/type/schema';
6
+
4
7
  import {generateTypeFiles, processPragmas} from '../generateTypeFiles';
5
8
  import {processFiles} from '../parser/parse';
6
9
  import {resolveDocuments} from '../parser/resolve';
@@ -15,7 +18,6 @@ import {print} from 'graphql/language/printer';
15
18
  import {validate} from 'graphql/validation';
16
19
  import path from 'path';
17
20
  import {dirname} from 'path';
18
- import type {GenerateConfig} from '../types';
19
21
 
20
22
  /**
21
23
  * This CLI tool executes the following steps:
@@ -32,7 +34,7 @@ import type {GenerateConfig} from '../types';
32
34
 
33
35
  const findGraphqlTagReferences = (root: string): Array<string> => {
34
36
  const response = execSync(
35
- "git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx'",
37
+ "git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'",
36
38
  {
37
39
  encoding: 'utf8',
38
40
  cwd: root,
@@ -81,7 +83,16 @@ const files = processFiles(inputFiles, (f) => {
81
83
  return readFileSync(f, 'utf8');
82
84
  }
83
85
  if (existsSync(f + '.js')) {
84
- return readFileSync(f + '.js', 'utf8');
86
+ return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};
87
+ }
88
+ if (existsSync(f + '.ts')) {
89
+ return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};
90
+ }
91
+ if (existsSync(f + '.tsx')) {
92
+ return {
93
+ text: readFileSync(f + '.tsx', 'utf8'),
94
+ resolvedPath: f + '.tsx',
95
+ };
85
96
  }
86
97
  throw new Error(`Unable to find ${f}`);
87
98
  });
@@ -118,7 +129,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
118
129
 
119
130
  /** Step (4) */
120
131
 
121
- const schemaCache = {};
132
+ const schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};
122
133
  const getCachedSchemas = (schemaFilePath: string) => {
123
134
  if (!schemaCache[schemaFilePath]) {
124
135
  schemaCache[schemaFilePath] = getSchemas(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFilePath","cliFiles","process","argv","console","log","exit","makeAbsPath","maybeRelativePath","basePath","isAbsolute","absConfigPath","config","inputFiles","length","crawl","dirname","files","f","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","schemaCache","getCachedSchemas","schemaFilePath","validationFailures","printedOperations","filePathAndLine","document","raw","hasNonFragments","definitions","some","kind","rawSource","literals","generateConfig","generate","withTypeNames","printed","includes","push","pragmaResult","strict","strictNullability","schemaForValidation","schemaForTypeGeneration","err","dumpOperations","parent","recursive","JSON","stringify","sort"],"mappings":"AAAA;;AAEA;;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;;;AAPwD;;AAWxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA,MAAMA,wBAAwB,GAAIC,IAAD,IAAiC;AAC9D,QAAMC,QAAQ,GAAG,6BACb,uFADa,EAEb;AACIC,IAAAA,QAAQ,EAAE,MADd;AAEIC,IAAAA,GAAG,EAAEH;AAFT,GAFa,CAAjB;AAOA,SAAOC,QAAQ,CACVG,IADE,GAEFC,KAFE,CAEI,IAFJ,EAGFC,GAHE,CAGGC,QAAD,IAAcC,cAAKC,IAAL,CAAUT,IAAV,EAAgBO,QAAhB,CAHhB,CAAP;AAIH,CAZD;;AAcA,MAAM,CAACG,CAAD,EAAIC,EAAJ,EAAQC,cAAR,EAAwB,GAAGC,QAA3B,IAAuCC,OAAO,CAACC,IAArD;;AAEA,IACIH,cAAc,KAAK,IAAnB,IACAA,cAAc,KAAK,QADnB,IAEAA,cAAc,KAAK,MAFnB,IAGA,CAACA,cAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,EA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node\n// @flow\n/* eslint-disable no-console */\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {findApplicableConfig, getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\nimport {dirname} from 'path';\nimport type {GenerateConfig} from '../types';\n\n/**\n * This CLI tool executes the following steps:\n * 1) parse & validate config file\n * 2) crawl files to find all operations and fragments, with\n * tagged template literals and expressions.\n * 3) resolve the found operations, passing the literals and\n * fragments into the `graphql-tag` function to produce\n * the DocumentNodes.\n * 4) generate types for all resolved Queries & Mutations\n */\n\n/** Step (1) */\n\nconst findGraphqlTagReferences = (root: string): Array<string> => {\n const response = execSync(\n \"git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx'\",\n {\n encoding: 'utf8',\n cwd: root,\n },\n );\n return response\n .trim()\n .split('\\n')\n .map((relative) => path.join(root, relative));\n};\n\nconst [_, __, configFilePath, ...cliFiles] = process.argv;\n\nif (\n configFilePath === '-h' ||\n configFilePath === '--help' ||\n configFilePath === 'help' ||\n !configFilePath\n) {\n console.log(`graphql-flow\n\nUsage: graphql-flow [configFile.json] [filesToCrawl...]`);\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconst makeAbsPath = (maybeRelativePath: string, basePath: string) => {\n return path.isAbsolute(maybeRelativePath)\n ? maybeRelativePath\n : path.join(basePath, maybeRelativePath);\n};\n\nconst absConfigPath = makeAbsPath(configFilePath, process.cwd());\n\nconst config = loadConfigFile(absConfigPath);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(\n makeAbsPath(config.crawl.root, path.dirname(absConfigPath)),\n );\n\n/** Step (2) */\n\nconst files = processFiles(inputFiles, (f) => {\n if (existsSync(f)) {\n return readFileSync(f, 'utf8');\n }\n if (existsSync(f + '.js')) {\n return readFileSync(f + '.js', 'utf8');\n }\n throw new Error(`Unable to find ${f}`);\n});\n\nlet filesHadErrors = false;\nObject.keys(files).forEach((key) => {\n const file = files[key];\n if (file.errors.length) {\n filesHadErrors = true;\n console.error(`Errors in ${file.path}`);\n file.errors.forEach((error) => {\n console.error(` - ${error.message}`);\n });\n }\n});\n\nif (filesHadErrors) {\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\n/** Step (3) */\n\nconst {resolved, errors} = resolveDocuments(files);\nif (errors.length) {\n errors.forEach((error) => {\n console.error(`Resolution error ${error.message} in ${error.loc.path}`);\n });\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconsole.log(Object.keys(resolved).length, 'resolved queries');\n\n/** Step (4) */\n\nconst schemaCache = {};\nconst getCachedSchemas = (schemaFilePath: string) => {\n if (!schemaCache[schemaFilePath]) {\n schemaCache[schemaFilePath] = getSchemas(\n makeAbsPath(schemaFilePath, path.dirname(absConfigPath)),\n );\n }\n\n return schemaCache[schemaFilePath];\n};\n\nlet validationFailures: number = 0;\nconst printedOperations: Array<string> = [];\n\nObject.keys(resolved).forEach((filePathAndLine) => {\n const {document, raw} = resolved[filePathAndLine];\n\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n\n const generateConfig = findApplicableConfig(\n // strip off the trailing line number, e.g. `:23`\n filePathAndLine.split(':')[0],\n config.generate,\n );\n if (!generateConfig) {\n return; // no generate config matches, bail\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\n if (hasNonFragments && !printedOperations.includes(printed)) {\n printedOperations.push(printed);\n }\n\n const pragmaResult = processPragmas(\n generateConfig,\n config.crawl,\n rawSource,\n );\n if (!pragmaResult.generate) {\n return;\n }\n if (pragmaResult.strict != null) {\n generateConfig.strictNullability = pragmaResult.strict;\n }\n\n const [schemaForValidation, schemaForTypeGeneration] = getCachedSchemas(\n generateConfig.schemaFilePath,\n );\n\n if (hasNonFragments) {\n /* eslint-disable flowtype-errors/uncovered */\n const errors = validate(schemaForValidation, withTypeNames);\n /* eslint-disable flowtype-errors/uncovered */\n if (errors.length) {\n errors.forEach((error) => {\n console.error(\n `Schema validation found errors for ${raw.loc.path}!`,\n );\n console.error(printed);\n console.error(error);\n validationFailures++;\n });\n }\n /* eslint-enable flowtype-errors/uncovered */\n }\n\n try {\n generateTypeFiles(\n raw.loc.path,\n schemaForTypeGeneration,\n withTypeNames,\n generateConfig,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n } catch (err) {\n console.error(`Error while generating operation from ${raw.loc.path}`);\n console.error(printed);\n // eslint-disable-next-line flowtype-errors/uncovered\n console.error(err);\n validationFailures++;\n }\n});\n\nif (validationFailures) {\n console.error(\n `Encountered ${validationFailures} validation failures while printing types.`,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n process.exit(1);\n}\n\nif (config.crawl.dumpOperations) {\n const dumpOperations = config.crawl.dumpOperations;\n const parent = dirname(dumpOperations);\n mkdirSync(parent, {recursive: true});\n writeFileSync(\n dumpOperations,\n JSON.stringify(printedOperations.sort(), null, 2),\n );\n}\n"],"file":"run.js"}
1
+ {"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFilePath","cliFiles","process","argv","console","log","exit","makeAbsPath","maybeRelativePath","basePath","isAbsolute","absConfigPath","config","inputFiles","length","crawl","dirname","files","f","text","resolvedPath","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","schemaCache","getCachedSchemas","schemaFilePath","validationFailures","printedOperations","filePathAndLine","document","raw","hasNonFragments","definitions","some","kind","rawSource","literals","generateConfig","generate","withTypeNames","printed","includes","push","pragmaResult","strict","strictNullability","schemaForValidation","schemaForTypeGeneration","err","dumpOperations","parent","recursive","JSON","stringify","sort"],"mappings":"AAAA;;AAEA;;;AAIA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;;;AAPwD;;AAUxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AAEA,MAAMA,wBAAwB,GAAIC,IAAD,IAAiC;AAC9D,QAAMC,QAAQ,GAAG,6BACb,sGADa,EAEb;AACIC,IAAAA,QAAQ,EAAE,MADd;AAEIC,IAAAA,GAAG,EAAEH;AAFT,GAFa,CAAjB;AAOA,SAAOC,QAAQ,CACVG,IADE,GAEFC,KAFE,CAEI,IAFJ,EAGFC,GAHE,CAGGC,QAAD,IAAcC,cAAKC,IAAL,CAAUT,IAAV,EAAgBO,QAAhB,CAHhB,CAAP;AAIH,CAZD;;AAcA,MAAM,CAACG,CAAD,EAAIC,EAAJ,EAAQC,cAAR,EAAwB,GAAGC,QAA3B,IAAuCC,OAAO,CAACC,IAArD;;AAEA,IACIH,cAAc,KAAK,IAAnB,IACAA,cAAc,KAAK,QADnB,IAEAA,cAAc,KAAK,MAFnB,IAGA,CAACA,cAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,EAJF,CAImB;AACpB;;AAED,MAAMC,WAAW,GAAG,CAACC,iBAAD,EAA4BC,QAA5B,KAAiD;AACjE,SAAOb,cAAKc,UAAL,CAAgBF,iBAAhB,IACDA,iBADC,GAEDZ,cAAKC,IAAL,CAAUY,QAAV,EAAoBD,iBAApB,CAFN;AAGH,CAJD;;AAMA,MAAMG,aAAa,GAAGJ,WAAW,CAACP,cAAD,EAAiBE,OAAO,CAACX,GAAR,EAAjB,CAAjC;AAEA,MAAMqB,MAA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AS,EAAE;AAAZ,GAAlB;AACA,yBACIF,cADJ,EAEIG,IAAI,CAACC,SAAL,CAAe1B,iBAAiB,CAAC2B,IAAlB,EAAf,EAAyC,IAAzC,EAA+C,CAA/C,CAFJ;AAIH","sourcesContent":["#!/usr/bin/env node\n// @flow\n/* eslint-disable no-console */\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {findApplicableConfig, getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\nimport {dirname} from 'path';\n\n/**\n * This CLI tool executes the following steps:\n * 1) parse & validate config file\n * 2) crawl files to find all operations and fragments, with\n * tagged template literals and expressions.\n * 3) resolve the found operations, passing the literals and\n * fragments into the `graphql-tag` function to produce\n * the DocumentNodes.\n * 4) generate types for all resolved Queries & Mutations\n */\n\n/** Step (1) */\n\nconst findGraphqlTagReferences = (root: string): Array<string> => {\n const response = execSync(\n \"git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'\",\n {\n encoding: 'utf8',\n cwd: root,\n },\n );\n return response\n .trim()\n .split('\\n')\n .map((relative) => path.join(root, relative));\n};\n\nconst [_, __, configFilePath, ...cliFiles] = process.argv;\n\nif (\n configFilePath === '-h' ||\n configFilePath === '--help' ||\n configFilePath === 'help' ||\n !configFilePath\n) {\n console.log(`graphql-flow\n\nUsage: graphql-flow [configFile.json] [filesToCrawl...]`);\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconst makeAbsPath = (maybeRelativePath: string, basePath: string) => {\n return path.isAbsolute(maybeRelativePath)\n ? maybeRelativePath\n : path.join(basePath, maybeRelativePath);\n};\n\nconst absConfigPath = makeAbsPath(configFilePath, process.cwd());\n\nconst config = loadConfigFile(absConfigPath);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(\n makeAbsPath(config.crawl.root, path.dirname(absConfigPath)),\n );\n\n/** Step (2) */\n\nconst files = processFiles(inputFiles, (f) => {\n if (existsSync(f)) {\n return readFileSync(f, 'utf8');\n }\n if (existsSync(f + '.js')) {\n return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};\n }\n if (existsSync(f + '.ts')) {\n return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};\n }\n if (existsSync(f + '.tsx')) {\n return {\n text: readFileSync(f + '.tsx', 'utf8'),\n resolvedPath: f + '.tsx',\n };\n }\n throw new Error(`Unable to find ${f}`);\n});\n\nlet filesHadErrors = false;\nObject.keys(files).forEach((key) => {\n const file = files[key];\n if (file.errors.length) {\n filesHadErrors = true;\n console.error(`Errors in ${file.path}`);\n file.errors.forEach((error) => {\n console.error(` - ${error.message}`);\n });\n }\n});\n\nif (filesHadErrors) {\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\n/** Step (3) */\n\nconst {resolved, errors} = resolveDocuments(files);\nif (errors.length) {\n errors.forEach((error) => {\n console.error(`Resolution error ${error.message} in ${error.loc.path}`);\n });\n console.error('Aborting');\n process.exit(1); // eslint-disable-line flowtype-errors/uncovered\n}\n\nconsole.log(Object.keys(resolved).length, 'resolved queries');\n\n/** Step (4) */\n\nconst schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};\nconst getCachedSchemas = (schemaFilePath: string) => {\n if (!schemaCache[schemaFilePath]) {\n schemaCache[schemaFilePath] = getSchemas(\n makeAbsPath(schemaFilePath, path.dirname(absConfigPath)),\n );\n }\n\n return schemaCache[schemaFilePath];\n};\n\nlet validationFailures: number = 0;\nconst printedOperations: Array<string> = [];\n\nObject.keys(resolved).forEach((filePathAndLine) => {\n const {document, raw} = resolved[filePathAndLine];\n\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n\n const generateConfig = findApplicableConfig(\n // strip off the trailing line number, e.g. `:23`\n filePathAndLine.split(':')[0],\n config.generate,\n );\n if (!generateConfig) {\n return; // no generate config matches, bail\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\n if (hasNonFragments && !printedOperations.includes(printed)) {\n printedOperations.push(printed);\n }\n\n const pragmaResult = processPragmas(\n generateConfig,\n config.crawl,\n rawSource,\n );\n if (!pragmaResult.generate) {\n return;\n }\n if (pragmaResult.strict != null) {\n generateConfig.strictNullability = pragmaResult.strict;\n }\n\n const [schemaForValidation, schemaForTypeGeneration] = getCachedSchemas(\n generateConfig.schemaFilePath,\n );\n\n if (hasNonFragments) {\n /* eslint-disable flowtype-errors/uncovered */\n const errors = validate(schemaForValidation, withTypeNames);\n /* eslint-disable flowtype-errors/uncovered */\n if (errors.length) {\n errors.forEach((error) => {\n console.error(\n `Schema validation found errors for ${raw.loc.path}!`,\n );\n console.error(printed);\n console.error(error);\n validationFailures++;\n });\n }\n /* eslint-enable flowtype-errors/uncovered */\n }\n\n try {\n generateTypeFiles(\n raw.loc.path,\n schemaForTypeGeneration,\n withTypeNames,\n generateConfig,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n } catch (err) {\n console.error(`Error while generating operation from ${raw.loc.path}`);\n console.error(printed);\n // eslint-disable-next-line flowtype-errors/uncovered\n console.error(err);\n validationFailures++;\n }\n});\n\nif (validationFailures) {\n console.error(\n `Encountered ${validationFailures} validation failures while printing types.`,\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n process.exit(1);\n}\n\nif (config.crawl.dumpOperations) {\n const dumpOperations = config.crawl.dumpOperations;\n const parent = dirname(dumpOperations);\n mkdirSync(parent, {recursive: true});\n writeFileSync(\n dumpOperations,\n JSON.stringify(printedOperations.sort(), null, 2),\n );\n}\n"],"file":"run.js"}
@@ -31,6 +31,9 @@
31
31
  "scalars": {
32
32
  "type": "object"
33
33
  },
34
+ "typeScript": {
35
+ "type": "boolean"
36
+ },
34
37
  "strictNullability": {
35
38
  "type": "boolean"
36
39
  },
@@ -11,8 +11,11 @@ var _path = _interopRequireDefault(require("path"));
11
11
 
12
12
  var _ = require(".");
13
13
 
14
+ var _convert = require("@khanacademy/flow-to-ts/dist/convert.bundle");
15
+
14
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
17
 
18
+ // eslint-disable-next-line flowtype-errors/uncovered
16
19
  const indexPrelude = regenerateCommand => `// @flow
17
20
  //
18
21
  // AUTOGENERATED
@@ -29,6 +32,11 @@ const generateTypeFileContents = (fileName, schema, document, options, generated
29
32
  const files = {}; /// Write export for __generated__/index.js if it doesn't exist
30
33
 
31
34
  const addToIndex = (filePath, typeName) => {
35
+ if (options.typeScript) {
36
+ // Typescript doesn't like file extensions
37
+ filePath = filePath.replace(/\.js$/, '');
38
+ }
39
+
32
40
  const newLine = `export type {${typeName}} from './${_path.default.basename(filePath)}';`;
33
41
 
34
42
  if (indexContents.indexOf('./' + _path.default.basename(filePath)) === -1) {
@@ -108,7 +116,7 @@ const getGeneratedDir = (fileName, options) => {
108
116
  const generateTypeFiles = (fileName, schema, document, options) => {
109
117
  const generatedDir = getGeneratedDir(fileName, options);
110
118
 
111
- const indexFile = _path.default.join(generatedDir, 'index.js');
119
+ const indexFile = _path.default.join(generatedDir, 'index' + (options.typeScript ? '.ts' : '.js'));
112
120
 
113
121
  if (!_fs.default.existsSync(generatedDir)) {
114
122
  _fs.default.mkdirSync(generatedDir, {
@@ -128,7 +136,15 @@ const generateTypeFiles = (fileName, schema, document, options) => {
128
136
  _fs.default.writeFileSync(indexFile, indexContents);
129
137
 
130
138
  Object.keys(files).forEach(key => {
131
- _fs.default.writeFileSync(key, files[key]);
139
+ let fname = key;
140
+
141
+ if (options.typeScript) {
142
+ // eslint-disable-next-line flowtype-errors/uncovered
143
+ files[key] = (0, _convert.convert)(files[key]);
144
+ fname = key.replace(/\.js$/, '.ts');
145
+ }
146
+
147
+ _fs.default.writeFileSync(fname, files[key]);
132
148
  });
133
149
 
134
150
  _fs.default.writeFileSync(indexFile, indexContents);
@@ -4,6 +4,8 @@ import type {GenerateConfig, CrawlConfig, Schema} from './types';
4
4
  import fs from 'fs';
5
5
  import path from 'path';
6
6
  import {documentToFlowTypes} from '.';
7
+ // eslint-disable-next-line flowtype-errors/uncovered
8
+ import {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';
7
9
 
8
10
  export const indexPrelude = (regenerateCommand?: string): string => `// @flow
9
11
  //
@@ -27,6 +29,10 @@ export const generateTypeFileContents = (
27
29
 
28
30
  /// Write export for __generated__/index.js if it doesn't exist
29
31
  const addToIndex = (filePath, typeName) => {
32
+ if (options.typeScript) {
33
+ // Typescript doesn't like file extensions
34
+ filePath = filePath.replace(/\.js$/, '');
35
+ }
30
36
  const newLine = `export type {${typeName}} from './${path.basename(
31
37
  filePath,
32
38
  )}';`;
@@ -120,7 +126,10 @@ export const generateTypeFiles = (
120
126
  options: GenerateConfig,
121
127
  ) => {
122
128
  const generatedDir = getGeneratedDir(fileName, options);
123
- const indexFile = path.join(generatedDir, 'index.js');
129
+ const indexFile = path.join(
130
+ generatedDir,
131
+ 'index' + (options.typeScript ? '.ts' : '.js'),
132
+ );
124
133
 
125
134
  if (!fs.existsSync(generatedDir)) {
126
135
  fs.mkdirSync(generatedDir, {recursive: true});
@@ -140,7 +149,13 @@ export const generateTypeFiles = (
140
149
 
141
150
  fs.writeFileSync(indexFile, indexContents);
142
151
  Object.keys(files).forEach((key) => {
143
- fs.writeFileSync(key, files[key]);
152
+ let fname = key;
153
+ if (options.typeScript) {
154
+ // eslint-disable-next-line flowtype-errors/uncovered
155
+ files[key] = convert(files[key]);
156
+ fname = key.replace(/\.js$/, '.ts');
157
+ }
158
+ fs.writeFileSync(fname, files[key]);
144
159
  });
145
160
 
146
161
  fs.writeFileSync(indexFile, indexContents);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","replace","targetPath","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;;;AAEO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,QADoC,EAEpCC,MAFoC,EAGpCC,QAHoC,EAIpCC,OAJoC,EAKpCC,YALoC,EAMpCC,aANoC,KAOsB;AAC1D,QAAMC,KAAK,GAAG,EAAd,CAD0D,CAG1D;;AACA,QAAMC,UAAU,GAAG,CAACC,QAAD,EAAWC,QAAX,KAAwB;AACvC,UAAMC,OAAO,GAAI,gBAAeD,QAAS,aAAYE,cAAKC,QAAL,CACjDJ,QADiD,CAEnD,IAFF;;AAGA,QAAIH,aAAa,CAACQ,OAAd,CAAsB,OAAOF,cAAKC,QAAL,CAAcJ,QAAd,CAA7B,MAA0D,CAAC,CAA/D,EAAkE;AAC9DH,MAAAA,aAAa,IAAIK,OAAO,GAAG,IAA3B;AAC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AAmBqC,WAAW,CAACE,YAA/B,CAFJ,EAGE;AACE,WAAO;AAACC,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;;AAED,QAAMC,OAAO,GAAGJ,WAAW,CAACK,WAAZ,GACVJ,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACK,WAA/B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAGN,WAAW,CAACO,MAAZ,GAChBN,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACO,MAA/B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACR,WAAW,CAACK,WAAb,IAA4B,CAACL,WAAW,CAACO,MAA3D;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHL,MAAAA,QAAQ,EAAE,IADP;AAEHM,MAAAA,MAAM,EAAED,SAAS,GACXT,cAAc,CAACW,iBADJ,GAEXJ,aAAa,IAAI,CAACF;AAJrB,KAAP;AAMH,GAPD,MAOO;AACH,WAAO;AAACD,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;AACJ,CA9BM","sourcesContent":["// @flow\nimport type {DocumentNode} from 'graphql';\nimport type {GenerateConfig, CrawlConfig, Schema} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {\n indexContents += newLine + '\\n';\n } else {\n const lines = indexContents.split('\\n').map((line) => {\n if (line.includes('./' + path.basename(filePath))) {\n return newLine;\n }\n return line;\n });\n indexContents = lines.join('\\n');\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(generatedDir, 'index.js');\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n fs.writeFileSync(key, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
1
+ {"version":3,"sources":["../src/generateTypeFiles.js"],"names":["indexPrelude","regenerateCommand","generateTypeFileContents","fileName","schema","document","options","generatedDir","indexContents","files","addToIndex","filePath","typeName","typeScript","replace","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","experimentalEnums","targetFileName","typeFileName","targetPath","fileContents","splitTypes","Object","keys","enumNames","length","getGeneratedDir","generatedDirectory","isAbsolute","relative","process","cwd","dirname","generateTypeFiles","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","fname","processPragmas","generateConfig","crawlConfig","rawSource","ignorePragma","generate","autogen","loosePragma","autogenStrict","pragma","noPragmas","strict","strictNullability"],"mappings":";;;;;;;AAGA;;AACA;;AACA;;AAEA;;;;AADA;AAGO,MAAMA,YAAY,GAAIC,iBAAD,IAAyC;AACrE;AACA;AACA;AACA;AACA,IAAIA,iBAAiB,GAAG,8BAA8BA,iBAAjC,GAAqD,EAAG;AAC7E;AACA;AACA,CARO;;;;AAUA,MAAMC,wBAAwB,GAAG,CACpCC,QADoC,EAEpCC,MAFoC,EAGpCC,QAHoC,EAIpCC,OAJoC,EAKpCC,YALoC,EAMpCC,aANoC,KAOsB;AAC1D,QAAMC,KAAK,GAAG,EAAd,CAD0D,CAG1D;;AACA,QAAMC,UAAU,GAAG,CAACC,QAAD,EAAWC,QAAX,KAAwB;AACvC,QAAIN,OAAO,CAACO,UAAZ,EAAwB;AACpB;AACAF,MAAAA,QAAQ,GAAGA,QAAQ,CAACG,OAAT,CAAiB,OAAjB,EAA0B,EAA1B,CAAX;AACH;;AACD,UAAMC,OAAO,GAAI,gBAAeH,QAAS,aAAYI,cAAKC,QAAL,CACjDN,QADiD,CAEnD,IAFF;;AAGA,QAAIH,aAAa,CAACU,OAAd,CAAsB,OAAOF,cAAKC,QAAL,CAAcN,QAAd,CAA7B,MAA0D,CAAC,CAA/D,EAAkE;AAC9DH,MAAAA,aAAa,IAAIO,OAAO,GAAG,IAA3B;AACH,KAFD,MAEO;AACH,YAAMI,KAAK,GAAGX,aAAa,CAACY,KAAd,CAAoB,IAApB,EAA0BC,GAA1B,CAA+BC,IAAD,IAAU;AACl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,cAAGI,aAAH,CAAiBL,SAAjB,EAA4BzC,aAA5B;AACH,CAxCM;;;;AA0CA,MAAMkD,cAAc,GAAG,CAC1BC,cAD0B,EAE1BC,WAF0B,EAG1BC,SAH0B,KAIc;AACxC,MACID,WAAW,CAACE,YAAZ,IACAD,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACE,YAA/B,CAFJ,EAGE;AACE,WAAO;AAACC,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;;AAED,QAAMC,OAAO,GAAGJ,WAAW,CAACK,WAAZ,GACVJ,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACK,WAA/B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAGN,WAAW,CAACO,MAAZ,GAChBN,SAAS,CAACtC,QAAV,CAAmBqC,WAAW,CAACO,MAA/B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACR,WAAW,CAACK,WAAb,IAA4B,CAACL,WAAW,CAACO,MAA3D;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHL,MAAAA,QAAQ,EAAE,IADP;AAEHM,MAAAA,MAAM,EAAED,SAAS,GACXT,cAAc,CAACW,iBADJ,GAEXJ,aAAa,IAAI,CAACF;AAJrB,KAAP;AAMH,GAPD,MAOO;AACH,WAAO;AAACD,MAAAA,QAAQ,EAAE;AAAX,KAAP;AACH;AACJ,CA9BM","sourcesContent":["// @flow\nimport type {DocumentNode} from 'graphql';\nimport type {GenerateConfig, CrawlConfig, Schema} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n// eslint-disable-next-line flowtype-errors/uncovered\nimport {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';\n\nexport const indexPrelude = (regenerateCommand?: string): string => `// @flow\n//\n// AUTOGENERATED\n// NOTE: New response types are added to this file automatically.\n// Outdated response types can be removed manually as they are deprecated.\n//${regenerateCommand ? ' To regenerate, run ' + regenerateCommand : ''}\n//\n\n`;\n\nexport const generateTypeFileContents = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n generatedDir: string,\n indexContents: string,\n): {indexContents: string, files: {[key: string]: string}} => {\n const files = {};\n\n /// Write export for __generated__/index.js if it doesn't exist\n const addToIndex = (filePath, typeName) => {\n if (options.typeScript) {\n // Typescript doesn't like file extensions\n filePath = filePath.replace(/\\.js$/, '');\n }\n const newLine = `export type {${typeName}} from './${path.basename(\n filePath,\n )}';`;\n if (indexContents.indexOf('./' + path.basename(filePath)) === -1) {\n indexContents += newLine + '\\n';\n } else {\n const lines = indexContents.split('\\n').map((line) => {\n if (line.includes('./' + path.basename(filePath))) {\n return newLine;\n }\n return line;\n });\n indexContents = lines.join('\\n');\n }\n };\n\n const generated = documentToFlowTypes(document, schema, options);\n generated.forEach(\n ({name, typeName, code, isFragment, extraTypes, experimentalEnums}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = options.typeFileName\n ? options.typeFileName.replace('[operationName]', name)\n : `${name}.js`;\n const targetPath = path.join(generatedDir, targetFileName);\n\n let fileContents =\n '// @' +\n `flow\\n// AUTOGENERATED -- DO NOT EDIT\\n` +\n `// Generated for operation '${name}' in file '../${path.basename(\n fileName,\n )}'\\n` +\n (options.regenerateCommand\n ? `// To regenerate, run '${options.regenerateCommand}'.\\n`\n : '') +\n code;\n if (options.splitTypes && !isFragment) {\n fileContents +=\n `\\nexport type ${name} = ${typeName}['response'];\\n` +\n `export type ${name}Variables = ${typeName}['variables'];\\n`;\n }\n Object.keys(extraTypes).forEach(\n (name) =>\n (fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`),\n );\n const enumNames = Object.keys(experimentalEnums);\n if (options.experimentalEnums && enumNames.length) {\n // TODO(somewhatabstract, FEI-4172): Update to fixed eslint-plugin-flowtype\n // and remove this disable.\n fileContents += `\\n\\n/* eslint-disable no-undef */`;\n enumNames.forEach(\n (name) =>\n (fileContents += `\\nexport ${experimentalEnums[name]};\\n`),\n );\n fileContents += `/* eslint-enable no-undef */`;\n }\n\n addToIndex(targetPath, typeName);\n files[targetPath] =\n fileContents\n // Remove whitespace from the ends of lines; babel's generate sometimes\n // leaves them hanging around.\n .replace(/\\s+$/gm, '') + '\\n';\n },\n );\n\n return {files, indexContents};\n};\n\nconst getGeneratedDir = (fileName: string, options: GenerateConfig) => {\n const generatedDirectory = options.generatedDirectory ?? '__generated__';\n if (path.isAbsolute(generatedDirectory)) {\n // fileName is absolute here, so we make it relative to cwd\n // for more reasonable filenames. We convert leading ..'s\n // to `__` so this doesn't escape the output directory.\n return path.join(\n generatedDirectory,\n path\n .relative(process.cwd(), path.dirname(fileName))\n .replace(/\\.\\.\\//g, '__/'),\n );\n } else {\n return path.join(path.dirname(fileName), generatedDirectory);\n }\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: GenerateConfig,\n) => {\n const generatedDir = getGeneratedDir(fileName, options);\n const indexFile = path.join(\n generatedDir,\n 'index' + (options.typeScript ? '.ts' : '.js'),\n );\n\n if (!fs.existsSync(generatedDir)) {\n fs.mkdirSync(generatedDir, {recursive: true});\n }\n if (!fs.existsSync(indexFile)) {\n fs.writeFileSync(indexFile, indexPrelude(options.regenerateCommand));\n }\n\n const {indexContents, files} = generateTypeFileContents(\n fileName,\n schema,\n document,\n options,\n generatedDir,\n fs.readFileSync(indexFile, 'utf8'),\n );\n\n fs.writeFileSync(indexFile, indexContents);\n Object.keys(files).forEach((key) => {\n let fname = key;\n if (options.typeScript) {\n // eslint-disable-next-line flowtype-errors/uncovered\n files[key] = convert(files[key]);\n fname = key.replace(/\\.js$/, '.ts');\n }\n fs.writeFileSync(fname, files[key]);\n });\n\n fs.writeFileSync(indexFile, indexContents);\n};\n\nexport const processPragmas = (\n generateConfig: GenerateConfig,\n crawlConfig: CrawlConfig,\n rawSource: string,\n): {generate: boolean, strict?: boolean} => {\n if (\n crawlConfig.ignorePragma &&\n rawSource.includes(crawlConfig.ignorePragma)\n ) {\n return {generate: false};\n }\n\n const autogen = crawlConfig.loosePragma\n ? rawSource.includes(crawlConfig.loosePragma)\n : false;\n const autogenStrict = crawlConfig.pragma\n ? rawSource.includes(crawlConfig.pragma)\n : false;\n const noPragmas = !crawlConfig.loosePragma && !crawlConfig.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n generate: true,\n strict: noPragmas\n ? generateConfig.strictNullability\n : autogenStrict || !autogen,\n };\n } else {\n return {generate: false};\n }\n};\n"],"file":"generateTypeFiles.js"}
package/dist/index.js CHANGED
@@ -25,12 +25,13 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
25
25
  */
26
26
  // eslint-disable-line flowtype-errors/uncovered
27
27
  const optionsToConfig = (schema, definitions, options, errors = []) => {
28
- var _options$strictNullab, _options$readOnlyArra, _options$scalars;
28
+ var _options$strictNullab, _options$readOnlyArra, _options$scalars, _options$typeScript;
29
29
 
30
30
  const internalOptions = {
31
31
  strictNullability: (_options$strictNullab = options === null || options === void 0 ? void 0 : options.strictNullability) !== null && _options$strictNullab !== void 0 ? _options$strictNullab : true,
32
32
  readOnlyArray: (_options$readOnlyArra = options === null || options === void 0 ? void 0 : options.readOnlyArray) !== null && _options$readOnlyArra !== void 0 ? _options$readOnlyArra : true,
33
- scalars: (_options$scalars = options === null || options === void 0 ? void 0 : options.scalars) !== null && _options$scalars !== void 0 ? _options$scalars : {}
33
+ scalars: (_options$scalars = options === null || options === void 0 ? void 0 : options.scalars) !== null && _options$scalars !== void 0 ? _options$scalars : {},
34
+ typeScript: (_options$typeScript = options === null || options === void 0 ? void 0 : options.typeScript) !== null && _options$typeScript !== void 0 ? _options$typeScript : false
34
35
  };
35
36
  const fragments = {};
36
37
  definitions.forEach(def => {
@@ -29,6 +29,7 @@ const optionsToConfig = (
29
29
  strictNullability: options?.strictNullability ?? true,
30
30
  readOnlyArray: options?.readOnlyArray ?? true,
31
31
  scalars: options?.scalars ?? {},
32
+ typeScript: options?.typeScript ?? false,
32
33
  };
33
34
  const fragments = {};
34
35
  definitions.forEach((def) => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","fragments","forEach","def","kind","name","value","config","allObjectTypes","path","experimentalEnumsMap","experimentalEnums","undefined","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","codegenExtraTypes","typeName","isFragment","operation","response","variables","filter","Boolean","length","Object","keys","k"],"mappings":";;;;;;;AAWA;;AACA;;AAIA;;;;AAhBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKV;AAAA;;AACV,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,2BAAEH,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEG,iBAAX,yEAAgC,IAD7B;AAEpBC,IAAAA,aAAa,2BAAEJ,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEI,aAAX,yEAA4B,IAFrB;AAGpBC,IAAAA,OAAO,sBAAEL,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEK,OAAX,+DAAsB;AAHT,GAAxB;AAKA,QAAMC,SAAS,GAAG,EAAlB;AACAP,EAAAA,WAAW,CAACQ,OAAZ,CAAqBC,GAAD,IAAS;AACzB,QAAIA,GAAG,CAACC,IAAJ,KAAa,oBAAjB,EAAuC;AACnCH,MAAAA,SAAS,CAACE,GAAG,CAACE,IAAJ,CAASC,KAAV,CAAT,GAA4BH,GAA5B;AACH;AACJ,GAJD;AAKA,QAAMI,MAAM,GAAG;AACXN,IAAAA,SADW;AAEXR,IAAAA,MAFW;AAGXG,IAAAA,MAHW;AAIXY,IA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AAD;AAAOuB,QAAAA,QAAP;AAAiBJ,QAAAA,IAAjB;AAAuBE,QAAAA,UAAvB;AAAmCf,QAAAA;AAAnC,OAAP;AACH;AACJ,GA9DU,EA+DVsB,MA/DU,CA+DHC,OA/DG,CAAf;;AAgEA,MAAItC,MAAM,CAACuC,MAAX,EAAmB;AACf,UAAM,IAAItB,mBAAJ,CAAwBjB,MAAxB,CAAN;AACH;;AACD,SAAOwB,MAAP;AACH,CAvFM;;;;AAyFP,SAASO,iBAAT,CAA2BJ,KAA3B,EAEE;AACE,QAAMG,UAAmC,GAAG,EAA5C;AACAU,EAAAA,MAAM,CAACC,IAAP,CAAYd,KAAZ,EAAmBrB,OAAnB,CAA4BoC,CAAD,IAAe;AACtC;AACAZ,IAAAA,UAAU,CAACY,CAAD,CAAV,GAAgB,wBAASf,KAAK,CAACe,CAAD,CAAd,EAAmBd,IAAnC;AACH,GAHD;AAIA,SAAOE,UAAP;AACH","sourcesContent":["/* eslint-disable no-console */\n/* flow-uncovered-file */\n// @flow\n/**\n * This tool generates flowtype definitions from graphql queries.\n *\n * It relies on `introspection-query.json` existing in this directory,\n * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.\n */\nimport type {DefinitionNode, DocumentNode} from 'graphql';\n\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport {\n generateFragmentType,\n generateResponseType,\n} from './generateResponseType';\nimport {generateVariablesType} from './generateVariablesType';\nimport type {BabelNode} from '@babel/types';\n\nimport type {Context, Schema, GenerateConfig} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: GenerateConfig,\n errors: Array<string> = [],\n): Context => {\n const internalOptions = {\n strictNullability: options?.strictNullability ?? true,\n readOnlyArray: options?.readOnlyArray ?? true,\n scalars: options?.scalars ?? {},\n };\n const fragments = {};\n definitions.forEach((def) => {\n if (def.kind === 'FragmentDefinition') {\n fragments[def.name.value] = def;\n }\n });\n const config = {\n fragments,\n schema,\n errors,\n allObjectTypes: null,\n path: [],\n experimentalEnumsMap: options?.experimentalEnums ? {} : undefined,\n ...internalOptions,\n };\n\n return config;\n};\n\nexport class FlowGenerationError extends Error {\n messages: Array<string>;\n constructor(errors: Array<string>) {\n super(`Graphql-flow type generation failed! ${errors.join('; ')}`);\n this.messages = errors;\n }\n}\n\nexport const documentToFlowTypes = (\n document: DocumentNode,\n schema: Schema,\n options?: GenerateConfig,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n isFragment?: boolean,\n extraTypes: {[key: string]: string},\n experimentalEnums: {[key: string]: string},\n}> => {\n const errors: Array<string> = [];\n const config = optionsToConfig(\n schema,\n document.definitions,\n options,\n errors,\n );\n const result = document.definitions\n .map((item) => {\n if (item.kind === 'FragmentDefinition') {\n const name = item.name.value;\n const types = {};\n const code = `export type ${name} = ${generateFragmentType(\n schema,\n item,\n {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n },\n )};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {\n name,\n typeName: name,\n code,\n isFragment: true,\n extraTypes,\n experimentalEnums,\n };\n }\n if (\n item.kind === 'OperationDefinition' &&\n (item.operation === 'query' || item.operation === 'mutation') &&\n item.name\n ) {\n const types = {};\n const name = item.name.value;\n const response = generateResponseType(schema, item, {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n });\n const variables = generateVariablesType(schema, item, {\n ...config,\n path: [name],\n });\n\n const typeName = `${name}Type`;\n // TODO(jared): Maybe make this template configurable?\n // We'll see what's required to get webapp on board.\n const code = `export type ${typeName} = {|\\n variables: ${variables},\\n response: ${response}\\n|};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {name, typeName, code, extraTypes, experimentalEnums};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n\nfunction codegenExtraTypes(types: {[key: string]: BabelNode}): {\n [key: string]: string,\n} {\n const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k: string) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return extraTypes;\n}\n"],"file":"index.js"}
1
+ {"version":3,"sources":["../src/index.js"],"names":["optionsToConfig","schema","definitions","options","errors","internalOptions","strictNullability","readOnlyArray","scalars","typeScript","fragments","forEach","def","kind","name","value","config","allObjectTypes","path","experimentalEnumsMap","experimentalEnums","undefined","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","codegenExtraTypes","typeName","isFragment","operation","response","variables","filter","Boolean","length","Object","keys","k"],"mappings":";;;;;;;AAWA;;AACA;;AAIA;;;;AAhBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKV;AAAA;;AACV,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,2BAAEH,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEG,iBAAX,yEAAgC,IAD7B;AAEpBC,IAAAA,aAAa,2BAAEJ,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEI,aAAX,yEAA4B,IAFrB;AAGpBC,IAAAA,OAAO,sBAAEL,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEK,OAAX,+DAAsB,EAHT;AAIpBC,IAAAA,UAAU,yBAAEN,OAAF,aAAEA,OAAF,uBAAEA,OAAO,CAAEM,UAAX,qEAAyB;AAJf,GAAxB;AAMA,QAAMC,SAAS,GAAG,EAAlB;AACAR,EAAAA,WAAW,CAACS,OAAZ,CAAqBC,GAAD,IAAS;AACzB,QAAIA,GAAG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,IAAI,GAAI,eAAcI,QAAS,yBAAwBI,SAAU,oBAAmBD,QAAS,OAAnG;AAEA,YAAML,UAAU,GAAGC,iBAAiB,CAACJ,KAAD,CAApC;AACA,YAAMZ,iBAAiB,GAAGgB,iBAAiB,CACvCpB,MAAM,CAACG,oBAAP,IAA+B,EADQ,CAA3C;AAIA,aAAO;AAACL,QAAAA,IAAD;AAAOuB,QAAAA,QAAP;AAAiBJ,QAAAA,IAAjB;AAAuBE,QAAAA,UAAvB;AAAmCf,QAAAA;AAAnC,OAAP;AACH;AACJ,GA9DU,EA+DVsB,MA/DU,CA+DHC,OA/DG,CAAf;;AAgEA,MAAIvC,MAAM,CAACwC,MAAX,EAAmB;AACf,UAAM,IAAItB,mBAAJ,CAAwBlB,MAAxB,CAAN;AACH;;AACD,SAAOyB,MAAP;AACH,CAvFM;;;;AAyFP,SAASO,iBAAT,CAA2BJ,KAA3B,EAEE;AACE,QAAMG,UAAmC,GAAG,EAA5C;AACAU,EAAAA,MAAM,CAACC,IAAP,CAAYd,KAAZ,EAAmBrB,OAAnB,CAA4BoC,CAAD,IAAe;AACtC;AACAZ,IAAAA,UAAU,CAACY,CAAD,CAAV,GAAgB,wBAASf,KAAK,CAACe,CAAD,CAAd,EAAmBd,IAAnC;AACH,GAHD;AAIA,SAAOE,UAAP;AACH","sourcesContent":["/* eslint-disable no-console */\n/* flow-uncovered-file */\n// @flow\n/**\n * This tool generates flowtype definitions from graphql queries.\n *\n * It relies on `introspection-query.json` existing in this directory,\n * which is produced by running `./tools/graphql-flow/sendIntrospection.js`.\n */\nimport type {DefinitionNode, DocumentNode} from 'graphql';\n\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport {\n generateFragmentType,\n generateResponseType,\n} from './generateResponseType';\nimport {generateVariablesType} from './generateVariablesType';\nimport type {BabelNode} from '@babel/types';\n\nimport type {Context, Schema, GenerateConfig} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: GenerateConfig,\n errors: Array<string> = [],\n): Context => {\n const internalOptions = {\n strictNullability: options?.strictNullability ?? true,\n readOnlyArray: options?.readOnlyArray ?? true,\n scalars: options?.scalars ?? {},\n typeScript: options?.typeScript ?? false,\n };\n const fragments = {};\n definitions.forEach((def) => {\n if (def.kind === 'FragmentDefinition') {\n fragments[def.name.value] = def;\n }\n });\n const config = {\n fragments,\n schema,\n errors,\n allObjectTypes: null,\n path: [],\n experimentalEnumsMap: options?.experimentalEnums ? {} : undefined,\n ...internalOptions,\n };\n\n return config;\n};\n\nexport class FlowGenerationError extends Error {\n messages: Array<string>;\n constructor(errors: Array<string>) {\n super(`Graphql-flow type generation failed! ${errors.join('; ')}`);\n this.messages = errors;\n }\n}\n\nexport const documentToFlowTypes = (\n document: DocumentNode,\n schema: Schema,\n options?: GenerateConfig,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n isFragment?: boolean,\n extraTypes: {[key: string]: string},\n experimentalEnums: {[key: string]: string},\n}> => {\n const errors: Array<string> = [];\n const config = optionsToConfig(\n schema,\n document.definitions,\n options,\n errors,\n );\n const result = document.definitions\n .map((item) => {\n if (item.kind === 'FragmentDefinition') {\n const name = item.name.value;\n const types = {};\n const code = `export type ${name} = ${generateFragmentType(\n schema,\n item,\n {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n },\n )};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {\n name,\n typeName: name,\n code,\n isFragment: true,\n extraTypes,\n experimentalEnums,\n };\n }\n if (\n item.kind === 'OperationDefinition' &&\n (item.operation === 'query' || item.operation === 'mutation') &&\n item.name\n ) {\n const types = {};\n const name = item.name.value;\n const response = generateResponseType(schema, item, {\n ...config,\n path: [name],\n allObjectTypes: options?.exportAllObjectTypes\n ? types\n : null,\n });\n const variables = generateVariablesType(schema, item, {\n ...config,\n path: [name],\n });\n\n const typeName = `${name}Type`;\n // TODO(jared): Maybe make this template configurable?\n // We'll see what's required to get webapp on board.\n const code = `export type ${typeName} = {|\\n variables: ${variables},\\n response: ${response}\\n|};`;\n\n const extraTypes = codegenExtraTypes(types);\n const experimentalEnums = codegenExtraTypes(\n config.experimentalEnumsMap || {},\n );\n\n return {name, typeName, code, extraTypes, experimentalEnums};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n\nfunction codegenExtraTypes(types: {[key: string]: BabelNode}): {\n [key: string]: string,\n} {\n const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k: string) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return extraTypes;\n}\n"],"file":"index.js"}
@@ -5,7 +5,9 @@ import {resolveDocuments} from '../resolve';
5
5
 
6
6
  import {print} from 'graphql/language/printer';
7
7
 
8
- const fixtureFiles: {[key: string]: string} = {
8
+ const fixtureFiles: {
9
+ [key: string]: string | {text: string, resolvedPath: string},
10
+ } = {
9
11
  '/firstFile.js': `
10
12
  // Note that you can import graphql-tag as
11
13
  // something other than gql.
@@ -57,14 +57,17 @@ const processFile = (filePath, contents) => {
57
57
  locals: {},
58
58
  errors: []
59
59
  };
60
+ const resolved = typeof contents === 'string' ? filePath : contents.resolvedPath;
61
+ const text = typeof contents === 'string' ? contents : contents.text;
62
+ const plugins = resolved.match(/\.tsx?$/) ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean) : [['flow', {
63
+ enums: true
64
+ }], 'jsx'];
60
65
  /* eslint-disable flowtype-errors/uncovered */
61
66
 
62
- const ast = (0, _parser.parse)(contents, {
67
+ const ast = (0, _parser.parse)(text, {
63
68
  sourceType: 'module',
64
69
  allowImportExportEverywhere: true,
65
- plugins: [['flow', {
66
- enums: true
67
- }], 'jsx']
70
+ plugins: plugins
68
71
  });
69
72
  /* eslint-enable flowtype-errors/uncovered */
70
73
 
@@ -121,7 +121,10 @@ const listExternalReferences = (file: FileResult): Array<string> => {
121
121
  return Object.keys(paths);
122
122
  };
123
123
 
124
- export const processFile = (filePath: string, contents: string): FileResult => {
124
+ export const processFile = (
125
+ filePath: string,
126
+ contents: string | {text: string, resolvedPath: string},
127
+ ): FileResult => {
125
128
  const dir = path.dirname(filePath);
126
129
  const result: FileResult = {
127
130
  path: filePath,
@@ -130,11 +133,17 @@ export const processFile = (filePath: string, contents: string): FileResult => {
130
133
  locals: {},
131
134
  errors: [],
132
135
  };
136
+ const resolved =
137
+ typeof contents === 'string' ? filePath : contents.resolvedPath;
138
+ const text = typeof contents === 'string' ? contents : contents.text;
139
+ const plugins = resolved.match(/\.tsx?$/)
140
+ ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)
141
+ : [['flow', {enums: true}], 'jsx'];
133
142
  /* eslint-disable flowtype-errors/uncovered */
134
- const ast: BabelNodeFile = parse(contents, {
143
+ const ast: BabelNodeFile = parse(text, {
135
144
  sourceType: 'module',
136
145
  allowImportExportEverywhere: true,
137
- plugins: [['flow', {enums: true}], 'jsx'],
146
+ plugins: plugins,
138
147
  });
139
148
  /* eslint-enable flowtype-errors/uncovered */
140
149
  const gqlTagNames = [];
@@ -382,7 +391,9 @@ const getLocals = (
382
391
 
383
392
  export const processFiles = (
384
393
  filePaths: Array<string>,
385
- getFileSource: (path: string) => string,
394
+ getFileSource: (
395
+ path: string,
396
+ ) => string | {text: string, resolvedPath: string},
386
397
  ): Files => {
387
398
  const files: Files = {};
388
399
  const toProcess = filePaths.slice();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","ast","sourceType","allowImportExportEverywhere","plugins","enums","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","filter","Boolean","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;;;AAHqC;AACG;;AAoExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAAMC,KAAK,GAAG,EAAd;;AACA,QAAMC,GAAG,GAAG,CAACC,CAAD,EAAuBC,aAAvB,KAAkD;AAC1D,QAAID,CAAC,CAACE,IAAF,KAAW,QAAf,EAAyB;AACrB,UAAID,aAAJ,EAAmB;AACfH,QAAAA,KAAK,CAACE,CAAC,CAACG,IAAH,CAAL,GAAgB,IAAhB;AACH;AACJ,KAJD,MAIO;AACHH,MAAAA,CAAC,CAACI,MAAF,CAASC,WAAT,CAAqBC,OAArB,CAA8BC,IAAD,IAAUR,GAAG,CAACQ,IAAD,EAAO,IAAP,CAA1C;AACH;AACJ,GARD;;AASAC,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACa,OAAjB,EAA0BJ,OAA1B,CAAmCK,CAAD,IAC9BZ,GAAG,CACCF,IAAI,CAACa,OAAL,CAAaC,CAAb,CADD,EAEC;AACA,MAHD,CADP;AAOAH,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACe,MAAjB,EAAyBN,OAAzB,CAAkCK,CAAD,IAC7BZ,GAAG,CACCF,IAAI,CAACe,MAAL,CAAYD,CAAZ,CADD,EAEC;AACA;AACA,OAJD,CADP;AAQAd,EAAAA,IAAI,CAACgB,UAAL,CAAgBP,OAAhB,CAAyBQ,EAAD,IACpBA,EAAE,CAACV,MAAH,CAAUC,WAAV,CAAsBC,OAAtB,CAA+BC,IAAD,IAC1BR,GAAG,CACCQ,IADD,EAE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,GAAGH,SAAS,CAACI,KAAV,EAAlB;;AACA,SAAOD,SAAS,CAACE,MAAjB,EAAyB;AACrB,UAAMC,IAAI,GAAGH,SAAS,CAACI,KAAV,EAAb;;AACA,QAAIL,KAAK,CAACI,IAAD,CAAT,EAAiB;AACb;AACH;;AACD,UAAMpE,MAAM,GAAGL,WAAW,CAACyE,IAAD,EAAOL,aAAa,CAACK,IAAD,CAApB,CAA1B;AACAJ,IAAAA,KAAK,CAACI,IAAD,CAAL,GAAcpE,MAAd;AACAxB,IAAAA,sBAAsB,CAACwB,MAAD,CAAtB,CAA+Bd,OAA/B,CAAwCH,IAAD,IAAU;AAC7C,UAAI,CAACiF,KAAK,CAACjF,IAAD,CAAN,IAAgB,CAACkF,SAAS,CAAC9B,QAAV,CAAmBpD,IAAnB,CAArB,EAA+C;AAC3CkF,QAAAA,SAAS,CAAChD,IAAV,CAAelC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOiF,KAAP;AACH,CApBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n paths[v.path] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (filePath: string, contents: string): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(contents, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [['flow', {enums: true}], 'jsx'],\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (path: string) => string,\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
1
+ {"version":3,"sources":["../../src/parser/parse.js"],"names":["listExternalReferences","file","paths","add","v","followImports","type","path","source","expressions","forEach","expr","Object","keys","exports","k","locals","operations","op","processFile","filePath","contents","dir","dirname","result","errors","resolved","resolvedPath","text","plugins","match","endsWith","filter","Boolean","enums","ast","sourceType","allowImportExportEverywhere","gqlTagNames","seenTemplates","program","body","toplevel","newLocals","getLocals","local","startsWith","name","push","importPath","value","resolve","join","specifiers","spec","exported","loc","start","end","line","processDeclarator","decl","isExported","id","init","tag","includes","tpl","processTemplate","document","declarations","declaration","visitTpl","node","getBinding","TaggedTemplateExpression","binding","scope","getTemplate","literals","quasi","quasis","map","q","cooked","message","found","myPath","importKind","imported","processFiles","filePaths","getFileSource","files","toProcess","slice","length","next","shift"],"mappings":";;;;;;;AAQA;;AACA;;AAEA;;;;AAHqC;AACG;;AAoExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,sBAAsB,GAAIC,IAAD,IAAqC;AAChE,QAAMC,KAAK,GAAG,EAAd;;AACA,QAAMC,GAAG,GAAG,CAACC,CAAD,EAAuBC,aAAvB,KAAkD;AAC1D,QAAID,CAAC,CAACE,IAAF,KAAW,QAAf,EAAyB;AACrB,UAAID,aAAJ,EAAmB;AACfH,QAAAA,KAAK,CAACE,CAAC,CAACG,IAAH,CAAL,GAAgB,IAAhB;AACH;AACJ,KAJD,MAIO;AACHH,MAAAA,CAAC,CAACI,MAAF,CAASC,WAAT,CAAqBC,OAArB,CAA8BC,IAAD,IAAUR,GAAG,CAACQ,IAAD,EAAO,IAAP,CAA1C;AACH;AACJ,GARD;;AASAC,EAAAA,MAAM,CAACC,IAAP,CAAYZ,IAAI,CAACa,OAAjB,EAA0BJ,OAA1B,CAAmCK,CAAD,IAC9BZ,GAAG,CACCF,IAAI,CAACa,OAAL,CAAaC,CAAb,CADD,EAEC;AACA,MAHD,CADP;A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uF,QAAAA,SAAS,CAAC9C,IAAV,CAAezC,IAAf;AACH;AACJ,KAJD;AAKH;;AACD,SAAOsF,KAAP;AACH,CAtBM","sourcesContent":["// @flow\nimport type {\n BabelNodeImportDeclaration,\n BabelNodeVariableDeclarator,\n BabelNodeTaggedTemplateExpression,\n BabelNodeFile,\n} from '@babel/types';\n\nimport {parse} from '@babel/parser'; // eslint-disable-line flowtype-errors/uncovered\nimport traverse from '@babel/traverse'; // eslint-disable-line flowtype-errors/uncovered\n\nimport path from 'path';\n\n/**\n * This file is responsible for finding all gql`-annotated\n * template strings in a set of provided files, and for resolving\n * all fragment references to their eventual sources.\n *\n * Things that are supported:\n * - importing fragments from other files\n * - re-exporting fragments that were imported\n * - using locally-defined fragments, even if they're\n * not at the top level (scope is honored correctly)\n * - importing the gql tag as some other name\n * \t (e.g. 'import blah from \"graphql-tag\"')\n * - renaming fragments at the top level\n *\n * Things that are *not* supported:\n * - doing anything other than 'const x = gql`my template`'\n * \t e.g. const x = someCond ? one fragment literal : another fragment literal\n * or const x = someFragmentPreprocessor(fragment literal)\n * - importing the graphql tag fn from anywhere other than \"graphql-tag\"\n * - anything else fancy with the graphql tag fn, e.g. 'const blah = gql; blah`xyz`'\n * - including a fragment in an operation by anything other than a bare identifier,\n * e.g. 'const myQuery = gql`query xyz {...} ${cond ? someFrag : otherFrag}`.\n * - getting fragments from e.g. function arguments, or renaming non-toplevel fragments\n *\n * Things that could be supported, but are not yet:\n * - tracking whether a given graphql operation has already been wrapped\n * in `gqlOp<Type>()` or not (to inform an auto-wrapper of the future)\n */\n\nexport type Template = {|\n literals: Array<string>,\n expressions: Array<Document | Import>,\n loc: Loc,\n|};\nexport type Loc = {start: number, end: number, path: string, line: number};\n\nexport type Document = {|\n type: 'document',\n source: Template,\n|};\nexport type Import = {|\n type: 'import',\n name: string,\n path: string,\n loc: Loc,\n|};\n\nexport type Operation = {|\n source: Template,\n // TODO: Determine if an operation is already wrapped\n // in `gqlOp` so we can automatically wrap if needed.\n // needsWrapping: boolean,\n|};\n\nexport type FileResult = {|\n path: string,\n operations: Array<Operation>,\n exports: {[key: string]: Document | Import},\n locals: {[key: string]: Document | Import},\n errors: Array<{loc: Loc, message: string}>,\n|};\n\nexport type Files = {[path: string]: FileResult};\n\n/**\n * Finds all referenced imports that might possibly be relevant\n * graphql fragments.\n *\n * Importantly, any values that are re-exported are treated as\n * potentially relevant, and of course any values referenced\n * from a graphql template are treated as relevant.\n */\nconst listExternalReferences = (file: FileResult): Array<string> => {\n const paths = {};\n const add = (v: Document | Import, followImports: boolean) => {\n if (v.type === 'import') {\n if (followImports) {\n paths[v.path] = true;\n }\n } else {\n v.source.expressions.forEach((expr) => add(expr, true));\n }\n };\n Object.keys(file.exports).forEach((k) =>\n add(\n file.exports[k],\n // If we're re-exporting something, we need to follow that import.\n true,\n ),\n );\n Object.keys(file.locals).forEach((k) =>\n add(\n file.locals[k],\n // If we've imported something but haven't used it or exported it,\n // we don't need to follow the import.\n false,\n ),\n );\n file.operations.forEach((op) =>\n op.source.expressions.forEach((expr) =>\n add(\n expr,\n // Imports that are used in graphql expressions definitely need to be followed.\n true,\n ),\n ),\n );\n return Object.keys(paths);\n};\n\nexport const processFile = (\n filePath: string,\n contents: string | {text: string, resolvedPath: string},\n): FileResult => {\n const dir = path.dirname(filePath);\n const result: FileResult = {\n path: filePath,\n operations: [],\n exports: {},\n locals: {},\n errors: [],\n };\n const resolved =\n typeof contents === 'string' ? filePath : contents.resolvedPath;\n const text = typeof contents === 'string' ? contents : contents.text;\n const plugins = resolved.match(/\\.tsx?$/)\n ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)\n : [['flow', {enums: true}], 'jsx'];\n /* eslint-disable flowtype-errors/uncovered */\n const ast: BabelNodeFile = parse(text, {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: plugins,\n });\n /* eslint-enable flowtype-errors/uncovered */\n const gqlTagNames = [];\n const seenTemplates: {[key: number]: Document | false} = {};\n\n ast.program.body.forEach((toplevel) => {\n if (toplevel.type === 'ImportDeclaration') {\n const newLocals = getLocals(dir, toplevel, filePath);\n if (newLocals) {\n Object.keys(newLocals).forEach((k) => {\n const local = newLocals[k];\n if (local.path.startsWith('/')) {\n result.locals[k] = local;\n }\n if (\n local.path === 'graphql-tag' &&\n local.name === 'default'\n ) {\n gqlTagNames.push(k);\n }\n });\n }\n }\n if (toplevel.type === 'ExportNamedDeclaration') {\n if (toplevel.source) {\n const source = toplevel.source;\n const importPath = source.value.startsWith('.')\n ? path.resolve(path.join(dir, source.value))\n : source.value;\n toplevel.specifiers?.forEach((spec) => {\n if (\n spec.type === 'ExportSpecifier' &&\n spec.exported.type === 'Identifier'\n ) {\n result.exports[spec.exported.name] = {\n type: 'import',\n name: spec.local.name,\n path: importPath,\n loc: {\n start: spec.start ?? -1,\n end: spec.end ?? -1,\n line: spec.loc?.start.line ?? -1,\n path: filePath,\n },\n };\n }\n });\n } else {\n toplevel.specifiers?.forEach((spec) => {\n if (spec.type === 'ExportSpecifier') {\n const local = result.locals[spec.local.name];\n if (local && spec.exported.type === 'Identifier') {\n result.exports[spec.exported.name] = local;\n }\n }\n });\n }\n }\n\n const processDeclarator = (\n decl: BabelNodeVariableDeclarator,\n isExported: boolean,\n ) => {\n if (decl.id.type !== 'Identifier' || !decl.init) {\n return;\n }\n const {init} = decl;\n const id = decl.id.name;\n if (\n init.type === 'TaggedTemplateExpression' &&\n init.tag.type === 'Identifier'\n ) {\n if (gqlTagNames.includes(init.tag.name)) {\n const tpl = processTemplate(init, result);\n if (tpl) {\n const document = (result.locals[id] = {\n type: 'document',\n source: tpl,\n });\n seenTemplates[init.start ?? -1] = document;\n if (isExported) {\n result.exports[id] = document;\n }\n } else {\n seenTemplates[init.start ?? -1] = false;\n }\n }\n }\n if (init.type === 'Identifier' && result.locals[init.name]) {\n result.locals[id] = result.locals[init.name];\n if (isExported) {\n result.exports[id] = result.locals[init.name];\n }\n }\n };\n\n if (toplevel.type === 'VariableDeclaration') {\n toplevel.declarations.forEach((decl) => {\n processDeclarator(decl, false);\n });\n }\n\n if (\n toplevel.type === 'ExportNamedDeclaration' &&\n toplevel.declaration?.type === 'VariableDeclaration'\n ) {\n toplevel.declaration.declarations.forEach((decl) => {\n processDeclarator(decl, true);\n });\n }\n });\n\n const visitTpl = (\n node: BabelNodeTaggedTemplateExpression,\n getBinding: (name: string) => Document | null,\n ) => {\n if (seenTemplates[node.start ?? -1] != null) {\n return;\n }\n if (\n node.tag.type !== 'Identifier' ||\n !gqlTagNames.includes(node.tag.name)\n ) {\n return;\n }\n const tpl = processTemplate(node, result, getBinding);\n if (tpl) {\n seenTemplates[node.start ?? -1] = {type: 'document', source: tpl};\n result.operations.push({\n source: tpl,\n });\n } else {\n seenTemplates[node.start ?? -1] = false;\n }\n };\n\n /* eslint-disable flowtype-errors/uncovered */\n traverse(ast, {\n TaggedTemplateExpression(path) {\n visitTpl(path.node, (name) => {\n const binding = path.scope.getBinding(name);\n const start = binding.path.node.init\n ? binding.path.node.init.start\n : null;\n if (start && seenTemplates[start]) {\n return seenTemplates[start];\n }\n return null;\n });\n },\n });\n /* eslint-enable flowtype-errors/uncovered */\n\n return result;\n};\n\nconst processTemplate = (\n tpl: BabelNodeTaggedTemplateExpression,\n result: FileResult,\n getTemplate?: (name: string) => Document | null,\n // getBinding?: (name: string) => Binding,\n // seenTemplates,\n): ?Template => {\n // 'cooked' is the string as runtime javascript will see it.\n const literals = tpl.quasi.quasis.map((q) => q.value.cooked || '');\n const expressions = tpl.quasi.expressions.map(\n (expr): null | Document | Import => {\n const loc: Loc = {\n start: expr.start ?? -1,\n end: expr.end ?? -1,\n line: expr.loc?.start.line ?? -1,\n path: result.path,\n };\n if (expr.type !== 'Identifier') {\n result.errors.push({\n loc,\n message: `Template literal interpolation must be an identifier`,\n });\n return null;\n }\n if (!result.locals[expr.name]) {\n if (getTemplate) {\n const found = getTemplate(expr.name);\n return found;\n }\n result.errors.push({\n loc,\n message: `Unable to resolve ${expr.name}`,\n });\n return null;\n }\n return result.locals[expr.name];\n },\n );\n if (expressions.includes(null)) {\n // bail, stop processing.\n return;\n }\n return {\n literals,\n expressions: expressions.filter(Boolean),\n loc: {\n line: tpl.loc?.start.line ?? -1,\n start: tpl.start ?? -1,\n end: tpl.end ?? -1,\n path: result.path,\n },\n };\n};\n\nconst getLocals = (\n dir,\n toplevel: BabelNodeImportDeclaration,\n myPath: string,\n): ?{[key: string]: Import} => {\n if (toplevel.importKind === 'type') {\n return null;\n }\n const importPath = toplevel.source.value.startsWith('.')\n ? path.resolve(path.join(dir, toplevel.source.value))\n : toplevel.source.value;\n const locals = {};\n toplevel.specifiers.forEach((spec) => {\n if (spec.type === 'ImportDefaultSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name: 'default',\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n } else if (spec.type === 'ImportSpecifier') {\n locals[spec.local.name] = {\n type: 'import',\n name:\n spec.imported.type === 'Identifier'\n ? spec.imported.name\n : spec.imported.value,\n path: importPath,\n loc: {start: spec.start, end: spec.end, path: myPath},\n };\n }\n });\n return locals;\n};\n\nexport const processFiles = (\n filePaths: Array<string>,\n getFileSource: (\n path: string,\n ) => string | {text: string, resolvedPath: string},\n): Files => {\n const files: Files = {};\n const toProcess = filePaths.slice();\n while (toProcess.length) {\n const next = toProcess.shift();\n if (files[next]) {\n continue;\n }\n const result = processFile(next, getFileSource(next));\n files[next] = result;\n listExternalReferences(result).forEach((path) => {\n if (!files[path] && !toProcess.includes(path)) {\n toProcess.push(path);\n }\n });\n }\n return files;\n};\n"],"file":"parse.js"}
@@ -19,6 +19,7 @@ export type GenerateConfig = {|
19
19
  match?: Array<RegExp | string>,
20
20
  exclude?: Array<RegExp | string>,
21
21
 
22
+ typeScript?: boolean,
22
23
  scalars?: Scalars,
23
24
  strictNullability?: boolean,
24
25
  /**
@@ -79,6 +80,7 @@ export type Context = {
79
80
  scalars: Scalars,
80
81
  errors: Array<string>,
81
82
  allObjectTypes: null | {[key: string]: BabelNode},
83
+ typeScript: boolean,
82
84
 
83
85
  experimentalEnumsMap?: {[key: string]: BabelNode}, // index signature that is populated with declarations
84
86
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanacademy/graphql-flow",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "bin": {
5
5
  "graphql-flow": "./dist/cli/run.js"
6
6
  },
@@ -37,6 +37,7 @@
37
37
  "@babel/generator": "^7.17.3",
38
38
  "@babel/traverse": "^7.17.3",
39
39
  "@babel/types": "^7.17.0",
40
+ "@khanacademy/flow-to-ts": "^0.5.2",
40
41
  "apollo-utilities": "^1.3.4",
41
42
  "graphql": "14.5.8",
42
43
  "jsonschema": "^1.4.1",
package/src/cli/config.js CHANGED
@@ -28,10 +28,9 @@ export const validateOrThrow = (value: mixed, jsonSchema: mixed) => {
28
28
  };
29
29
 
30
30
  export const loadConfigFile = (configFile: string): Config => {
31
- // $FlowIgnore // eslint-disable-next-line flowtype-errors/uncovered
32
- const data: Config = require(configFile);
33
- // eslint-disable-next-line flowtype-errors/uncovered
34
- validateOrThrow(data, configSchema);
31
+ // $FlowIgnore
32
+ const data: Config = require(configFile); // eslint-disable-line flowtype-errors/uncovered
33
+ validateOrThrow(data, configSchema); // eslint-disable-line flowtype-errors/uncovered
35
34
  return data;
36
35
  };
37
36
 
package/src/cli/run.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // @flow
3
3
  /* eslint-disable no-console */
4
+ import type {Schema} from '../types';
5
+ import type {GraphQLSchema} from 'graphql/type/schema';
6
+
4
7
  import {generateTypeFiles, processPragmas} from '../generateTypeFiles';
5
8
  import {processFiles} from '../parser/parse';
6
9
  import {resolveDocuments} from '../parser/resolve';
@@ -15,7 +18,6 @@ import {print} from 'graphql/language/printer';
15
18
  import {validate} from 'graphql/validation';
16
19
  import path from 'path';
17
20
  import {dirname} from 'path';
18
- import type {GenerateConfig} from '../types';
19
21
 
20
22
  /**
21
23
  * This CLI tool executes the following steps:
@@ -32,7 +34,7 @@ import type {GenerateConfig} from '../types';
32
34
 
33
35
  const findGraphqlTagReferences = (root: string): Array<string> => {
34
36
  const response = execSync(
35
- "git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx'",
37
+ "git grep -I --word-regexp --name-only --fixed-strings 'graphql-tag' -- '*.js' '*.jsx' '*.ts' '*.tsx'",
36
38
  {
37
39
  encoding: 'utf8',
38
40
  cwd: root,
@@ -81,7 +83,16 @@ const files = processFiles(inputFiles, (f) => {
81
83
  return readFileSync(f, 'utf8');
82
84
  }
83
85
  if (existsSync(f + '.js')) {
84
- return readFileSync(f + '.js', 'utf8');
86
+ return {text: readFileSync(f + '.js', 'utf8'), resolvedPath: f + '.js'};
87
+ }
88
+ if (existsSync(f + '.ts')) {
89
+ return {text: readFileSync(f + '.ts', 'utf8'), resolvedPath: f + '.ts'};
90
+ }
91
+ if (existsSync(f + '.tsx')) {
92
+ return {
93
+ text: readFileSync(f + '.tsx', 'utf8'),
94
+ resolvedPath: f + '.tsx',
95
+ };
85
96
  }
86
97
  throw new Error(`Unable to find ${f}`);
87
98
  });
@@ -118,7 +129,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
118
129
 
119
130
  /** Step (4) */
120
131
 
121
- const schemaCache = {};
132
+ const schemaCache: {[key: string]: [GraphQLSchema, Schema]} = {};
122
133
  const getCachedSchemas = (schemaFilePath: string) => {
123
134
  if (!schemaCache[schemaFilePath]) {
124
135
  schemaCache[schemaFilePath] = getSchemas(
@@ -31,6 +31,9 @@
31
31
  "scalars": {
32
32
  "type": "object"
33
33
  },
34
+ "typeScript": {
35
+ "type": "boolean"
36
+ },
34
37
  "strictNullability": {
35
38
  "type": "boolean"
36
39
  },
@@ -4,6 +4,8 @@ import type {GenerateConfig, CrawlConfig, Schema} from './types';
4
4
  import fs from 'fs';
5
5
  import path from 'path';
6
6
  import {documentToFlowTypes} from '.';
7
+ // eslint-disable-next-line flowtype-errors/uncovered
8
+ import {convert} from '@khanacademy/flow-to-ts/dist/convert.bundle';
7
9
 
8
10
  export const indexPrelude = (regenerateCommand?: string): string => `// @flow
9
11
  //
@@ -27,6 +29,10 @@ export const generateTypeFileContents = (
27
29
 
28
30
  /// Write export for __generated__/index.js if it doesn't exist
29
31
  const addToIndex = (filePath, typeName) => {
32
+ if (options.typeScript) {
33
+ // Typescript doesn't like file extensions
34
+ filePath = filePath.replace(/\.js$/, '');
35
+ }
30
36
  const newLine = `export type {${typeName}} from './${path.basename(
31
37
  filePath,
32
38
  )}';`;
@@ -120,7 +126,10 @@ export const generateTypeFiles = (
120
126
  options: GenerateConfig,
121
127
  ) => {
122
128
  const generatedDir = getGeneratedDir(fileName, options);
123
- const indexFile = path.join(generatedDir, 'index.js');
129
+ const indexFile = path.join(
130
+ generatedDir,
131
+ 'index' + (options.typeScript ? '.ts' : '.js'),
132
+ );
124
133
 
125
134
  if (!fs.existsSync(generatedDir)) {
126
135
  fs.mkdirSync(generatedDir, {recursive: true});
@@ -140,7 +149,13 @@ export const generateTypeFiles = (
140
149
 
141
150
  fs.writeFileSync(indexFile, indexContents);
142
151
  Object.keys(files).forEach((key) => {
143
- fs.writeFileSync(key, files[key]);
152
+ let fname = key;
153
+ if (options.typeScript) {
154
+ // eslint-disable-next-line flowtype-errors/uncovered
155
+ files[key] = convert(files[key]);
156
+ fname = key.replace(/\.js$/, '.ts');
157
+ }
158
+ fs.writeFileSync(fname, files[key]);
144
159
  });
145
160
 
146
161
  fs.writeFileSync(indexFile, indexContents);
package/src/index.js CHANGED
@@ -29,6 +29,7 @@ const optionsToConfig = (
29
29
  strictNullability: options?.strictNullability ?? true,
30
30
  readOnlyArray: options?.readOnlyArray ?? true,
31
31
  scalars: options?.scalars ?? {},
32
+ typeScript: options?.typeScript ?? false,
32
33
  };
33
34
  const fragments = {};
34
35
  definitions.forEach((def) => {
@@ -5,7 +5,9 @@ import {resolveDocuments} from '../resolve';
5
5
 
6
6
  import {print} from 'graphql/language/printer';
7
7
 
8
- const fixtureFiles: {[key: string]: string} = {
8
+ const fixtureFiles: {
9
+ [key: string]: string | {text: string, resolvedPath: string},
10
+ } = {
9
11
  '/firstFile.js': `
10
12
  // Note that you can import graphql-tag as
11
13
  // something other than gql.
@@ -121,7 +121,10 @@ const listExternalReferences = (file: FileResult): Array<string> => {
121
121
  return Object.keys(paths);
122
122
  };
123
123
 
124
- export const processFile = (filePath: string, contents: string): FileResult => {
124
+ export const processFile = (
125
+ filePath: string,
126
+ contents: string | {text: string, resolvedPath: string},
127
+ ): FileResult => {
125
128
  const dir = path.dirname(filePath);
126
129
  const result: FileResult = {
127
130
  path: filePath,
@@ -130,11 +133,17 @@ export const processFile = (filePath: string, contents: string): FileResult => {
130
133
  locals: {},
131
134
  errors: [],
132
135
  };
136
+ const resolved =
137
+ typeof contents === 'string' ? filePath : contents.resolvedPath;
138
+ const text = typeof contents === 'string' ? contents : contents.text;
139
+ const plugins = resolved.match(/\.tsx?$/)
140
+ ? ['typescript', filePath.endsWith('x') ? 'jsx' : null].filter(Boolean)
141
+ : [['flow', {enums: true}], 'jsx'];
133
142
  /* eslint-disable flowtype-errors/uncovered */
134
- const ast: BabelNodeFile = parse(contents, {
143
+ const ast: BabelNodeFile = parse(text, {
135
144
  sourceType: 'module',
136
145
  allowImportExportEverywhere: true,
137
- plugins: [['flow', {enums: true}], 'jsx'],
146
+ plugins: plugins,
138
147
  });
139
148
  /* eslint-enable flowtype-errors/uncovered */
140
149
  const gqlTagNames = [];
@@ -382,7 +391,9 @@ const getLocals = (
382
391
 
383
392
  export const processFiles = (
384
393
  filePaths: Array<string>,
385
- getFileSource: (path: string) => string,
394
+ getFileSource: (
395
+ path: string,
396
+ ) => string | {text: string, resolvedPath: string},
386
397
  ): Files => {
387
398
  const files: Files = {};
388
399
  const toProcess = filePaths.slice();
package/src/types.js CHANGED
@@ -19,6 +19,7 @@ export type GenerateConfig = {|
19
19
  match?: Array<RegExp | string>,
20
20
  exclude?: Array<RegExp | string>,
21
21
 
22
+ typeScript?: boolean,
22
23
  scalars?: Scalars,
23
24
  strictNullability?: boolean,
24
25
  /**
@@ -79,6 +80,7 @@ export type Context = {
79
80
  scalars: Scalars,
80
81
  errors: Array<string>,
81
82
  allObjectTypes: null | {[key: string]: BabelNode},
83
+ typeScript: boolean,
82
84
 
83
85
  experimentalEnumsMap?: {[key: string]: BabelNode}, // index signature that is populated with declarations
84
86
  };