@khanacademy/graphql-flow 0.2.1 → 0.2.4
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/.babelrc +1 -1
- package/CHANGELOG.md +18 -0
- package/Readme.md +4 -0
- package/dist/cli/config.js +7 -6
- package/dist/cli/config.js.flow +10 -1
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/run.js +35 -9
- package/dist/cli/run.js.flow +30 -6
- package/dist/cli/run.js.map +1 -1
- package/dist/generateResponseType.js +2 -2
- package/dist/generateResponseType.js.map +1 -1
- package/dist/generateTypeFiles.js +6 -3
- package/dist/generateTypeFiles.js.flow +5 -1
- package/dist/generateTypeFiles.js.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/parser/parse.js +27 -17
- package/dist/parser/parse.js.map +1 -1
- package/dist/types.js.flow +1 -0
- package/package.json +1 -1
- package/src/__test__/generateTypeFileContents.test.js +42 -0
- package/src/cli/config.js +10 -1
- package/src/cli/run.js +30 -6
- package/src/generateTypeFiles.js +5 -1
- package/src/types.js +1 -0
package/.babelrc
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @khanacademy/graphql-flow
|
|
2
2
|
|
|
3
|
+
## 0.2.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 843839c: Add 'dumpOperations' config option, to enable safelisting
|
|
8
|
+
|
|
9
|
+
## 0.2.3
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- f5ea353: Add 'typeFileName' config option to fit the mobile repo's expectations
|
|
14
|
+
|
|
15
|
+
## 0.2.2
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 31dd235: Compile for node 12 instead of 16
|
|
20
|
+
|
|
3
21
|
## 0.2.1
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/Readme.md
CHANGED
|
@@ -70,6 +70,10 @@ type Options = {
|
|
|
70
70
|
// Names are generated by concatenating the attribute names
|
|
71
71
|
// of the path to the object type, separated by underscores.
|
|
72
72
|
exportAllObjectTypes?: boolean,
|
|
73
|
+
|
|
74
|
+
// A template for the name of generated files
|
|
75
|
+
// default: [operationName].js
|
|
76
|
+
typeFileName?: string,
|
|
73
77
|
}
|
|
74
78
|
```
|
|
75
79
|
|
package/dist/cli/config.js
CHANGED
|
@@ -16,11 +16,11 @@ var _path = _interopRequireDefault(require("path"));
|
|
|
16
16
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
17
17
|
|
|
18
18
|
const loadConfigFile = configFile => {
|
|
19
|
-
var _data$excludes;
|
|
19
|
+
var _data$options, _data$excludes$map, _data$excludes;
|
|
20
20
|
|
|
21
21
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
22
22
|
const data = JSON.parse(_fs.default.readFileSync(configFile, 'utf8'));
|
|
23
|
-
const toplevelKeys = ['excludes', 'schemaFilePath', 'options'];
|
|
23
|
+
const toplevelKeys = ['excludes', 'schemaFilePath', 'options', 'dumpOperations'];
|
|
24
24
|
Object.keys(data).forEach(k => {
|
|
25
25
|
if (!toplevelKeys.includes(k)) {
|
|
26
26
|
throw new Error(`Invalid attribute in config file ${configFile}: ${k}. Allowed attributes: ${toplevelKeys.join(', ')}`);
|
|
@@ -28,7 +28,7 @@ const loadConfigFile = configFile => {
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
if (data.options) {
|
|
31
|
-
const externalOptionsKeys = ['pragma', 'loosePragma', 'ignorePragma', 'scalars', 'strictNullability', 'regenerateCommand', 'readOnlyArray', 'splitTypes', 'generatedDirectory', 'exportAllObjectTypes'];
|
|
31
|
+
const externalOptionsKeys = ['pragma', 'loosePragma', 'ignorePragma', 'scalars', 'strictNullability', 'regenerateCommand', 'readOnlyArray', 'splitTypes', 'generatedDirectory', 'exportAllObjectTypes', 'typeFileName'];
|
|
32
32
|
Object.keys(data.options).forEach(k => {
|
|
33
33
|
if (!externalOptionsKeys.includes(k)) {
|
|
34
34
|
throw new Error(`Invalid option in config file ${configFile}: ${k}. Allowed options: ${externalOptionsKeys.join(', ')}`);
|
|
@@ -37,9 +37,10 @@ const loadConfigFile = configFile => {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
return {
|
|
40
|
-
options: data.options
|
|
41
|
-
excludes: ((_data$excludes = data.excludes) === null || _data$excludes === void 0 ? void 0 : _data$excludes.map(string => new RegExp(string)))
|
|
42
|
-
schemaFilePath: _path.default.join(_path.default.dirname(configFile), data.schemaFilePath)
|
|
40
|
+
options: (_data$options = data.options) !== null && _data$options !== void 0 ? _data$options : {},
|
|
41
|
+
excludes: (_data$excludes$map = (_data$excludes = data.excludes) === null || _data$excludes === void 0 ? void 0 : _data$excludes.map(string => new RegExp(string))) !== null && _data$excludes$map !== void 0 ? _data$excludes$map : [],
|
|
42
|
+
schemaFilePath: _path.default.join(_path.default.dirname(configFile), data.schemaFilePath),
|
|
43
|
+
dumpOperations: data.dumpOperations
|
|
43
44
|
};
|
|
44
45
|
};
|
|
45
46
|
/**
|
package/dist/cli/config.js.flow
CHANGED
|
@@ -18,6 +18,7 @@ import path from 'path';
|
|
|
18
18
|
export type CliConfig = {
|
|
19
19
|
excludes: Array<RegExp>,
|
|
20
20
|
schemaFilePath: string,
|
|
21
|
+
dumpOperations?: string,
|
|
21
22
|
options: ExternalOptions,
|
|
22
23
|
};
|
|
23
24
|
|
|
@@ -29,12 +30,18 @@ type JSONConfig = {
|
|
|
29
30
|
excludes?: Array<string>,
|
|
30
31
|
schemaFilePath: string,
|
|
31
32
|
options?: ExternalOptions,
|
|
33
|
+
dumpOperations?: string,
|
|
32
34
|
};
|
|
33
35
|
|
|
34
36
|
export const loadConfigFile = (configFile: string): CliConfig => {
|
|
35
37
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
36
38
|
const data: JSONConfig = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
|
37
|
-
const toplevelKeys = [
|
|
39
|
+
const toplevelKeys = [
|
|
40
|
+
'excludes',
|
|
41
|
+
'schemaFilePath',
|
|
42
|
+
'options',
|
|
43
|
+
'dumpOperations',
|
|
44
|
+
];
|
|
38
45
|
Object.keys(data).forEach((k) => {
|
|
39
46
|
if (!toplevelKeys.includes(k)) {
|
|
40
47
|
throw new Error(
|
|
@@ -56,6 +63,7 @@ export const loadConfigFile = (configFile: string): CliConfig => {
|
|
|
56
63
|
'splitTypes',
|
|
57
64
|
'generatedDirectory',
|
|
58
65
|
'exportAllObjectTypes',
|
|
66
|
+
'typeFileName',
|
|
59
67
|
];
|
|
60
68
|
Object.keys(data.options).forEach((k) => {
|
|
61
69
|
if (!externalOptionsKeys.includes(k)) {
|
|
@@ -74,6 +82,7 @@ export const loadConfigFile = (configFile: string): CliConfig => {
|
|
|
74
82
|
path.dirname(configFile),
|
|
75
83
|
data.schemaFilePath,
|
|
76
84
|
),
|
|
85
|
+
dumpOperations: data.dumpOperations,
|
|
77
86
|
};
|
|
78
87
|
};
|
|
79
88
|
|
package/dist/cli/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/config.js"],"names":["loadConfigFile","configFile","data","JSON","parse","fs","readFileSync","toplevelKeys","Object","keys","forEach","k","includes","Error","join","options","externalOptionsKeys","excludes","map","string","RegExp","schemaFilePath","path","dirname","getSchemas","raw","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData"],"mappings":";;;;;;;AAKA;;AAEA;;AACA;;AAOA;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/cli/config.js"],"names":["loadConfigFile","configFile","data","JSON","parse","fs","readFileSync","toplevelKeys","Object","keys","forEach","k","includes","Error","join","options","externalOptionsKeys","excludes","map","string","RegExp","schemaFilePath","path","dirname","dumpOperations","getSchemas","raw","endsWith","schemaForValidation","queryResponse","descriptions","schemaForTypeGeneration","introspectionData"],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ACe,QAAP,mDAAE,eAAeC,GAAf,CAAoBC,MAAD,IAAY,IAAIC,MAAJ,CAAWD,MAAX,CAA/B,CAAF,mEAAwD,EAF7D;AAGHE,IAAAA,cAAc,EAAEC,cAAKR,IAAL,CACZQ,cAAKC,OAAL,CAAatB,UAAb,CADY,EAEZC,IAAI,CAACmB,cAFO,CAHb;AAOHG,IAAAA,cAAc,EAAEtB,IAAI,CAACsB;AAPlB,GAAP;AASH,CAnDM;AAqDP;AACA;AACA;;;;;AACO,MAAMC,UAAU,GAAIJ,cAAD,IAAqD;AAC3E,QAAMK,GAAG,GAAGrB,YAAGC,YAAH,CAAgBe,cAAhB,EAAgC,MAAhC,CAAZ;;AACA,MAAIA,cAAc,CAACM,QAAf,CAAwB,UAAxB,CAAJ,EAAyC;AACrC,UAAMC,mBAAmB,GAAG,0BAAYF,GAAZ,CAA5B;AACA,UAAMG,aAAa,GAAG,0BAClBD,mBADkB,EAElB,oCAAsB;AAACE,MAAAA,YAAY,EAAE;AAAf,KAAtB,CAFkB,CAAtB;AAIA,UAAMC,uBAAuB,GAAG,+DAC5B;AACEF,IAAAA,aAAa,CAAC3B,IAFY,CAAhC;AAIA,WAAO,CAAC0B,mBAAD,EAAsBG,uBAAtB,CAAP;AACH,GAXD,MAWO;AACH;AACA,UAAMC,iBAAqC,GAAG7B,IAAI,CAACC,KAAL,CAAWsB,GAAX,CAA9C;AACA,UAAME,mBAAmB,GAAG,gCAAkBI,iBAAlB,CAA5B;AACA,UAAMD,uBAAuB,GACzB,8DAA4BC,iBAA5B,CADJ;AAEA,WAAO,CAACJ,mBAAD,EAAsBG,uBAAtB,CAAP;AACH;AACJ,CArBM","sourcesContent":["// @flow\nimport type {ExternalOptions} from '../generateTypeFiles';\nimport type {Schema} from '../types';\nimport type {GraphQLSchema} from 'graphql/type/schema';\n\nimport {schemaFromIntrospectionData} from '../schemaFromIntrospectionData';\n\nimport fs from 'fs';\nimport {\n buildClientSchema,\n buildSchema,\n getIntrospectionQuery,\n graphqlSync,\n type IntrospectionQuery,\n} from 'graphql';\nimport path from 'path';\n\nexport type CliConfig = {\n excludes: Array<RegExp>,\n schemaFilePath: string,\n dumpOperations?: string,\n options: ExternalOptions,\n};\n\n/**\n * This is the json-compatible form of the config\n * object.\n */\ntype JSONConfig = {\n excludes?: Array<string>,\n schemaFilePath: string,\n options?: ExternalOptions,\n dumpOperations?: string,\n};\n\nexport const loadConfigFile = (configFile: string): CliConfig => {\n // eslint-disable-next-line flowtype-errors/uncovered\n const data: JSONConfig = JSON.parse(fs.readFileSync(configFile, 'utf8'));\n const toplevelKeys = [\n 'excludes',\n 'schemaFilePath',\n 'options',\n 'dumpOperations',\n ];\n Object.keys(data).forEach((k) => {\n if (!toplevelKeys.includes(k)) {\n throw new Error(\n `Invalid attribute in config file ${configFile}: ${k}. Allowed attributes: ${toplevelKeys.join(\n ', ',\n )}`,\n );\n }\n });\n if (data.options) {\n const externalOptionsKeys = [\n 'pragma',\n 'loosePragma',\n 'ignorePragma',\n 'scalars',\n 'strictNullability',\n 'regenerateCommand',\n 'readOnlyArray',\n 'splitTypes',\n 'generatedDirectory',\n 'exportAllObjectTypes',\n 'typeFileName',\n ];\n Object.keys(data.options).forEach((k) => {\n if (!externalOptionsKeys.includes(k)) {\n throw new Error(\n `Invalid option in config file ${configFile}: ${k}. Allowed options: ${externalOptionsKeys.join(\n ', ',\n )}`,\n );\n }\n });\n }\n return {\n options: data.options ?? {},\n excludes: data.excludes?.map((string) => new RegExp(string)) ?? [],\n schemaFilePath: path.join(\n path.dirname(configFile),\n data.schemaFilePath,\n ),\n dumpOperations: data.dumpOperations,\n };\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"],"file":"config.js"}
|
package/dist/cli/run.js
CHANGED
|
@@ -21,9 +21,11 @@ var _printer = require("graphql/language/printer");
|
|
|
21
21
|
|
|
22
22
|
var _validation = require("graphql/validation");
|
|
23
23
|
|
|
24
|
-
var _path =
|
|
24
|
+
var _path = _interopRequireWildcard(require("path"));
|
|
25
25
|
|
|
26
|
-
function
|
|
26
|
+
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
|
27
|
+
|
|
28
|
+
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
|
27
29
|
|
|
28
30
|
// eslint-disable-line flowtype-errors/uncovered
|
|
29
31
|
|
|
@@ -61,7 +63,17 @@ const [schemaForValidation, schemaForTypeGeneration] = (0, _config.getSchemas)(c
|
|
|
61
63
|
const inputFiles = cliFiles.length ? cliFiles : findGraphqlTagReferences(process.cwd());
|
|
62
64
|
/** Step (2) */
|
|
63
65
|
|
|
64
|
-
const files = (0, _parse.processFiles)(inputFiles, f =>
|
|
66
|
+
const files = (0, _parse.processFiles)(inputFiles, f => {
|
|
67
|
+
if ((0, _fs.existsSync)(f)) {
|
|
68
|
+
return (0, _fs.readFileSync)(f, 'utf8');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if ((0, _fs.existsSync)(f + '.js')) {
|
|
72
|
+
return (0, _fs.readFileSync)(f + '.js', 'utf8');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
throw new Error(`Unable to find ${f}`);
|
|
76
|
+
});
|
|
65
77
|
let filesHadErrors = false;
|
|
66
78
|
Object.keys(files).forEach(key => {
|
|
67
79
|
const file = files[key];
|
|
@@ -99,6 +111,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
|
|
|
99
111
|
/** Step (4) */
|
|
100
112
|
|
|
101
113
|
let validationFailures = 0;
|
|
114
|
+
const printedOperations = [];
|
|
102
115
|
Object.keys(resolved).forEach(k => {
|
|
103
116
|
const {
|
|
104
117
|
document,
|
|
@@ -112,16 +125,20 @@ Object.keys(resolved).forEach(k => {
|
|
|
112
125
|
const hasNonFragments = document.definitions.some(({
|
|
113
126
|
kind
|
|
114
127
|
}) => kind !== 'FragmentDefinition');
|
|
115
|
-
const rawSource = raw.literals[0];
|
|
128
|
+
const rawSource = raw.literals[0]; // eslint-disable-next-line flowtype-errors/uncovered
|
|
129
|
+
|
|
130
|
+
const withTypeNames = (0, _apolloUtilities.addTypenameToDocument)(document);
|
|
131
|
+
const printed = (0, _printer.print)(withTypeNames);
|
|
132
|
+
|
|
133
|
+
if (hasNonFragments && !printedOperations.includes(printed)) {
|
|
134
|
+
printedOperations.push(printed);
|
|
135
|
+
}
|
|
136
|
+
|
|
116
137
|
const processedOptions = (0, _generateTypeFiles.processPragmas)(config.options, rawSource);
|
|
117
138
|
|
|
118
139
|
if (!processedOptions) {
|
|
119
140
|
return;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const withTypeNames = (0, _apolloUtilities.addTypenameToDocument)(document);
|
|
124
|
-
const printed = (0, _printer.print)(withTypeNames);
|
|
141
|
+
}
|
|
125
142
|
|
|
126
143
|
if (hasNonFragments) {
|
|
127
144
|
/* eslint-disable flowtype-errors/uncovered */
|
|
@@ -156,4 +173,13 @@ if (validationFailures) {
|
|
|
156
173
|
|
|
157
174
|
process.exit(1);
|
|
158
175
|
}
|
|
176
|
+
|
|
177
|
+
if (config.dumpOperations) {
|
|
178
|
+
const dumpOperations = config.dumpOperations;
|
|
179
|
+
const parent = (0, _path.dirname)(dumpOperations);
|
|
180
|
+
(0, _fs.mkdirSync)(parent, {
|
|
181
|
+
recursive: true
|
|
182
|
+
});
|
|
183
|
+
(0, _fs.writeFileSync)(dumpOperations, JSON.stringify(printedOperations.sort(), null, 2));
|
|
184
|
+
}
|
|
159
185
|
//# sourceMappingURL=run.js.map
|
package/dist/cli/run.js.flow
CHANGED
|
@@ -9,11 +9,12 @@ import {getSchemas, loadConfigFile} from './config';
|
|
|
9
9
|
import {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered
|
|
10
10
|
|
|
11
11
|
import {execSync} from 'child_process';
|
|
12
|
-
import {readFileSync} from 'fs';
|
|
12
|
+
import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';
|
|
13
13
|
import {type DocumentNode} from 'graphql';
|
|
14
14
|
import {print} from 'graphql/language/printer';
|
|
15
15
|
import {validate} from 'graphql/validation';
|
|
16
16
|
import path from 'path';
|
|
17
|
+
import {dirname} from 'path';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* This CLI tool executes the following steps:
|
|
@@ -68,7 +69,15 @@ const inputFiles = cliFiles.length
|
|
|
68
69
|
|
|
69
70
|
/** Step (2) */
|
|
70
71
|
|
|
71
|
-
const files = processFiles(inputFiles, (f) =>
|
|
72
|
+
const files = processFiles(inputFiles, (f) => {
|
|
73
|
+
if (existsSync(f)) {
|
|
74
|
+
return readFileSync(f, 'utf8');
|
|
75
|
+
}
|
|
76
|
+
if (existsSync(f + '.js')) {
|
|
77
|
+
return readFileSync(f + '.js', 'utf8');
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`Unable to find ${f}`);
|
|
80
|
+
});
|
|
72
81
|
|
|
73
82
|
let filesHadErrors = false;
|
|
74
83
|
Object.keys(files).forEach((key) => {
|
|
@@ -103,6 +112,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
|
|
|
103
112
|
/** Step (4) */
|
|
104
113
|
|
|
105
114
|
let validationFailures: number = 0;
|
|
115
|
+
const printedOperations: Array<string> = [];
|
|
106
116
|
|
|
107
117
|
Object.keys(resolved).forEach((k) => {
|
|
108
118
|
const {document, raw} = resolved[k];
|
|
@@ -113,14 +123,18 @@ Object.keys(resolved).forEach((k) => {
|
|
|
113
123
|
({kind}) => kind !== 'FragmentDefinition',
|
|
114
124
|
);
|
|
115
125
|
const rawSource: string = raw.literals[0];
|
|
116
|
-
const processedOptions = processPragmas(config.options, rawSource);
|
|
117
|
-
if (!processedOptions) {
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
126
|
|
|
121
127
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
122
128
|
const withTypeNames: DocumentNode = addTypenameToDocument(document);
|
|
123
129
|
const printed = print(withTypeNames);
|
|
130
|
+
if (hasNonFragments && !printedOperations.includes(printed)) {
|
|
131
|
+
printedOperations.push(printed);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const processedOptions = processPragmas(config.options, rawSource);
|
|
135
|
+
if (!processedOptions) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
124
138
|
|
|
125
139
|
if (hasNonFragments) {
|
|
126
140
|
/* eslint-disable flowtype-errors/uncovered */
|
|
@@ -163,3 +177,13 @@ if (validationFailures) {
|
|
|
163
177
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
164
178
|
process.exit(1);
|
|
165
179
|
}
|
|
180
|
+
|
|
181
|
+
if (config.dumpOperations) {
|
|
182
|
+
const dumpOperations = config.dumpOperations;
|
|
183
|
+
const parent = dirname(dumpOperations);
|
|
184
|
+
mkdirSync(parent, {recursive: true});
|
|
185
|
+
writeFileSync(
|
|
186
|
+
dumpOperations,
|
|
187
|
+
JSON.stringify(printedOperations.sort(), null, 2),
|
|
188
|
+
);
|
|
189
|
+
}
|
package/dist/cli/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFile","cliFiles","process","argv","console","log","exit","config","schemaForValidation","schemaForTypeGeneration","schemaFilePath","inputFiles","length","files","f","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","validationFailures","k","document","raw","excludes","some","rx","test","hasNonFragments","definitions","kind","rawSource","literals","processedOptions","options","withTypeNames","printed","err"],"mappings":"AAAA;;AAEA;;;AACA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;AAPwD;;AASxD;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,CA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A,MAAI,CAACE,gBAAL,EAAuB;AACnB;AACH,GAZgC,CAcjC;;;AACA,QAAME,aAA2B,GAAG,4CAAsBb,QAAtB,CAApC;AACA,QAAMc,OAAO,GAAG,oBAAMD,aAAN,CAAhB;;AAEA,MAAIP,eAAJ,EAAqB;AACjB;AACA,UAAMb,MAAM,GAAG,0BAASb,mBAAT,EAA8BiC,aAA9B,CAAf;AACA;;AACA,QAAIpB,MAAM,CAACT,MAAX,EAAmB;AACfS,MAAAA,MAAM,CAACH,OAAP,CAAgBI,KAAD,IAAW;AACtBlB,QAAAA,OAAO,CAACkB,KAAR,CACK,sCAAqCO,GAAG,CAACJ,GAAJ,CAAQ7B,IAAK,GADvD;AAGAQ,QAAAA,OAAO,CAACkB,KAAR,CAAcoB,OAAd;AACAtC,QAAAA,OAAO,CAACkB,KAAR,CAAcA,KAAd;AACAI,QAAAA,kBAAkB;AACrB,OAPD;AAQH;AACD;;AACH;;AAED,MAAI;AACA,8CACIG,GAAG,CAACJ,GAAJ,CAAQ7B,IADZ,EAEIa,uBAFJ,EAGIgC,aAHJ,EAIIF,gBAJJ,EADA,CAOA;AACH,GARD,CAQE,OAAOI,GAAP,EAAY;AACVvC,IAAAA,OAAO,CAACkB,KAAR,CAAe,yCAAwCO,GAAG,CAACJ,GAAJ,CAAQ7B,IAAK,EAApE;AACAQ,IAAAA,OAAO,CAACkB,KAAR,CAAcoB,OAAd,EAFU,CAGV;;AACAtC,IAAAA,OAAO,CAACkB,KAAR,CAAcqB,GAAd;AACAjB,IAAAA,kBAAkB;AACrB;AACJ,CAlDD;;AAoDA,IAAIA,kBAAJ,EAAwB;AACpBtB,EAAAA,OAAO,CAACkB,KAAR,CACK,eAAcI,kBAAmB,4CADtC,EADoB,CAIpB;;AACAxB,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb;AACH","sourcesContent":["#!/usr/bin/env node\n// @flow\n/* eslint-disable no-console */\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {getSchemas, loadConfigFile} from './config';\n\nimport {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered\n\nimport {execSync} from 'child_process';\nimport {readFileSync} from 'fs';\nimport {type DocumentNode} from 'graphql';\nimport {print} from 'graphql/language/printer';\nimport {validate} from 'graphql/validation';\nimport path from 'path';\n\n/**\n * This CLI tool executes the following steps:\n * 1) process options\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 [_, __, configFile, ...cliFiles] = process.argv;\n\nif (\n configFile === '-h' ||\n configFile === '--help' ||\n configFile === 'help' ||\n !configFile\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 config = loadConfigFile(configFile);\n\nconst [schemaForValidation, schemaForTypeGeneration] = getSchemas(\n config.schemaFilePath,\n);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(process.cwd());\n\n/** Step (2) */\n\nconst files = processFiles(inputFiles, (f) => readFileSync(f, 'utf8'));\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\nlet validationFailures: number = 0;\n\nObject.keys(resolved).forEach((k) => {\n const {document, raw} = resolved[k];\n if (config.excludes.some((rx) => rx.test(raw.loc.path))) {\n return; // skip\n }\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\n const processedOptions = processPragmas(config.options, rawSource);\n if (!processedOptions) {\n return;\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n const withTypeNames: DocumentNode = addTypenameToDocument(document);\n const printed = print(withTypeNames);\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 processedOptions,\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"],"file":"run.js"}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/run.js"],"names":["findGraphqlTagReferences","root","response","encoding","cwd","trim","split","map","relative","path","join","_","__","configFile","cliFiles","process","argv","console","log","exit","config","schemaForValidation","schemaForTypeGeneration","schemaFilePath","inputFiles","length","files","f","Error","filesHadErrors","Object","keys","forEach","key","file","errors","error","message","resolved","loc","validationFailures","printedOperations","k","document","raw","excludes","some","rx","test","hasNonFragments","definitions","kind","rawSource","literals","withTypeNames","printed","includes","push","processedOptions","options","err","dumpOperations","parent","recursive","JSON","stringify","sort"],"mappings":"AAAA;;AAEA;;;AACA;;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,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,UAAR,EAAoB,GAAGC,QAAvB,IAAmCC,OAAO,CAACC,IAAjD;;AAEA,IACIH,UAAU,KAAK,IAAf,IACAA,UAAU,KAAK,QADf,IAEAA,UAAU,KAAK,MAFf,IAGA,CAACA,UAJL,EAKE;AACEI,EAAAA,OAAO,CAACC,GAAR,CAAa;AACjB;AACA,wDAFI;AAGAH,EAAAA,OAAO,CAACI,IAAR,CAAa,CAAb,EAJF,CAImB;AACpB;;AAED,MAAMC,MAAM,GAAG,4BAAeP,UAAf,CAAf;AAEA,MAAM,CAACQ,mBAAD,EAAsBC,uBAAtB,IAAiD,wBACnDF,MAAM,CAACG,cAD4C,CAAvD;AAIA,MAAMC,UAAU,GAAGV,QAAQ,CAACW,MAAT,GACbX,Q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E;AAAZ,GAAlB;AACA,yBACIF,cADJ,EAEIG,IAAI,CAACC,SAAL,CAAexB,iBAAiB,CAACyB,IAAlB,EAAf,EAAyC,IAAzC,EAA+C,CAA/C,CAFJ;AAIH","sourcesContent":["#!/usr/bin/env node\n// @flow\n/* eslint-disable no-console */\nimport {generateTypeFiles, processPragmas} from '../generateTypeFiles';\nimport {processFiles} from '../parser/parse';\nimport {resolveDocuments} from '../parser/resolve';\nimport {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) process options\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 [_, __, configFile, ...cliFiles] = process.argv;\n\nif (\n configFile === '-h' ||\n configFile === '--help' ||\n configFile === 'help' ||\n !configFile\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 config = loadConfigFile(configFile);\n\nconst [schemaForValidation, schemaForTypeGeneration] = getSchemas(\n config.schemaFilePath,\n);\n\nconst inputFiles = cliFiles.length\n ? cliFiles\n : findGraphqlTagReferences(process.cwd());\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\nlet validationFailures: number = 0;\nconst printedOperations: Array<string> = [];\n\nObject.keys(resolved).forEach((k) => {\n const {document, raw} = resolved[k];\n if (config.excludes.some((rx) => rx.test(raw.loc.path))) {\n return; // skip\n }\n const hasNonFragments = document.definitions.some(\n ({kind}) => kind !== 'FragmentDefinition',\n );\n const rawSource: string = raw.literals[0];\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 processedOptions = processPragmas(config.options, rawSource);\n if (!processedOptions) {\n return;\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 processedOptions,\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.dumpOperations) {\n const dumpOperations = config.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"}
|
|
@@ -185,9 +185,9 @@ const objectPropertiesToFlow = (config, type, typeName, selections) => {
|
|
|
185
185
|
switch (selection.kind) {
|
|
186
186
|
case 'InlineFragment':
|
|
187
187
|
{
|
|
188
|
-
var _selection$typeCondit;
|
|
188
|
+
var _selection$typeCondit, _selection$typeCondit2;
|
|
189
189
|
|
|
190
|
-
const newTypeName = (
|
|
190
|
+
const newTypeName = (_selection$typeCondit = (_selection$typeCondit2 = selection.typeCondition) === null || _selection$typeCondit2 === void 0 ? void 0 : _selection$typeCondit2.name.value) !== null && _selection$typeCondit !== void 0 ? _selection$typeCondit : typeName;
|
|
191
191
|
|
|
192
192
|
if (newTypeName !== typeName) {
|
|
193
193
|
return [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateResponseType.js"],"names":["generateResponseType","schema","query","config","ast","querySelectionToObjectType","selectionSet","selections","operation","typesByName","Mutation","Query","code","sortedObjectTypeAnnotation","properties","obj","babelTypes","objectTypeAnnotation","sort","a","b","type","aName","key","name","bName","undefined","path","join","isTopLevelType","length","allObjectTypes","genericTypeAnnotation","identifier","generateFragmentType","fragment","onType","typeCondition","value","objectPropertiesToFlow","interfacesByName","unionOrInterfaceToFlow","unionsByName","Error","_typeToFlow","selection","kind","readOnlyArray","typeParameterInstantiation","typeToFlow","ofType","union","console","log","anyTypeAnnotation","tname","childType","description","strictNullability","inner","result","nullableTypeAnnotation","ensureOnlyOneTypenameProperty","seenTypeName","filter","typeName","concat","map","newTypeName","fragments","errors","push","objectTypeProperty","alias","stringLiteralTypeAnnotation","fieldsByName","typeField","allFields","every","selectedAttributes","possibleTypes","slice","possible","configWithUpdatedPath","attributes","unionOrInterfaceSelection","flat","sharedAttributes","typeNameIndex","findIndex","x","unionTypeAnnotation","attrs","possibleTypesByName","indirectMatch"],"mappings":";;;;;;;AAEA;;AACA;;AASA;;AAKA;;;;;;;;AAhBA;AACyC;AA2BlC,MAAMA,oBAAoB,GAAG,CAChCC,MADgC,EAEhCC,KAFgC,EAGhCC,MAHgC,KAIvB;AACT,QAAMC,GAAG,GAAGC,0BAA0B,CAClCF,MADkC,EAElCD,KAAK,CAACI,YAAN,CAAmBC,UAFe,EAGlCL,KAAK,CAACM,SAAN,KAAoB,UAApB,GACMP,MAAM,CAACQ,WAAP,CAAmBC,QADzB,GAEMT,MAAM,CAACQ,WAAP,CAAmBE,KALS,EAMlCT,KAAK,CAACM,SAAN,KAAoB,UAApB,GAAiC,UAAjC,GAA8C,OANZ,CAAtC,CADS,CAST;;AACA,SAAO,wBAASJ,GAAT,EAAcQ,IAArB;AACH,CAfM;;;;AAiBP,MAAMC,0BAA0B,GAAG,CAC/BV,MAD+B,EAE/BW,UAF+B,KAK9B;AACD,QAAMC,GAAG,GAAGC,UAAU,CAACC,oBAAX,CACRH,UAAU,CAACI,IAAX,CAAgB,CAACC,CAAD,EAAIC,CAAJ,KAAU;AACtB,QACID,CAAC,CAACE,IAAF,KAAW,oBAAX,IACAD,CAAC,CAACC,IAAF,KAAW,oBAFf,EAGE;AACE,YAAMC,KAAK,GAAGH,CAAC,CAACI,GAAF,CAAMF,IAAN,KAAe,YAAf,GAA8BF,CAAC,CAACI,GAAF,CAA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ACmE,MAAP,CACKC,IADL,CACW,kDAAiDlD,IAAI,CAACG,IAAK;AAClF;AACA,mDAHY;AAIH;;AACD,WAAO,EAAP;AACH;;AACD,MAAIqB,SAAS,CAACR,aAAd,EAA6B;AAAA;;AACzB,UAAM4B,QAAQ,GAAGpB,SAAS,CAACR,aAAV,CAAwBb,IAAxB,CAA6Bc,KAA9C;AACA,UAAMwD,aAAa,4BACf3F,MAAM,CAACF,MAAP,CAAcuC,gBAAd,CAA+ByB,QAA/B,CADe,0DACf,sBAA0C4B,mBAA1C,CACIX,QAAQ,CAAC1D,IADb,CADJ;;AAIA,QAAIyC,QAAQ,KAAKiB,QAAQ,CAAC1D,IAAtB,IAA8B,CAACsE,aAAnC,EAAkD;AAC9C,aAAO,EAAP;AACH;AACJ;;AACD,SAAOvD,sBAAsB,CACzBpC,MADyB,EAEzBA,MAAM,CAACF,MAAP,CAAcQ,WAAd,CAA0ByE,QAAQ,CAAC1D,IAAnC,CAFyB,EAGzB0D,QAAQ,CAAC1D,IAHgB,EAIzBqB,SAAS,CAACvC,YAAV,CAAuBC,UAJE,CAA7B;AAMH,CA5GD","sourcesContent":["// @flow\n/* eslint-disable no-console */\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport * as babelTypes from '@babel/types';\nimport {type BabelNodeFlowType} from '@babel/types';\nimport type {\n FieldNode,\n IntrospectionOutputTypeRef,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n} from 'graphql';\nimport type {Config, Schema, Selections} from './types';\nimport {\n liftLeadingPropertyComments,\n maybeAddDescriptionComment,\n transferLeadingComments,\n} from './utils';\nimport {enumTypeToFlow, scalarTypeToFlow} from './enums';\nimport type {\n IntrospectionField,\n IntrospectionInterfaceType,\n IntrospectionObjectType,\n IntrospectionUnionType,\n} from 'graphql/utilities/introspectionQuery';\nimport {\n BabelNodeObjectTypeProperty,\n BabelNodeObjectTypeSpreadProperty,\n} from '@babel/types';\n\nexport const generateResponseType = (\n schema: Schema,\n query: OperationDefinitionNode,\n config: Config,\n): string => {\n const ast = querySelectionToObjectType(\n config,\n query.selectionSet.selections,\n query.operation === 'mutation'\n ? schema.typesByName.Mutation\n : schema.typesByName.Query,\n query.operation === 'mutation' ? 'mutation' : 'query',\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n return generate(ast).code;\n};\n\nconst sortedObjectTypeAnnotation = (\n config: Config,\n properties: Array<\n BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty,\n >,\n) => {\n const obj = babelTypes.objectTypeAnnotation(\n properties.sort((a, b) => {\n if (\n a.type === 'ObjectTypeProperty' &&\n b.type === 'ObjectTypeProperty'\n ) {\n const aName = a.key.type === 'Identifier' ? a.key.name : '';\n const bName = b.key.type === 'Identifier' ? b.key.name : '';\n return aName < bName ? -1 : 1;\n }\n return 0;\n }),\n undefined /* indexers */,\n undefined /* callProperties */,\n undefined /* internalSlots */,\n true /* exact */,\n );\n const name = config.path.join('_');\n const isTopLevelType = config.path.length <= 1;\n if (config.allObjectTypes != null && !isTopLevelType) {\n config.allObjectTypes[name] = obj;\n return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));\n } else {\n return obj;\n }\n};\n\nexport const generateFragmentType = (\n schema: Schema,\n fragment: FragmentDefinitionNode,\n config: Config,\n): string => {\n const onType = fragment.typeCondition.name.value;\n let ast;\n\n if (schema.typesByName[onType]) {\n ast = sortedObjectTypeAnnotation(\n config,\n objectPropertiesToFlow(\n config,\n schema.typesByName[onType],\n onType,\n fragment.selectionSet.selections,\n ),\n );\n } else if (schema.interfacesByName[onType]) {\n ast = unionOrInterfaceToFlow(\n config,\n config.schema.interfacesByName[onType],\n fragment.selectionSet.selections,\n );\n } else if (schema.unionsByName[onType]) {\n ast = unionOrInterfaceToFlow(\n config,\n config.schema.unionsByName[onType],\n fragment.selectionSet.selections,\n );\n } else {\n throw new Error(`Unknown ${onType}`);\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n return generate(ast).code;\n};\n\nconst _typeToFlow = (\n config: Config,\n type,\n selection,\n): babelTypes.BabelNodeFlowType => {\n if (type.kind === 'SCALAR') {\n return scalarTypeToFlow(config, type.name);\n }\n if (type.kind === 'LIST') {\n return babelTypes.genericTypeAnnotation(\n config.readOnlyArray\n ? babelTypes.identifier('$ReadOnlyArray')\n : babelTypes.identifier('Array'),\n babelTypes.typeParameterInstantiation([\n typeToFlow(config, type.ofType, selection),\n ]),\n );\n }\n if (type.kind === 'UNION') {\n const union = config.schema.unionsByName[type.name];\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return unionOrInterfaceToFlow(\n config,\n union,\n selection.selectionSet.selections,\n );\n }\n\n if (type.kind === 'INTERFACE') {\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return unionOrInterfaceToFlow(\n config,\n config.schema.interfacesByName[type.name],\n selection.selectionSet.selections,\n );\n }\n if (type.kind === 'ENUM') {\n return enumTypeToFlow(config, type.name);\n }\n if (type.kind !== 'OBJECT') {\n console.log('not object', type);\n return babelTypes.anyTypeAnnotation();\n }\n\n const tname = type.name;\n if (!config.schema.typesByName[tname]) {\n console.log('unknown referenced type', tname);\n return babelTypes.anyTypeAnnotation();\n }\n const childType = config.schema.typesByName[tname];\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return maybeAddDescriptionComment(\n childType.description,\n querySelectionToObjectType(\n config,\n selection.selectionSet.selections,\n childType,\n tname,\n ),\n );\n};\n\nexport const typeToFlow = (\n config: Config,\n type: IntrospectionOutputTypeRef,\n selection: FieldNode,\n): babelTypes.BabelNodeFlowType => {\n // throw new Error('npoe');\n if (type.kind === 'NON_NULL') {\n return _typeToFlow(config, type.ofType, selection);\n }\n // If we don'babelTypes care about strict nullability checking, then pretend everything is non-null\n if (!config.strictNullability) {\n return _typeToFlow(config, type, selection);\n }\n const inner = _typeToFlow(config, type, selection);\n const result = babelTypes.nullableTypeAnnotation(inner);\n return transferLeadingComments(inner, result);\n};\n\nconst ensureOnlyOneTypenameProperty = (properties) => {\n let seenTypeName: false | string = false;\n return properties.filter((type) => {\n // The apollo-utilities \"addTypeName\" utility will add it\n // even if it's already specified :( so we have to filter out\n // the extra one here.\n if (\n type.type === 'ObjectTypeProperty' &&\n type.key.name === '__typename'\n ) {\n const name =\n type.value.type === 'StringLiteralTypeAnnotation'\n ? type.value.value\n : 'INVALID';\n if (seenTypeName) {\n if (name !== seenTypeName) {\n throw new Error(\n `Got two different type names ${name}, ${seenTypeName}`,\n );\n }\n return false;\n }\n seenTypeName = name;\n }\n return true;\n });\n};\n\nconst querySelectionToObjectType = (\n config: Config,\n selections,\n type,\n typeName: string,\n): BabelNodeFlowType => {\n return sortedObjectTypeAnnotation(\n config,\n ensureOnlyOneTypenameProperty(\n objectPropertiesToFlow(config, type, typeName, selections),\n ),\n );\n};\n\nexport const objectPropertiesToFlow = (\n config: Config,\n type: IntrospectionObjectType & {\n fieldsByName: {[name: string]: IntrospectionField},\n },\n typeName: string,\n selections: Selections,\n): Array<BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty> => {\n return [].concat(\n ...selections.map((selection) => {\n switch (selection.kind) {\n case 'InlineFragment': {\n const newTypeName =\n selection.typeCondition?.name.value ?? typeName;\n if (newTypeName !== typeName) {\n return [];\n }\n return objectPropertiesToFlow(\n config,\n config.schema.typesByName[newTypeName],\n newTypeName,\n selection.selectionSet.selections,\n );\n }\n case 'FragmentSpread':\n if (!config.fragments[selection.name.value]) {\n config.errors.push(\n `No fragment named '${selection.name.value}'. Did you forget to include it in the template literal?`,\n );\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(selection.name.value),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(`UNKNOWN_FRAGMENT`),\n ),\n ),\n ];\n }\n\n return objectPropertiesToFlow(\n config,\n type,\n typeName,\n config.fragments[selection.name.value].selectionSet\n .selections,\n );\n\n case 'Field':\n const name = selection.name.value;\n const alias: string = selection.alias\n ? selection.alias.value\n : name;\n if (name === '__typename') {\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.stringLiteralTypeAnnotation(\n typeName,\n ),\n ),\n ];\n }\n if (!type.fieldsByName[name]) {\n config.errors.push(\n `Unknown field '${name}' for type '${typeName}'`,\n );\n return babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(\n `UNKNOWN_FIELD[\"${name}\"]`,\n ),\n ),\n );\n }\n const typeField = type.fieldsByName[name];\n\n return [\n maybeAddDescriptionComment(\n typeField.description,\n liftLeadingPropertyComments(\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n typeToFlow(\n {\n ...config,\n path: config.path.concat([alias]),\n },\n typeField.type,\n selection,\n ),\n ),\n ),\n ),\n ];\n\n default:\n config.errors.push(\n // eslint-disable-next-line flowtype-errors/uncovered\n `Unsupported selection kind '${selection.kind}'`,\n );\n return [];\n }\n }),\n );\n};\n\nexport const unionOrInterfaceToFlow = (\n config: Config,\n type:\n | IntrospectionUnionType\n | (IntrospectionInterfaceType & {\n fieldsByName: {[key: string]: IntrospectionField},\n }),\n selections: Selections,\n): BabelNodeFlowType => {\n const allFields = selections.every(\n (selection) => selection.kind === 'Field',\n );\n const selectedAttributes: Array<{\n attributes: Array<\n BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty,\n >,\n typeName: string,\n }> = type.possibleTypes\n .slice()\n .sort((a, b) => {\n return a.name < b.name ? -1 : 1;\n })\n .map((possible) => {\n const configWithUpdatedPath = {\n ...config,\n path: allFields\n ? config.path\n : config.path.concat([possible.name]),\n };\n return {\n typeName: possible.name,\n attributes: ensureOnlyOneTypenameProperty(\n selections\n .map((selection) =>\n unionOrInterfaceSelection(\n configWithUpdatedPath,\n type,\n possible,\n selection,\n ),\n )\n .flat(),\n ),\n };\n });\n // If they're all fields, the only selection that could be different is __typename\n if (allFields) {\n const sharedAttributes = selectedAttributes[0].attributes.slice();\n const typeNameIndex = selectedAttributes[0].attributes.findIndex(\n (x) =>\n x.type === 'ObjectTypeProperty' &&\n x.key.type === 'Identifier' &&\n x.key.name === '__typename',\n );\n if (typeNameIndex !== -1) {\n sharedAttributes[typeNameIndex] = babelTypes.objectTypeProperty(\n babelTypes.identifier('__typename'),\n babelTypes.unionTypeAnnotation(\n selectedAttributes.map(\n (attrs) =>\n // eslint-disable-next-line flowtype-errors/uncovered\n ((attrs.attributes[\n typeNameIndex\n ]: any): BabelNodeObjectTypeProperty).value,\n ),\n ),\n );\n }\n return sortedObjectTypeAnnotation(config, sharedAttributes);\n }\n if (selectedAttributes.length === 1) {\n return sortedObjectTypeAnnotation(\n config,\n selectedAttributes[0].attributes,\n );\n }\n /**\n * When generating the objects for the sub-options of a union, the path needs\n * to include the name of the object type.\n * ```\n * query getFriend {\n * friend {\n * ... on Human { id }\n * ... on Droid { arms }\n * }\n * }\n * ```\n * produces\n * ```\n * type getFriend = {friend: getFriend_friend_Human | getFriend_friend_Droid }\n * type getFriend_friend_Human = {id: string}\n * type getFriend_friend_Droid = {arms: number}\n * ```\n * Note that this is different from when an attribute has a plain object type.\n * ```\n * query getHuman {\n * me: human(id: \"me\") { id }\n * }\n * ```\n * produces\n * ```\n * type getHuman = {me: getHuman_me}\n * type getHuman_me = {id: string}\n * ```\n * instead of e.g. `getHuman_me_Human`.\n */\n const result = babelTypes.unionTypeAnnotation(\n selectedAttributes.map(({typeName, attributes}) =>\n sortedObjectTypeAnnotation(\n {...config, path: config.path.concat([typeName])},\n attributes,\n ),\n ),\n );\n const name = config.path.join('_');\n if (config.allObjectTypes && config.path.length > 1) {\n config.allObjectTypes[name] = result;\n return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));\n }\n return result;\n};\nconst unionOrInterfaceSelection = (\n config,\n type,\n possible,\n selection,\n): Array<BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty> => {\n if (selection.kind === 'Field' && selection.name.value === '__typename') {\n const alias = selection.alias\n ? selection.alias.value\n : selection.name.value;\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.stringLiteralTypeAnnotation(possible.name),\n ),\n ];\n }\n if (selection.kind === 'Field' && type.kind !== 'UNION') {\n // this is an interface\n const name = selection.name.value;\n const alias = selection.alias ? selection.alias.value : name;\n if (!type.fieldsByName[name]) {\n config.errors.push(\n 'Unknown field: ' +\n name +\n ' on type ' +\n type.name +\n ' for possible ' +\n possible.name,\n );\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(`UNKNOWN_FIELD`),\n ),\n ),\n ];\n }\n const typeField = type.fieldsByName[name];\n return [\n liftLeadingPropertyComments(\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n typeToFlow(\n {...config, path: config.path.concat([name])},\n typeField.type,\n selection,\n ),\n ),\n ),\n ];\n }\n if (selection.kind === 'FragmentSpread') {\n const fragment = config.fragments[selection.name.value];\n if (!fragment) {\n throw new Error(`Unknown fragment ${selection.name.value}`);\n }\n const typeName = fragment.typeCondition.name.value;\n if (\n (config.schema.interfacesByName[typeName] &&\n config.schema.interfacesByName[typeName].possibleTypesByName[\n possible.name\n ]) ||\n typeName === possible.name\n ) {\n return [].concat(\n ...fragment.selectionSet.selections.map((selection) =>\n unionOrInterfaceSelection(\n config,\n config.schema.typesByName[possible.name],\n possible,\n selection,\n ),\n ),\n );\n } else {\n return [];\n }\n }\n if (selection.kind !== 'InlineFragment') {\n config.errors.push(\n `union selectors must be inline fragment: found ${selection.kind}`,\n );\n if (type.kind === 'UNION') {\n config.errors\n .push(`You're trying to select a field from the union ${type.name},\nbut the only field you're allowed to select is \"__typename\".\nTry using an inline fragment \"... on SomeType {}\".`);\n }\n return [];\n }\n if (selection.typeCondition) {\n const typeName = selection.typeCondition.name.value;\n const indirectMatch =\n config.schema.interfacesByName[typeName]?.possibleTypesByName[\n possible.name\n ];\n if (typeName !== possible.name && !indirectMatch) {\n return [];\n }\n }\n return objectPropertiesToFlow(\n config,\n config.schema.typesByName[possible.name],\n possible.name,\n selection.selectionSet.selections,\n );\n};\n"],"file":"generateResponseType.js"}
|
|
1
|
+
{"version":3,"sources":["../src/generateResponseType.js"],"names":["generateResponseType","schema","query","config","ast","querySelectionToObjectType","selectionSet","selections","operation","typesByName","Mutation","Query","code","sortedObjectTypeAnnotation","properties","obj","babelTypes","objectTypeAnnotation","sort","a","b","type","aName","key","name","bName","undefined","path","join","isTopLevelType","length","allObjectTypes","genericTypeAnnotation","identifier","generateFragmentType","fragment","onType","typeCondition","value","objectPropertiesToFlow","interfacesByName","unionOrInterfaceToFlow","unionsByName","Error","_typeToFlow","selection","kind","readOnlyArray","typeParameterInstantiation","typeToFlow","ofType","union","console","log","anyTypeAnnotation","tname","childType","description","strictNullability","inner","result","nullableTypeAnnotation","ensureOnlyOneTypenameProperty","seenTypeName","filter","typeName","concat","map","newTypeName","fragments","errors","push","objectTypeProperty","alias","stringLiteralTypeAnnotation","fieldsByName","typeField","allFields","every","selectedAttributes","possibleTypes","slice","possible","configWithUpdatedPath","attributes","unionOrInterfaceSelection","flat","sharedAttributes","typeNameIndex","findIndex","x","unionTypeAnnotation","attrs","possibleTypesByName","indirectMatch"],"mappings":";;;;;;;AAEA;;AACA;;AASA;;AAKA;;;;;;;;AAhBA;AACyC;AA2BlC,MAAMA,oBAAoB,GAAG,CAChCC,MADgC,EAEhCC,KAFgC,EAGhCC,MAHgC,KAIvB;AACT,QAAMC,GAAG,GAAGC,0BAA0B,CAClCF,MADkC,EAElCD,KAAK,CAACI,YAAN,CAAmBC,UAFe,EAGlCL,KAAK,CAACM,SAAN,KAAoB,UAApB,GACMP,MAAM,CAACQ,WAAP,CAAmBC,QADzB,GAEMT,MAAM,CAACQ,WAAP,CAAmBE,KALS,EAMlCT,KAAK,CAACM,SAAN,KAAoB,UAApB,GAAiC,UAAjC,GAA8C,OANZ,CAAtC,C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BAAyB,CACrBlF,MADqB,EAErBA,MAAM,CAACF,MAAP,CAAcQ,WAAd,CAA0ByE,QAAQ,CAAC1D,IAAnC,CAFqB,EAGrB0D,QAHqB,EAIrBrC,SAJqB,CAD1B,CADA,CAAP;AAUH,KAjBD,MAiBO;AACH,aAAO,EAAP;AACH;AACJ;;AACD,MAAIA,SAAS,CAACC,IAAV,KAAmB,gBAAvB,EAAyC;AACrC3C,IAAAA,MAAM,CAACmE,MAAP,CAAcC,IAAd,CACK,kDAAiD1B,SAAS,CAACC,IAAK,EADrE;;AAGA,QAAIzB,IAAI,CAACyB,IAAL,KAAc,OAAlB,EAA2B;AACvB3C,MAAAA,MAAM,CAACmE,MAAP,CACKC,IADL,CACW,kDAAiDlD,IAAI,CAACG,IAAK;AAClF;AACA,mDAHY;AAIH;;AACD,WAAO,EAAP;AACH;;AACD,MAAIqB,SAAS,CAACR,aAAd,EAA6B;AAAA;;AACzB,UAAM4B,QAAQ,GAAGpB,SAAS,CAACR,aAAV,CAAwBb,IAAxB,CAA6Bc,KAA9C;AACA,UAAMwD,aAAa,4BACf3F,MAAM,CAACF,MAAP,CAAcuC,gBAAd,CAA+ByB,QAA/B,CADe,0DACf,sBAA0C4B,mBAA1C,CACIX,QAAQ,CAAC1D,IADb,CADJ;;AAIA,QAAIyC,QAAQ,KAAKiB,QAAQ,CAAC1D,IAAtB,IAA8B,CAACsE,aAAnC,EAAkD;AAC9C,aAAO,EAAP;AACH;AACJ;;AACD,SAAOvD,sBAAsB,CACzBpC,MADyB,EAEzBA,MAAM,CAACF,MAAP,CAAcQ,WAAd,CAA0ByE,QAAQ,CAAC1D,IAAnC,CAFyB,EAGzB0D,QAAQ,CAAC1D,IAHgB,EAIzBqB,SAAS,CAACvC,YAAV,CAAuBC,UAJE,CAA7B;AAMH,CA5GD","sourcesContent":["// @flow\n/* eslint-disable no-console */\nimport generate from '@babel/generator'; // eslint-disable-line flowtype-errors/uncovered\nimport * as babelTypes from '@babel/types';\nimport {type BabelNodeFlowType} from '@babel/types';\nimport type {\n FieldNode,\n IntrospectionOutputTypeRef,\n OperationDefinitionNode,\n FragmentDefinitionNode,\n} from 'graphql';\nimport type {Config, Schema, Selections} from './types';\nimport {\n liftLeadingPropertyComments,\n maybeAddDescriptionComment,\n transferLeadingComments,\n} from './utils';\nimport {enumTypeToFlow, scalarTypeToFlow} from './enums';\nimport type {\n IntrospectionField,\n IntrospectionInterfaceType,\n IntrospectionObjectType,\n IntrospectionUnionType,\n} from 'graphql/utilities/introspectionQuery';\nimport {\n BabelNodeObjectTypeProperty,\n BabelNodeObjectTypeSpreadProperty,\n} from '@babel/types';\n\nexport const generateResponseType = (\n schema: Schema,\n query: OperationDefinitionNode,\n config: Config,\n): string => {\n const ast = querySelectionToObjectType(\n config,\n query.selectionSet.selections,\n query.operation === 'mutation'\n ? schema.typesByName.Mutation\n : schema.typesByName.Query,\n query.operation === 'mutation' ? 'mutation' : 'query',\n );\n // eslint-disable-next-line flowtype-errors/uncovered\n return generate(ast).code;\n};\n\nconst sortedObjectTypeAnnotation = (\n config: Config,\n properties: Array<\n BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty,\n >,\n) => {\n const obj = babelTypes.objectTypeAnnotation(\n properties.sort((a, b) => {\n if (\n a.type === 'ObjectTypeProperty' &&\n b.type === 'ObjectTypeProperty'\n ) {\n const aName = a.key.type === 'Identifier' ? a.key.name : '';\n const bName = b.key.type === 'Identifier' ? b.key.name : '';\n return aName < bName ? -1 : 1;\n }\n return 0;\n }),\n undefined /* indexers */,\n undefined /* callProperties */,\n undefined /* internalSlots */,\n true /* exact */,\n );\n const name = config.path.join('_');\n const isTopLevelType = config.path.length <= 1;\n if (config.allObjectTypes != null && !isTopLevelType) {\n config.allObjectTypes[name] = obj;\n return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));\n } else {\n return obj;\n }\n};\n\nexport const generateFragmentType = (\n schema: Schema,\n fragment: FragmentDefinitionNode,\n config: Config,\n): string => {\n const onType = fragment.typeCondition.name.value;\n let ast;\n\n if (schema.typesByName[onType]) {\n ast = sortedObjectTypeAnnotation(\n config,\n objectPropertiesToFlow(\n config,\n schema.typesByName[onType],\n onType,\n fragment.selectionSet.selections,\n ),\n );\n } else if (schema.interfacesByName[onType]) {\n ast = unionOrInterfaceToFlow(\n config,\n config.schema.interfacesByName[onType],\n fragment.selectionSet.selections,\n );\n } else if (schema.unionsByName[onType]) {\n ast = unionOrInterfaceToFlow(\n config,\n config.schema.unionsByName[onType],\n fragment.selectionSet.selections,\n );\n } else {\n throw new Error(`Unknown ${onType}`);\n }\n\n // eslint-disable-next-line flowtype-errors/uncovered\n return generate(ast).code;\n};\n\nconst _typeToFlow = (\n config: Config,\n type,\n selection,\n): babelTypes.BabelNodeFlowType => {\n if (type.kind === 'SCALAR') {\n return scalarTypeToFlow(config, type.name);\n }\n if (type.kind === 'LIST') {\n return babelTypes.genericTypeAnnotation(\n config.readOnlyArray\n ? babelTypes.identifier('$ReadOnlyArray')\n : babelTypes.identifier('Array'),\n babelTypes.typeParameterInstantiation([\n typeToFlow(config, type.ofType, selection),\n ]),\n );\n }\n if (type.kind === 'UNION') {\n const union = config.schema.unionsByName[type.name];\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return unionOrInterfaceToFlow(\n config,\n union,\n selection.selectionSet.selections,\n );\n }\n\n if (type.kind === 'INTERFACE') {\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return unionOrInterfaceToFlow(\n config,\n config.schema.interfacesByName[type.name],\n selection.selectionSet.selections,\n );\n }\n if (type.kind === 'ENUM') {\n return enumTypeToFlow(config, type.name);\n }\n if (type.kind !== 'OBJECT') {\n console.log('not object', type);\n return babelTypes.anyTypeAnnotation();\n }\n\n const tname = type.name;\n if (!config.schema.typesByName[tname]) {\n console.log('unknown referenced type', tname);\n return babelTypes.anyTypeAnnotation();\n }\n const childType = config.schema.typesByName[tname];\n if (!selection.selectionSet) {\n console.log('no selection set', selection);\n return babelTypes.anyTypeAnnotation();\n }\n return maybeAddDescriptionComment(\n childType.description,\n querySelectionToObjectType(\n config,\n selection.selectionSet.selections,\n childType,\n tname,\n ),\n );\n};\n\nexport const typeToFlow = (\n config: Config,\n type: IntrospectionOutputTypeRef,\n selection: FieldNode,\n): babelTypes.BabelNodeFlowType => {\n // throw new Error('npoe');\n if (type.kind === 'NON_NULL') {\n return _typeToFlow(config, type.ofType, selection);\n }\n // If we don'babelTypes care about strict nullability checking, then pretend everything is non-null\n if (!config.strictNullability) {\n return _typeToFlow(config, type, selection);\n }\n const inner = _typeToFlow(config, type, selection);\n const result = babelTypes.nullableTypeAnnotation(inner);\n return transferLeadingComments(inner, result);\n};\n\nconst ensureOnlyOneTypenameProperty = (properties) => {\n let seenTypeName: false | string = false;\n return properties.filter((type) => {\n // The apollo-utilities \"addTypeName\" utility will add it\n // even if it's already specified :( so we have to filter out\n // the extra one here.\n if (\n type.type === 'ObjectTypeProperty' &&\n type.key.name === '__typename'\n ) {\n const name =\n type.value.type === 'StringLiteralTypeAnnotation'\n ? type.value.value\n : 'INVALID';\n if (seenTypeName) {\n if (name !== seenTypeName) {\n throw new Error(\n `Got two different type names ${name}, ${seenTypeName}`,\n );\n }\n return false;\n }\n seenTypeName = name;\n }\n return true;\n });\n};\n\nconst querySelectionToObjectType = (\n config: Config,\n selections,\n type,\n typeName: string,\n): BabelNodeFlowType => {\n return sortedObjectTypeAnnotation(\n config,\n ensureOnlyOneTypenameProperty(\n objectPropertiesToFlow(config, type, typeName, selections),\n ),\n );\n};\n\nexport const objectPropertiesToFlow = (\n config: Config,\n type: IntrospectionObjectType & {\n fieldsByName: {[name: string]: IntrospectionField},\n },\n typeName: string,\n selections: Selections,\n): Array<BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty> => {\n return [].concat(\n ...selections.map((selection) => {\n switch (selection.kind) {\n case 'InlineFragment': {\n const newTypeName =\n selection.typeCondition?.name.value ?? typeName;\n if (newTypeName !== typeName) {\n return [];\n }\n return objectPropertiesToFlow(\n config,\n config.schema.typesByName[newTypeName],\n newTypeName,\n selection.selectionSet.selections,\n );\n }\n case 'FragmentSpread':\n if (!config.fragments[selection.name.value]) {\n config.errors.push(\n `No fragment named '${selection.name.value}'. Did you forget to include it in the template literal?`,\n );\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(selection.name.value),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(`UNKNOWN_FRAGMENT`),\n ),\n ),\n ];\n }\n\n return objectPropertiesToFlow(\n config,\n type,\n typeName,\n config.fragments[selection.name.value].selectionSet\n .selections,\n );\n\n case 'Field':\n const name = selection.name.value;\n const alias: string = selection.alias\n ? selection.alias.value\n : name;\n if (name === '__typename') {\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.stringLiteralTypeAnnotation(\n typeName,\n ),\n ),\n ];\n }\n if (!type.fieldsByName[name]) {\n config.errors.push(\n `Unknown field '${name}' for type '${typeName}'`,\n );\n return babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(\n `UNKNOWN_FIELD[\"${name}\"]`,\n ),\n ),\n );\n }\n const typeField = type.fieldsByName[name];\n\n return [\n maybeAddDescriptionComment(\n typeField.description,\n liftLeadingPropertyComments(\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n typeToFlow(\n {\n ...config,\n path: config.path.concat([alias]),\n },\n typeField.type,\n selection,\n ),\n ),\n ),\n ),\n ];\n\n default:\n config.errors.push(\n // eslint-disable-next-line flowtype-errors/uncovered\n `Unsupported selection kind '${selection.kind}'`,\n );\n return [];\n }\n }),\n );\n};\n\nexport const unionOrInterfaceToFlow = (\n config: Config,\n type:\n | IntrospectionUnionType\n | (IntrospectionInterfaceType & {\n fieldsByName: {[key: string]: IntrospectionField},\n }),\n selections: Selections,\n): BabelNodeFlowType => {\n const allFields = selections.every(\n (selection) => selection.kind === 'Field',\n );\n const selectedAttributes: Array<{\n attributes: Array<\n BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty,\n >,\n typeName: string,\n }> = type.possibleTypes\n .slice()\n .sort((a, b) => {\n return a.name < b.name ? -1 : 1;\n })\n .map((possible) => {\n const configWithUpdatedPath = {\n ...config,\n path: allFields\n ? config.path\n : config.path.concat([possible.name]),\n };\n return {\n typeName: possible.name,\n attributes: ensureOnlyOneTypenameProperty(\n selections\n .map((selection) =>\n unionOrInterfaceSelection(\n configWithUpdatedPath,\n type,\n possible,\n selection,\n ),\n )\n .flat(),\n ),\n };\n });\n // If they're all fields, the only selection that could be different is __typename\n if (allFields) {\n const sharedAttributes = selectedAttributes[0].attributes.slice();\n const typeNameIndex = selectedAttributes[0].attributes.findIndex(\n (x) =>\n x.type === 'ObjectTypeProperty' &&\n x.key.type === 'Identifier' &&\n x.key.name === '__typename',\n );\n if (typeNameIndex !== -1) {\n sharedAttributes[typeNameIndex] = babelTypes.objectTypeProperty(\n babelTypes.identifier('__typename'),\n babelTypes.unionTypeAnnotation(\n selectedAttributes.map(\n (attrs) =>\n // eslint-disable-next-line flowtype-errors/uncovered\n ((attrs.attributes[\n typeNameIndex\n ]: any): BabelNodeObjectTypeProperty).value,\n ),\n ),\n );\n }\n return sortedObjectTypeAnnotation(config, sharedAttributes);\n }\n if (selectedAttributes.length === 1) {\n return sortedObjectTypeAnnotation(\n config,\n selectedAttributes[0].attributes,\n );\n }\n /**\n * When generating the objects for the sub-options of a union, the path needs\n * to include the name of the object type.\n * ```\n * query getFriend {\n * friend {\n * ... on Human { id }\n * ... on Droid { arms }\n * }\n * }\n * ```\n * produces\n * ```\n * type getFriend = {friend: getFriend_friend_Human | getFriend_friend_Droid }\n * type getFriend_friend_Human = {id: string}\n * type getFriend_friend_Droid = {arms: number}\n * ```\n * Note that this is different from when an attribute has a plain object type.\n * ```\n * query getHuman {\n * me: human(id: \"me\") { id }\n * }\n * ```\n * produces\n * ```\n * type getHuman = {me: getHuman_me}\n * type getHuman_me = {id: string}\n * ```\n * instead of e.g. `getHuman_me_Human`.\n */\n const result = babelTypes.unionTypeAnnotation(\n selectedAttributes.map(({typeName, attributes}) =>\n sortedObjectTypeAnnotation(\n {...config, path: config.path.concat([typeName])},\n attributes,\n ),\n ),\n );\n const name = config.path.join('_');\n if (config.allObjectTypes && config.path.length > 1) {\n config.allObjectTypes[name] = result;\n return babelTypes.genericTypeAnnotation(babelTypes.identifier(name));\n }\n return result;\n};\nconst unionOrInterfaceSelection = (\n config,\n type,\n possible,\n selection,\n): Array<BabelNodeObjectTypeProperty | BabelNodeObjectTypeSpreadProperty> => {\n if (selection.kind === 'Field' && selection.name.value === '__typename') {\n const alias = selection.alias\n ? selection.alias.value\n : selection.name.value;\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.stringLiteralTypeAnnotation(possible.name),\n ),\n ];\n }\n if (selection.kind === 'Field' && type.kind !== 'UNION') {\n // this is an interface\n const name = selection.name.value;\n const alias = selection.alias ? selection.alias.value : name;\n if (!type.fieldsByName[name]) {\n config.errors.push(\n 'Unknown field: ' +\n name +\n ' on type ' +\n type.name +\n ' for possible ' +\n possible.name,\n );\n return [\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n babelTypes.genericTypeAnnotation(\n babelTypes.identifier(`UNKNOWN_FIELD`),\n ),\n ),\n ];\n }\n const typeField = type.fieldsByName[name];\n return [\n liftLeadingPropertyComments(\n babelTypes.objectTypeProperty(\n babelTypes.identifier(alias),\n typeToFlow(\n {...config, path: config.path.concat([name])},\n typeField.type,\n selection,\n ),\n ),\n ),\n ];\n }\n if (selection.kind === 'FragmentSpread') {\n const fragment = config.fragments[selection.name.value];\n if (!fragment) {\n throw new Error(`Unknown fragment ${selection.name.value}`);\n }\n const typeName = fragment.typeCondition.name.value;\n if (\n (config.schema.interfacesByName[typeName] &&\n config.schema.interfacesByName[typeName].possibleTypesByName[\n possible.name\n ]) ||\n typeName === possible.name\n ) {\n return [].concat(\n ...fragment.selectionSet.selections.map((selection) =>\n unionOrInterfaceSelection(\n config,\n config.schema.typesByName[possible.name],\n possible,\n selection,\n ),\n ),\n );\n } else {\n return [];\n }\n }\n if (selection.kind !== 'InlineFragment') {\n config.errors.push(\n `union selectors must be inline fragment: found ${selection.kind}`,\n );\n if (type.kind === 'UNION') {\n config.errors\n .push(`You're trying to select a field from the union ${type.name},\nbut the only field you're allowed to select is \"__typename\".\nTry using an inline fragment \"... on SomeType {}\".`);\n }\n return [];\n }\n if (selection.typeCondition) {\n const typeName = selection.typeCondition.name.value;\n const indirectMatch =\n config.schema.interfacesByName[typeName]?.possibleTypesByName[\n possible.name\n ];\n if (typeName !== possible.name && !indirectMatch) {\n return [];\n }\n }\n return objectPropertiesToFlow(\n config,\n config.schema.typesByName[possible.name],\n possible.name,\n selection.selectionSet.selections,\n );\n};\n"],"file":"generateResponseType.js"}
|
|
@@ -56,7 +56,7 @@ const generateTypeFileContents = (fileName, schema, document, options, generated
|
|
|
56
56
|
}) => {
|
|
57
57
|
// We write all generated files to a `__generated__` subdir to keep
|
|
58
58
|
// things tidy.
|
|
59
|
-
const targetFileName = `${name}.js`;
|
|
59
|
+
const targetFileName = options.typeFileName ? options.typeFileName.replace('[operationName]', name) : `${name}.js`;
|
|
60
60
|
|
|
61
61
|
const targetPath = _path.default.join(generatedDir, targetFileName);
|
|
62
62
|
|
|
@@ -83,7 +83,9 @@ const generateTypeFileContents = (fileName, schema, document, options, generated
|
|
|
83
83
|
exports.generateTypeFileContents = generateTypeFileContents;
|
|
84
84
|
|
|
85
85
|
const generateTypeFiles = (fileName, schema, document, options) => {
|
|
86
|
-
|
|
86
|
+
var _options$generatedDir;
|
|
87
|
+
|
|
88
|
+
const generatedDir = _path.default.join(_path.default.dirname(fileName), (_options$generatedDir = options.generatedDirectory) !== null && _options$generatedDir !== void 0 ? _options$generatedDir : '__generated__');
|
|
87
89
|
|
|
88
90
|
const indexFile = _path.default.join(generatedDir, 'index.js');
|
|
89
91
|
|
|
@@ -130,7 +132,8 @@ const processPragmas = (options, rawSource) => {
|
|
|
130
132
|
scalars: options.scalars,
|
|
131
133
|
splitTypes: options.splitTypes,
|
|
132
134
|
generatedDirectory: options.generatedDirectory,
|
|
133
|
-
exportAllObjectTypes: options.exportAllObjectTypes
|
|
135
|
+
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
136
|
+
typeFileName: options.typeFileName
|
|
134
137
|
};
|
|
135
138
|
} else {
|
|
136
139
|
return null;
|
|
@@ -20,6 +20,7 @@ export type ExternalOptions = {
|
|
|
20
20
|
splitTypes?: boolean,
|
|
21
21
|
generatedDirectory?: string,
|
|
22
22
|
exportAllObjectTypes?: boolean,
|
|
23
|
+
typeFileName?: string,
|
|
23
24
|
};
|
|
24
25
|
|
|
25
26
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -64,7 +65,9 @@ export const generateTypeFileContents = (
|
|
|
64
65
|
generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
|
|
65
66
|
// We write all generated files to a `__generated__` subdir to keep
|
|
66
67
|
// things tidy.
|
|
67
|
-
const targetFileName =
|
|
68
|
+
const targetFileName = options.typeFileName
|
|
69
|
+
? options.typeFileName.replace('[operationName]', name)
|
|
70
|
+
: `${name}.js`;
|
|
68
71
|
const targetPath = path.join(generatedDir, targetFileName);
|
|
69
72
|
|
|
70
73
|
let fileContents =
|
|
@@ -160,6 +163,7 @@ export const processPragmas = (
|
|
|
160
163
|
splitTypes: options.splitTypes,
|
|
161
164
|
generatedDirectory: options.generatedDirectory,
|
|
162
165
|
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
166
|
+
typeFileName: options.typeFileName,
|
|
163
167
|
};
|
|
164
168
|
} else {
|
|
165
169
|
return null;
|
|
@@ -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","targetFileName","targetPath","fileContents","splitTypes","Object","keys","replace","generateTypeFiles","dirname","generatedDirectory","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","processPragmas","rawSource","ignorePragma","autogen","loosePragma","autogenStrict","pragma","noPragmas","strictNullability","readOnlyArray","scalars","exportAllObjectTypes"],"mappings":";;;;;;;AAIA;;AACA;;AACA;;;;AALA;AAuBO,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;AACH,KAFD,MAEO;AACH,YAAMI,KAAK,GAAGT,aAAa,CAACU,KAAd,CAAoB,IAApB,EAA0BC,GAA1B,CAA+BC,IAAD,IAAU;AAClD,YAAIA,IAAI,CAACC,QAAL,CAAc,OAAOP,cAAKC,QAAL,CAAcJ,QAAd,CAArB,CAAJ,EAAmD;AAC/C,iBAAOE,OAAP;AACH;;AACD,eAAOO,IAAP;AACH,OALa,CAAd;AAMAZ,MAAAA,aAAa,GAAGS,KAAK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IAAwBD,SAAS,CAAC3B,QAAV,CAAmBf,OAAO,CAAC2C,YAA3B,CAA5B,EAAsE;AAClE,WAAO,IAAP;AACH;;AAED,QAAMC,OAAO,GAAG5C,OAAO,CAAC6C,WAAR,GACVH,SAAS,CAAC3B,QAAV,CAAmBf,OAAO,CAAC6C,WAA3B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAG9C,OAAO,CAAC+C,MAAR,GAChBL,SAAS,CAAC3B,QAAV,CAAmBf,OAAO,CAAC+C,MAA3B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAAChD,OAAO,CAAC6C,WAAT,IAAwB,CAAC7C,OAAO,CAAC+C,MAAnD;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHrD,MAAAA,iBAAiB,EAAEK,OAAO,CAACL,iBADxB;AAEHsD,MAAAA,iBAAiB,EAAED,SAAS,GACtBhD,OAAO,CAACiD,iBADc,GAEtBH,aAAa,IAAI,CAACF,OAJrB;AAKHM,MAAAA,aAAa,EAAElD,OAAO,CAACkD,aALpB;AAMHC,MAAAA,OAAO,EAAEnD,OAAO,CAACmD,OANd;AAOHzB,MAAAA,UAAU,EAAE1B,OAAO,CAAC0B,UAPjB;AAQHM,MAAAA,kBAAkB,EAAEhC,OAAO,CAACgC,kBARzB;AASHoB,MAAAA,oBAAoB,EAAEpD,OAAO,CAACoD;AAT3B,KAAP;AAWH,GAZD,MAYO;AACH,WAAO,IAAP;AACH;AACJ,CA/BM","sourcesContent":["// @flow\n// Import this in your jest setup, to mock out graphql-tag!\nimport type {DocumentNode} from 'graphql';\nimport type {Options, Schema, Scalars} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n\nexport type ExternalOptions = {\n pragma?: string,\n loosePragma?: string,\n ignorePragma?: string,\n scalars?: Scalars,\n strictNullability?: boolean,\n /**\n * The command that users should run to regenerate the types files.\n */\n regenerateCommand?: string,\n readOnlyArray?: boolean,\n splitTypes?: boolean,\n generatedDirectory?: string,\n exportAllObjectTypes?: boolean,\n};\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: Options,\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(({name, typeName, code, isFragment, extraTypes}) => {\n // We write all generated files to a `__generated__` subdir to keep\n // things tidy.\n const targetFileName = `${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((name) => {\n fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`;\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 return {files, indexContents};\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: Options,\n) => {\n const generatedDir = path.join(\n path.dirname(fileName),\n options.generatedDirectory ?? '__generated__',\n );\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 options: ExternalOptions,\n rawSource: string,\n): null | Options => {\n if (options.ignorePragma && rawSource.includes(options.ignorePragma)) {\n return null;\n }\n\n const autogen = options.loosePragma\n ? rawSource.includes(options.loosePragma)\n : false;\n const autogenStrict = options.pragma\n ? rawSource.includes(options.pragma)\n : false;\n const noPragmas = !options.loosePragma && !options.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n regenerateCommand: options.regenerateCommand,\n strictNullability: noPragmas\n ? options.strictNullability\n : autogenStrict || !autogen,\n readOnlyArray: options.readOnlyArray,\n scalars: options.scalars,\n splitTypes: options.splitTypes,\n generatedDirectory: options.generatedDirectory,\n exportAllObjectTypes: options.exportAllObjectTypes,\n };\n } else {\n return null;\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","newLine","path","basename","indexOf","lines","split","map","line","includes","join","generated","forEach","name","code","isFragment","extraTypes","targetFileName","typeFileName","replace","targetPath","fileContents","splitTypes","Object","keys","generateTypeFiles","dirname","generatedDirectory","indexFile","fs","existsSync","mkdirSync","recursive","writeFileSync","readFileSync","key","processPragmas","rawSource","ignorePragma","autogen","loosePragma","autogenStrict","pragma","noPragmas","strictNullability","readOnlyArray","scalars","exportAllObjectTypes"],"mappings":";;;;;;;AAIA;;AACA;;AACA;;;;AALA;AAwBO,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;AACH,KAFD,MAEO;AACH,YAAMI,KAAK,GAAGT,aAAa,CAACU,KAAd,CAAoB,IAApB,EAA0BC,GAA1B,CAA+BC,IAAD,IAAU;AAClD,YAAIA,IAAI,CAACC,QAAL,CAAc,OAAOP,cAAKC,QAAL,CAAcJ,QAAd,CAArB,CAAJ,EAAmD;AAC/C,iBAAOE,OAAP;AACH;;AACD,eAAOO,IAAP;AACH,OALa,CAAd;AAMAZ,MAAAA,aAAa,GAAGS,KAAK,CAACK,IAAN,CAAW,IAAX,CAAhB;AACH;AACJ,GAfD;;AAiBA,QAAMC,SAAS,GAAG,2BAAoBl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,MAAI3C,OAAO,CAAC4C,YAAR,IAAwBD,SAAS,CAAC5B,QAAV,CAAmBf,OAAO,CAAC4C,YAA3B,CAA5B,EAAsE;AAClE,WAAO,IAAP;AACH;;AAED,QAAMC,OAAO,GAAG7C,OAAO,CAAC8C,WAAR,GACVH,SAAS,CAAC5B,QAAV,CAAmBf,OAAO,CAAC8C,WAA3B,CADU,GAEV,KAFN;AAGA,QAAMC,aAAa,GAAG/C,OAAO,CAACgD,MAAR,GAChBL,SAAS,CAAC5B,QAAV,CAAmBf,OAAO,CAACgD,MAA3B,CADgB,GAEhB,KAFN;AAGA,QAAMC,SAAS,GAAG,CAACjD,OAAO,CAAC8C,WAAT,IAAwB,CAAC9C,OAAO,CAACgD,MAAnD;;AAEA,MAAIH,OAAO,IAAIE,aAAX,IAA4BE,SAAhC,EAA2C;AACvC,WAAO;AACHtD,MAAAA,iBAAiB,EAAEK,OAAO,CAACL,iBADxB;AAEHuD,MAAAA,iBAAiB,EAAED,SAAS,GACtBjD,OAAO,CAACkD,iBADc,GAEtBH,aAAa,IAAI,CAACF,OAJrB;AAKHM,MAAAA,aAAa,EAAEnD,OAAO,CAACmD,aALpB;AAMHC,MAAAA,OAAO,EAAEpD,OAAO,CAACoD,OANd;AAOHxB,MAAAA,UAAU,EAAE5B,OAAO,CAAC4B,UAPjB;AAQHK,MAAAA,kBAAkB,EAAEjC,OAAO,CAACiC,kBARzB;AASHoB,MAAAA,oBAAoB,EAAErD,OAAO,CAACqD,oBAT3B;AAUH7B,MAAAA,YAAY,EAAExB,OAAO,CAACwB;AAVnB,KAAP;AAYH,GAbD,MAaO;AACH,WAAO,IAAP;AACH;AACJ,CAhCM","sourcesContent":["// @flow\n// Import this in your jest setup, to mock out graphql-tag!\nimport type {DocumentNode} from 'graphql';\nimport type {Options, Schema, Scalars} from './types';\nimport fs from 'fs';\nimport path from 'path';\nimport {documentToFlowTypes} from '.';\n\nexport type ExternalOptions = {\n pragma?: string,\n loosePragma?: string,\n ignorePragma?: string,\n scalars?: Scalars,\n strictNullability?: boolean,\n /**\n * The command that users should run to regenerate the types files.\n */\n regenerateCommand?: string,\n readOnlyArray?: boolean,\n splitTypes?: boolean,\n generatedDirectory?: string,\n exportAllObjectTypes?: boolean,\n typeFileName?: string,\n};\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: Options,\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(({name, typeName, code, isFragment, extraTypes}) => {\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((name) => {\n fileContents += `\\n\\nexport type ${name} = ${extraTypes[name]};`;\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 return {files, indexContents};\n};\n\nexport const generateTypeFiles = (\n fileName: string,\n schema: Schema,\n document: DocumentNode,\n options: Options,\n) => {\n const generatedDir = path.join(\n path.dirname(fileName),\n options.generatedDirectory ?? '__generated__',\n );\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 options: ExternalOptions,\n rawSource: string,\n): null | Options => {\n if (options.ignorePragma && rawSource.includes(options.ignorePragma)) {\n return null;\n }\n\n const autogen = options.loosePragma\n ? rawSource.includes(options.loosePragma)\n : false;\n const autogenStrict = options.pragma\n ? rawSource.includes(options.pragma)\n : false;\n const noPragmas = !options.loosePragma && !options.pragma;\n\n if (autogen || autogenStrict || noPragmas) {\n return {\n regenerateCommand: options.regenerateCommand,\n strictNullability: noPragmas\n ? options.strictNullability\n : autogenStrict || !autogen,\n readOnlyArray: options.readOnlyArray,\n scalars: options.scalars,\n splitTypes: options.splitTypes,\n generatedDirectory: options.generatedDirectory,\n exportAllObjectTypes: options.exportAllObjectTypes,\n typeFileName: options.typeFileName,\n };\n } else {\n return null;\n }\n};\n"],"file":"generateTypeFiles.js"}
|
package/dist/index.js
CHANGED
|
@@ -33,10 +33,12 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
|
|
|
33
33
|
*/
|
|
34
34
|
// eslint-disable-line flowtype-errors/uncovered
|
|
35
35
|
const optionsToConfig = (schema, definitions, options, errors = []) => {
|
|
36
|
+
var _options$strictNullab, _options$readOnlyArra, _options$scalars;
|
|
37
|
+
|
|
36
38
|
const internalOptions = {
|
|
37
|
-
strictNullability: (options === null || options === void 0 ? void 0 : options.strictNullability)
|
|
38
|
-
readOnlyArray: (options === null || options === void 0 ? void 0 : options.readOnlyArray)
|
|
39
|
-
scalars: (options === null || options === void 0 ? void 0 : options.scalars)
|
|
39
|
+
strictNullability: (_options$strictNullab = options === null || options === void 0 ? void 0 : options.strictNullability) !== null && _options$strictNullab !== void 0 ? _options$strictNullab : true,
|
|
40
|
+
readOnlyArray: (_options$readOnlyArra = options === null || options === void 0 ? void 0 : options.readOnlyArray) !== null && _options$readOnlyArra !== void 0 ? _options$readOnlyArra : true,
|
|
41
|
+
scalars: (_options$scalars = options === null || options === void 0 ? void 0 : options.scalars) !== null && _options$scalars !== void 0 ? _options$scalars : {}
|
|
40
42
|
};
|
|
41
43
|
const fragments = {};
|
|
42
44
|
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","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","Object","keys","k","typeName","isFragment","operation","response","variables","filter","Boolean","length"],"mappings":";;;;;;;;;;;;;AAWA;;AACA;;AAIA;;AACA;;;;AAjBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKX;AACT,QAAMC,eAAe,GAAG;AACpBC,IAAAA,iBAAiB,
|
|
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","FlowGenerationError","Error","constructor","join","messages","documentToFlowTypes","document","result","map","item","types","code","exportAllObjectTypes","extraTypes","Object","keys","k","typeName","isFragment","operation","response","variables","filter","Boolean","length"],"mappings":";;;;;;;;;;;;;AAWA;;AACA;;AAIA;;AACA;;;;AAjBA;;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AAGyC;AAUzC,MAAMA,eAAe,GAAG,CACpBC,MADoB,EAEpBC,WAFoB,EAGpBC,OAHoB,EAIpBC,MAAqB,GAAG,EAJJ,KAKX;AAAA;;AACT,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,IAAAA,cAAc,EAAE,IAJL;AAKXC,IAAAA,IAAI,EAAE,EALK;AAMX,OAAGZ;AANQ,GAAf;AASA,SAAOU,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vB,OAAP;AACH;AACJ,GA5DU,EA6DVS,MA7DU,CA6DHC,OA7DG,CAAf;;AA8DA,MAAIrC,MAAM,CAACsC,MAAX,EAAmB;AACf,UAAM,IAAIxB,mBAAJ,CAAwBd,MAAxB,CAAN;AACH;;AACD,SAAOqB,MAAP;AACH,CApFM","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';\nexport {spyOnGraphqlTagToCollectQueries} from './jest-mock-graphql-tag';\n\nimport type {Config, Options, Schema} from './types';\n\nconst optionsToConfig = (\n schema: Schema,\n definitions: $ReadOnlyArray<DefinitionNode>,\n options?: Options,\n errors: Array<string> = [],\n): Config => {\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 ...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?: Options,\n): $ReadOnlyArray<{\n name: string,\n typeName: string,\n code: string,\n isFragment?: boolean,\n extraTypes: {[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 const extraTypes: {[key: string]: string} = {};\n Object.keys(types).forEach((k) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return {\n name,\n typeName: name,\n code,\n isFragment: true,\n extraTypes,\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: {[key: string]: string} = {};\n Object.keys(types).forEach((k) => {\n // eslint-disable-next-line flowtype-errors/uncovered\n extraTypes[k] = generate(types[k]).code;\n });\n return {name, typeName, code, extraTypes};\n }\n })\n .filter(Boolean);\n if (errors.length) {\n throw new FlowGenerationError(errors);\n }\n return result;\n};\n"],"file":"index.js"}
|
package/dist/parser/parse.js
CHANGED
|
@@ -99,16 +99,16 @@ const processFile = (filePath, contents) => {
|
|
|
99
99
|
const importPath = source.value.startsWith('.') ? _path.default.resolve(_path.default.join(dir, source.value)) : source.value;
|
|
100
100
|
(_toplevel$specifiers = toplevel.specifiers) === null || _toplevel$specifiers === void 0 ? void 0 : _toplevel$specifiers.forEach(spec => {
|
|
101
101
|
if (spec.type === 'ExportSpecifier' && spec.exported.type === 'Identifier') {
|
|
102
|
-
var _spec$loc;
|
|
102
|
+
var _spec$start, _spec$end, _spec$loc$start$line, _spec$loc;
|
|
103
103
|
|
|
104
104
|
result.exports[spec.exported.name] = {
|
|
105
105
|
type: 'import',
|
|
106
106
|
name: spec.local.name,
|
|
107
107
|
path: importPath,
|
|
108
108
|
loc: {
|
|
109
|
-
start: spec.start
|
|
110
|
-
end: spec.end
|
|
111
|
-
line: ((_spec$loc = spec.loc) === null || _spec$loc === void 0 ? void 0 : _spec$loc.start.line)
|
|
109
|
+
start: (_spec$start = spec.start) !== null && _spec$start !== void 0 ? _spec$start : -1,
|
|
110
|
+
end: (_spec$end = spec.end) !== null && _spec$end !== void 0 ? _spec$end : -1,
|
|
111
|
+
line: (_spec$loc$start$line = (_spec$loc = spec.loc) === null || _spec$loc === void 0 ? void 0 : _spec$loc.start.line) !== null && _spec$loc$start$line !== void 0 ? _spec$loc$start$line : -1,
|
|
112
112
|
path: filePath
|
|
113
113
|
}
|
|
114
114
|
};
|
|
@@ -144,17 +144,21 @@ const processFile = (filePath, contents) => {
|
|
|
144
144
|
const tpl = processTemplate(init, result);
|
|
145
145
|
|
|
146
146
|
if (tpl) {
|
|
147
|
+
var _init$start;
|
|
148
|
+
|
|
147
149
|
const document = result.locals[id] = {
|
|
148
150
|
type: 'document',
|
|
149
151
|
source: tpl
|
|
150
152
|
};
|
|
151
|
-
seenTemplates[init.start
|
|
153
|
+
seenTemplates[(_init$start = init.start) !== null && _init$start !== void 0 ? _init$start : -1] = document;
|
|
152
154
|
|
|
153
155
|
if (isExported) {
|
|
154
156
|
result.exports[id] = document;
|
|
155
157
|
}
|
|
156
158
|
} else {
|
|
157
|
-
|
|
159
|
+
var _init$start2;
|
|
160
|
+
|
|
161
|
+
seenTemplates[(_init$start2 = init.start) !== null && _init$start2 !== void 0 ? _init$start2 : -1] = false;
|
|
158
162
|
}
|
|
159
163
|
}
|
|
160
164
|
}
|
|
@@ -182,7 +186,9 @@ const processFile = (filePath, contents) => {
|
|
|
182
186
|
});
|
|
183
187
|
|
|
184
188
|
const visitTpl = (node, getBinding) => {
|
|
185
|
-
|
|
189
|
+
var _node$start;
|
|
190
|
+
|
|
191
|
+
if (seenTemplates[(_node$start = node.start) !== null && _node$start !== void 0 ? _node$start : -1] != null) {
|
|
186
192
|
return;
|
|
187
193
|
}
|
|
188
194
|
|
|
@@ -193,7 +199,9 @@ const processFile = (filePath, contents) => {
|
|
|
193
199
|
const tpl = processTemplate(node, result, getBinding);
|
|
194
200
|
|
|
195
201
|
if (tpl) {
|
|
196
|
-
|
|
202
|
+
var _node$start2;
|
|
203
|
+
|
|
204
|
+
seenTemplates[(_node$start2 = node.start) !== null && _node$start2 !== void 0 ? _node$start2 : -1] = {
|
|
197
205
|
type: 'document',
|
|
198
206
|
source: tpl
|
|
199
207
|
};
|
|
@@ -201,7 +209,9 @@ const processFile = (filePath, contents) => {
|
|
|
201
209
|
source: tpl
|
|
202
210
|
});
|
|
203
211
|
} else {
|
|
204
|
-
|
|
212
|
+
var _node$start3;
|
|
213
|
+
|
|
214
|
+
seenTemplates[(_node$start3 = node.start) !== null && _node$start3 !== void 0 ? _node$start3 : -1] = false;
|
|
205
215
|
}
|
|
206
216
|
};
|
|
207
217
|
/* eslint-disable flowtype-errors/uncovered */
|
|
@@ -232,17 +242,17 @@ exports.processFile = processFile;
|
|
|
232
242
|
const processTemplate = (tpl, result, getTemplate // getBinding?: (name: string) => Binding,
|
|
233
243
|
// seenTemplates,
|
|
234
244
|
) => {
|
|
235
|
-
var _tpl$loc;
|
|
245
|
+
var _tpl$loc$start$line, _tpl$loc, _tpl$start, _tpl$end;
|
|
236
246
|
|
|
237
247
|
// 'cooked' is the string as runtime javascript will see it.
|
|
238
248
|
const literals = tpl.quasi.quasis.map(q => q.value.cooked || '');
|
|
239
249
|
const expressions = tpl.quasi.expressions.map(expr => {
|
|
240
|
-
var _expr$loc;
|
|
250
|
+
var _expr$start, _expr$end, _expr$loc$start$line, _expr$loc;
|
|
241
251
|
|
|
242
252
|
const loc = {
|
|
243
|
-
start: expr.start
|
|
244
|
-
end: expr.end
|
|
245
|
-
line: ((_expr$loc = expr.loc) === null || _expr$loc === void 0 ? void 0 : _expr$loc.start.line)
|
|
253
|
+
start: (_expr$start = expr.start) !== null && _expr$start !== void 0 ? _expr$start : -1,
|
|
254
|
+
end: (_expr$end = expr.end) !== null && _expr$end !== void 0 ? _expr$end : -1,
|
|
255
|
+
line: (_expr$loc$start$line = (_expr$loc = expr.loc) === null || _expr$loc === void 0 ? void 0 : _expr$loc.start.line) !== null && _expr$loc$start$line !== void 0 ? _expr$loc$start$line : -1,
|
|
246
256
|
path: result.path
|
|
247
257
|
};
|
|
248
258
|
|
|
@@ -279,9 +289,9 @@ const processTemplate = (tpl, result, getTemplate // getBinding?: (name: string)
|
|
|
279
289
|
literals,
|
|
280
290
|
expressions: expressions.filter(Boolean),
|
|
281
291
|
loc: {
|
|
282
|
-
line: ((_tpl$loc = tpl.loc) === null || _tpl$loc === void 0 ? void 0 : _tpl$loc.start.line)
|
|
283
|
-
start: tpl.start
|
|
284
|
-
end: tpl.end
|
|
292
|
+
line: (_tpl$loc$start$line = (_tpl$loc = tpl.loc) === null || _tpl$loc === void 0 ? void 0 : _tpl$loc.start.line) !== null && _tpl$loc$start$line !== void 0 ? _tpl$loc$start$line : -1,
|
|
293
|
+
start: (_tpl$start = tpl.start) !== null && _tpl$start !== void 0 ? _tpl$start : -1,
|
|
294
|
+
end: (_tpl$end = tpl.end) !== null && _tpl$end !== void 0 ? _tpl$end : -1,
|
|
285
295
|
path: result.path
|
|
286
296
|
}
|
|
287
297
|
};
|
package/dist/parser/parse.js.map
CHANGED
|
@@ -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,EAEC;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AyB;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","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,CA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AA,GAAG,EAAEJ,IAAI,CAACI,GAA9B;AAAmC5C,UAAAA,IAAI,EAAE2E;AAAzC;AAPiB,OAA1B;AASH;AACJ,GAnBD;AAoBA,SAAOlE,MAAP;AACH,CAjCD;;AAmCO,MAAMqE,YAAY,GAAG,CACxBC,SADwB,EAExBC,aAFwB,KAGhB;AACR,QAAMC,KAAY,GAAG,EAArB;AACA,QAAMC,SAAS,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"}
|
package/dist/types.js.flow
CHANGED
package/package.json
CHANGED
|
@@ -58,4 +58,46 @@ describe('generateTypeFileContents', () => {
|
|
|
58
58
|
"
|
|
59
59
|
`);
|
|
60
60
|
});
|
|
61
|
+
|
|
62
|
+
it('should respect the typeFileName option', () => {
|
|
63
|
+
const {files} = generateTypeFileContents(
|
|
64
|
+
'hello.js',
|
|
65
|
+
exampleSchema,
|
|
66
|
+
gql`
|
|
67
|
+
query Hello {
|
|
68
|
+
human(id: "Han") {
|
|
69
|
+
id
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
`,
|
|
73
|
+
{
|
|
74
|
+
splitTypes: true,
|
|
75
|
+
typeFileName: 'prefix-[operationName]-suffix.js',
|
|
76
|
+
},
|
|
77
|
+
'__generated__',
|
|
78
|
+
indexPrelude('yarn queries'),
|
|
79
|
+
);
|
|
80
|
+
expect(
|
|
81
|
+
Object.keys(files)
|
|
82
|
+
.map((k) => `// ${k}\n${files[k]}`)
|
|
83
|
+
.join('\n\n'),
|
|
84
|
+
).toMatchInlineSnapshot(`
|
|
85
|
+
"// __generated__/prefix-Hello-suffix.js
|
|
86
|
+
// @flow
|
|
87
|
+
// AUTOGENERATED -- DO NOT EDIT
|
|
88
|
+
// Generated for operation 'Hello' in file '../hello.js'
|
|
89
|
+
export type HelloType = {|
|
|
90
|
+
variables: {||},
|
|
91
|
+
response: {|
|
|
92
|
+
/** A human character*/
|
|
93
|
+
human: ?{|
|
|
94
|
+
id: string
|
|
95
|
+
|}
|
|
96
|
+
|}
|
|
97
|
+
|};
|
|
98
|
+
export type Hello = HelloType['response'];
|
|
99
|
+
export type HelloVariables = HelloType['variables'];
|
|
100
|
+
"
|
|
101
|
+
`);
|
|
102
|
+
});
|
|
61
103
|
});
|
package/src/cli/config.js
CHANGED
|
@@ -18,6 +18,7 @@ import path from 'path';
|
|
|
18
18
|
export type CliConfig = {
|
|
19
19
|
excludes: Array<RegExp>,
|
|
20
20
|
schemaFilePath: string,
|
|
21
|
+
dumpOperations?: string,
|
|
21
22
|
options: ExternalOptions,
|
|
22
23
|
};
|
|
23
24
|
|
|
@@ -29,12 +30,18 @@ type JSONConfig = {
|
|
|
29
30
|
excludes?: Array<string>,
|
|
30
31
|
schemaFilePath: string,
|
|
31
32
|
options?: ExternalOptions,
|
|
33
|
+
dumpOperations?: string,
|
|
32
34
|
};
|
|
33
35
|
|
|
34
36
|
export const loadConfigFile = (configFile: string): CliConfig => {
|
|
35
37
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
36
38
|
const data: JSONConfig = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
|
37
|
-
const toplevelKeys = [
|
|
39
|
+
const toplevelKeys = [
|
|
40
|
+
'excludes',
|
|
41
|
+
'schemaFilePath',
|
|
42
|
+
'options',
|
|
43
|
+
'dumpOperations',
|
|
44
|
+
];
|
|
38
45
|
Object.keys(data).forEach((k) => {
|
|
39
46
|
if (!toplevelKeys.includes(k)) {
|
|
40
47
|
throw new Error(
|
|
@@ -56,6 +63,7 @@ export const loadConfigFile = (configFile: string): CliConfig => {
|
|
|
56
63
|
'splitTypes',
|
|
57
64
|
'generatedDirectory',
|
|
58
65
|
'exportAllObjectTypes',
|
|
66
|
+
'typeFileName',
|
|
59
67
|
];
|
|
60
68
|
Object.keys(data.options).forEach((k) => {
|
|
61
69
|
if (!externalOptionsKeys.includes(k)) {
|
|
@@ -74,6 +82,7 @@ export const loadConfigFile = (configFile: string): CliConfig => {
|
|
|
74
82
|
path.dirname(configFile),
|
|
75
83
|
data.schemaFilePath,
|
|
76
84
|
),
|
|
85
|
+
dumpOperations: data.dumpOperations,
|
|
77
86
|
};
|
|
78
87
|
};
|
|
79
88
|
|
package/src/cli/run.js
CHANGED
|
@@ -9,11 +9,12 @@ import {getSchemas, loadConfigFile} from './config';
|
|
|
9
9
|
import {addTypenameToDocument} from 'apollo-utilities'; // eslint-disable-line flowtype-errors/uncovered
|
|
10
10
|
|
|
11
11
|
import {execSync} from 'child_process';
|
|
12
|
-
import {readFileSync} from 'fs';
|
|
12
|
+
import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'fs';
|
|
13
13
|
import {type DocumentNode} from 'graphql';
|
|
14
14
|
import {print} from 'graphql/language/printer';
|
|
15
15
|
import {validate} from 'graphql/validation';
|
|
16
16
|
import path from 'path';
|
|
17
|
+
import {dirname} from 'path';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* This CLI tool executes the following steps:
|
|
@@ -68,7 +69,15 @@ const inputFiles = cliFiles.length
|
|
|
68
69
|
|
|
69
70
|
/** Step (2) */
|
|
70
71
|
|
|
71
|
-
const files = processFiles(inputFiles, (f) =>
|
|
72
|
+
const files = processFiles(inputFiles, (f) => {
|
|
73
|
+
if (existsSync(f)) {
|
|
74
|
+
return readFileSync(f, 'utf8');
|
|
75
|
+
}
|
|
76
|
+
if (existsSync(f + '.js')) {
|
|
77
|
+
return readFileSync(f + '.js', 'utf8');
|
|
78
|
+
}
|
|
79
|
+
throw new Error(`Unable to find ${f}`);
|
|
80
|
+
});
|
|
72
81
|
|
|
73
82
|
let filesHadErrors = false;
|
|
74
83
|
Object.keys(files).forEach((key) => {
|
|
@@ -103,6 +112,7 @@ console.log(Object.keys(resolved).length, 'resolved queries');
|
|
|
103
112
|
/** Step (4) */
|
|
104
113
|
|
|
105
114
|
let validationFailures: number = 0;
|
|
115
|
+
const printedOperations: Array<string> = [];
|
|
106
116
|
|
|
107
117
|
Object.keys(resolved).forEach((k) => {
|
|
108
118
|
const {document, raw} = resolved[k];
|
|
@@ -113,14 +123,18 @@ Object.keys(resolved).forEach((k) => {
|
|
|
113
123
|
({kind}) => kind !== 'FragmentDefinition',
|
|
114
124
|
);
|
|
115
125
|
const rawSource: string = raw.literals[0];
|
|
116
|
-
const processedOptions = processPragmas(config.options, rawSource);
|
|
117
|
-
if (!processedOptions) {
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
126
|
|
|
121
127
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
122
128
|
const withTypeNames: DocumentNode = addTypenameToDocument(document);
|
|
123
129
|
const printed = print(withTypeNames);
|
|
130
|
+
if (hasNonFragments && !printedOperations.includes(printed)) {
|
|
131
|
+
printedOperations.push(printed);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const processedOptions = processPragmas(config.options, rawSource);
|
|
135
|
+
if (!processedOptions) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
124
138
|
|
|
125
139
|
if (hasNonFragments) {
|
|
126
140
|
/* eslint-disable flowtype-errors/uncovered */
|
|
@@ -163,3 +177,13 @@ if (validationFailures) {
|
|
|
163
177
|
// eslint-disable-next-line flowtype-errors/uncovered
|
|
164
178
|
process.exit(1);
|
|
165
179
|
}
|
|
180
|
+
|
|
181
|
+
if (config.dumpOperations) {
|
|
182
|
+
const dumpOperations = config.dumpOperations;
|
|
183
|
+
const parent = dirname(dumpOperations);
|
|
184
|
+
mkdirSync(parent, {recursive: true});
|
|
185
|
+
writeFileSync(
|
|
186
|
+
dumpOperations,
|
|
187
|
+
JSON.stringify(printedOperations.sort(), null, 2),
|
|
188
|
+
);
|
|
189
|
+
}
|
package/src/generateTypeFiles.js
CHANGED
|
@@ -20,6 +20,7 @@ export type ExternalOptions = {
|
|
|
20
20
|
splitTypes?: boolean,
|
|
21
21
|
generatedDirectory?: string,
|
|
22
22
|
exportAllObjectTypes?: boolean,
|
|
23
|
+
typeFileName?: string,
|
|
23
24
|
};
|
|
24
25
|
|
|
25
26
|
export const indexPrelude = (regenerateCommand?: string): string => `// @flow
|
|
@@ -64,7 +65,9 @@ export const generateTypeFileContents = (
|
|
|
64
65
|
generated.forEach(({name, typeName, code, isFragment, extraTypes}) => {
|
|
65
66
|
// We write all generated files to a `__generated__` subdir to keep
|
|
66
67
|
// things tidy.
|
|
67
|
-
const targetFileName =
|
|
68
|
+
const targetFileName = options.typeFileName
|
|
69
|
+
? options.typeFileName.replace('[operationName]', name)
|
|
70
|
+
: `${name}.js`;
|
|
68
71
|
const targetPath = path.join(generatedDir, targetFileName);
|
|
69
72
|
|
|
70
73
|
let fileContents =
|
|
@@ -160,6 +163,7 @@ export const processPragmas = (
|
|
|
160
163
|
splitTypes: options.splitTypes,
|
|
161
164
|
generatedDirectory: options.generatedDirectory,
|
|
162
165
|
exportAllObjectTypes: options.exportAllObjectTypes,
|
|
166
|
+
typeFileName: options.typeFileName,
|
|
163
167
|
};
|
|
164
168
|
} else {
|
|
165
169
|
return null;
|