graphql-jit 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/execution.js CHANGED
@@ -3,10 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isPromiseInliner = exports.isPromise = exports.createBoundQuery = exports.isCompiledQuery = exports.compileQuery = exports.GLOBAL_VARIABLES_NAME = void 0;
6
+ exports.isAsyncIterable = exports.isPromiseInliner = exports.isPromise = exports.createBoundQuery = exports.isCompiledQuery = exports.compileQuery = exports.GLOBAL_VARIABLES_NAME = void 0;
7
7
  const fast_json_stringify_1 = __importDefault(require("fast-json-stringify"));
8
8
  const generate_function_1 = __importDefault(require("generate-function"));
9
9
  const graphql_1 = require("graphql");
10
+ const Path_1 = require("graphql/jsutils/Path");
10
11
  const ast_1 = require("./ast");
11
12
  const error_1 = require("./error");
12
13
  const inspect_1 = __importDefault(require("./inspect"));
@@ -14,7 +15,7 @@ const json_1 = require("./json");
14
15
  const non_null_1 = require("./non-null");
15
16
  const resolve_info_1 = require("./resolve-info");
16
17
  const variables_1 = require("./variables");
17
- const inspect = inspect_1.default();
18
+ const inspect = (0, inspect_1.default)();
18
19
  // prefix for the variable used ot cache validation results
19
20
  const SAFETY_CHECK_PREFIX = "__validNode";
20
21
  const GLOBAL_DATA_NAME = "__context.data";
@@ -44,7 +45,7 @@ function compileQuery(schema, document, operationName, partialOptions) {
44
45
  throw new Error(`Expected ${schema} to be a GraphQL schema.`);
45
46
  }
46
47
  if (!document) {
47
- throw new Error("Must provide document");
48
+ throw new Error("Must provide document.");
48
49
  }
49
50
  if (partialOptions &&
50
51
  partialOptions.resolverInfoEnricher &&
@@ -58,24 +59,34 @@ function compileQuery(schema, document, operationName, partialOptions) {
58
59
  const context = buildCompilationContext(schema, document, options, operationName);
59
60
  let stringify;
60
61
  if (options.customJSONSerializer) {
61
- const jsonSchema = json_1.queryToJSONSchema(context);
62
- stringify = fast_json_stringify_1.default(jsonSchema);
62
+ const jsonSchema = (0, json_1.queryToJSONSchema)(context);
63
+ stringify = (0, fast_json_stringify_1.default)(jsonSchema);
63
64
  }
64
65
  else {
65
66
  stringify = JSON.stringify;
66
67
  }
67
- const getVariables = variables_1.compileVariableParsing(schema, context.operation.variableDefinitions || []);
68
- const functionBody = compileOperation(context);
68
+ const getVariables = (0, variables_1.compileVariableParsing)(schema, context.operation.variableDefinitions || []);
69
+ const type = (0, graphql_1.getOperationRootType)(context.schema, context.operation);
70
+ const fieldMap = (0, ast_1.collectFields)(context, type, context.operation.selectionSet, Object.create(null), Object.create(null));
71
+ const functionBody = compileOperation(context, type, fieldMap);
69
72
  const compiledQuery = {
70
- query: createBoundQuery(context, document, new Function("return " + functionBody)(), getVariables, context.operation.name != null
73
+ query: createBoundQuery(context, document,
74
+ // eslint-disable-next-line no-new-func
75
+ new Function("return " + functionBody)(), getVariables, context.operation.name != null
71
76
  ? context.operation.name.value
72
77
  : undefined),
73
78
  stringify
74
79
  };
80
+ if (context.operation.operation === "subscription") {
81
+ compiledQuery.subscribe = createBoundSubscribe(context, document, compileSubscriptionOperation(context, type, fieldMap, compiledQuery.query), getVariables, context.operation.name != null
82
+ ? context.operation.name.value
83
+ : undefined);
84
+ }
75
85
  if (options.debug) {
76
86
  // result of the compilation useful for debugging issues
77
87
  // and visualization tools like try-jit.
78
- compiledQuery.__DO_NOT_USE_THIS_OR_YOU_WILL_BE_FIRED_compilation = functionBody;
88
+ compiledQuery.__DO_NOT_USE_THIS_OR_YOU_WILL_BE_FIRED_compilation =
89
+ functionBody;
79
90
  }
80
91
  return compiledQuery;
81
92
  }
@@ -93,9 +104,9 @@ exports.isCompiledQuery = isCompiledQuery;
93
104
  // Exported only for an error test
94
105
  function createBoundQuery(compilationContext, document, func, getVariableValues, operationName) {
95
106
  const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } = compilationContext;
96
- const trimmer = non_null_1.createNullTrimmer(compilationContext);
97
- const fnName = operationName ? operationName : "query";
98
- /* tslint:disable */
107
+ const trimmer = (0, non_null_1.createNullTrimmer)(compilationContext);
108
+ const fnName = operationName || "query";
109
+ /* eslint-disable */
99
110
  /**
100
111
  * In-order to assign a debuggable name to the bound query function,
101
112
  * we create an intermediate object with a method named as the
@@ -106,13 +117,13 @@ function createBoundQuery(compilationContext, document, func, getVariableValues,
106
117
  *
107
118
  * section: 14.3.9.3 - calls SetFunctionName
108
119
  */
109
- /* tslint:enable */
120
+ /* eslint-enable */
110
121
  const ret = {
111
122
  [fnName](rootValue, context, variables) {
112
123
  // this can be shared across in a batch request
113
124
  const parsedVariables = getVariableValues(variables || {});
114
125
  // Return early errors if variable coercing failed.
115
- if (variables_1.failToParseVariables(parsedVariables)) {
126
+ if ((0, variables_1.failToParseVariables)(parsedVariables)) {
116
127
  return { errors: parsedVariables.errors };
117
128
  }
118
129
  const executionContext = {
@@ -133,6 +144,7 @@ function createBoundQuery(compilationContext, document, func, getVariableValues,
133
144
  nullErrors: [],
134
145
  errors: []
135
146
  };
147
+ // eslint-disable-next-line no-useless-call
136
148
  const result = func.call(null, executionContext);
137
149
  if (isPromise(result)) {
138
150
  return result.then(postProcessResult);
@@ -170,10 +182,8 @@ function postProcessResult({ data, nullErrors, errors, trimmer }) {
170
182
  * @param {CompilationContext} context compilation context with the execution context
171
183
  * @returns {string} a function body to be instantiated together with the header, footer
172
184
  */
173
- function compileOperation(context) {
174
- const type = graphql_1.getOperationRootType(context.schema, context.operation);
185
+ function compileOperation(context, type, fieldMap) {
175
186
  const serialExecution = context.operation.operation === "mutation";
176
- const fieldMap = ast_1.collectFields(context, type, context.operation.selectionSet, Object.create(null), Object.create(null));
177
187
  const topLevel = compileObjectType(context, type, [], [GLOBAL_ROOT_NAME], [GLOBAL_DATA_NAME], undefined, GLOBAL_ERRORS_NAME, fieldMap, true);
178
188
  let body = `function query (${GLOBAL_EXECUTION_CONTEXT}) {
179
189
  "use strict";
@@ -289,14 +299,14 @@ function compileDeferredField(context, deferredField, appendix) {
289
299
  ${generateUniqueDeclarations(subContext)}
290
300
  ${GLOBAL_PARENT_NAME}.${name} = ${nodeBody};
291
301
  ${compileDeferredFields(subContext)}
292
- ${appendix ? appendix : ""}
302
+ ${appendix || ""}
293
303
  }
294
304
  `);
295
305
  return body;
296
306
  }
297
307
  function compileDeferredFieldsSerially(context) {
298
308
  let body = "";
299
- context.deferred.forEach(deferredField => {
309
+ context.deferred.forEach((deferredField) => {
300
310
  const { name, fieldName, parentType } = deferredField;
301
311
  const resolverName = getResolverName(parentType.name, fieldName);
302
312
  const mutationHandler = getHoistedFunctionName(context, `${name}${resolverName}Mutation`);
@@ -331,7 +341,7 @@ function compileType(context, parentType, type, fieldNodes, originPaths, destina
331
341
  const sourcePath = originPaths.join(".");
332
342
  let body = `${sourcePath} == null ? `;
333
343
  let errorDestination;
334
- if (graphql_1.isNonNullType(type)) {
344
+ if ((0, graphql_1.isNonNullType)(type)) {
335
345
  type = type.ofType;
336
346
  const nullErrorStr = `"Cannot return null for non-nullable field ${parentType.name}.${getFieldNodesName(fieldNodes)}."`;
337
347
  body += `(${GLOBAL_NULL_ERRORS_NAME}.push(${createErrorObject(context, fieldNodes, previousPath, nullErrorStr)}), null) :`;
@@ -345,17 +355,17 @@ function compileType(context, parentType, type, fieldNodes, originPaths, destina
345
355
  // value can be an error obj
346
356
  const errorPath = `${sourcePath}.message != null ? ${sourcePath}.message : ${sourcePath}`;
347
357
  body += `${sourcePath} instanceof Error ? (${errorDestination}.push(${createErrorObject(context, fieldNodes, previousPath, errorPath, sourcePath)}), null) : `;
348
- if (graphql_1.isLeafType(type)) {
358
+ if ((0, graphql_1.isLeafType)(type)) {
349
359
  body += compileLeafType(context, type, originPaths, fieldNodes, previousPath, errorDestination);
350
360
  }
351
- else if (graphql_1.isObjectType(type)) {
352
- const fieldMap = ast_1.collectSubfields(context, type, fieldNodes);
361
+ else if ((0, graphql_1.isObjectType)(type)) {
362
+ const fieldMap = (0, ast_1.collectSubfields)(context, type, fieldNodes);
353
363
  body += compileObjectType(context, type, fieldNodes, originPaths, destinationPaths, previousPath, errorDestination, fieldMap, false);
354
364
  }
355
- else if (graphql_1.isAbstractType(type)) {
365
+ else if ((0, graphql_1.isAbstractType)(type)) {
356
366
  body += compileAbstractType(context, parentType, type, fieldNodes, originPaths, previousPath, errorDestination);
357
367
  }
358
- else if (graphql_1.isListType(type)) {
368
+ else if ((0, graphql_1.isListType)(type)) {
359
369
  body += compileListType(context, parentType, type, fieldNodes, originPaths, previousPath, errorDestination);
360
370
  }
361
371
  else {
@@ -368,7 +378,7 @@ function compileType(context, parentType, type, fieldNodes, originPaths, destina
368
378
  function compileLeafType(context, type, originPaths, fieldNodes, previousPath, errorDestination) {
369
379
  let body = "";
370
380
  if (context.options.disableLeafSerialization &&
371
- (type instanceof graphql_1.GraphQLEnumType || graphql_1.isSpecifiedScalarType(type))) {
381
+ (type instanceof graphql_1.GraphQLEnumType || (0, graphql_1.isSpecifiedScalarType)(type))) {
372
382
  body += `${originPaths.join(".")}`;
373
383
  }
374
384
  else {
@@ -398,7 +408,7 @@ function compileLeafType(context, type, originPaths, fieldNodes, previousPath, e
398
408
  * @returns {string}
399
409
  */
400
410
  function compileObjectType(context, type, fieldNodes, originPaths, destinationPaths, responsePath, errorDestination, fieldMap, alwaysDefer) {
401
- const body = generate_function_1.default();
411
+ const body = (0, generate_function_1.default)();
402
412
  // Begin object compilation paren
403
413
  body("(");
404
414
  if (typeof type.isTypeOf === "function" && !alwaysDefer) {
@@ -409,7 +419,7 @@ function compileObjectType(context, type, fieldNodes, originPaths, destinationPa
409
419
  body("{");
410
420
  for (const name of Object.keys(fieldMap)) {
411
421
  const fieldNodes = fieldMap[name];
412
- const field = ast_1.resolveFieldDef(context, type, fieldNodes);
422
+ const field = (0, ast_1.resolveFieldDef)(context, type, fieldNodes);
413
423
  if (!field) {
414
424
  // Field is invalid, should have been caught in validation
415
425
  // but the error is swallowed for compatibility reasons.
@@ -444,8 +454,8 @@ function compileObjectType(context, type, fieldNodes, originPaths, destinationPa
444
454
  body(`
445
455
  (
446
456
  ${fieldNodes
447
- .map(it => it.__internalShouldInclude)
448
- .filter(it => it)
457
+ .map((it) => it.__internalShouldInclude)
458
+ .filter((it) => it)
449
459
  .join(" || ") || /* if(true) - default */ "true"}
450
460
  )
451
461
  `);
@@ -460,12 +470,12 @@ function compileObjectType(context, type, fieldNodes, originPaths, destinationPa
460
470
  let resolver = field.resolve;
461
471
  if (!resolver && alwaysDefer) {
462
472
  const fieldName = field.name;
463
- resolver = parent => parent && parent[fieldName];
473
+ resolver = (parent) => parent && parent[fieldName];
464
474
  }
465
475
  if (resolver) {
466
476
  context.deferred.push({
467
477
  name,
468
- responsePath: ast_1.addPath(responsePath, name),
478
+ responsePath: (0, ast_1.addPath)(responsePath, name),
469
479
  originPaths,
470
480
  destinationPaths,
471
481
  parentType: type,
@@ -473,7 +483,7 @@ function compileObjectType(context, type, fieldNodes, originPaths, destinationPa
473
483
  jsFieldName: getJsFieldName(field.name),
474
484
  fieldType: field.type,
475
485
  fieldNodes,
476
- args: ast_1.getArgumentDefs(field, fieldNodes[0])
486
+ args: (0, ast_1.getArgumentDefs)(field, fieldNodes[0])
477
487
  });
478
488
  context.resolvers[getResolverName(type.name, field.name)] = resolver;
479
489
  body(`
@@ -490,7 +500,7 @@ function compileObjectType(context, type, fieldNodes, originPaths, destinationPa
490
500
  else {
491
501
  // if included
492
502
  body("?");
493
- body(compileType(context, type, field.type, fieldNodes, originPaths.concat(field.name), destinationPaths.concat(name), ast_1.addPath(responsePath, name)));
503
+ body(compileType(context, type, field.type, fieldNodes, originPaths.concat(field.name), destinationPaths.concat(name), (0, ast_1.addPath)(responsePath, name)));
494
504
  // if not included
495
505
  body(": undefined");
496
506
  }
@@ -515,9 +525,9 @@ function compileAbstractType(context, parentType, type, fieldNodes, originPaths,
515
525
  context.typeResolvers[typeResolverName] = resolveType;
516
526
  const collectedTypes = context.schema
517
527
  .getPossibleTypes(type)
518
- .map(objectType => {
528
+ .map((objectType) => {
519
529
  const subContext = createSubCompilationContext(context);
520
- const object = compileType(subContext, parentType, objectType, fieldNodes, originPaths, ["__concrete"], ast_1.addPath(previousPath, objectType.name, "meta"));
530
+ const object = compileType(subContext, parentType, objectType, fieldNodes, originPaths, ["__concrete"], (0, ast_1.addPath)(previousPath, objectType.name, "meta"));
521
531
  return `case "${objectType.name}": {
522
532
  ${generateUniqueDeclarations(subContext)}
523
533
  const __concrete = ${object};
@@ -528,12 +538,14 @@ function compileAbstractType(context, parentType, type, fieldNodes, originPaths,
528
538
  .join("\n");
529
539
  const finalTypeName = "finalType";
530
540
  const nullTypeError = `"Runtime Object type is not a possible type for \\"${type.name}\\"."`;
531
- // tslint:disable:max-line-length
532
- const notPossibleTypeError = '`Runtime Object type "${nodeType}" is not a possible type for "' +
541
+ /* eslint-disable max-len */
542
+ const notPossibleTypeError =
543
+ // eslint-disable-next-line no-template-curly-in-string
544
+ '`Runtime Object type "${nodeType}" is not a possible type for "' +
533
545
  type.name +
534
546
  '".`';
535
547
  const noTypeError = `${finalTypeName} ? ${notPossibleTypeError} : "Abstract type ${type.name} must resolve to an Object type at runtime for field ${parentType.name}.${getFieldNodesName(fieldNodes)}. Either the ${type.name} type should provide a \\"resolveType\\" function or each possible types should provide an \\"isTypeOf\\" function."`;
536
- // tslint:enable:max-line-length
548
+ /* eslint-enable max-len */
537
549
  return `((nodeType, err) =>
538
550
  {
539
551
  if (err != null) {
@@ -574,10 +586,10 @@ function compileListType(context, parentType, type, fieldNodes, originalObjectPa
574
586
  // context depth will be mutated, so we cache the current value.
575
587
  const newDepth = ++listContext.depth;
576
588
  const fieldType = type.ofType;
577
- const dataBody = compileType(listContext, parentType, fieldType, fieldNodes, ["__currentItem"], [`${GLOBAL_PARENT_NAME}[idx${newDepth}]`], ast_1.addPath(responsePath, "idx" + newDepth, "variable"));
589
+ const dataBody = compileType(listContext, parentType, fieldType, fieldNodes, ["__currentItem"], [`${GLOBAL_PARENT_NAME}[idx${newDepth}]`], (0, ast_1.addPath)(responsePath, "idx" + newDepth, "variable"));
578
590
  const errorMessage = `"Expected Iterable, but did not find one for field ${parentType.name}.${getFieldNodesName(fieldNodes)}."`;
579
591
  const errorCase = `(${errorDestination}.push(${createErrorObject(context, fieldNodes, responsePath, errorMessage)}), null)`;
580
- const executionError = createErrorObject(context, fieldNodes, ast_1.addPath(responsePath, "idx" + newDepth, "variable"), "err.message != null ? err.message : err", "err");
592
+ const executionError = createErrorObject(context, fieldNodes, (0, ast_1.addPath)(responsePath, "idx" + newDepth, "variable"), "err.message != null ? err.message : err", "err");
581
593
  const emptyError = createErrorObject(context, fieldNodes, responsePath, '""');
582
594
  const uniqueDeclarations = generateUniqueDeclarations(listContext);
583
595
  const deferredFields = compileDeferredFields(listContext);
@@ -671,7 +683,7 @@ function objectStringify(val) {
671
683
  function getExecutionInfo(context, parentType, fieldType, fieldName, fieldNodes, responsePath) {
672
684
  const resolveInfoName = createResolveInfoName(responsePath);
673
685
  const { schema, fragments, operation } = context;
674
- context.resolveInfos[resolveInfoName] = resolve_info_1.createResolveInfoThunk({
686
+ context.resolveInfos[resolveInfoName] = (0, resolve_info_1.createResolveInfoThunk)({
675
687
  schema,
676
688
  fragments,
677
689
  operation,
@@ -693,7 +705,7 @@ function objectPath(topLevel, path) {
693
705
  return topLevel;
694
706
  }
695
707
  let objectPath = topLevel;
696
- const flattened = ast_1.flattenPath(path);
708
+ const flattened = (0, ast_1.flattenPath)(path);
697
709
  for (const section of flattened) {
698
710
  if (section.type === "literal") {
699
711
  objectPath += `["${section.key}"]`;
@@ -725,8 +737,8 @@ function compileArguments(context, args, topLevelArg, validArgs, returnType, pat
725
737
  for (const variable of args.missing) {
726
738
  const varName = variable.valueNode.name.value;
727
739
  body += `if (Object.prototype.hasOwnProperty.call(${exports.GLOBAL_VARIABLES_NAME}, "${varName}")) {`;
728
- if (variable.argument && graphql_1.isNonNullType(variable.argument.definition.type)) {
729
- const message = `'Argument "${variable.argument.definition.name}" of non-null type "${inspect(variable.argument.definition.type)}" must not be null.'`;
740
+ if (variable.argument && (0, graphql_1.isNonNullType)(variable.argument.definition.type)) {
741
+ const message = `'Argument "${variable.argument.definition.name}" of non-null type "${variable.argument.definition.type.toString()}" must not be null.'`;
730
742
  body += `if (${exports.GLOBAL_VARIABLES_NAME}['${variable.valueNode.name.value}'] == null) {
731
743
  ${errorDestination}.push(${createErrorObject(context, [variable.argument.node.value], path, message)});
732
744
  ${validArgs} = false;
@@ -738,9 +750,9 @@ function compileArguments(context, args, topLevelArg, validArgs, returnType, pat
738
750
  // If there is no default value and no variable input
739
751
  // throw a field error
740
752
  if (variable.argument &&
741
- graphql_1.isNonNullType(variable.argument.definition.type) &&
753
+ (0, graphql_1.isNonNullType)(variable.argument.definition.type) &&
742
754
  variable.argument.definition.defaultValue === undefined) {
743
- const message = `'Argument "${variable.argument.definition.name}" of required type "${inspect(variable.argument.definition.type)}" was provided the variable "$${varName}" which was not provided a runtime value.'`;
755
+ const message = `'Argument "${variable.argument.definition.name}" of required type "${variable.argument.definition.type.toString()}" was provided the variable "$${varName}" which was not provided a runtime value.'`;
744
756
  body += ` else {
745
757
  ${errorDestination}.push(${createErrorObject(context, [variable.argument.node.value], path, message)});
746
758
  ${validArgs} = false;
@@ -786,7 +798,7 @@ exports.isPromiseInliner = isPromiseInliner;
786
798
  * @returns {string} filtered serialization of the response path
787
799
  */
788
800
  function serializeResponsePathAsArray(path) {
789
- const flattened = ast_1.flattenPath(path);
801
+ const flattened = (0, ast_1.flattenPath)(path);
790
802
  let src = "[";
791
803
  for (let i = flattened.length - 1; i >= 0; i--) {
792
804
  // meta is only used for the function name
@@ -801,11 +813,11 @@ function serializeResponsePathAsArray(path) {
801
813
  return src + "]";
802
814
  }
803
815
  function getErrorDestination(type) {
804
- return graphql_1.isNonNullType(type) ? GLOBAL_NULL_ERRORS_NAME : GLOBAL_ERRORS_NAME;
816
+ return (0, graphql_1.isNonNullType)(type) ? GLOBAL_NULL_ERRORS_NAME : GLOBAL_ERRORS_NAME;
805
817
  }
806
818
  function createResolveInfoName(path) {
807
- return (ast_1.flattenPath(path)
808
- .map(p => p.key)
819
+ return ((0, ast_1.flattenPath)(path)
820
+ .map((p) => p.key)
809
821
  .join("_") + "Info");
810
822
  }
811
823
  /**
@@ -835,9 +847,7 @@ function serializeResponsePath(path) {
835
847
  */
836
848
  function getSerializer(scalar, customSerializer) {
837
849
  const { name } = scalar;
838
- const serialize = customSerializer
839
- ? customSerializer
840
- : (val) => scalar.serialize(val);
850
+ const serialize = customSerializer || ((val) => scalar.serialize(val));
841
851
  return function leafSerializer(context, v, onError, ...idx) {
842
852
  try {
843
853
  const value = serialize(v);
@@ -862,7 +872,7 @@ function getSerializer(scalar, customSerializer) {
862
872
  * @param contextValue
863
873
  * @param {GraphQLResolveInfo} info
864
874
  * @param {GraphQLAbstractType} abstractType
865
- * @returns {string | GraphQLObjectType}
875
+ * @returns {string}
866
876
  */
867
877
  function defaultResolveTypeFn(value, contextValue, info, abstractType) {
868
878
  // First, look for `__typename`.
@@ -880,7 +890,7 @@ function defaultResolveTypeFn(value, contextValue, info, abstractType) {
880
890
  throw new Error(`Promises are not supported for resolving type of ${value}`);
881
891
  }
882
892
  else if (isTypeOfResult) {
883
- return type;
893
+ return type.name;
884
894
  }
885
895
  }
886
896
  }
@@ -941,8 +951,7 @@ function buildCompilationContext(schema, document, options, operationName) {
941
951
  deferred: [],
942
952
  depth: -1,
943
953
  variableValues: {},
944
- fieldResolver: undefined,
945
- errors: errors
954
+ errors
946
955
  };
947
956
  }
948
957
  function getFieldNodesName(nodes) {
@@ -961,9 +970,9 @@ function getHoistedFunctionName(context, name) {
961
970
  }
962
971
  function createErrorObject(context, nodes, path, message, originalError) {
963
972
  return `new ${GRAPHQL_ERROR}(${message},
964
- ${JSON.stringify(ast_1.computeLocations(nodes))},
973
+ ${JSON.stringify((0, ast_1.computeLocations)(nodes))},
965
974
  ${serializeResponsePathAsArray(path)},
966
- ${originalError ? originalError : "undefined"},
975
+ ${originalError || "undefined"},
967
976
  ${context.options.disablingCapturingStackErrors ? "true" : "false"})`;
968
977
  }
969
978
  function getResolverName(parentName, name) {
@@ -991,7 +1000,7 @@ function promiseDone() {
991
1000
  }
992
1001
  function normalizeErrors(err) {
993
1002
  if (Array.isArray(err)) {
994
- return err.map(e => normalizeError(e));
1003
+ return err.map((e) => normalizeError(e));
995
1004
  }
996
1005
  return [normalizeError(err)];
997
1006
  }
@@ -1004,6 +1013,7 @@ function normalizeError(err) {
1004
1013
  * Returns true if a value is undefined, or NaN.
1005
1014
  */
1006
1015
  function isInvalid(value) {
1016
+ // eslint-disable-next-line no-self-compare
1007
1017
  return value === undefined || value !== value;
1008
1018
  }
1009
1019
  function getParentArgIndexes(context) {
@@ -1019,4 +1029,147 @@ function getParentArgIndexes(context) {
1019
1029
  function getJsFieldName(fieldName) {
1020
1030
  return `${LOCAL_JS_FIELD_NAME_PREFIX}${fieldName}`;
1021
1031
  }
1032
+ function isAsyncIterable(val) {
1033
+ return typeof Object(val)[Symbol.asyncIterator] === "function";
1034
+ }
1035
+ exports.isAsyncIterable = isAsyncIterable;
1036
+ function compileSubscriptionOperation(context, type, fieldMap, queryFn) {
1037
+ const fieldNodes = Object.values(fieldMap)[0];
1038
+ const fieldNode = fieldNodes[0];
1039
+ const fieldName = fieldNode.name.value;
1040
+ const field = (0, ast_1.resolveFieldDef)(context, type, fieldNodes);
1041
+ if (!field) {
1042
+ throw new graphql_1.GraphQLError(`The subscription field "${fieldName}" is not defined.`, fieldNodes);
1043
+ }
1044
+ const responsePath = (0, ast_1.addPath)(undefined, fieldName);
1045
+ const resolveInfoName = createResolveInfoName(responsePath);
1046
+ const subscriber = field.subscribe;
1047
+ async function executeSubscription(executionContext) {
1048
+ const resolveInfo = executionContext.resolveInfos[resolveInfoName](executionContext.rootValue, executionContext.variables, responsePath);
1049
+ try {
1050
+ const eventStream = await (subscriber === null || subscriber === void 0 ? void 0 : subscriber(executionContext.rootValue, executionContext.variables, executionContext.context, resolveInfo));
1051
+ if (eventStream instanceof Error) {
1052
+ throw eventStream;
1053
+ }
1054
+ return eventStream;
1055
+ }
1056
+ catch (error) {
1057
+ throw (0, graphql_1.locatedError)(error, resolveInfo.fieldNodes, (0, Path_1.pathToArray)(resolveInfo.path));
1058
+ }
1059
+ }
1060
+ async function createSourceEventStream(executionContext) {
1061
+ try {
1062
+ const eventStream = await executeSubscription(executionContext);
1063
+ // Assert field returned an event stream, otherwise yield an error.
1064
+ if (!isAsyncIterable(eventStream)) {
1065
+ throw new Error("Subscription field must return Async Iterable. " +
1066
+ `Received: ${inspect(eventStream)}.`);
1067
+ }
1068
+ return eventStream;
1069
+ }
1070
+ catch (error) {
1071
+ // If it is a GraphQLError, report it as an ExecutionResult, containing only errors and no data.
1072
+ // Otherwise treat the error as a system-class error and re-throw it.
1073
+ if (error instanceof graphql_1.GraphQLError) {
1074
+ return { errors: [error] };
1075
+ }
1076
+ throw error;
1077
+ }
1078
+ }
1079
+ return async function subscribe(executionContext) {
1080
+ const resultOrStream = await createSourceEventStream(executionContext);
1081
+ if (!isAsyncIterable(resultOrStream)) {
1082
+ return resultOrStream;
1083
+ }
1084
+ // For each payload yielded from a subscription, map it over the normal
1085
+ // GraphQL `execute` function, with `payload` as the rootValue.
1086
+ // This implements the "MapSourceToResponseEvent" algorithm described in
1087
+ // the GraphQL specification. The `execute` function provides the
1088
+ // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
1089
+ // "ExecuteQuery" algorithm, for which `execute` is also used.
1090
+ // We use our `query` function in place of `execute`
1091
+ const mapSourceToResponse = (payload) => queryFn(payload, executionContext.context, executionContext.variables);
1092
+ return mapAsyncIterator(resultOrStream, mapSourceToResponse);
1093
+ };
1094
+ }
1095
+ function createBoundSubscribe(compilationContext, document, func, getVariableValues, operationName) {
1096
+ const { resolvers, typeResolvers, isTypeOfs, serializers, resolveInfos } = compilationContext;
1097
+ const trimmer = (0, non_null_1.createNullTrimmer)(compilationContext);
1098
+ const fnName = operationName || "subscribe";
1099
+ const ret = {
1100
+ async [fnName](rootValue, context, variables) {
1101
+ // this can be shared across in a batch request
1102
+ const parsedVariables = getVariableValues(variables || {});
1103
+ // Return early errors if variable coercing failed.
1104
+ if ((0, variables_1.failToParseVariables)(parsedVariables)) {
1105
+ return { errors: parsedVariables.errors };
1106
+ }
1107
+ const executionContext = {
1108
+ rootValue,
1109
+ context,
1110
+ variables: parsedVariables.coerced,
1111
+ safeMap,
1112
+ inspect,
1113
+ GraphQLError: error_1.GraphQLError,
1114
+ resolvers,
1115
+ typeResolvers,
1116
+ isTypeOfs,
1117
+ serializers,
1118
+ resolveInfos,
1119
+ trimmer,
1120
+ promiseCounter: 0,
1121
+ nullErrors: [],
1122
+ errors: [],
1123
+ data: {}
1124
+ };
1125
+ // eslint-disable-next-line no-useless-call
1126
+ return func.call(null, executionContext);
1127
+ }
1128
+ };
1129
+ return ret[fnName];
1130
+ }
1131
+ /**
1132
+ * Given an AsyncIterable and a callback function, return an AsyncIterator
1133
+ * which produces values mapped via calling the callback function.
1134
+ */
1135
+ function mapAsyncIterator(iterable, callback) {
1136
+ const iterator = iterable[Symbol.asyncIterator]();
1137
+ async function mapResult(result) {
1138
+ if (result.done) {
1139
+ return result;
1140
+ }
1141
+ try {
1142
+ return { value: await callback(result.value), done: false };
1143
+ }
1144
+ catch (error) {
1145
+ if (typeof iterator.return === "function") {
1146
+ try {
1147
+ await iterator.return();
1148
+ }
1149
+ catch (e) {
1150
+ /* ignore error */
1151
+ }
1152
+ }
1153
+ throw error;
1154
+ }
1155
+ }
1156
+ return {
1157
+ async next() {
1158
+ return mapResult(await iterator.next());
1159
+ },
1160
+ async return() {
1161
+ return typeof iterator.return === "function"
1162
+ ? mapResult(await iterator.return())
1163
+ : { value: undefined, done: true };
1164
+ },
1165
+ async throw(error) {
1166
+ return typeof iterator.throw === "function"
1167
+ ? mapResult(await iterator.throw(error))
1168
+ : Promise.reject(error);
1169
+ },
1170
+ [Symbol.asyncIterator]() {
1171
+ return this;
1172
+ }
1173
+ };
1174
+ }
1022
1175
  //# sourceMappingURL=execution.js.map