@khanacademy/graphql-flow 3.1.1 → 3.1.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @khanacademy/graphql-flow
2
2
 
3
+ ## 3.1.3
4
+
5
+ ### Patch Changes
6
+
7
+ - a8be4ea: Fix file extension toggling, improve file writing.
8
+
9
+ ## 3.1.2
10
+
11
+ ### Patch Changes
12
+
13
+ - 09f72b5: Fix handling of input objects with required attributes that have a default value
14
+
3
15
  ## 3.1.1
4
16
 
5
17
  ### Patch Changes
@@ -4,45 +4,31 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.validateOrThrow = exports.loadConfigFile = exports.getSchemas = exports.findApplicableConfig = void 0;
7
-
8
7
  var _schemaFromIntrospectionData = require("../schemaFromIntrospectionData");
9
-
10
8
  var _schema = _interopRequireDefault(require("../../schema.json"));
11
-
12
9
  var _fs = _interopRequireDefault(require("fs"));
13
-
14
10
  var _graphql = require("graphql");
15
-
16
11
  var _jsonschema = require("jsonschema");
17
-
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
-
12
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
20
13
  const validateOrThrow = (value, jsonSchema) => {
21
14
  const result = (0, _jsonschema.validate)(value, jsonSchema);
22
-
23
15
  if (!result.valid) {
24
16
  throw new Error(result.errors.map(error => error.toString()).join("\n"));
25
17
  }
26
18
  };
27
-
28
19
  exports.validateOrThrow = validateOrThrow;
29
-
30
20
  const loadConfigFile = configFile => {
31
21
  const data = require(configFile);
32
-
33
22
  validateOrThrow(data, _schema.default);
34
23
  return data;
35
24
  };
25
+
36
26
  /**
37
27
  * Loads a .json 'introspection query response', or a .graphql schema definition.
38
28
  */
39
-
40
-
41
29
  exports.loadConfigFile = loadConfigFile;
42
-
43
30
  const getSchemas = schemaFilePath => {
44
31
  const raw = _fs.default.readFileSync(schemaFilePath, "utf8");
45
-
46
32
  if (schemaFilePath.endsWith(".graphql")) {
47
33
  const schemaForValidation = (0, _graphql.buildSchema)(raw);
48
34
  const queryResponse = (0, _graphql.graphqlSync)({
@@ -60,33 +46,26 @@ const getSchemas = schemaFilePath => {
60
46
  return [schemaForValidation, schemaForTypeGeneration];
61
47
  }
62
48
  };
49
+
63
50
  /**
64
51
  * Find the first item of the `config.generate` array where both:
65
52
  * - no item of `exclude` matches
66
53
  * - at least one item of `match` matches
67
54
  */
68
-
69
-
70
55
  exports.getSchemas = getSchemas;
71
-
72
56
  const findApplicableConfig = (path, configs) => {
73
57
  if (!Array.isArray(configs)) {
74
58
  configs = [configs];
75
59
  }
76
-
77
60
  return configs.find(config => {
78
61
  var _config$exclude;
79
-
80
62
  if ((_config$exclude = config.exclude) !== null && _config$exclude !== void 0 && _config$exclude.some(exclude => new RegExp(exclude).test(path))) {
81
63
  return false;
82
64
  }
83
-
84
65
  if (!config.match) {
85
66
  return true;
86
67
  }
87
-
88
68
  return config.match.some(matcher => new RegExp(matcher).test(path));
89
69
  });
90
70
  };
91
-
92
71
  exports.findApplicableConfig = findApplicableConfig;
package/dist/cli/run.js CHANGED
@@ -1,34 +1,20 @@
1
1
  #!/usr/bin/env node
2
-
3
2
  /* eslint-disable no-console */
4
3
  "use strict";
5
4
 
6
5
  var _generateTypeFiles = require("../generateTypeFiles");
7
-
8
6
  var _parse = require("../parser/parse");
9
-
10
7
  var _resolve = require("../parser/resolve");
11
-
12
8
  var _utils = require("../parser/utils");
13
-
14
9
  var _config = require("./config");
15
-
16
10
  var _apolloUtilities = require("apollo-utilities");
17
-
18
11
  var _child_process = require("child_process");
19
-
20
12
  var _fs = require("fs");
21
-
22
13
  var _printer = require("graphql/language/printer");
23
-
24
14
  var _validation = require("graphql/validation");
25
-
26
15
  var _path = _interopRequireWildcard(require("path"));
27
-
28
- 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); }
29
-
30
- 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; }
31
-
16
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
17
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
32
18
  /**
33
19
  * This CLI tool executes the following steps:
34
20
  * 1) parse & validate config file
@@ -39,7 +25,6 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj &&
39
25
  * the DocumentNodes.
40
26
  * 4) generate types for all resolved Queries & Mutations
41
27
  */
42
-
43
28
  /** Step (1) */
44
29
  const findGraphqlTagReferences = root => {
45
30
  // NOTE(john): We want to include untracked files here so that we can
@@ -51,32 +36,30 @@ const findGraphqlTagReferences = root => {
51
36
  });
52
37
  return response.trim().split("\n").map(relative => _path.default.join(root, relative));
53
38
  };
54
-
55
39
  const [_, __, configFilePath, ...cliFiles] = process.argv;
56
-
57
40
  if (configFilePath === "-h" || configFilePath === "--help" || configFilePath === "help" || !configFilePath) {
58
41
  console.log(`graphql-flow
59
42
 
60
43
  Usage: graphql-flow [configFile.json] [filesToCrawl...]`);
61
44
  process.exit(1);
62
45
  }
63
-
64
46
  const makeAbsPath = (maybeRelativePath, basePath) => {
65
47
  return _path.default.isAbsolute(maybeRelativePath) ? maybeRelativePath : _path.default.join(basePath, maybeRelativePath);
66
48
  };
67
-
68
49
  const absConfigPath = makeAbsPath(configFilePath, process.cwd());
69
50
  const config = (0, _config.loadConfigFile)(absConfigPath);
70
51
  const inputFiles = cliFiles.length ? cliFiles : findGraphqlTagReferences(makeAbsPath(config.crawl.root, _path.default.dirname(absConfigPath)));
52
+
71
53
  /** Step (2) */
72
54
 
73
55
  const files = (0, _parse.processFiles)(inputFiles, config, f => {
74
56
  const resolvedPath = (0, _utils.getPathWithExtension)(f, config);
75
-
76
57
  if (!resolvedPath) {
77
58
  throw new Error(`Unable to find ${f}`);
78
59
  }
79
-
60
+ if (!(0, _fs.existsSync)(resolvedPath)) {
61
+ return null;
62
+ }
80
63
  return {
81
64
  text: (0, _fs.readFileSync)(resolvedPath, "utf8"),
82
65
  resolvedPath
@@ -85,7 +68,6 @@ const files = (0, _parse.processFiles)(inputFiles, config, f => {
85
68
  let filesHadErrors = false;
86
69
  Object.keys(files).forEach(key => {
87
70
  const file = files[key];
88
-
89
71
  if (file.errors.length) {
90
72
  filesHadErrors = true;
91
73
  console.error(`Errors in ${file.path}`);
@@ -94,19 +76,17 @@ Object.keys(files).forEach(key => {
94
76
  });
95
77
  }
96
78
  });
97
-
98
79
  if (filesHadErrors) {
99
80
  console.error("Aborting");
100
81
  process.exit(1);
101
82
  }
102
- /** Step (3) */
103
83
 
84
+ /** Step (3) */
104
85
 
105
86
  const {
106
87
  resolved,
107
88
  errors
108
89
  } = (0, _resolve.resolveDocuments)(files, config);
109
-
110
90
  if (errors.length) {
111
91
  errors.forEach(error => {
112
92
  console.error(`Resolution error ${error.message} in ${error.loc.path}`);
@@ -114,22 +94,20 @@ if (errors.length) {
114
94
  console.error("Aborting");
115
95
  process.exit(1);
116
96
  }
117
-
118
97
  console.log(Object.keys(resolved).length, "resolved queries");
98
+
119
99
  /** Step (4) */
120
100
 
121
101
  const schemaCache = {};
122
-
123
102
  const getCachedSchemas = schemaFilePath => {
124
103
  if (!schemaCache[schemaFilePath]) {
125
104
  schemaCache[schemaFilePath] = (0, _config.getSchemas)(makeAbsPath(schemaFilePath, _path.default.dirname(absConfigPath)));
126
105
  }
127
-
128
106
  return schemaCache[schemaFilePath];
129
107
  };
130
-
131
108
  let validationFailures = 0;
132
109
  const printedOperations = [];
110
+ let outputFiles = {};
133
111
  Object.keys(resolved).forEach(filePathAndLine => {
134
112
  const {
135
113
  document,
@@ -139,35 +117,27 @@ Object.keys(resolved).forEach(filePathAndLine => {
139
117
  kind
140
118
  }) => kind !== "FragmentDefinition");
141
119
  const rawSource = raw.literals[0];
142
- const generateConfig = (0, _config.findApplicableConfig)( // strip off the trailing line number, e.g. `:23`
120
+ const generateConfig = (0, _config.findApplicableConfig)(
121
+ // strip off the trailing line number, e.g. `:23`
143
122
  filePathAndLine.split(":")[0], config.generate);
144
-
145
123
  if (!generateConfig) {
146
124
  return; // no generate config matches, bail
147
125
  }
148
-
149
126
  const withTypeNames = (0, _apolloUtilities.addTypenameToDocument)(document);
150
127
  const printed = (0, _printer.print)(withTypeNames);
151
-
152
128
  if (hasNonFragments && !printedOperations.includes(printed)) {
153
129
  printedOperations.push(printed);
154
130
  }
155
-
156
131
  const pragmaResult = (0, _generateTypeFiles.processPragmas)(generateConfig, config.crawl, rawSource);
157
-
158
132
  if (!pragmaResult.generate) {
159
133
  return;
160
134
  }
161
-
162
135
  if (pragmaResult.strict != null) {
163
136
  generateConfig.strictNullability = pragmaResult.strict;
164
137
  }
165
-
166
138
  const [schemaForValidation, schemaForTypeGeneration] = getCachedSchemas(generateConfig.schemaFilePath);
167
-
168
139
  if (hasNonFragments) {
169
140
  const errors = (0, _validation.validate)(schemaForValidation, withTypeNames);
170
-
171
141
  if (errors.length) {
172
142
  errors.forEach(error => {
173
143
  console.error(`Schema validation found errors for ${raw.loc.path}!`);
@@ -177,9 +147,8 @@ Object.keys(resolved).forEach(filePathAndLine => {
177
147
  });
178
148
  }
179
149
  }
180
-
181
150
  try {
182
- (0, _generateTypeFiles.generateTypeFiles)(raw.loc.path, schemaForTypeGeneration, withTypeNames, generateConfig);
151
+ outputFiles = (0, _generateTypeFiles.generateTypeFiles)(raw.loc.path, schemaForTypeGeneration, withTypeNames, generateConfig, outputFiles);
183
152
  } catch (err) {
184
153
  console.error(`Error while generating operation from ${raw.loc.path}`);
185
154
  console.error(printed);
@@ -188,11 +157,15 @@ Object.keys(resolved).forEach(filePathAndLine => {
188
157
  }
189
158
  });
190
159
 
160
+ /** Step (5) */
161
+
162
+ for (const [fname, content] of Object.entries(outputFiles)) {
163
+ (0, _fs.writeFileSync)(fname, content, "utf8");
164
+ }
191
165
  if (validationFailures) {
192
166
  console.error(`Encountered ${validationFailures} validation failures while printing types.`);
193
167
  process.exit(1);
194
168
  }
195
-
196
169
  if (config.crawl.dumpOperations) {
197
170
  const dumpOperations = config.crawl.dumpOperations;
198
171
  const parent = (0, _path.dirname)(dumpOperations);
package/dist/enums.js CHANGED
@@ -4,44 +4,34 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.scalarTypeToFlow = exports.experimentalEnumTypeToFlow = exports.enumTypeToFlow = exports.builtinScalars = void 0;
7
-
8
7
  var babelTypes = _interopRequireWildcard(require("@babel/types"));
9
-
10
8
  var _utils = require("./utils");
11
-
12
- 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); }
13
-
14
- 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; }
15
-
9
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
10
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
16
11
  /**
17
12
  * Both input & output types can have enums & scalars.
18
13
  */
14
+
19
15
  const experimentalEnumTypeToFlow = (ctx, enumConfig, description) => {
20
- const enumDeclaration = babelTypes.tsEnumDeclaration( // pass id into generic type annotation
16
+ const enumDeclaration = babelTypes.tsEnumDeclaration(
17
+ // pass id into generic type annotation
21
18
  babelTypes.identifier(enumConfig.name), enumConfig.enumValues.map(v => babelTypes.tsEnumMember(babelTypes.identifier(v.name), babelTypes.stringLiteral(v.name))));
22
-
23
19
  if (ctx.experimentalEnumsMap) {
24
20
  ctx.experimentalEnumsMap[enumConfig.name] = enumDeclaration;
25
21
  }
26
-
27
22
  return (0, _utils.maybeAddDescriptionComment)(description, babelTypes.tsTypeReference(enumDeclaration.id));
28
23
  };
29
-
30
24
  exports.experimentalEnumTypeToFlow = experimentalEnumTypeToFlow;
31
-
32
25
  const enumTypeToFlow = (ctx, name) => {
33
26
  const enumConfig = ctx.schema.enumsByName[name];
34
27
  let combinedDescription = enumConfig.enumValues.map(n => `- ${n.name}` + (n.description ? "\n\n " + n.description.replace(/\n/g, "\n ") : "")).join("\n");
35
-
36
28
  if (enumConfig.description) {
37
29
  combinedDescription = enumConfig.description + "\n\n" + combinedDescription;
38
30
  }
39
-
40
31
  return ctx.experimentalEnumsMap ? experimentalEnumTypeToFlow(ctx, enumConfig, combinedDescription) : (0, _utils.maybeAddDescriptionComment)(combinedDescription, babelTypes.tsUnionType(enumConfig.enumValues.map(n => babelTypes.tsLiteralType(babelTypes.stringLiteral(n.name)))));
41
32
  };
42
-
43
33
  exports.enumTypeToFlow = enumTypeToFlow;
44
- const builtinScalars = {
34
+ const builtinScalars = exports.builtinScalars = {
45
35
  Boolean: "boolean",
46
36
  String: "string",
47
37
  DateTime: "string",
@@ -50,21 +40,15 @@ const builtinScalars = {
50
40
  Int: "number",
51
41
  Float: "number"
52
42
  };
53
- exports.builtinScalars = builtinScalars;
54
-
55
43
  const scalarTypeToFlow = (ctx, name) => {
56
44
  if (builtinScalars[name]) {
57
45
  return babelTypes.tsTypeReference(babelTypes.identifier(builtinScalars[name]));
58
46
  }
59
-
60
47
  const underlyingType = ctx.scalars[name];
61
-
62
48
  if (underlyingType != null) {
63
49
  return babelTypes.tsTypeReference(babelTypes.identifier(underlyingType));
64
50
  }
65
-
66
51
  ctx.errors.push(`Unexpected scalar '${name}'! Please add it to the "scalars" argument at the callsite of 'generateFlowTypes()'.`);
67
52
  return babelTypes.tsTypeReference(babelTypes.identifier(`UNKNOWN_SCALAR["${name}"]`));
68
53
  };
69
-
70
54
  exports.scalarTypeToFlow = scalarTypeToFlow;