relay-compiler 0.0.0-main-4d287de9 → 0.0.0-main-9a79039d

Sign up to get free protection for your applications and to get access to all the features.
Files changed (259) hide show
  1. package/cli.js +23 -0
  2. package/index.js +19 -3
  3. package/linux-x64/relay +0 -0
  4. package/macos-x64/relay +0 -0
  5. package/package.json +2 -26
  6. package/win-x64/relay.exe +0 -0
  7. package/bin/RelayCompilerBin.js.flow +0 -168
  8. package/bin/RelayCompilerMain.js.flow +0 -513
  9. package/bin/__fixtures__/plugin-module.js.flow +0 -17
  10. package/bin/relay-compiler +0 -19066
  11. package/codegen/CodegenDirectory.js.flow +0 -372
  12. package/codegen/CodegenRunner.js.flow +0 -424
  13. package/codegen/CodegenTypes.js.flow +0 -28
  14. package/codegen/CodegenWatcher.js.flow +0 -250
  15. package/codegen/NormalizationCodeGenerator.js.flow +0 -565
  16. package/codegen/ReaderCodeGenerator.js.flow +0 -510
  17. package/codegen/RelayCodeGenerator.js.flow +0 -85
  18. package/codegen/RelayFileWriter.js.flow +0 -365
  19. package/codegen/SourceControl.js.flow +0 -58
  20. package/codegen/compileRelayArtifacts.js.flow +0 -181
  21. package/codegen/createPrintRequireModuleDependency.js.flow +0 -19
  22. package/codegen/sortObjectByKey.js.flow +0 -25
  23. package/codegen/writeRelayGeneratedFile.js.flow +0 -235
  24. package/core/ASTCache.js.flow +0 -73
  25. package/core/ASTConvert.js.flow +0 -230
  26. package/core/CompilerContext.js.flow +0 -189
  27. package/core/CompilerError.js.flow +0 -255
  28. package/core/DotGraphQLParser.js.flow +0 -37
  29. package/core/GraphQLCompilerProfiler.js.flow +0 -341
  30. package/core/GraphQLDerivedFromMetadata.js.flow +0 -36
  31. package/core/GraphQLWatchmanClient.js.flow +0 -109
  32. package/core/IR.js.flow +0 -326
  33. package/core/IRPrinter.js.flow +0 -472
  34. package/core/IRTransformer.js.flow +0 -376
  35. package/core/IRValidator.js.flow +0 -259
  36. package/core/IRVisitor.js.flow +0 -150
  37. package/core/JSModuleParser.js.flow +0 -24
  38. package/core/RelayCompilerScope.js.flow +0 -199
  39. package/core/RelayFindGraphQLTags.js.flow +0 -118
  40. package/core/RelayGraphQLEnumsGenerator.js.flow +0 -55
  41. package/core/RelayIRTransforms.js.flow +0 -138
  42. package/core/RelayParser.js.flow +0 -1731
  43. package/core/RelaySourceModuleParser.js.flow +0 -133
  44. package/core/Schema.js.flow +0 -2035
  45. package/core/SchemaUtils.js.flow +0 -120
  46. package/core/filterContextForNode.js.flow +0 -49
  47. package/core/getFieldDefinition.js.flow +0 -156
  48. package/core/getIdentifierForArgumentValue.js.flow +0 -49
  49. package/core/getIdentifierForSelection.js.flow +0 -68
  50. package/core/getLiteralArgumentValues.js.flow +0 -32
  51. package/core/getNormalizationOperationName.js.flow +0 -19
  52. package/core/inferRootArgumentDefinitions.js.flow +0 -322
  53. package/index.js.flow +0 -198
  54. package/language/RelayLanguagePluginInterface.js.flow +0 -283
  55. package/language/javascript/FindGraphQLTags.js.flow +0 -136
  56. package/language/javascript/RelayFlowBabelFactories.js.flow +0 -176
  57. package/language/javascript/RelayFlowGenerator.js.flow +0 -1096
  58. package/language/javascript/RelayFlowTypeTransformers.js.flow +0 -181
  59. package/language/javascript/RelayLanguagePluginJavaScript.js.flow +0 -33
  60. package/language/javascript/formatGeneratedModule.js.flow +0 -65
  61. package/lib/bin/RelayCompilerBin.js +0 -143
  62. package/lib/bin/RelayCompilerMain.js +0 -486
  63. package/lib/bin/__fixtures__/plugin-module.js +0 -16
  64. package/lib/codegen/CodegenDirectory.js +0 -335
  65. package/lib/codegen/CodegenRunner.js +0 -433
  66. package/lib/codegen/CodegenTypes.js +0 -11
  67. package/lib/codegen/CodegenWatcher.js +0 -271
  68. package/lib/codegen/NormalizationCodeGenerator.js +0 -487
  69. package/lib/codegen/ReaderCodeGenerator.js +0 -473
  70. package/lib/codegen/RelayCodeGenerator.js +0 -75
  71. package/lib/codegen/RelayFileWriter.js +0 -270
  72. package/lib/codegen/SourceControl.js +0 -60
  73. package/lib/codegen/compileRelayArtifacts.js +0 -157
  74. package/lib/codegen/createPrintRequireModuleDependency.js +0 -19
  75. package/lib/codegen/sortObjectByKey.js +0 -41
  76. package/lib/codegen/writeRelayGeneratedFile.js +0 -206
  77. package/lib/core/ASTCache.js +0 -70
  78. package/lib/core/ASTConvert.js +0 -198
  79. package/lib/core/CompilerContext.js +0 -165
  80. package/lib/core/CompilerError.js +0 -252
  81. package/lib/core/DotGraphQLParser.js +0 -40
  82. package/lib/core/GraphQLCompilerProfiler.js +0 -299
  83. package/lib/core/GraphQLDerivedFromMetadata.js +0 -31
  84. package/lib/core/GraphQLWatchmanClient.js +0 -150
  85. package/lib/core/IR.js +0 -11
  86. package/lib/core/IRPrinter.js +0 -388
  87. package/lib/core/IRTransformer.js +0 -345
  88. package/lib/core/IRValidator.js +0 -226
  89. package/lib/core/IRVisitor.js +0 -45
  90. package/lib/core/JSModuleParser.js +0 -18
  91. package/lib/core/RelayCompilerScope.js +0 -183
  92. package/lib/core/RelayFindGraphQLTags.js +0 -79
  93. package/lib/core/RelayGraphQLEnumsGenerator.js +0 -50
  94. package/lib/core/RelayIRTransforms.js +0 -109
  95. package/lib/core/RelayParser.js +0 -1381
  96. package/lib/core/RelaySourceModuleParser.js +0 -104
  97. package/lib/core/Schema.js +0 -1877
  98. package/lib/core/SchemaUtils.js +0 -98
  99. package/lib/core/filterContextForNode.js +0 -50
  100. package/lib/core/getFieldDefinition.js +0 -145
  101. package/lib/core/getIdentifierForArgumentValue.js +0 -54
  102. package/lib/core/getIdentifierForSelection.js +0 -49
  103. package/lib/core/getLiteralArgumentValues.js +0 -26
  104. package/lib/core/getNormalizationOperationName.js +0 -17
  105. package/lib/core/inferRootArgumentDefinitions.js +0 -351
  106. package/lib/index.js +0 -178
  107. package/lib/language/RelayLanguagePluginInterface.js +0 -26
  108. package/lib/language/javascript/FindGraphQLTags.js +0 -126
  109. package/lib/language/javascript/RelayFlowBabelFactories.js +0 -160
  110. package/lib/language/javascript/RelayFlowGenerator.js +0 -856
  111. package/lib/language/javascript/RelayFlowTypeTransformers.js +0 -119
  112. package/lib/language/javascript/RelayLanguagePluginJavaScript.js +0 -30
  113. package/lib/language/javascript/formatGeneratedModule.js +0 -36
  114. package/lib/reporters/ConsoleReporter.js +0 -61
  115. package/lib/reporters/MultiReporter.js +0 -45
  116. package/lib/reporters/Reporter.js +0 -11
  117. package/lib/runner/Artifacts.js +0 -323
  118. package/lib/runner/BufferedFilesystem.js +0 -262
  119. package/lib/runner/GraphQLASTNodeGroup.js +0 -256
  120. package/lib/runner/GraphQLASTUtils.js +0 -23
  121. package/lib/runner/GraphQLNodeMap.js +0 -81
  122. package/lib/runner/Sources.js +0 -271
  123. package/lib/runner/StrictMap.js +0 -134
  124. package/lib/runner/compileArtifacts.js +0 -39
  125. package/lib/runner/extractAST.js +0 -77
  126. package/lib/runner/getChangedNodeNames.js +0 -82
  127. package/lib/runner/getSchemaInstance.js +0 -30
  128. package/lib/runner/types.js +0 -12
  129. package/lib/transforms/ApplyFragmentArgumentTransform.js +0 -393
  130. package/lib/transforms/ClientExtensionsTransform.js +0 -221
  131. package/lib/transforms/ConnectionTransform.js +0 -639
  132. package/lib/transforms/DeclarativeConnectionMutationTransform.js +0 -218
  133. package/lib/transforms/DeferStreamTransform.js +0 -246
  134. package/lib/transforms/DisallowIdAsAlias.js +0 -40
  135. package/lib/transforms/DisallowTypenameOnRoot.js +0 -53
  136. package/lib/transforms/FieldHandleTransform.js +0 -79
  137. package/lib/transforms/FilterCompilerDirectivesTransform.js +0 -29
  138. package/lib/transforms/FilterDirectivesTransform.js +0 -42
  139. package/lib/transforms/FlattenTransform.js +0 -306
  140. package/lib/transforms/GenerateIDFieldTransform.js +0 -135
  141. package/lib/transforms/GenerateTypeNameTransform.js +0 -149
  142. package/lib/transforms/InlineDataFragmentTransform.js +0 -100
  143. package/lib/transforms/InlineFragmentsTransform.js +0 -61
  144. package/lib/transforms/MaskTransform.js +0 -117
  145. package/lib/transforms/MatchTransform.js +0 -434
  146. package/lib/transforms/ReactFlightComponentTransform.js +0 -158
  147. package/lib/transforms/RefetchableFragmentTransform.js +0 -249
  148. package/lib/transforms/RelayDirectiveTransform.js +0 -83
  149. package/lib/transforms/RequiredFieldTransform.js +0 -369
  150. package/lib/transforms/SkipClientExtensionsTransform.js +0 -46
  151. package/lib/transforms/SkipHandleFieldTransform.js +0 -45
  152. package/lib/transforms/SkipRedundantNodesTransform.js +0 -261
  153. package/lib/transforms/SkipSplitOperationTransform.js +0 -32
  154. package/lib/transforms/SkipUnreachableNodeTransform.js +0 -158
  155. package/lib/transforms/SkipUnusedVariablesTransform.js +0 -75
  156. package/lib/transforms/SplitModuleImportTransform.js +0 -82
  157. package/lib/transforms/TestOperationTransform.js +0 -144
  158. package/lib/transforms/TransformUtils.js +0 -21
  159. package/lib/transforms/ValidateGlobalVariablesTransform.js +0 -92
  160. package/lib/transforms/ValidateRequiredArgumentsTransform.js +0 -114
  161. package/lib/transforms/ValidateServerOnlyDirectivesTransform.js +0 -108
  162. package/lib/transforms/ValidateUnusedVariablesTransform.js +0 -96
  163. package/lib/transforms/query-generators/FetchableQueryGenerator.js +0 -157
  164. package/lib/transforms/query-generators/NodeQueryGenerator.js +0 -166
  165. package/lib/transforms/query-generators/QueryQueryGenerator.js +0 -48
  166. package/lib/transforms/query-generators/ViewerQueryGenerator.js +0 -77
  167. package/lib/transforms/query-generators/index.js +0 -60
  168. package/lib/transforms/query-generators/utils.js +0 -92
  169. package/lib/util/CodeMarker.js +0 -80
  170. package/lib/util/DefaultHandleKey.js +0 -15
  171. package/lib/util/RelayCompilerCache.js +0 -97
  172. package/lib/util/Rollout.js +0 -40
  173. package/lib/util/TimeReporter.js +0 -83
  174. package/lib/util/areEqualArgValues.js +0 -135
  175. package/lib/util/argumentContainsVariables.js +0 -37
  176. package/lib/util/dedupeJSONStringify.js +0 -160
  177. package/lib/util/generateAbstractTypeRefinementKey.js +0 -24
  178. package/lib/util/getDefinitionNodeHash.js +0 -22
  179. package/lib/util/getModuleName.js +0 -32
  180. package/lib/util/joinArgumentDefinitions.js +0 -67
  181. package/lib/util/md5.js +0 -17
  182. package/lib/util/murmurHash.js +0 -86
  183. package/lib/util/nullthrowsOSS.js +0 -23
  184. package/lib/util/orList.js +0 -36
  185. package/lib/util/partitionArray.js +0 -35
  186. package/relay-compiler.js +0 -17
  187. package/relay-compiler.min.js +0 -22
  188. package/reporters/ConsoleReporter.js.flow +0 -81
  189. package/reporters/MultiReporter.js.flow +0 -43
  190. package/reporters/Reporter.js.flow +0 -19
  191. package/runner/Artifacts.js.flow +0 -215
  192. package/runner/BufferedFilesystem.js.flow +0 -194
  193. package/runner/GraphQLASTNodeGroup.js.flow +0 -174
  194. package/runner/GraphQLASTUtils.js.flow +0 -26
  195. package/runner/GraphQLNodeMap.js.flow +0 -55
  196. package/runner/Sources.js.flow +0 -227
  197. package/runner/StrictMap.js.flow +0 -96
  198. package/runner/compileArtifacts.js.flow +0 -75
  199. package/runner/extractAST.js.flow +0 -98
  200. package/runner/getChangedNodeNames.js.flow +0 -48
  201. package/runner/getSchemaInstance.js.flow +0 -36
  202. package/runner/types.js.flow +0 -37
  203. package/transforms/ApplyFragmentArgumentTransform.js.flow +0 -524
  204. package/transforms/ClientExtensionsTransform.js.flow +0 -224
  205. package/transforms/ConnectionTransform.js.flow +0 -850
  206. package/transforms/DeclarativeConnectionMutationTransform.js.flow +0 -245
  207. package/transforms/DeferStreamTransform.js.flow +0 -263
  208. package/transforms/DisallowIdAsAlias.js.flow +0 -46
  209. package/transforms/DisallowTypenameOnRoot.js.flow +0 -44
  210. package/transforms/FieldHandleTransform.js.flow +0 -77
  211. package/transforms/FilterCompilerDirectivesTransform.js.flow +0 -33
  212. package/transforms/FilterDirectivesTransform.js.flow +0 -45
  213. package/transforms/FlattenTransform.js.flow +0 -458
  214. package/transforms/GenerateIDFieldTransform.js.flow +0 -151
  215. package/transforms/GenerateTypeNameTransform.js.flow +0 -159
  216. package/transforms/InlineDataFragmentTransform.js.flow +0 -123
  217. package/transforms/InlineFragmentsTransform.js.flow +0 -70
  218. package/transforms/MaskTransform.js.flow +0 -124
  219. package/transforms/MatchTransform.js.flow +0 -587
  220. package/transforms/ReactFlightComponentTransform.js.flow +0 -194
  221. package/transforms/RefetchableFragmentTransform.js.flow +0 -266
  222. package/transforms/RelayDirectiveTransform.js.flow +0 -96
  223. package/transforms/RequiredFieldTransform.js.flow +0 -413
  224. package/transforms/SkipClientExtensionsTransform.js.flow +0 -54
  225. package/transforms/SkipHandleFieldTransform.js.flow +0 -44
  226. package/transforms/SkipRedundantNodesTransform.js.flow +0 -255
  227. package/transforms/SkipSplitOperationTransform.js.flow +0 -37
  228. package/transforms/SkipUnreachableNodeTransform.js.flow +0 -148
  229. package/transforms/SkipUnusedVariablesTransform.js.flow +0 -59
  230. package/transforms/SplitModuleImportTransform.js.flow +0 -97
  231. package/transforms/TestOperationTransform.js.flow +0 -142
  232. package/transforms/TransformUtils.js.flow +0 -26
  233. package/transforms/ValidateGlobalVariablesTransform.js.flow +0 -80
  234. package/transforms/ValidateRequiredArgumentsTransform.js.flow +0 -126
  235. package/transforms/ValidateServerOnlyDirectivesTransform.js.flow +0 -111
  236. package/transforms/ValidateUnusedVariablesTransform.js.flow +0 -88
  237. package/transforms/query-generators/FetchableQueryGenerator.js.flow +0 -188
  238. package/transforms/query-generators/NodeQueryGenerator.js.flow +0 -217
  239. package/transforms/query-generators/QueryQueryGenerator.js.flow +0 -57
  240. package/transforms/query-generators/ViewerQueryGenerator.js.flow +0 -97
  241. package/transforms/query-generators/index.js.flow +0 -89
  242. package/transforms/query-generators/utils.js.flow +0 -76
  243. package/util/CodeMarker.js.flow +0 -79
  244. package/util/DefaultHandleKey.js.flow +0 -17
  245. package/util/RelayCompilerCache.js.flow +0 -86
  246. package/util/Rollout.js.flow +0 -39
  247. package/util/TimeReporter.js.flow +0 -79
  248. package/util/areEqualArgValues.js.flow +0 -126
  249. package/util/argumentContainsVariables.js.flow +0 -38
  250. package/util/dedupeJSONStringify.js.flow +0 -152
  251. package/util/generateAbstractTypeRefinementKey.js.flow +0 -29
  252. package/util/getDefinitionNodeHash.js.flow +0 -24
  253. package/util/getModuleName.js.flow +0 -39
  254. package/util/joinArgumentDefinitions.js.flow +0 -105
  255. package/util/md5.js.flow +0 -19
  256. package/util/murmurHash.js.flow +0 -94
  257. package/util/nullthrowsOSS.js.flow +0 -25
  258. package/util/orList.js.flow +0 -37
  259. package/util/partitionArray.js.flow +0 -37
@@ -1,189 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- import type {Reporter} from '../reporters/Reporter';
16
- import type {Fragment, Location, Root, SplitOperation} from './IR';
17
- import type {Schema} from './Schema';
18
-
19
- const {createUserError} = require('./CompilerError');
20
- const Profiler = require('./GraphQLCompilerProfiler');
21
- // $FlowFixMe[untyped-import] - immutable.js is not flow-typed
22
- const {OrderedMap: ImmutableOrderedMap} = require('immutable');
23
- const invariant = require('invariant');
24
-
25
- export type IRTransform = CompilerContext => CompilerContext;
26
-
27
- export type CompilerContextDocument = Fragment | Root | SplitOperation;
28
-
29
- /**
30
- * An immutable representation of a corpus of documents being compiled together.
31
- * For each document, the context stores the IR and any validation errors.
32
- */
33
- class CompilerContext {
34
- _isMutable: boolean;
35
- // $FlowFixMe[value-as-type]
36
- _documents: ImmutableOrderedMap<string, CompilerContextDocument>;
37
- _withTransform: WeakMap<IRTransform, CompilerContext>;
38
- +_schema: Schema;
39
-
40
- constructor(schema: Schema) {
41
- this._isMutable = false;
42
- this._documents = new ImmutableOrderedMap();
43
- this._withTransform = new WeakMap();
44
- this._schema = schema;
45
- }
46
-
47
- /**
48
- * Returns the documents for the context in the order they were added.
49
- */
50
- documents(): Array<CompilerContextDocument> {
51
- return this._documents.toArray();
52
- }
53
-
54
- forEachDocument(fn: CompilerContextDocument => void): void {
55
- this._documents.forEach(fn);
56
- }
57
-
58
- replace(node: CompilerContextDocument): CompilerContext {
59
- return this._update(
60
- this._documents.update(node.name, existing => {
61
- invariant(
62
- existing,
63
- 'CompilerContext: Expected to replace existing node %s, but ' +
64
- 'one was not found in the context.',
65
- node.name,
66
- );
67
- return node;
68
- }),
69
- );
70
- }
71
-
72
- add(node: CompilerContextDocument): CompilerContext {
73
- return this._update(
74
- this._documents.update(node.name, existing => {
75
- invariant(
76
- !existing,
77
- 'CompilerContext: Duplicate document named `%s`. GraphQL ' +
78
- 'fragments and roots must have unique names.',
79
- node.name,
80
- );
81
- return node;
82
- }),
83
- );
84
- }
85
-
86
- addAll(nodes: $ReadOnlyArray<CompilerContextDocument>): CompilerContext {
87
- return this.withMutations(mutable =>
88
- nodes.reduce((ctx, definition) => ctx.add(definition), mutable),
89
- );
90
- }
91
-
92
- /**
93
- * Apply a list of compiler transforms and return a new compiler context.
94
- */
95
- applyTransforms(
96
- transforms: $ReadOnlyArray<IRTransform>,
97
- reporter?: Reporter,
98
- ): CompilerContext {
99
- return Profiler.run('applyTransforms', () =>
100
- transforms.reduce(
101
- (ctx, transform) => ctx.applyTransform(transform, reporter),
102
- this,
103
- ),
104
- );
105
- }
106
-
107
- /**
108
- * Applies a transform to this context, returning a new context.
109
- *
110
- * This is memoized such that applying the same sequence of transforms will
111
- * not result in duplicated work.
112
- */
113
- applyTransform(transform: IRTransform, reporter?: Reporter): CompilerContext {
114
- let transformed = this._withTransform.get(transform);
115
- if (!transformed) {
116
- const start = process.hrtime();
117
- transformed = Profiler.instrument(transform)(this);
118
- const delta = process.hrtime(start);
119
- const deltaMs = Math.round((delta[0] * 1e9 + delta[1]) / 1e6);
120
- reporter && reporter.reportTime(transform.name, deltaMs);
121
- this._withTransform.set(transform, transformed);
122
- }
123
- return transformed;
124
- }
125
-
126
- get(name: string): ?CompilerContextDocument {
127
- return this._documents.get(name);
128
- }
129
-
130
- getFragment(name: string, referencedFrom?: ?Location): Fragment {
131
- const node = this._documents.get(name);
132
- if (node == null) {
133
- throw createUserError(
134
- `Cannot find fragment '${name}'.`,
135
- referencedFrom != null ? [referencedFrom] : null,
136
- );
137
- } else if (node.kind !== 'Fragment') {
138
- throw createUserError(
139
- `Cannot find fragment '${name}', a document with this name exists ` +
140
- 'but is not a fragment.',
141
- [node.loc, referencedFrom].filter(Boolean),
142
- );
143
- }
144
- return node;
145
- }
146
-
147
- getRoot(name: string): Root {
148
- const node = this._documents.get(name);
149
- if (node == null) {
150
- throw createUserError(`Cannot find root '${name}'.`);
151
- } else if (node.kind !== 'Root') {
152
- throw createUserError(
153
- `Cannot find root '${name}', a document with this name exists but ` +
154
- 'is not a root.',
155
- [node.loc],
156
- );
157
- }
158
- return node;
159
- }
160
-
161
- remove(name: string): CompilerContext {
162
- return this._update(this._documents.delete(name));
163
- }
164
-
165
- withMutations(fn: CompilerContext => CompilerContext): CompilerContext {
166
- const mutableCopy = this._update(this._documents.asMutable());
167
- mutableCopy._isMutable = true;
168
- const result = fn(mutableCopy);
169
- result._isMutable = false;
170
- result._documents = result._documents.asImmutable();
171
- return this._documents === result._documents ? this : result;
172
- }
173
-
174
- _update(
175
- documents: ImmutableOrderedMap<string, CompilerContextDocument>,
176
- ): CompilerContext {
177
- const context = this._isMutable
178
- ? this
179
- : new CompilerContext(this.getSchema());
180
- context._documents = documents;
181
- return context;
182
- }
183
-
184
- getSchema(): Schema {
185
- return this._schema;
186
- }
187
- }
188
-
189
- module.exports = CompilerContext;
@@ -1,255 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- import type {Location} from './IR';
16
- import type {ASTNode, Source, SourceLocation} from 'graphql';
17
-
18
- const {GraphQLError} = require('graphql');
19
-
20
- // Combined results of multiple user errors
21
- export opaque type CombinedUserError: Error = Error;
22
-
23
- // Error describing invalid application code from which the compiler
24
- // can recover, ie which does not prevent processing of other inputs.
25
- export opaque type UserError: Error = GraphQLError;
26
-
27
- // Error describing invalid application code from which the compiler
28
- // *cannot* recover, ie where the validity of subsequent inputs cannot
29
- // be determined. Try to avoid these errors.
30
- export opaque type NonRecoverableUserError: Error = Error;
31
-
32
- // Error describing a bug in the compiler
33
- export opaque type CompilerError: Error = Error;
34
-
35
- /**
36
- * Creates an error describing invalid application code (GraphQL/Schema)
37
- * that must be fixed by the end developer. This should only be used
38
- * for local errors that don't affect processing of other user code.
39
- */
40
- function createUserError(
41
- message: string,
42
- locations?: ?$ReadOnlyArray<Location>,
43
- nodes?: ?$ReadOnlyArray<ASTNode>,
44
- ): UserError {
45
- let messageWithLocations = message;
46
- if (locations != null) {
47
- const printedLocations = printLocations(locations);
48
- messageWithLocations =
49
- printedLocations.length === 0
50
- ? message
51
- : [message, ...printedLocations].join('\n\n') + '\n';
52
- }
53
- return new GraphQLError(messageWithLocations, nodes ?? []);
54
- }
55
-
56
- /**
57
- * Similar to createUserError but for errors that are *not* recoverable:
58
- * the compiler should not continue to process other inputs because their
59
- * validity can't be determined.
60
- */
61
- function createNonRecoverableUserError(
62
- message: string,
63
- locations?: ?$ReadOnlyArray<Location>,
64
- nodes?: ?$ReadOnlyArray<ASTNode>,
65
- ): NonRecoverableUserError {
66
- let messageWithLocations = message;
67
- if (locations != null) {
68
- const printedLocations = printLocations(locations);
69
- messageWithLocations =
70
- printedLocations.length === 0
71
- ? message
72
- : [message, ...printedLocations].join('\n\n') + '\n';
73
- }
74
- const error = new GraphQLError(messageWithLocations, nodes ?? []);
75
- return new Error(error.message);
76
- }
77
-
78
- /**
79
- * Creates an error describing a problem with the compiler itself - such
80
- * as a broken invariant - that must be fixed within the compiler.
81
- */
82
- function createCompilerError(
83
- message: string,
84
- locations?: ?$ReadOnlyArray<Location>,
85
- nodes?: ?$ReadOnlyArray<ASTNode>,
86
- ): CompilerError {
87
- let messageWithLocations = message;
88
- if (locations != null) {
89
- const printedLocations = printLocations(locations);
90
- messageWithLocations =
91
- printedLocations.length === 0
92
- ? message
93
- : [message, ...printedLocations].join('\n\n') + '\n';
94
- }
95
- const error = new GraphQLError(
96
- `Internal Error: ${messageWithLocations}`,
97
- nodes ?? [],
98
- );
99
- return new Error(error.message);
100
- }
101
-
102
- /**
103
- * Iterates over the elements of some iterable value, calling the
104
- * supplied callback for each item with a guard for user errors.
105
- *
106
- * Non-user errors abort the iteration and are instantly rethrown.
107
- * User errors are collected and rethrown at the end, if multiple user errors
108
- * occur, a combined error is thrown.
109
- */
110
- function eachWithCombinedError<T>(iterable: Iterable<T>, fn: T => void): void {
111
- const errors: Array<UserError> = [];
112
- for (const item of iterable) {
113
- try {
114
- fn(item);
115
- } catch (error) {
116
- if (error instanceof GraphQLError) {
117
- errors.push(error);
118
- } else {
119
- throw error;
120
- }
121
- }
122
- }
123
- if (errors.length > 0) {
124
- if (errors.length === 1) {
125
- throw createUserError(
126
- String(errors[0])
127
- .split('\n')
128
- .map((line, index) => (index === 0 ? `- ${line}` : ` ${line}`))
129
- .join('\n'),
130
- );
131
- }
132
- throw createUserError(
133
- `Encountered ${errors.length} errors:\n` +
134
- errors
135
- .map(error =>
136
- String(error)
137
- .split('\n')
138
- .map((line, index) => (index === 0 ? `- ${line}` : ` ${line}`))
139
- .join('\n'),
140
- )
141
- .join('\n'),
142
- );
143
- }
144
- }
145
-
146
- function printLocations(locations: $ReadOnlyArray<Location>): Array<string> {
147
- const printedLocations = [];
148
- for (const location of locations) {
149
- let sourceLocation = location;
150
- while (sourceLocation.kind === 'Derived') {
151
- sourceLocation = sourceLocation.source;
152
- }
153
- switch (sourceLocation.kind) {
154
- case 'Source': {
155
- // source location
156
- const prefix =
157
- sourceLocation === location ? 'Source: ' : 'Source (derived): ';
158
- printedLocations.push(
159
- prefix +
160
- highlightSourceAtLocation(
161
- sourceLocation.source,
162
- getLocation(sourceLocation.source, sourceLocation.start),
163
- ),
164
- );
165
- break;
166
- }
167
- case 'Generated': {
168
- printedLocations.push('Source: (generated)');
169
- break;
170
- }
171
- case 'Unknown': {
172
- printedLocations.push('Source: (unknown)');
173
- break;
174
- }
175
- default: {
176
- (sourceLocation: empty);
177
- throw createCompilerError(
178
- `CompilerError: cannot print location '${String(sourceLocation)}'.`,
179
- );
180
- }
181
- }
182
- }
183
- return printedLocations;
184
- }
185
-
186
- /**
187
- * Render a helpful description of the location of the error in the GraphQL
188
- * Source document.
189
- */
190
- function highlightSourceAtLocation(
191
- source: Source,
192
- location: SourceLocation,
193
- ): string {
194
- const firstLineColumnOffset = source.locationOffset.column - 1;
195
- const body = whitespace(firstLineColumnOffset) + source.body;
196
-
197
- const lineIndex = location.line - 1;
198
- const lineOffset = source.locationOffset.line - 1;
199
- const lineNum = location.line + lineOffset;
200
-
201
- const columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
202
- const columnNum = location.column + columnOffset;
203
-
204
- const lines = body.split(/\r\n|[\n\r]/g);
205
- return (
206
- `${source.name} (${lineNum}:${columnNum})\n` +
207
- printPrefixedLines([
208
- // Lines specified like this: ["prefix", "string"],
209
- [`${lineNum - 1}: `, lines[lineIndex - 1]],
210
- [`${lineNum}: `, lines[lineIndex]],
211
- ['', whitespace(columnNum - 1) + '^'],
212
- [`${lineNum + 1}: `, lines[lineIndex + 1]],
213
- ])
214
- );
215
- }
216
-
217
- function printPrefixedLines(lines: Array<[string, string]>): string {
218
- const existingLines = lines.filter(([_, line]) => line !== undefined);
219
-
220
- let padLen = 0;
221
- for (const [prefix] of existingLines) {
222
- padLen = Math.max(padLen, prefix.length);
223
- }
224
-
225
- return existingLines
226
- .map(([prefix, line]) => lpad(padLen, prefix) + line)
227
- .join('\n');
228
- }
229
-
230
- function whitespace(len: number): string {
231
- return Array(len + 1).join(' ');
232
- }
233
-
234
- function lpad(len: number, str: string): string {
235
- return whitespace(len - str.length) + str;
236
- }
237
-
238
- function getLocation(source: Source, position: number): SourceLocation {
239
- const lineRegexp = /\r\n|[\n\r]/g;
240
- let line = 1;
241
- let column = position + 1;
242
- let match;
243
- while ((match = lineRegexp.exec(source.body)) && match.index < position) {
244
- line += 1;
245
- column = position + 1 - (match.index + match[0].length);
246
- }
247
- return {line, column};
248
- }
249
-
250
- module.exports = {
251
- createCompilerError,
252
- createNonRecoverableUserError,
253
- createUserError,
254
- eachWithCombinedError,
255
- };
@@ -1,37 +0,0 @@
1
- /**
2
- * Copyright (c) Facebook, Inc. and its affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- * @flow strict
8
- * @format
9
- */
10
-
11
- // flowlint ambiguous-object-type:error
12
-
13
- 'use strict';
14
-
15
- import type {File} from '../codegen/CodegenTypes';
16
- import type {DocumentNode} from 'graphql';
17
-
18
- const ASTCache = require('./ASTCache');
19
- const fs = require('fs');
20
- const {Source, parse} = require('graphql');
21
- const path = require('path');
22
-
23
- function parseFile(baseDir: string, file: File): ?DocumentNode {
24
- const text = fs.readFileSync(path.join(baseDir, file.relPath), 'utf8');
25
- return parse(new Source(text, file.relPath), {
26
- experimentalFragmentVariables: true,
27
- });
28
- }
29
-
30
- function getParser(baseDir: string): ASTCache {
31
- return new ASTCache({baseDir, parse: parseFile});
32
- }
33
-
34
- module.exports = {
35
- parseFile,
36
- getParser,
37
- };