@luvio/graphql-parser 0.158.7 → 5.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/index.js +6 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/types/index.d.ts +0 -0
  4. package/dist/types/v1/__tests__/gql.spec.d.ts +1 -0
  5. package/dist/types/v1/__tests__/utils.d.ts +4 -0
  6. package/dist/types/v1/index.d.ts +6 -0
  7. package/dist/v1/index.js +2629 -0
  8. package/dist/v1/index.js.map +1 -0
  9. package/package.json +24 -21
  10. package/dist/cjs/luvioGraphqlParser.js +0 -11537
  11. package/dist/cjs/types/argument-node.d.ts +0 -4
  12. package/dist/cjs/types/ast.d.ts +0 -95
  13. package/dist/cjs/types/constants.d.ts +0 -12
  14. package/dist/cjs/types/directive-node.d.ts +0 -5
  15. package/dist/cjs/types/document.d.ts +0 -3
  16. package/dist/cjs/types/field-node.d.ts +0 -4
  17. package/dist/cjs/types/fragment-spread-node.d.ts +0 -4
  18. package/dist/cjs/types/fragment.d.ts +0 -3
  19. package/dist/cjs/types/inline-fragment-node.d.ts +0 -4
  20. package/dist/cjs/types/main.d.ts +0 -18
  21. package/dist/cjs/types/metaschema.d.ts +0 -10
  22. package/dist/cjs/types/operation/index.d.ts +0 -3
  23. package/dist/cjs/types/operation/query/index.d.ts +0 -6
  24. package/dist/cjs/types/type-node.d.ts +0 -3
  25. package/dist/cjs/types/util/language.d.ts +0 -9
  26. package/dist/cjs/types/value-node.d.ts +0 -4
  27. package/dist/cjs/types/variable-definition.d.ts +0 -4
  28. package/dist/cjs/types/visitor.d.ts +0 -4
  29. package/dist/esm/luvioGraphqlParser.js +0 -11516
  30. package/dist/esm/types/argument-node.d.ts +0 -4
  31. package/dist/esm/types/ast.d.ts +0 -95
  32. package/dist/esm/types/constants.d.ts +0 -12
  33. package/dist/esm/types/directive-node.d.ts +0 -5
  34. package/dist/esm/types/document.d.ts +0 -3
  35. package/dist/esm/types/field-node.d.ts +0 -4
  36. package/dist/esm/types/fragment-spread-node.d.ts +0 -4
  37. package/dist/esm/types/fragment.d.ts +0 -3
  38. package/dist/esm/types/gql.d.ts +0 -47
  39. package/dist/esm/types/inline-fragment-node.d.ts +0 -4
  40. package/dist/esm/types/main.d.ts +0 -18
  41. package/dist/esm/types/metaschema.d.ts +0 -10
  42. package/dist/esm/types/operation/index.d.ts +0 -3
  43. package/dist/esm/types/operation/query/index.d.ts +0 -6
  44. package/dist/esm/types/type-node.d.ts +0 -3
  45. package/dist/esm/types/util/language.d.ts +0 -9
  46. package/dist/esm/types/value-node.d.ts +0 -4
  47. package/dist/esm/types/variable-definition.d.ts +0 -4
  48. package/dist/esm/types/visitor.d.ts +0 -4
  49. /package/dist/{cjs/types → types/v1}/gql.d.ts +0 -0
@@ -0,0 +1,2629 @@
1
+ /*!
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+ function devAssert(condition, message) {
7
+ const booleanCondition = Boolean(condition);
8
+ if (!booleanCondition) {
9
+ throw new Error(message);
10
+ }
11
+ }
12
+ const MAX_ARRAY_LENGTH = 10;
13
+ const MAX_RECURSIVE_DEPTH = 2;
14
+ function inspect(value) {
15
+ return formatValue(value, []);
16
+ }
17
+ function formatValue(value, seenValues) {
18
+ switch (typeof value) {
19
+ case "string":
20
+ return JSON.stringify(value);
21
+ case "function":
22
+ return value.name ? `[function ${value.name}]` : "[function]";
23
+ case "object":
24
+ return formatObjectValue(value, seenValues);
25
+ default:
26
+ return String(value);
27
+ }
28
+ }
29
+ function formatObjectValue(value, previouslySeenValues) {
30
+ if (value === null) {
31
+ return "null";
32
+ }
33
+ if (previouslySeenValues.includes(value)) {
34
+ return "[Circular]";
35
+ }
36
+ const seenValues = [...previouslySeenValues, value];
37
+ if (isJSONable(value)) {
38
+ const jsonValue = value.toJSON();
39
+ if (jsonValue !== value) {
40
+ return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues);
41
+ }
42
+ } else if (Array.isArray(value)) {
43
+ return formatArray(value, seenValues);
44
+ }
45
+ return formatObject(value, seenValues);
46
+ }
47
+ function isJSONable(value) {
48
+ return typeof value.toJSON === "function";
49
+ }
50
+ function formatObject(object, seenValues) {
51
+ const entries = Object.entries(object);
52
+ if (entries.length === 0) {
53
+ return "{}";
54
+ }
55
+ if (seenValues.length > MAX_RECURSIVE_DEPTH) {
56
+ return "[" + getObjectTag(object) + "]";
57
+ }
58
+ const properties = entries.map(
59
+ ([key, value]) => key + ": " + formatValue(value, seenValues)
60
+ );
61
+ return "{ " + properties.join(", ") + " }";
62
+ }
63
+ function formatArray(array, seenValues) {
64
+ if (array.length === 0) {
65
+ return "[]";
66
+ }
67
+ if (seenValues.length > MAX_RECURSIVE_DEPTH) {
68
+ return "[Array]";
69
+ }
70
+ const len = Math.min(MAX_ARRAY_LENGTH, array.length);
71
+ const remaining = array.length - len;
72
+ const items = [];
73
+ for (let i = 0; i < len; ++i) {
74
+ items.push(formatValue(array[i], seenValues));
75
+ }
76
+ if (remaining === 1) {
77
+ items.push("... 1 more item");
78
+ } else if (remaining > 1) {
79
+ items.push(`... ${remaining} more items`);
80
+ }
81
+ return "[" + items.join(", ") + "]";
82
+ }
83
+ function getObjectTag(object) {
84
+ const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
85
+ if (tag === "Object" && typeof object.constructor === "function") {
86
+ const name = object.constructor.name;
87
+ if (typeof name === "string" && name !== "") {
88
+ return name;
89
+ }
90
+ }
91
+ return tag;
92
+ }
93
+ const isProduction = globalThis.process && // eslint-disable-next-line no-undef
94
+ process.env.NODE_ENV === "production";
95
+ const instanceOf = (
96
+ /* c8 ignore next 6 */
97
+ // FIXME: https://github.com/graphql/graphql-js/issues/2317
98
+ isProduction ? function instanceOf2(value, constructor) {
99
+ return value instanceof constructor;
100
+ } : function instanceOf3(value, constructor) {
101
+ if (value instanceof constructor) {
102
+ return true;
103
+ }
104
+ if (typeof value === "object" && value !== null) {
105
+ var _value$constructor;
106
+ const className = constructor.prototype[Symbol.toStringTag];
107
+ const valueClassName = (
108
+ // We still need to support constructor's name to detect conflicts with older versions of this library.
109
+ Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name
110
+ );
111
+ if (className === valueClassName) {
112
+ const stringifiedValue = inspect(value);
113
+ throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.
114
+
115
+ Ensure that there is only one instance of "graphql" in the node_modules
116
+ directory. If different versions of "graphql" are the dependencies of other
117
+ relied on modules, use "resolutions" to ensure only one version is installed.
118
+
119
+ https://yarnpkg.com/en/docs/selective-version-resolutions
120
+
121
+ Duplicate "graphql" modules cannot be used at the same time since different
122
+ versions may have different capabilities and behavior. The data from one
123
+ version used in the function from another could produce confusing and
124
+ spurious results.`);
125
+ }
126
+ }
127
+ return false;
128
+ }
129
+ );
130
+ class Source {
131
+ constructor(body, name = "GraphQL request", locationOffset = {
132
+ line: 1,
133
+ column: 1
134
+ }) {
135
+ typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);
136
+ this.body = body;
137
+ this.name = name;
138
+ this.locationOffset = locationOffset;
139
+ this.locationOffset.line > 0 || devAssert(
140
+ false,
141
+ "line in locationOffset is 1-indexed and must be positive."
142
+ );
143
+ this.locationOffset.column > 0 || devAssert(
144
+ false,
145
+ "column in locationOffset is 1-indexed and must be positive."
146
+ );
147
+ }
148
+ get [Symbol.toStringTag]() {
149
+ return "Source";
150
+ }
151
+ }
152
+ function isSource(source) {
153
+ return instanceOf(source, Source);
154
+ }
155
+ function invariant(condition, message) {
156
+ const booleanCondition = Boolean(condition);
157
+ if (!booleanCondition) {
158
+ throw new Error(
159
+ "Unexpected invariant triggered."
160
+ );
161
+ }
162
+ }
163
+ const LineRegExp = /\r\n|[\n\r]/g;
164
+ function getLocation(source, position) {
165
+ let lastLineStart = 0;
166
+ let line = 1;
167
+ for (const match of source.body.matchAll(LineRegExp)) {
168
+ typeof match.index === "number" || invariant(false);
169
+ if (match.index >= position) {
170
+ break;
171
+ }
172
+ lastLineStart = match.index + match[0].length;
173
+ line += 1;
174
+ }
175
+ return {
176
+ line,
177
+ column: position + 1 - lastLineStart
178
+ };
179
+ }
180
+ function printLocation(location) {
181
+ return printSourceLocation(
182
+ location.source,
183
+ getLocation(location.source, location.start)
184
+ );
185
+ }
186
+ function printSourceLocation(source, sourceLocation) {
187
+ const firstLineColumnOffset = source.locationOffset.column - 1;
188
+ const body = "".padStart(firstLineColumnOffset) + source.body;
189
+ const lineIndex = sourceLocation.line - 1;
190
+ const lineOffset = source.locationOffset.line - 1;
191
+ const lineNum = sourceLocation.line + lineOffset;
192
+ const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
193
+ const columnNum = sourceLocation.column + columnOffset;
194
+ const locationStr = `${source.name}:${lineNum}:${columnNum}
195
+ `;
196
+ const lines = body.split(/\r\n|[\n\r]/g);
197
+ const locationLine = lines[lineIndex];
198
+ if (locationLine.length > 120) {
199
+ const subLineIndex = Math.floor(columnNum / 80);
200
+ const subLineColumnNum = columnNum % 80;
201
+ const subLines = [];
202
+ for (let i = 0; i < locationLine.length; i += 80) {
203
+ subLines.push(locationLine.slice(i, i + 80));
204
+ }
205
+ return locationStr + printPrefixedLines([
206
+ [`${lineNum} |`, subLines[0]],
207
+ ...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]),
208
+ ["|", "^".padStart(subLineColumnNum)],
209
+ ["|", subLines[subLineIndex + 1]]
210
+ ]);
211
+ }
212
+ return locationStr + printPrefixedLines([
213
+ // Lines specified like this: ["prefix", "string"],
214
+ [`${lineNum - 1} |`, lines[lineIndex - 1]],
215
+ [`${lineNum} |`, locationLine],
216
+ ["|", "^".padStart(columnNum)],
217
+ [`${lineNum + 1} |`, lines[lineIndex + 1]]
218
+ ]);
219
+ }
220
+ function printPrefixedLines(lines) {
221
+ const existingLines = lines.filter(([_, line]) => line !== void 0);
222
+ const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
223
+ return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join("\n");
224
+ }
225
+ var Kind;
226
+ (function(Kind2) {
227
+ Kind2["NAME"] = "Name";
228
+ Kind2["DOCUMENT"] = "Document";
229
+ Kind2["OPERATION_DEFINITION"] = "OperationDefinition";
230
+ Kind2["VARIABLE_DEFINITION"] = "VariableDefinition";
231
+ Kind2["SELECTION_SET"] = "SelectionSet";
232
+ Kind2["FIELD"] = "Field";
233
+ Kind2["ARGUMENT"] = "Argument";
234
+ Kind2["FRAGMENT_SPREAD"] = "FragmentSpread";
235
+ Kind2["INLINE_FRAGMENT"] = "InlineFragment";
236
+ Kind2["FRAGMENT_DEFINITION"] = "FragmentDefinition";
237
+ Kind2["VARIABLE"] = "Variable";
238
+ Kind2["INT"] = "IntValue";
239
+ Kind2["FLOAT"] = "FloatValue";
240
+ Kind2["STRING"] = "StringValue";
241
+ Kind2["BOOLEAN"] = "BooleanValue";
242
+ Kind2["NULL"] = "NullValue";
243
+ Kind2["ENUM"] = "EnumValue";
244
+ Kind2["LIST"] = "ListValue";
245
+ Kind2["OBJECT"] = "ObjectValue";
246
+ Kind2["OBJECT_FIELD"] = "ObjectField";
247
+ Kind2["DIRECTIVE"] = "Directive";
248
+ Kind2["NAMED_TYPE"] = "NamedType";
249
+ Kind2["LIST_TYPE"] = "ListType";
250
+ Kind2["NON_NULL_TYPE"] = "NonNullType";
251
+ Kind2["SCHEMA_DEFINITION"] = "SchemaDefinition";
252
+ Kind2["OPERATION_TYPE_DEFINITION"] = "OperationTypeDefinition";
253
+ Kind2["SCALAR_TYPE_DEFINITION"] = "ScalarTypeDefinition";
254
+ Kind2["OBJECT_TYPE_DEFINITION"] = "ObjectTypeDefinition";
255
+ Kind2["FIELD_DEFINITION"] = "FieldDefinition";
256
+ Kind2["INPUT_VALUE_DEFINITION"] = "InputValueDefinition";
257
+ Kind2["INTERFACE_TYPE_DEFINITION"] = "InterfaceTypeDefinition";
258
+ Kind2["UNION_TYPE_DEFINITION"] = "UnionTypeDefinition";
259
+ Kind2["ENUM_TYPE_DEFINITION"] = "EnumTypeDefinition";
260
+ Kind2["ENUM_VALUE_DEFINITION"] = "EnumValueDefinition";
261
+ Kind2["INPUT_OBJECT_TYPE_DEFINITION"] = "InputObjectTypeDefinition";
262
+ Kind2["DIRECTIVE_DEFINITION"] = "DirectiveDefinition";
263
+ Kind2["SCHEMA_EXTENSION"] = "SchemaExtension";
264
+ Kind2["SCALAR_TYPE_EXTENSION"] = "ScalarTypeExtension";
265
+ Kind2["OBJECT_TYPE_EXTENSION"] = "ObjectTypeExtension";
266
+ Kind2["INTERFACE_TYPE_EXTENSION"] = "InterfaceTypeExtension";
267
+ Kind2["UNION_TYPE_EXTENSION"] = "UnionTypeExtension";
268
+ Kind2["ENUM_TYPE_EXTENSION"] = "EnumTypeExtension";
269
+ Kind2["INPUT_OBJECT_TYPE_EXTENSION"] = "InputObjectTypeExtension";
270
+ })(Kind || (Kind = {}));
271
+ var TokenKind;
272
+ (function(TokenKind2) {
273
+ TokenKind2["SOF"] = "<SOF>";
274
+ TokenKind2["EOF"] = "<EOF>";
275
+ TokenKind2["BANG"] = "!";
276
+ TokenKind2["DOLLAR"] = "$";
277
+ TokenKind2["AMP"] = "&";
278
+ TokenKind2["PAREN_L"] = "(";
279
+ TokenKind2["PAREN_R"] = ")";
280
+ TokenKind2["SPREAD"] = "...";
281
+ TokenKind2["COLON"] = ":";
282
+ TokenKind2["EQUALS"] = "=";
283
+ TokenKind2["AT"] = "@";
284
+ TokenKind2["BRACKET_L"] = "[";
285
+ TokenKind2["BRACKET_R"] = "]";
286
+ TokenKind2["BRACE_L"] = "{";
287
+ TokenKind2["PIPE"] = "|";
288
+ TokenKind2["BRACE_R"] = "}";
289
+ TokenKind2["NAME"] = "Name";
290
+ TokenKind2["INT"] = "Int";
291
+ TokenKind2["FLOAT"] = "Float";
292
+ TokenKind2["STRING"] = "String";
293
+ TokenKind2["BLOCK_STRING"] = "BlockString";
294
+ TokenKind2["COMMENT"] = "Comment";
295
+ })(TokenKind || (TokenKind = {}));
296
+ function isObjectLike(value) {
297
+ return typeof value == "object" && value !== null;
298
+ }
299
+ function toNormalizedOptions(args) {
300
+ const firstArg = args[0];
301
+ if (firstArg == null || "kind" in firstArg || "length" in firstArg) {
302
+ return {
303
+ nodes: firstArg,
304
+ source: args[1],
305
+ positions: args[2],
306
+ path: args[3],
307
+ originalError: args[4],
308
+ extensions: args[5]
309
+ };
310
+ }
311
+ return firstArg;
312
+ }
313
+ class GraphQLError extends Error {
314
+ /**
315
+ * An array of `{ line, column }` locations within the source GraphQL document
316
+ * which correspond to this error.
317
+ *
318
+ * Errors during validation often contain multiple locations, for example to
319
+ * point out two things with the same name. Errors during execution include a
320
+ * single location, the field which produced the error.
321
+ *
322
+ * Enumerable, and appears in the result of JSON.stringify().
323
+ */
324
+ /**
325
+ * An array describing the JSON-path into the execution response which
326
+ * corresponds to this error. Only included for errors during execution.
327
+ *
328
+ * Enumerable, and appears in the result of JSON.stringify().
329
+ */
330
+ /**
331
+ * An array of GraphQL AST Nodes corresponding to this error.
332
+ */
333
+ /**
334
+ * The source GraphQL document for the first location of this error.
335
+ *
336
+ * Note that if this Error represents more than one node, the source may not
337
+ * represent nodes after the first node.
338
+ */
339
+ /**
340
+ * An array of character offsets within the source GraphQL document
341
+ * which correspond to this error.
342
+ */
343
+ /**
344
+ * The original error thrown from a field resolver during execution.
345
+ */
346
+ /**
347
+ * Extension fields to add to the formatted error.
348
+ */
349
+ /**
350
+ * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
351
+ */
352
+ constructor(message, ...rawArgs) {
353
+ var _this$nodes, _nodeLocations$, _ref;
354
+ const { nodes, source, positions, path, originalError, extensions } = toNormalizedOptions(rawArgs);
355
+ super(message);
356
+ this.name = "GraphQLError";
357
+ this.path = path !== null && path !== void 0 ? path : void 0;
358
+ this.originalError = originalError !== null && originalError !== void 0 ? originalError : void 0;
359
+ this.nodes = undefinedIfEmpty(
360
+ Array.isArray(nodes) ? nodes : nodes ? [nodes] : void 0
361
+ );
362
+ const nodeLocations = undefinedIfEmpty(
363
+ (_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null)
364
+ );
365
+ this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source;
366
+ this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start);
367
+ this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
368
+ const originalExtensions = isObjectLike(
369
+ originalError === null || originalError === void 0 ? void 0 : originalError.extensions
370
+ ) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : void 0;
371
+ this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : /* @__PURE__ */ Object.create(null);
372
+ Object.defineProperties(this, {
373
+ message: {
374
+ writable: true,
375
+ enumerable: true
376
+ },
377
+ name: {
378
+ enumerable: false
379
+ },
380
+ nodes: {
381
+ enumerable: false
382
+ },
383
+ source: {
384
+ enumerable: false
385
+ },
386
+ positions: {
387
+ enumerable: false
388
+ },
389
+ originalError: {
390
+ enumerable: false
391
+ }
392
+ });
393
+ if (originalError !== null && originalError !== void 0 && originalError.stack) {
394
+ Object.defineProperty(this, "stack", {
395
+ value: originalError.stack,
396
+ writable: true,
397
+ configurable: true
398
+ });
399
+ } else if (Error.captureStackTrace) {
400
+ Error.captureStackTrace(this, GraphQLError);
401
+ } else {
402
+ Object.defineProperty(this, "stack", {
403
+ value: Error().stack,
404
+ writable: true,
405
+ configurable: true
406
+ });
407
+ }
408
+ }
409
+ get [Symbol.toStringTag]() {
410
+ return "GraphQLError";
411
+ }
412
+ toString() {
413
+ let output = this.message;
414
+ if (this.nodes) {
415
+ for (const node of this.nodes) {
416
+ if (node.loc) {
417
+ output += "\n\n" + printLocation(node.loc);
418
+ }
419
+ }
420
+ } else if (this.source && this.locations) {
421
+ for (const location of this.locations) {
422
+ output += "\n\n" + printSourceLocation(this.source, location);
423
+ }
424
+ }
425
+ return output;
426
+ }
427
+ toJSON() {
428
+ const formattedError = {
429
+ message: this.message
430
+ };
431
+ if (this.locations != null) {
432
+ formattedError.locations = this.locations;
433
+ }
434
+ if (this.path != null) {
435
+ formattedError.path = this.path;
436
+ }
437
+ if (this.extensions != null && Object.keys(this.extensions).length > 0) {
438
+ formattedError.extensions = this.extensions;
439
+ }
440
+ return formattedError;
441
+ }
442
+ }
443
+ function undefinedIfEmpty(array) {
444
+ return array === void 0 || array.length === 0 ? void 0 : array;
445
+ }
446
+ function syntaxError(source, position, description) {
447
+ return new GraphQLError(`Syntax Error: ${description}`, {
448
+ source,
449
+ positions: [position]
450
+ });
451
+ }
452
+ class Location {
453
+ /**
454
+ * The character offset at which this Node begins.
455
+ */
456
+ /**
457
+ * The character offset at which this Node ends.
458
+ */
459
+ /**
460
+ * The Token at which this Node begins.
461
+ */
462
+ /**
463
+ * The Token at which this Node ends.
464
+ */
465
+ /**
466
+ * The Source document the AST represents.
467
+ */
468
+ constructor(startToken, endToken, source) {
469
+ this.start = startToken.start;
470
+ this.end = endToken.end;
471
+ this.startToken = startToken;
472
+ this.endToken = endToken;
473
+ this.source = source;
474
+ }
475
+ get [Symbol.toStringTag]() {
476
+ return "Location";
477
+ }
478
+ toJSON() {
479
+ return {
480
+ start: this.start,
481
+ end: this.end
482
+ };
483
+ }
484
+ }
485
+ class Token {
486
+ /**
487
+ * The kind of Token.
488
+ */
489
+ /**
490
+ * The character offset at which this Node begins.
491
+ */
492
+ /**
493
+ * The character offset at which this Node ends.
494
+ */
495
+ /**
496
+ * The 1-indexed line number on which this Token appears.
497
+ */
498
+ /**
499
+ * The 1-indexed column number at which this Token begins.
500
+ */
501
+ /**
502
+ * For non-punctuation tokens, represents the interpreted value of the token.
503
+ *
504
+ * Note: is undefined for punctuation tokens, but typed as string for
505
+ * convenience in the parser.
506
+ */
507
+ /**
508
+ * Tokens exist as nodes in a double-linked-list amongst all tokens
509
+ * including ignored tokens. <SOF> is always the first node and <EOF>
510
+ * the last.
511
+ */
512
+ constructor(kind, start, end, line, column, value) {
513
+ this.kind = kind;
514
+ this.start = start;
515
+ this.end = end;
516
+ this.line = line;
517
+ this.column = column;
518
+ this.value = value;
519
+ this.prev = null;
520
+ this.next = null;
521
+ }
522
+ get [Symbol.toStringTag]() {
523
+ return "Token";
524
+ }
525
+ toJSON() {
526
+ return {
527
+ kind: this.kind,
528
+ value: this.value,
529
+ line: this.line,
530
+ column: this.column
531
+ };
532
+ }
533
+ }
534
+ const QueryDocumentKeys = {
535
+ Name: [],
536
+ Document: ["definitions"],
537
+ OperationDefinition: [
538
+ "name",
539
+ "variableDefinitions",
540
+ "directives",
541
+ "selectionSet"
542
+ ],
543
+ VariableDefinition: ["variable", "type", "defaultValue", "directives"],
544
+ Variable: ["name"],
545
+ SelectionSet: ["selections"],
546
+ Field: ["alias", "name", "arguments", "directives", "selectionSet"],
547
+ Argument: ["name", "value"],
548
+ FragmentSpread: ["name", "directives"],
549
+ InlineFragment: ["typeCondition", "directives", "selectionSet"],
550
+ FragmentDefinition: [
551
+ "name",
552
+ // Note: fragment variable definitions are deprecated and will removed in v17.0.0
553
+ "variableDefinitions",
554
+ "typeCondition",
555
+ "directives",
556
+ "selectionSet"
557
+ ],
558
+ IntValue: [],
559
+ FloatValue: [],
560
+ StringValue: [],
561
+ BooleanValue: [],
562
+ NullValue: [],
563
+ EnumValue: [],
564
+ ListValue: ["values"],
565
+ ObjectValue: ["fields"],
566
+ ObjectField: ["name", "value"],
567
+ Directive: ["name", "arguments"],
568
+ NamedType: ["name"],
569
+ ListType: ["type"],
570
+ NonNullType: ["type"],
571
+ SchemaDefinition: ["description", "directives", "operationTypes"],
572
+ OperationTypeDefinition: ["type"],
573
+ ScalarTypeDefinition: ["description", "name", "directives"],
574
+ ObjectTypeDefinition: [
575
+ "description",
576
+ "name",
577
+ "interfaces",
578
+ "directives",
579
+ "fields"
580
+ ],
581
+ FieldDefinition: ["description", "name", "arguments", "type", "directives"],
582
+ InputValueDefinition: [
583
+ "description",
584
+ "name",
585
+ "type",
586
+ "defaultValue",
587
+ "directives"
588
+ ],
589
+ InterfaceTypeDefinition: [
590
+ "description",
591
+ "name",
592
+ "interfaces",
593
+ "directives",
594
+ "fields"
595
+ ],
596
+ UnionTypeDefinition: ["description", "name", "directives", "types"],
597
+ EnumTypeDefinition: ["description", "name", "directives", "values"],
598
+ EnumValueDefinition: ["description", "name", "directives"],
599
+ InputObjectTypeDefinition: ["description", "name", "directives", "fields"],
600
+ DirectiveDefinition: ["description", "name", "arguments", "locations"],
601
+ SchemaExtension: ["directives", "operationTypes"],
602
+ ScalarTypeExtension: ["name", "directives"],
603
+ ObjectTypeExtension: ["name", "interfaces", "directives", "fields"],
604
+ InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"],
605
+ UnionTypeExtension: ["name", "directives", "types"],
606
+ EnumTypeExtension: ["name", "directives", "values"],
607
+ InputObjectTypeExtension: ["name", "directives", "fields"]
608
+ };
609
+ new Set(Object.keys(QueryDocumentKeys));
610
+ var OperationTypeNode;
611
+ (function(OperationTypeNode2) {
612
+ OperationTypeNode2["QUERY"] = "query";
613
+ OperationTypeNode2["MUTATION"] = "mutation";
614
+ OperationTypeNode2["SUBSCRIPTION"] = "subscription";
615
+ })(OperationTypeNode || (OperationTypeNode = {}));
616
+ function isWhiteSpace(code) {
617
+ return code === 9 || code === 32;
618
+ }
619
+ function isDigit(code) {
620
+ return code >= 48 && code <= 57;
621
+ }
622
+ function isLetter(code) {
623
+ return code >= 97 && code <= 122 || // A-Z
624
+ code >= 65 && code <= 90;
625
+ }
626
+ function isNameStart(code) {
627
+ return isLetter(code) || code === 95;
628
+ }
629
+ function isNameContinue(code) {
630
+ return isLetter(code) || isDigit(code) || code === 95;
631
+ }
632
+ function dedentBlockStringLines(lines) {
633
+ var _firstNonEmptyLine2;
634
+ let commonIndent = Number.MAX_SAFE_INTEGER;
635
+ let firstNonEmptyLine = null;
636
+ let lastNonEmptyLine = -1;
637
+ for (let i = 0; i < lines.length; ++i) {
638
+ var _firstNonEmptyLine;
639
+ const line = lines[i];
640
+ const indent = leadingWhitespace(line);
641
+ if (indent === line.length) {
642
+ continue;
643
+ }
644
+ firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i;
645
+ lastNonEmptyLine = i;
646
+ if (i !== 0 && indent < commonIndent) {
647
+ commonIndent = indent;
648
+ }
649
+ }
650
+ return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(
651
+ (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0,
652
+ lastNonEmptyLine + 1
653
+ );
654
+ }
655
+ function leadingWhitespace(str) {
656
+ let i = 0;
657
+ while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
658
+ ++i;
659
+ }
660
+ return i;
661
+ }
662
+ function printBlockString(value, options) {
663
+ const escapedValue = value.replace(/"""/g, '\\"""');
664
+ const lines = escapedValue.split(/\r\n|[\n\r]/g);
665
+ const isSingleLine = lines.length === 1;
666
+ const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
667
+ const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""');
668
+ const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes;
669
+ const hasTrailingSlash = value.endsWith("\\");
670
+ const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
671
+ const printAsMultipleLines = !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability
672
+ (!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes);
673
+ let result = "";
674
+ const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
675
+ if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) {
676
+ result += "\n";
677
+ }
678
+ result += escapedValue;
679
+ if (printAsMultipleLines || forceTrailingNewline) {
680
+ result += "\n";
681
+ }
682
+ return '"""' + result + '"""';
683
+ }
684
+ class Lexer {
685
+ /**
686
+ * The previously focused non-ignored token.
687
+ */
688
+ /**
689
+ * The currently focused non-ignored token.
690
+ */
691
+ /**
692
+ * The (1-indexed) line containing the current token.
693
+ */
694
+ /**
695
+ * The character offset at which the current line begins.
696
+ */
697
+ constructor(source) {
698
+ const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
699
+ this.source = source;
700
+ this.lastToken = startOfFileToken;
701
+ this.token = startOfFileToken;
702
+ this.line = 1;
703
+ this.lineStart = 0;
704
+ }
705
+ get [Symbol.toStringTag]() {
706
+ return "Lexer";
707
+ }
708
+ /**
709
+ * Advances the token stream to the next non-ignored token.
710
+ */
711
+ advance() {
712
+ this.lastToken = this.token;
713
+ const token = this.token = this.lookahead();
714
+ return token;
715
+ }
716
+ /**
717
+ * Looks ahead and returns the next non-ignored token, but does not change
718
+ * the state of Lexer.
719
+ */
720
+ lookahead() {
721
+ let token = this.token;
722
+ if (token.kind !== TokenKind.EOF) {
723
+ do {
724
+ if (token.next) {
725
+ token = token.next;
726
+ } else {
727
+ const nextToken = readNextToken(this, token.end);
728
+ token.next = nextToken;
729
+ nextToken.prev = token;
730
+ token = nextToken;
731
+ }
732
+ } while (token.kind === TokenKind.COMMENT);
733
+ }
734
+ return token;
735
+ }
736
+ }
737
+ function isPunctuatorTokenKind(kind) {
738
+ return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
739
+ }
740
+ function isUnicodeScalarValue(code) {
741
+ return code >= 0 && code <= 55295 || code >= 57344 && code <= 1114111;
742
+ }
743
+ function isSupplementaryCodePoint(body, location) {
744
+ return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1));
745
+ }
746
+ function isLeadingSurrogate(code) {
747
+ return code >= 55296 && code <= 56319;
748
+ }
749
+ function isTrailingSurrogate(code) {
750
+ return code >= 56320 && code <= 57343;
751
+ }
752
+ function printCodePointAt(lexer, location) {
753
+ const code = lexer.source.body.codePointAt(location);
754
+ if (code === void 0) {
755
+ return TokenKind.EOF;
756
+ } else if (code >= 32 && code <= 126) {
757
+ const char = String.fromCodePoint(code);
758
+ return char === '"' ? `'"'` : `"${char}"`;
759
+ }
760
+ return "U+" + code.toString(16).toUpperCase().padStart(4, "0");
761
+ }
762
+ function createToken(lexer, kind, start, end, value) {
763
+ const line = lexer.line;
764
+ const col = 1 + start - lexer.lineStart;
765
+ return new Token(kind, start, end, line, col, value);
766
+ }
767
+ function readNextToken(lexer, start) {
768
+ const body = lexer.source.body;
769
+ const bodyLength = body.length;
770
+ let position = start;
771
+ while (position < bodyLength) {
772
+ const code = body.charCodeAt(position);
773
+ switch (code) {
774
+ // Ignored ::
775
+ // - UnicodeBOM
776
+ // - WhiteSpace
777
+ // - LineTerminator
778
+ // - Comment
779
+ // - Comma
780
+ //
781
+ // UnicodeBOM :: "Byte Order Mark (U+FEFF)"
782
+ //
783
+ // WhiteSpace ::
784
+ // - "Horizontal Tab (U+0009)"
785
+ // - "Space (U+0020)"
786
+ //
787
+ // Comma :: ,
788
+ case 65279:
789
+ // <BOM>
790
+ case 9:
791
+ // \t
792
+ case 32:
793
+ // <space>
794
+ case 44:
795
+ ++position;
796
+ continue;
797
+ // LineTerminator ::
798
+ // - "New Line (U+000A)"
799
+ // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"]
800
+ // - "Carriage Return (U+000D)" "New Line (U+000A)"
801
+ case 10:
802
+ ++position;
803
+ ++lexer.line;
804
+ lexer.lineStart = position;
805
+ continue;
806
+ case 13:
807
+ if (body.charCodeAt(position + 1) === 10) {
808
+ position += 2;
809
+ } else {
810
+ ++position;
811
+ }
812
+ ++lexer.line;
813
+ lexer.lineStart = position;
814
+ continue;
815
+ // Comment
816
+ case 35:
817
+ return readComment(lexer, position);
818
+ // Token ::
819
+ // - Punctuator
820
+ // - Name
821
+ // - IntValue
822
+ // - FloatValue
823
+ // - StringValue
824
+ //
825
+ // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }
826
+ case 33:
827
+ return createToken(lexer, TokenKind.BANG, position, position + 1);
828
+ case 36:
829
+ return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
830
+ case 38:
831
+ return createToken(lexer, TokenKind.AMP, position, position + 1);
832
+ case 40:
833
+ return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
834
+ case 41:
835
+ return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
836
+ case 46:
837
+ if (body.charCodeAt(position + 1) === 46 && body.charCodeAt(position + 2) === 46) {
838
+ return createToken(lexer, TokenKind.SPREAD, position, position + 3);
839
+ }
840
+ break;
841
+ case 58:
842
+ return createToken(lexer, TokenKind.COLON, position, position + 1);
843
+ case 61:
844
+ return createToken(lexer, TokenKind.EQUALS, position, position + 1);
845
+ case 64:
846
+ return createToken(lexer, TokenKind.AT, position, position + 1);
847
+ case 91:
848
+ return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
849
+ case 93:
850
+ return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
851
+ case 123:
852
+ return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
853
+ case 124:
854
+ return createToken(lexer, TokenKind.PIPE, position, position + 1);
855
+ case 125:
856
+ return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
857
+ // StringValue
858
+ case 34:
859
+ if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
860
+ return readBlockString(lexer, position);
861
+ }
862
+ return readString(lexer, position);
863
+ }
864
+ if (isDigit(code) || code === 45) {
865
+ return readNumber(lexer, position, code);
866
+ }
867
+ if (isNameStart(code)) {
868
+ return readName(lexer, position);
869
+ }
870
+ throw syntaxError(
871
+ lexer.source,
872
+ position,
873
+ code === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`
874
+ );
875
+ }
876
+ return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
877
+ }
878
+ function readComment(lexer, start) {
879
+ const body = lexer.source.body;
880
+ const bodyLength = body.length;
881
+ let position = start + 1;
882
+ while (position < bodyLength) {
883
+ const code = body.charCodeAt(position);
884
+ if (code === 10 || code === 13) {
885
+ break;
886
+ }
887
+ if (isUnicodeScalarValue(code)) {
888
+ ++position;
889
+ } else if (isSupplementaryCodePoint(body, position)) {
890
+ position += 2;
891
+ } else {
892
+ break;
893
+ }
894
+ }
895
+ return createToken(
896
+ lexer,
897
+ TokenKind.COMMENT,
898
+ start,
899
+ position,
900
+ body.slice(start + 1, position)
901
+ );
902
+ }
903
+ function readNumber(lexer, start, firstCode) {
904
+ const body = lexer.source.body;
905
+ let position = start;
906
+ let code = firstCode;
907
+ let isFloat = false;
908
+ if (code === 45) {
909
+ code = body.charCodeAt(++position);
910
+ }
911
+ if (code === 48) {
912
+ code = body.charCodeAt(++position);
913
+ if (isDigit(code)) {
914
+ throw syntaxError(
915
+ lexer.source,
916
+ position,
917
+ `Invalid number, unexpected digit after 0: ${printCodePointAt(
918
+ lexer,
919
+ position
920
+ )}.`
921
+ );
922
+ }
923
+ } else {
924
+ position = readDigits(lexer, position, code);
925
+ code = body.charCodeAt(position);
926
+ }
927
+ if (code === 46) {
928
+ isFloat = true;
929
+ code = body.charCodeAt(++position);
930
+ position = readDigits(lexer, position, code);
931
+ code = body.charCodeAt(position);
932
+ }
933
+ if (code === 69 || code === 101) {
934
+ isFloat = true;
935
+ code = body.charCodeAt(++position);
936
+ if (code === 43 || code === 45) {
937
+ code = body.charCodeAt(++position);
938
+ }
939
+ position = readDigits(lexer, position, code);
940
+ code = body.charCodeAt(position);
941
+ }
942
+ if (code === 46 || isNameStart(code)) {
943
+ throw syntaxError(
944
+ lexer.source,
945
+ position,
946
+ `Invalid number, expected digit but got: ${printCodePointAt(
947
+ lexer,
948
+ position
949
+ )}.`
950
+ );
951
+ }
952
+ return createToken(
953
+ lexer,
954
+ isFloat ? TokenKind.FLOAT : TokenKind.INT,
955
+ start,
956
+ position,
957
+ body.slice(start, position)
958
+ );
959
+ }
960
+ function readDigits(lexer, start, firstCode) {
961
+ if (!isDigit(firstCode)) {
962
+ throw syntaxError(
963
+ lexer.source,
964
+ start,
965
+ `Invalid number, expected digit but got: ${printCodePointAt(
966
+ lexer,
967
+ start
968
+ )}.`
969
+ );
970
+ }
971
+ const body = lexer.source.body;
972
+ let position = start + 1;
973
+ while (isDigit(body.charCodeAt(position))) {
974
+ ++position;
975
+ }
976
+ return position;
977
+ }
978
+ function readString(lexer, start) {
979
+ const body = lexer.source.body;
980
+ const bodyLength = body.length;
981
+ let position = start + 1;
982
+ let chunkStart = position;
983
+ let value = "";
984
+ while (position < bodyLength) {
985
+ const code = body.charCodeAt(position);
986
+ if (code === 34) {
987
+ value += body.slice(chunkStart, position);
988
+ return createToken(lexer, TokenKind.STRING, start, position + 1, value);
989
+ }
990
+ if (code === 92) {
991
+ value += body.slice(chunkStart, position);
992
+ const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position);
993
+ value += escape.value;
994
+ position += escape.size;
995
+ chunkStart = position;
996
+ continue;
997
+ }
998
+ if (code === 10 || code === 13) {
999
+ break;
1000
+ }
1001
+ if (isUnicodeScalarValue(code)) {
1002
+ ++position;
1003
+ } else if (isSupplementaryCodePoint(body, position)) {
1004
+ position += 2;
1005
+ } else {
1006
+ throw syntaxError(
1007
+ lexer.source,
1008
+ position,
1009
+ `Invalid character within String: ${printCodePointAt(
1010
+ lexer,
1011
+ position
1012
+ )}.`
1013
+ );
1014
+ }
1015
+ }
1016
+ throw syntaxError(lexer.source, position, "Unterminated string.");
1017
+ }
1018
+ function readEscapedUnicodeVariableWidth(lexer, position) {
1019
+ const body = lexer.source.body;
1020
+ let point = 0;
1021
+ let size = 3;
1022
+ while (size < 12) {
1023
+ const code = body.charCodeAt(position + size++);
1024
+ if (code === 125) {
1025
+ if (size < 5 || !isUnicodeScalarValue(point)) {
1026
+ break;
1027
+ }
1028
+ return {
1029
+ value: String.fromCodePoint(point),
1030
+ size
1031
+ };
1032
+ }
1033
+ point = point << 4 | readHexDigit(code);
1034
+ if (point < 0) {
1035
+ break;
1036
+ }
1037
+ }
1038
+ throw syntaxError(
1039
+ lexer.source,
1040
+ position,
1041
+ `Invalid Unicode escape sequence: "${body.slice(
1042
+ position,
1043
+ position + size
1044
+ )}".`
1045
+ );
1046
+ }
1047
+ function readEscapedUnicodeFixedWidth(lexer, position) {
1048
+ const body = lexer.source.body;
1049
+ const code = read16BitHexCode(body, position + 2);
1050
+ if (isUnicodeScalarValue(code)) {
1051
+ return {
1052
+ value: String.fromCodePoint(code),
1053
+ size: 6
1054
+ };
1055
+ }
1056
+ if (isLeadingSurrogate(code)) {
1057
+ if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) {
1058
+ const trailingCode = read16BitHexCode(body, position + 8);
1059
+ if (isTrailingSurrogate(trailingCode)) {
1060
+ return {
1061
+ value: String.fromCodePoint(code, trailingCode),
1062
+ size: 12
1063
+ };
1064
+ }
1065
+ }
1066
+ }
1067
+ throw syntaxError(
1068
+ lexer.source,
1069
+ position,
1070
+ `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`
1071
+ );
1072
+ }
1073
+ function read16BitHexCode(body, position) {
1074
+ return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3));
1075
+ }
1076
+ function readHexDigit(code) {
1077
+ return code >= 48 && code <= 57 ? code - 48 : code >= 65 && code <= 70 ? code - 55 : code >= 97 && code <= 102 ? code - 87 : -1;
1078
+ }
1079
+ function readEscapedCharacter(lexer, position) {
1080
+ const body = lexer.source.body;
1081
+ const code = body.charCodeAt(position + 1);
1082
+ switch (code) {
1083
+ case 34:
1084
+ return {
1085
+ value: '"',
1086
+ size: 2
1087
+ };
1088
+ case 92:
1089
+ return {
1090
+ value: "\\",
1091
+ size: 2
1092
+ };
1093
+ case 47:
1094
+ return {
1095
+ value: "/",
1096
+ size: 2
1097
+ };
1098
+ case 98:
1099
+ return {
1100
+ value: "\b",
1101
+ size: 2
1102
+ };
1103
+ case 102:
1104
+ return {
1105
+ value: "\f",
1106
+ size: 2
1107
+ };
1108
+ case 110:
1109
+ return {
1110
+ value: "\n",
1111
+ size: 2
1112
+ };
1113
+ case 114:
1114
+ return {
1115
+ value: "\r",
1116
+ size: 2
1117
+ };
1118
+ case 116:
1119
+ return {
1120
+ value: " ",
1121
+ size: 2
1122
+ };
1123
+ }
1124
+ throw syntaxError(
1125
+ lexer.source,
1126
+ position,
1127
+ `Invalid character escape sequence: "${body.slice(
1128
+ position,
1129
+ position + 2
1130
+ )}".`
1131
+ );
1132
+ }
1133
+ function readBlockString(lexer, start) {
1134
+ const body = lexer.source.body;
1135
+ const bodyLength = body.length;
1136
+ let lineStart = lexer.lineStart;
1137
+ let position = start + 3;
1138
+ let chunkStart = position;
1139
+ let currentLine = "";
1140
+ const blockLines = [];
1141
+ while (position < bodyLength) {
1142
+ const code = body.charCodeAt(position);
1143
+ if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
1144
+ currentLine += body.slice(chunkStart, position);
1145
+ blockLines.push(currentLine);
1146
+ const token = createToken(
1147
+ lexer,
1148
+ TokenKind.BLOCK_STRING,
1149
+ start,
1150
+ position + 3,
1151
+ // Return a string of the lines joined with U+000A.
1152
+ dedentBlockStringLines(blockLines).join("\n")
1153
+ );
1154
+ lexer.line += blockLines.length - 1;
1155
+ lexer.lineStart = lineStart;
1156
+ return token;
1157
+ }
1158
+ if (code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
1159
+ currentLine += body.slice(chunkStart, position);
1160
+ chunkStart = position + 1;
1161
+ position += 4;
1162
+ continue;
1163
+ }
1164
+ if (code === 10 || code === 13) {
1165
+ currentLine += body.slice(chunkStart, position);
1166
+ blockLines.push(currentLine);
1167
+ if (code === 13 && body.charCodeAt(position + 1) === 10) {
1168
+ position += 2;
1169
+ } else {
1170
+ ++position;
1171
+ }
1172
+ currentLine = "";
1173
+ chunkStart = position;
1174
+ lineStart = position;
1175
+ continue;
1176
+ }
1177
+ if (isUnicodeScalarValue(code)) {
1178
+ ++position;
1179
+ } else if (isSupplementaryCodePoint(body, position)) {
1180
+ position += 2;
1181
+ } else {
1182
+ throw syntaxError(
1183
+ lexer.source,
1184
+ position,
1185
+ `Invalid character within String: ${printCodePointAt(
1186
+ lexer,
1187
+ position
1188
+ )}.`
1189
+ );
1190
+ }
1191
+ }
1192
+ throw syntaxError(lexer.source, position, "Unterminated string.");
1193
+ }
1194
+ function readName(lexer, start) {
1195
+ const body = lexer.source.body;
1196
+ const bodyLength = body.length;
1197
+ let position = start + 1;
1198
+ while (position < bodyLength) {
1199
+ const code = body.charCodeAt(position);
1200
+ if (isNameContinue(code)) {
1201
+ ++position;
1202
+ } else {
1203
+ break;
1204
+ }
1205
+ }
1206
+ return createToken(
1207
+ lexer,
1208
+ TokenKind.NAME,
1209
+ start,
1210
+ position,
1211
+ body.slice(start, position)
1212
+ );
1213
+ }
1214
+ var DirectiveLocation;
1215
+ (function(DirectiveLocation2) {
1216
+ DirectiveLocation2["QUERY"] = "QUERY";
1217
+ DirectiveLocation2["MUTATION"] = "MUTATION";
1218
+ DirectiveLocation2["SUBSCRIPTION"] = "SUBSCRIPTION";
1219
+ DirectiveLocation2["FIELD"] = "FIELD";
1220
+ DirectiveLocation2["FRAGMENT_DEFINITION"] = "FRAGMENT_DEFINITION";
1221
+ DirectiveLocation2["FRAGMENT_SPREAD"] = "FRAGMENT_SPREAD";
1222
+ DirectiveLocation2["INLINE_FRAGMENT"] = "INLINE_FRAGMENT";
1223
+ DirectiveLocation2["VARIABLE_DEFINITION"] = "VARIABLE_DEFINITION";
1224
+ DirectiveLocation2["SCHEMA"] = "SCHEMA";
1225
+ DirectiveLocation2["SCALAR"] = "SCALAR";
1226
+ DirectiveLocation2["OBJECT"] = "OBJECT";
1227
+ DirectiveLocation2["FIELD_DEFINITION"] = "FIELD_DEFINITION";
1228
+ DirectiveLocation2["ARGUMENT_DEFINITION"] = "ARGUMENT_DEFINITION";
1229
+ DirectiveLocation2["INTERFACE"] = "INTERFACE";
1230
+ DirectiveLocation2["UNION"] = "UNION";
1231
+ DirectiveLocation2["ENUM"] = "ENUM";
1232
+ DirectiveLocation2["ENUM_VALUE"] = "ENUM_VALUE";
1233
+ DirectiveLocation2["INPUT_OBJECT"] = "INPUT_OBJECT";
1234
+ DirectiveLocation2["INPUT_FIELD_DEFINITION"] = "INPUT_FIELD_DEFINITION";
1235
+ })(DirectiveLocation || (DirectiveLocation = {}));
1236
+ function parse(source, options) {
1237
+ const parser = new Parser(source, options);
1238
+ const document = parser.parseDocument();
1239
+ Object.defineProperty(document, "tokenCount", {
1240
+ enumerable: false,
1241
+ value: parser.tokenCount
1242
+ });
1243
+ return document;
1244
+ }
1245
+ class Parser {
1246
+ constructor(source, options = {}) {
1247
+ const sourceObj = isSource(source) ? source : new Source(source);
1248
+ this._lexer = new Lexer(sourceObj);
1249
+ this._options = options;
1250
+ this._tokenCounter = 0;
1251
+ }
1252
+ get tokenCount() {
1253
+ return this._tokenCounter;
1254
+ }
1255
+ /**
1256
+ * Converts a name lex token into a name parse node.
1257
+ */
1258
+ parseName() {
1259
+ const token = this.expectToken(TokenKind.NAME);
1260
+ return this.node(token, {
1261
+ kind: Kind.NAME,
1262
+ value: token.value
1263
+ });
1264
+ }
1265
+ // Implements the parsing rules in the Document section.
1266
+ /**
1267
+ * Document : Definition+
1268
+ */
1269
+ parseDocument() {
1270
+ return this.node(this._lexer.token, {
1271
+ kind: Kind.DOCUMENT,
1272
+ definitions: this.many(
1273
+ TokenKind.SOF,
1274
+ this.parseDefinition,
1275
+ TokenKind.EOF
1276
+ )
1277
+ });
1278
+ }
1279
+ /**
1280
+ * Definition :
1281
+ * - ExecutableDefinition
1282
+ * - TypeSystemDefinition
1283
+ * - TypeSystemExtension
1284
+ *
1285
+ * ExecutableDefinition :
1286
+ * - OperationDefinition
1287
+ * - FragmentDefinition
1288
+ *
1289
+ * TypeSystemDefinition :
1290
+ * - SchemaDefinition
1291
+ * - TypeDefinition
1292
+ * - DirectiveDefinition
1293
+ *
1294
+ * TypeDefinition :
1295
+ * - ScalarTypeDefinition
1296
+ * - ObjectTypeDefinition
1297
+ * - InterfaceTypeDefinition
1298
+ * - UnionTypeDefinition
1299
+ * - EnumTypeDefinition
1300
+ * - InputObjectTypeDefinition
1301
+ */
1302
+ parseDefinition() {
1303
+ if (this.peek(TokenKind.BRACE_L)) {
1304
+ return this.parseOperationDefinition();
1305
+ }
1306
+ const hasDescription = this.peekDescription();
1307
+ const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token;
1308
+ if (keywordToken.kind === TokenKind.NAME) {
1309
+ switch (keywordToken.value) {
1310
+ case "schema":
1311
+ return this.parseSchemaDefinition();
1312
+ case "scalar":
1313
+ return this.parseScalarTypeDefinition();
1314
+ case "type":
1315
+ return this.parseObjectTypeDefinition();
1316
+ case "interface":
1317
+ return this.parseInterfaceTypeDefinition();
1318
+ case "union":
1319
+ return this.parseUnionTypeDefinition();
1320
+ case "enum":
1321
+ return this.parseEnumTypeDefinition();
1322
+ case "input":
1323
+ return this.parseInputObjectTypeDefinition();
1324
+ case "directive":
1325
+ return this.parseDirectiveDefinition();
1326
+ }
1327
+ if (hasDescription) {
1328
+ throw syntaxError(
1329
+ this._lexer.source,
1330
+ this._lexer.token.start,
1331
+ "Unexpected description, descriptions are supported only on type definitions."
1332
+ );
1333
+ }
1334
+ switch (keywordToken.value) {
1335
+ case "query":
1336
+ case "mutation":
1337
+ case "subscription":
1338
+ return this.parseOperationDefinition();
1339
+ case "fragment":
1340
+ return this.parseFragmentDefinition();
1341
+ case "extend":
1342
+ return this.parseTypeSystemExtension();
1343
+ }
1344
+ }
1345
+ throw this.unexpected(keywordToken);
1346
+ }
1347
+ // Implements the parsing rules in the Operations section.
1348
+ /**
1349
+ * OperationDefinition :
1350
+ * - SelectionSet
1351
+ * - OperationType Name? VariableDefinitions? Directives? SelectionSet
1352
+ */
1353
+ parseOperationDefinition() {
1354
+ const start = this._lexer.token;
1355
+ if (this.peek(TokenKind.BRACE_L)) {
1356
+ return this.node(start, {
1357
+ kind: Kind.OPERATION_DEFINITION,
1358
+ operation: OperationTypeNode.QUERY,
1359
+ name: void 0,
1360
+ variableDefinitions: [],
1361
+ directives: [],
1362
+ selectionSet: this.parseSelectionSet()
1363
+ });
1364
+ }
1365
+ const operation = this.parseOperationType();
1366
+ let name;
1367
+ if (this.peek(TokenKind.NAME)) {
1368
+ name = this.parseName();
1369
+ }
1370
+ return this.node(start, {
1371
+ kind: Kind.OPERATION_DEFINITION,
1372
+ operation,
1373
+ name,
1374
+ variableDefinitions: this.parseVariableDefinitions(),
1375
+ directives: this.parseDirectives(false),
1376
+ selectionSet: this.parseSelectionSet()
1377
+ });
1378
+ }
1379
+ /**
1380
+ * OperationType : one of query mutation subscription
1381
+ */
1382
+ parseOperationType() {
1383
+ const operationToken = this.expectToken(TokenKind.NAME);
1384
+ switch (operationToken.value) {
1385
+ case "query":
1386
+ return OperationTypeNode.QUERY;
1387
+ case "mutation":
1388
+ return OperationTypeNode.MUTATION;
1389
+ case "subscription":
1390
+ return OperationTypeNode.SUBSCRIPTION;
1391
+ }
1392
+ throw this.unexpected(operationToken);
1393
+ }
1394
+ /**
1395
+ * VariableDefinitions : ( VariableDefinition+ )
1396
+ */
1397
+ parseVariableDefinitions() {
1398
+ return this.optionalMany(
1399
+ TokenKind.PAREN_L,
1400
+ this.parseVariableDefinition,
1401
+ TokenKind.PAREN_R
1402
+ );
1403
+ }
1404
+ /**
1405
+ * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
1406
+ */
1407
+ parseVariableDefinition() {
1408
+ return this.node(this._lexer.token, {
1409
+ kind: Kind.VARIABLE_DEFINITION,
1410
+ variable: this.parseVariable(),
1411
+ type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
1412
+ defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseConstValueLiteral() : void 0,
1413
+ directives: this.parseConstDirectives()
1414
+ });
1415
+ }
1416
+ /**
1417
+ * Variable : $ Name
1418
+ */
1419
+ parseVariable() {
1420
+ const start = this._lexer.token;
1421
+ this.expectToken(TokenKind.DOLLAR);
1422
+ return this.node(start, {
1423
+ kind: Kind.VARIABLE,
1424
+ name: this.parseName()
1425
+ });
1426
+ }
1427
+ /**
1428
+ * ```
1429
+ * SelectionSet : { Selection+ }
1430
+ * ```
1431
+ */
1432
+ parseSelectionSet() {
1433
+ return this.node(this._lexer.token, {
1434
+ kind: Kind.SELECTION_SET,
1435
+ selections: this.many(
1436
+ TokenKind.BRACE_L,
1437
+ this.parseSelection,
1438
+ TokenKind.BRACE_R
1439
+ )
1440
+ });
1441
+ }
1442
+ /**
1443
+ * Selection :
1444
+ * - Field
1445
+ * - FragmentSpread
1446
+ * - InlineFragment
1447
+ */
1448
+ parseSelection() {
1449
+ return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();
1450
+ }
1451
+ /**
1452
+ * Field : Alias? Name Arguments? Directives? SelectionSet?
1453
+ *
1454
+ * Alias : Name :
1455
+ */
1456
+ parseField() {
1457
+ const start = this._lexer.token;
1458
+ const nameOrAlias = this.parseName();
1459
+ let alias;
1460
+ let name;
1461
+ if (this.expectOptionalToken(TokenKind.COLON)) {
1462
+ alias = nameOrAlias;
1463
+ name = this.parseName();
1464
+ } else {
1465
+ name = nameOrAlias;
1466
+ }
1467
+ return this.node(start, {
1468
+ kind: Kind.FIELD,
1469
+ alias,
1470
+ name,
1471
+ arguments: this.parseArguments(false),
1472
+ directives: this.parseDirectives(false),
1473
+ selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : void 0
1474
+ });
1475
+ }
1476
+ /**
1477
+ * Arguments[Const] : ( Argument[?Const]+ )
1478
+ */
1479
+ parseArguments(isConst) {
1480
+ const item = isConst ? this.parseConstArgument : this.parseArgument;
1481
+ return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
1482
+ }
1483
+ /**
1484
+ * Argument[Const] : Name : Value[?Const]
1485
+ */
1486
+ parseArgument(isConst = false) {
1487
+ const start = this._lexer.token;
1488
+ const name = this.parseName();
1489
+ this.expectToken(TokenKind.COLON);
1490
+ return this.node(start, {
1491
+ kind: Kind.ARGUMENT,
1492
+ name,
1493
+ value: this.parseValueLiteral(isConst)
1494
+ });
1495
+ }
1496
+ parseConstArgument() {
1497
+ return this.parseArgument(true);
1498
+ }
1499
+ // Implements the parsing rules in the Fragments section.
1500
+ /**
1501
+ * Corresponds to both FragmentSpread and InlineFragment in the spec.
1502
+ *
1503
+ * FragmentSpread : ... FragmentName Directives?
1504
+ *
1505
+ * InlineFragment : ... TypeCondition? Directives? SelectionSet
1506
+ */
1507
+ parseFragment() {
1508
+ const start = this._lexer.token;
1509
+ this.expectToken(TokenKind.SPREAD);
1510
+ const hasTypeCondition = this.expectOptionalKeyword("on");
1511
+ if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
1512
+ return this.node(start, {
1513
+ kind: Kind.FRAGMENT_SPREAD,
1514
+ name: this.parseFragmentName(),
1515
+ directives: this.parseDirectives(false)
1516
+ });
1517
+ }
1518
+ return this.node(start, {
1519
+ kind: Kind.INLINE_FRAGMENT,
1520
+ typeCondition: hasTypeCondition ? this.parseNamedType() : void 0,
1521
+ directives: this.parseDirectives(false),
1522
+ selectionSet: this.parseSelectionSet()
1523
+ });
1524
+ }
1525
+ /**
1526
+ * FragmentDefinition :
1527
+ * - fragment FragmentName on TypeCondition Directives? SelectionSet
1528
+ *
1529
+ * TypeCondition : NamedType
1530
+ */
1531
+ parseFragmentDefinition() {
1532
+ const start = this._lexer.token;
1533
+ this.expectKeyword("fragment");
1534
+ if (this._options.allowLegacyFragmentVariables === true) {
1535
+ return this.node(start, {
1536
+ kind: Kind.FRAGMENT_DEFINITION,
1537
+ name: this.parseFragmentName(),
1538
+ variableDefinitions: this.parseVariableDefinitions(),
1539
+ typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
1540
+ directives: this.parseDirectives(false),
1541
+ selectionSet: this.parseSelectionSet()
1542
+ });
1543
+ }
1544
+ return this.node(start, {
1545
+ kind: Kind.FRAGMENT_DEFINITION,
1546
+ name: this.parseFragmentName(),
1547
+ typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
1548
+ directives: this.parseDirectives(false),
1549
+ selectionSet: this.parseSelectionSet()
1550
+ });
1551
+ }
1552
+ /**
1553
+ * FragmentName : Name but not `on`
1554
+ */
1555
+ parseFragmentName() {
1556
+ if (this._lexer.token.value === "on") {
1557
+ throw this.unexpected();
1558
+ }
1559
+ return this.parseName();
1560
+ }
1561
+ // Implements the parsing rules in the Values section.
1562
+ /**
1563
+ * Value[Const] :
1564
+ * - [~Const] Variable
1565
+ * - IntValue
1566
+ * - FloatValue
1567
+ * - StringValue
1568
+ * - BooleanValue
1569
+ * - NullValue
1570
+ * - EnumValue
1571
+ * - ListValue[?Const]
1572
+ * - ObjectValue[?Const]
1573
+ *
1574
+ * BooleanValue : one of `true` `false`
1575
+ *
1576
+ * NullValue : `null`
1577
+ *
1578
+ * EnumValue : Name but not `true`, `false` or `null`
1579
+ */
1580
+ parseValueLiteral(isConst) {
1581
+ const token = this._lexer.token;
1582
+ switch (token.kind) {
1583
+ case TokenKind.BRACKET_L:
1584
+ return this.parseList(isConst);
1585
+ case TokenKind.BRACE_L:
1586
+ return this.parseObject(isConst);
1587
+ case TokenKind.INT:
1588
+ this.advanceLexer();
1589
+ return this.node(token, {
1590
+ kind: Kind.INT,
1591
+ value: token.value
1592
+ });
1593
+ case TokenKind.FLOAT:
1594
+ this.advanceLexer();
1595
+ return this.node(token, {
1596
+ kind: Kind.FLOAT,
1597
+ value: token.value
1598
+ });
1599
+ case TokenKind.STRING:
1600
+ case TokenKind.BLOCK_STRING:
1601
+ return this.parseStringLiteral();
1602
+ case TokenKind.NAME:
1603
+ this.advanceLexer();
1604
+ switch (token.value) {
1605
+ case "true":
1606
+ return this.node(token, {
1607
+ kind: Kind.BOOLEAN,
1608
+ value: true
1609
+ });
1610
+ case "false":
1611
+ return this.node(token, {
1612
+ kind: Kind.BOOLEAN,
1613
+ value: false
1614
+ });
1615
+ case "null":
1616
+ return this.node(token, {
1617
+ kind: Kind.NULL
1618
+ });
1619
+ default:
1620
+ return this.node(token, {
1621
+ kind: Kind.ENUM,
1622
+ value: token.value
1623
+ });
1624
+ }
1625
+ case TokenKind.DOLLAR:
1626
+ if (isConst) {
1627
+ this.expectToken(TokenKind.DOLLAR);
1628
+ if (this._lexer.token.kind === TokenKind.NAME) {
1629
+ const varName = this._lexer.token.value;
1630
+ throw syntaxError(
1631
+ this._lexer.source,
1632
+ token.start,
1633
+ `Unexpected variable "$${varName}" in constant value.`
1634
+ );
1635
+ } else {
1636
+ throw this.unexpected(token);
1637
+ }
1638
+ }
1639
+ return this.parseVariable();
1640
+ default:
1641
+ throw this.unexpected();
1642
+ }
1643
+ }
1644
+ parseConstValueLiteral() {
1645
+ return this.parseValueLiteral(true);
1646
+ }
1647
+ parseStringLiteral() {
1648
+ const token = this._lexer.token;
1649
+ this.advanceLexer();
1650
+ return this.node(token, {
1651
+ kind: Kind.STRING,
1652
+ value: token.value,
1653
+ block: token.kind === TokenKind.BLOCK_STRING
1654
+ });
1655
+ }
1656
+ /**
1657
+ * ListValue[Const] :
1658
+ * - [ ]
1659
+ * - [ Value[?Const]+ ]
1660
+ */
1661
+ parseList(isConst) {
1662
+ const item = () => this.parseValueLiteral(isConst);
1663
+ return this.node(this._lexer.token, {
1664
+ kind: Kind.LIST,
1665
+ values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R)
1666
+ });
1667
+ }
1668
+ /**
1669
+ * ```
1670
+ * ObjectValue[Const] :
1671
+ * - { }
1672
+ * - { ObjectField[?Const]+ }
1673
+ * ```
1674
+ */
1675
+ parseObject(isConst) {
1676
+ const item = () => this.parseObjectField(isConst);
1677
+ return this.node(this._lexer.token, {
1678
+ kind: Kind.OBJECT,
1679
+ fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R)
1680
+ });
1681
+ }
1682
+ /**
1683
+ * ObjectField[Const] : Name : Value[?Const]
1684
+ */
1685
+ parseObjectField(isConst) {
1686
+ const start = this._lexer.token;
1687
+ const name = this.parseName();
1688
+ this.expectToken(TokenKind.COLON);
1689
+ return this.node(start, {
1690
+ kind: Kind.OBJECT_FIELD,
1691
+ name,
1692
+ value: this.parseValueLiteral(isConst)
1693
+ });
1694
+ }
1695
+ // Implements the parsing rules in the Directives section.
1696
+ /**
1697
+ * Directives[Const] : Directive[?Const]+
1698
+ */
1699
+ parseDirectives(isConst) {
1700
+ const directives = [];
1701
+ while (this.peek(TokenKind.AT)) {
1702
+ directives.push(this.parseDirective(isConst));
1703
+ }
1704
+ return directives;
1705
+ }
1706
+ parseConstDirectives() {
1707
+ return this.parseDirectives(true);
1708
+ }
1709
+ /**
1710
+ * ```
1711
+ * Directive[Const] : @ Name Arguments[?Const]?
1712
+ * ```
1713
+ */
1714
+ parseDirective(isConst) {
1715
+ const start = this._lexer.token;
1716
+ this.expectToken(TokenKind.AT);
1717
+ return this.node(start, {
1718
+ kind: Kind.DIRECTIVE,
1719
+ name: this.parseName(),
1720
+ arguments: this.parseArguments(isConst)
1721
+ });
1722
+ }
1723
+ // Implements the parsing rules in the Types section.
1724
+ /**
1725
+ * Type :
1726
+ * - NamedType
1727
+ * - ListType
1728
+ * - NonNullType
1729
+ */
1730
+ parseTypeReference() {
1731
+ const start = this._lexer.token;
1732
+ let type;
1733
+ if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
1734
+ const innerType = this.parseTypeReference();
1735
+ this.expectToken(TokenKind.BRACKET_R);
1736
+ type = this.node(start, {
1737
+ kind: Kind.LIST_TYPE,
1738
+ type: innerType
1739
+ });
1740
+ } else {
1741
+ type = this.parseNamedType();
1742
+ }
1743
+ if (this.expectOptionalToken(TokenKind.BANG)) {
1744
+ return this.node(start, {
1745
+ kind: Kind.NON_NULL_TYPE,
1746
+ type
1747
+ });
1748
+ }
1749
+ return type;
1750
+ }
1751
+ /**
1752
+ * NamedType : Name
1753
+ */
1754
+ parseNamedType() {
1755
+ return this.node(this._lexer.token, {
1756
+ kind: Kind.NAMED_TYPE,
1757
+ name: this.parseName()
1758
+ });
1759
+ }
1760
+ // Implements the parsing rules in the Type Definition section.
1761
+ peekDescription() {
1762
+ return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
1763
+ }
1764
+ /**
1765
+ * Description : StringValue
1766
+ */
1767
+ parseDescription() {
1768
+ if (this.peekDescription()) {
1769
+ return this.parseStringLiteral();
1770
+ }
1771
+ }
1772
+ /**
1773
+ * ```
1774
+ * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
1775
+ * ```
1776
+ */
1777
+ parseSchemaDefinition() {
1778
+ const start = this._lexer.token;
1779
+ const description = this.parseDescription();
1780
+ this.expectKeyword("schema");
1781
+ const directives = this.parseConstDirectives();
1782
+ const operationTypes = this.many(
1783
+ TokenKind.BRACE_L,
1784
+ this.parseOperationTypeDefinition,
1785
+ TokenKind.BRACE_R
1786
+ );
1787
+ return this.node(start, {
1788
+ kind: Kind.SCHEMA_DEFINITION,
1789
+ description,
1790
+ directives,
1791
+ operationTypes
1792
+ });
1793
+ }
1794
+ /**
1795
+ * OperationTypeDefinition : OperationType : NamedType
1796
+ */
1797
+ parseOperationTypeDefinition() {
1798
+ const start = this._lexer.token;
1799
+ const operation = this.parseOperationType();
1800
+ this.expectToken(TokenKind.COLON);
1801
+ const type = this.parseNamedType();
1802
+ return this.node(start, {
1803
+ kind: Kind.OPERATION_TYPE_DEFINITION,
1804
+ operation,
1805
+ type
1806
+ });
1807
+ }
1808
+ /**
1809
+ * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
1810
+ */
1811
+ parseScalarTypeDefinition() {
1812
+ const start = this._lexer.token;
1813
+ const description = this.parseDescription();
1814
+ this.expectKeyword("scalar");
1815
+ const name = this.parseName();
1816
+ const directives = this.parseConstDirectives();
1817
+ return this.node(start, {
1818
+ kind: Kind.SCALAR_TYPE_DEFINITION,
1819
+ description,
1820
+ name,
1821
+ directives
1822
+ });
1823
+ }
1824
+ /**
1825
+ * ObjectTypeDefinition :
1826
+ * Description?
1827
+ * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
1828
+ */
1829
+ parseObjectTypeDefinition() {
1830
+ const start = this._lexer.token;
1831
+ const description = this.parseDescription();
1832
+ this.expectKeyword("type");
1833
+ const name = this.parseName();
1834
+ const interfaces = this.parseImplementsInterfaces();
1835
+ const directives = this.parseConstDirectives();
1836
+ const fields = this.parseFieldsDefinition();
1837
+ return this.node(start, {
1838
+ kind: Kind.OBJECT_TYPE_DEFINITION,
1839
+ description,
1840
+ name,
1841
+ interfaces,
1842
+ directives,
1843
+ fields
1844
+ });
1845
+ }
1846
+ /**
1847
+ * ImplementsInterfaces :
1848
+ * - implements `&`? NamedType
1849
+ * - ImplementsInterfaces & NamedType
1850
+ */
1851
+ parseImplementsInterfaces() {
1852
+ return this.expectOptionalKeyword("implements") ? this.delimitedMany(TokenKind.AMP, this.parseNamedType) : [];
1853
+ }
1854
+ /**
1855
+ * ```
1856
+ * FieldsDefinition : { FieldDefinition+ }
1857
+ * ```
1858
+ */
1859
+ parseFieldsDefinition() {
1860
+ return this.optionalMany(
1861
+ TokenKind.BRACE_L,
1862
+ this.parseFieldDefinition,
1863
+ TokenKind.BRACE_R
1864
+ );
1865
+ }
1866
+ /**
1867
+ * FieldDefinition :
1868
+ * - Description? Name ArgumentsDefinition? : Type Directives[Const]?
1869
+ */
1870
+ parseFieldDefinition() {
1871
+ const start = this._lexer.token;
1872
+ const description = this.parseDescription();
1873
+ const name = this.parseName();
1874
+ const args = this.parseArgumentDefs();
1875
+ this.expectToken(TokenKind.COLON);
1876
+ const type = this.parseTypeReference();
1877
+ const directives = this.parseConstDirectives();
1878
+ return this.node(start, {
1879
+ kind: Kind.FIELD_DEFINITION,
1880
+ description,
1881
+ name,
1882
+ arguments: args,
1883
+ type,
1884
+ directives
1885
+ });
1886
+ }
1887
+ /**
1888
+ * ArgumentsDefinition : ( InputValueDefinition+ )
1889
+ */
1890
+ parseArgumentDefs() {
1891
+ return this.optionalMany(
1892
+ TokenKind.PAREN_L,
1893
+ this.parseInputValueDef,
1894
+ TokenKind.PAREN_R
1895
+ );
1896
+ }
1897
+ /**
1898
+ * InputValueDefinition :
1899
+ * - Description? Name : Type DefaultValue? Directives[Const]?
1900
+ */
1901
+ parseInputValueDef() {
1902
+ const start = this._lexer.token;
1903
+ const description = this.parseDescription();
1904
+ const name = this.parseName();
1905
+ this.expectToken(TokenKind.COLON);
1906
+ const type = this.parseTypeReference();
1907
+ let defaultValue;
1908
+ if (this.expectOptionalToken(TokenKind.EQUALS)) {
1909
+ defaultValue = this.parseConstValueLiteral();
1910
+ }
1911
+ const directives = this.parseConstDirectives();
1912
+ return this.node(start, {
1913
+ kind: Kind.INPUT_VALUE_DEFINITION,
1914
+ description,
1915
+ name,
1916
+ type,
1917
+ defaultValue,
1918
+ directives
1919
+ });
1920
+ }
1921
+ /**
1922
+ * InterfaceTypeDefinition :
1923
+ * - Description? interface Name Directives[Const]? FieldsDefinition?
1924
+ */
1925
+ parseInterfaceTypeDefinition() {
1926
+ const start = this._lexer.token;
1927
+ const description = this.parseDescription();
1928
+ this.expectKeyword("interface");
1929
+ const name = this.parseName();
1930
+ const interfaces = this.parseImplementsInterfaces();
1931
+ const directives = this.parseConstDirectives();
1932
+ const fields = this.parseFieldsDefinition();
1933
+ return this.node(start, {
1934
+ kind: Kind.INTERFACE_TYPE_DEFINITION,
1935
+ description,
1936
+ name,
1937
+ interfaces,
1938
+ directives,
1939
+ fields
1940
+ });
1941
+ }
1942
+ /**
1943
+ * UnionTypeDefinition :
1944
+ * - Description? union Name Directives[Const]? UnionMemberTypes?
1945
+ */
1946
+ parseUnionTypeDefinition() {
1947
+ const start = this._lexer.token;
1948
+ const description = this.parseDescription();
1949
+ this.expectKeyword("union");
1950
+ const name = this.parseName();
1951
+ const directives = this.parseConstDirectives();
1952
+ const types = this.parseUnionMemberTypes();
1953
+ return this.node(start, {
1954
+ kind: Kind.UNION_TYPE_DEFINITION,
1955
+ description,
1956
+ name,
1957
+ directives,
1958
+ types
1959
+ });
1960
+ }
1961
+ /**
1962
+ * UnionMemberTypes :
1963
+ * - = `|`? NamedType
1964
+ * - UnionMemberTypes | NamedType
1965
+ */
1966
+ parseUnionMemberTypes() {
1967
+ return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];
1968
+ }
1969
+ /**
1970
+ * EnumTypeDefinition :
1971
+ * - Description? enum Name Directives[Const]? EnumValuesDefinition?
1972
+ */
1973
+ parseEnumTypeDefinition() {
1974
+ const start = this._lexer.token;
1975
+ const description = this.parseDescription();
1976
+ this.expectKeyword("enum");
1977
+ const name = this.parseName();
1978
+ const directives = this.parseConstDirectives();
1979
+ const values = this.parseEnumValuesDefinition();
1980
+ return this.node(start, {
1981
+ kind: Kind.ENUM_TYPE_DEFINITION,
1982
+ description,
1983
+ name,
1984
+ directives,
1985
+ values
1986
+ });
1987
+ }
1988
+ /**
1989
+ * ```
1990
+ * EnumValuesDefinition : { EnumValueDefinition+ }
1991
+ * ```
1992
+ */
1993
+ parseEnumValuesDefinition() {
1994
+ return this.optionalMany(
1995
+ TokenKind.BRACE_L,
1996
+ this.parseEnumValueDefinition,
1997
+ TokenKind.BRACE_R
1998
+ );
1999
+ }
2000
+ /**
2001
+ * EnumValueDefinition : Description? EnumValue Directives[Const]?
2002
+ */
2003
+ parseEnumValueDefinition() {
2004
+ const start = this._lexer.token;
2005
+ const description = this.parseDescription();
2006
+ const name = this.parseEnumValueName();
2007
+ const directives = this.parseConstDirectives();
2008
+ return this.node(start, {
2009
+ kind: Kind.ENUM_VALUE_DEFINITION,
2010
+ description,
2011
+ name,
2012
+ directives
2013
+ });
2014
+ }
2015
+ /**
2016
+ * EnumValue : Name but not `true`, `false` or `null`
2017
+ */
2018
+ parseEnumValueName() {
2019
+ if (this._lexer.token.value === "true" || this._lexer.token.value === "false" || this._lexer.token.value === "null") {
2020
+ throw syntaxError(
2021
+ this._lexer.source,
2022
+ this._lexer.token.start,
2023
+ `${getTokenDesc(
2024
+ this._lexer.token
2025
+ )} is reserved and cannot be used for an enum value.`
2026
+ );
2027
+ }
2028
+ return this.parseName();
2029
+ }
2030
+ /**
2031
+ * InputObjectTypeDefinition :
2032
+ * - Description? input Name Directives[Const]? InputFieldsDefinition?
2033
+ */
2034
+ parseInputObjectTypeDefinition() {
2035
+ const start = this._lexer.token;
2036
+ const description = this.parseDescription();
2037
+ this.expectKeyword("input");
2038
+ const name = this.parseName();
2039
+ const directives = this.parseConstDirectives();
2040
+ const fields = this.parseInputFieldsDefinition();
2041
+ return this.node(start, {
2042
+ kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
2043
+ description,
2044
+ name,
2045
+ directives,
2046
+ fields
2047
+ });
2048
+ }
2049
+ /**
2050
+ * ```
2051
+ * InputFieldsDefinition : { InputValueDefinition+ }
2052
+ * ```
2053
+ */
2054
+ parseInputFieldsDefinition() {
2055
+ return this.optionalMany(
2056
+ TokenKind.BRACE_L,
2057
+ this.parseInputValueDef,
2058
+ TokenKind.BRACE_R
2059
+ );
2060
+ }
2061
+ /**
2062
+ * TypeSystemExtension :
2063
+ * - SchemaExtension
2064
+ * - TypeExtension
2065
+ *
2066
+ * TypeExtension :
2067
+ * - ScalarTypeExtension
2068
+ * - ObjectTypeExtension
2069
+ * - InterfaceTypeExtension
2070
+ * - UnionTypeExtension
2071
+ * - EnumTypeExtension
2072
+ * - InputObjectTypeDefinition
2073
+ */
2074
+ parseTypeSystemExtension() {
2075
+ const keywordToken = this._lexer.lookahead();
2076
+ if (keywordToken.kind === TokenKind.NAME) {
2077
+ switch (keywordToken.value) {
2078
+ case "schema":
2079
+ return this.parseSchemaExtension();
2080
+ case "scalar":
2081
+ return this.parseScalarTypeExtension();
2082
+ case "type":
2083
+ return this.parseObjectTypeExtension();
2084
+ case "interface":
2085
+ return this.parseInterfaceTypeExtension();
2086
+ case "union":
2087
+ return this.parseUnionTypeExtension();
2088
+ case "enum":
2089
+ return this.parseEnumTypeExtension();
2090
+ case "input":
2091
+ return this.parseInputObjectTypeExtension();
2092
+ }
2093
+ }
2094
+ throw this.unexpected(keywordToken);
2095
+ }
2096
+ /**
2097
+ * ```
2098
+ * SchemaExtension :
2099
+ * - extend schema Directives[Const]? { OperationTypeDefinition+ }
2100
+ * - extend schema Directives[Const]
2101
+ * ```
2102
+ */
2103
+ parseSchemaExtension() {
2104
+ const start = this._lexer.token;
2105
+ this.expectKeyword("extend");
2106
+ this.expectKeyword("schema");
2107
+ const directives = this.parseConstDirectives();
2108
+ const operationTypes = this.optionalMany(
2109
+ TokenKind.BRACE_L,
2110
+ this.parseOperationTypeDefinition,
2111
+ TokenKind.BRACE_R
2112
+ );
2113
+ if (directives.length === 0 && operationTypes.length === 0) {
2114
+ throw this.unexpected();
2115
+ }
2116
+ return this.node(start, {
2117
+ kind: Kind.SCHEMA_EXTENSION,
2118
+ directives,
2119
+ operationTypes
2120
+ });
2121
+ }
2122
+ /**
2123
+ * ScalarTypeExtension :
2124
+ * - extend scalar Name Directives[Const]
2125
+ */
2126
+ parseScalarTypeExtension() {
2127
+ const start = this._lexer.token;
2128
+ this.expectKeyword("extend");
2129
+ this.expectKeyword("scalar");
2130
+ const name = this.parseName();
2131
+ const directives = this.parseConstDirectives();
2132
+ if (directives.length === 0) {
2133
+ throw this.unexpected();
2134
+ }
2135
+ return this.node(start, {
2136
+ kind: Kind.SCALAR_TYPE_EXTENSION,
2137
+ name,
2138
+ directives
2139
+ });
2140
+ }
2141
+ /**
2142
+ * ObjectTypeExtension :
2143
+ * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
2144
+ * - extend type Name ImplementsInterfaces? Directives[Const]
2145
+ * - extend type Name ImplementsInterfaces
2146
+ */
2147
+ parseObjectTypeExtension() {
2148
+ const start = this._lexer.token;
2149
+ this.expectKeyword("extend");
2150
+ this.expectKeyword("type");
2151
+ const name = this.parseName();
2152
+ const interfaces = this.parseImplementsInterfaces();
2153
+ const directives = this.parseConstDirectives();
2154
+ const fields = this.parseFieldsDefinition();
2155
+ if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
2156
+ throw this.unexpected();
2157
+ }
2158
+ return this.node(start, {
2159
+ kind: Kind.OBJECT_TYPE_EXTENSION,
2160
+ name,
2161
+ interfaces,
2162
+ directives,
2163
+ fields
2164
+ });
2165
+ }
2166
+ /**
2167
+ * InterfaceTypeExtension :
2168
+ * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
2169
+ * - extend interface Name ImplementsInterfaces? Directives[Const]
2170
+ * - extend interface Name ImplementsInterfaces
2171
+ */
2172
+ parseInterfaceTypeExtension() {
2173
+ const start = this._lexer.token;
2174
+ this.expectKeyword("extend");
2175
+ this.expectKeyword("interface");
2176
+ const name = this.parseName();
2177
+ const interfaces = this.parseImplementsInterfaces();
2178
+ const directives = this.parseConstDirectives();
2179
+ const fields = this.parseFieldsDefinition();
2180
+ if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
2181
+ throw this.unexpected();
2182
+ }
2183
+ return this.node(start, {
2184
+ kind: Kind.INTERFACE_TYPE_EXTENSION,
2185
+ name,
2186
+ interfaces,
2187
+ directives,
2188
+ fields
2189
+ });
2190
+ }
2191
+ /**
2192
+ * UnionTypeExtension :
2193
+ * - extend union Name Directives[Const]? UnionMemberTypes
2194
+ * - extend union Name Directives[Const]
2195
+ */
2196
+ parseUnionTypeExtension() {
2197
+ const start = this._lexer.token;
2198
+ this.expectKeyword("extend");
2199
+ this.expectKeyword("union");
2200
+ const name = this.parseName();
2201
+ const directives = this.parseConstDirectives();
2202
+ const types = this.parseUnionMemberTypes();
2203
+ if (directives.length === 0 && types.length === 0) {
2204
+ throw this.unexpected();
2205
+ }
2206
+ return this.node(start, {
2207
+ kind: Kind.UNION_TYPE_EXTENSION,
2208
+ name,
2209
+ directives,
2210
+ types
2211
+ });
2212
+ }
2213
+ /**
2214
+ * EnumTypeExtension :
2215
+ * - extend enum Name Directives[Const]? EnumValuesDefinition
2216
+ * - extend enum Name Directives[Const]
2217
+ */
2218
+ parseEnumTypeExtension() {
2219
+ const start = this._lexer.token;
2220
+ this.expectKeyword("extend");
2221
+ this.expectKeyword("enum");
2222
+ const name = this.parseName();
2223
+ const directives = this.parseConstDirectives();
2224
+ const values = this.parseEnumValuesDefinition();
2225
+ if (directives.length === 0 && values.length === 0) {
2226
+ throw this.unexpected();
2227
+ }
2228
+ return this.node(start, {
2229
+ kind: Kind.ENUM_TYPE_EXTENSION,
2230
+ name,
2231
+ directives,
2232
+ values
2233
+ });
2234
+ }
2235
+ /**
2236
+ * InputObjectTypeExtension :
2237
+ * - extend input Name Directives[Const]? InputFieldsDefinition
2238
+ * - extend input Name Directives[Const]
2239
+ */
2240
+ parseInputObjectTypeExtension() {
2241
+ const start = this._lexer.token;
2242
+ this.expectKeyword("extend");
2243
+ this.expectKeyword("input");
2244
+ const name = this.parseName();
2245
+ const directives = this.parseConstDirectives();
2246
+ const fields = this.parseInputFieldsDefinition();
2247
+ if (directives.length === 0 && fields.length === 0) {
2248
+ throw this.unexpected();
2249
+ }
2250
+ return this.node(start, {
2251
+ kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
2252
+ name,
2253
+ directives,
2254
+ fields
2255
+ });
2256
+ }
2257
+ /**
2258
+ * ```
2259
+ * DirectiveDefinition :
2260
+ * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
2261
+ * ```
2262
+ */
2263
+ parseDirectiveDefinition() {
2264
+ const start = this._lexer.token;
2265
+ const description = this.parseDescription();
2266
+ this.expectKeyword("directive");
2267
+ this.expectToken(TokenKind.AT);
2268
+ const name = this.parseName();
2269
+ const args = this.parseArgumentDefs();
2270
+ const repeatable = this.expectOptionalKeyword("repeatable");
2271
+ this.expectKeyword("on");
2272
+ const locations = this.parseDirectiveLocations();
2273
+ return this.node(start, {
2274
+ kind: Kind.DIRECTIVE_DEFINITION,
2275
+ description,
2276
+ name,
2277
+ arguments: args,
2278
+ repeatable,
2279
+ locations
2280
+ });
2281
+ }
2282
+ /**
2283
+ * DirectiveLocations :
2284
+ * - `|`? DirectiveLocation
2285
+ * - DirectiveLocations | DirectiveLocation
2286
+ */
2287
+ parseDirectiveLocations() {
2288
+ return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
2289
+ }
2290
+ /*
2291
+ * DirectiveLocation :
2292
+ * - ExecutableDirectiveLocation
2293
+ * - TypeSystemDirectiveLocation
2294
+ *
2295
+ * ExecutableDirectiveLocation : one of
2296
+ * `QUERY`
2297
+ * `MUTATION`
2298
+ * `SUBSCRIPTION`
2299
+ * `FIELD`
2300
+ * `FRAGMENT_DEFINITION`
2301
+ * `FRAGMENT_SPREAD`
2302
+ * `INLINE_FRAGMENT`
2303
+ *
2304
+ * TypeSystemDirectiveLocation : one of
2305
+ * `SCHEMA`
2306
+ * `SCALAR`
2307
+ * `OBJECT`
2308
+ * `FIELD_DEFINITION`
2309
+ * `ARGUMENT_DEFINITION`
2310
+ * `INTERFACE`
2311
+ * `UNION`
2312
+ * `ENUM`
2313
+ * `ENUM_VALUE`
2314
+ * `INPUT_OBJECT`
2315
+ * `INPUT_FIELD_DEFINITION`
2316
+ */
2317
+ parseDirectiveLocation() {
2318
+ const start = this._lexer.token;
2319
+ const name = this.parseName();
2320
+ if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {
2321
+ return name;
2322
+ }
2323
+ throw this.unexpected(start);
2324
+ }
2325
+ // Core parsing utility functions
2326
+ /**
2327
+ * Returns a node that, if configured to do so, sets a "loc" field as a
2328
+ * location object, used to identify the place in the source that created a
2329
+ * given parsed object.
2330
+ */
2331
+ node(startToken, node) {
2332
+ if (this._options.noLocation !== true) {
2333
+ node.loc = new Location(
2334
+ startToken,
2335
+ this._lexer.lastToken,
2336
+ this._lexer.source
2337
+ );
2338
+ }
2339
+ return node;
2340
+ }
2341
+ /**
2342
+ * Determines if the next token is of a given kind
2343
+ */
2344
+ peek(kind) {
2345
+ return this._lexer.token.kind === kind;
2346
+ }
2347
+ /**
2348
+ * If the next token is of the given kind, return that token after advancing the lexer.
2349
+ * Otherwise, do not change the parser state and throw an error.
2350
+ */
2351
+ expectToken(kind) {
2352
+ const token = this._lexer.token;
2353
+ if (token.kind === kind) {
2354
+ this.advanceLexer();
2355
+ return token;
2356
+ }
2357
+ throw syntaxError(
2358
+ this._lexer.source,
2359
+ token.start,
2360
+ `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`
2361
+ );
2362
+ }
2363
+ /**
2364
+ * If the next token is of the given kind, return "true" after advancing the lexer.
2365
+ * Otherwise, do not change the parser state and return "false".
2366
+ */
2367
+ expectOptionalToken(kind) {
2368
+ const token = this._lexer.token;
2369
+ if (token.kind === kind) {
2370
+ this.advanceLexer();
2371
+ return true;
2372
+ }
2373
+ return false;
2374
+ }
2375
+ /**
2376
+ * If the next token is a given keyword, advance the lexer.
2377
+ * Otherwise, do not change the parser state and throw an error.
2378
+ */
2379
+ expectKeyword(value) {
2380
+ const token = this._lexer.token;
2381
+ if (token.kind === TokenKind.NAME && token.value === value) {
2382
+ this.advanceLexer();
2383
+ } else {
2384
+ throw syntaxError(
2385
+ this._lexer.source,
2386
+ token.start,
2387
+ `Expected "${value}", found ${getTokenDesc(token)}.`
2388
+ );
2389
+ }
2390
+ }
2391
+ /**
2392
+ * If the next token is a given keyword, return "true" after advancing the lexer.
2393
+ * Otherwise, do not change the parser state and return "false".
2394
+ */
2395
+ expectOptionalKeyword(value) {
2396
+ const token = this._lexer.token;
2397
+ if (token.kind === TokenKind.NAME && token.value === value) {
2398
+ this.advanceLexer();
2399
+ return true;
2400
+ }
2401
+ return false;
2402
+ }
2403
+ /**
2404
+ * Helper function for creating an error when an unexpected lexed token is encountered.
2405
+ */
2406
+ unexpected(atToken) {
2407
+ const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
2408
+ return syntaxError(
2409
+ this._lexer.source,
2410
+ token.start,
2411
+ `Unexpected ${getTokenDesc(token)}.`
2412
+ );
2413
+ }
2414
+ /**
2415
+ * Returns a possibly empty list of parse nodes, determined by the parseFn.
2416
+ * This list begins with a lex token of openKind and ends with a lex token of closeKind.
2417
+ * Advances the parser to the next lex token after the closing token.
2418
+ */
2419
+ any(openKind, parseFn, closeKind) {
2420
+ this.expectToken(openKind);
2421
+ const nodes = [];
2422
+ while (!this.expectOptionalToken(closeKind)) {
2423
+ nodes.push(parseFn.call(this));
2424
+ }
2425
+ return nodes;
2426
+ }
2427
+ /**
2428
+ * Returns a list of parse nodes, determined by the parseFn.
2429
+ * It can be empty only if open token is missing otherwise it will always return non-empty list
2430
+ * that begins with a lex token of openKind and ends with a lex token of closeKind.
2431
+ * Advances the parser to the next lex token after the closing token.
2432
+ */
2433
+ optionalMany(openKind, parseFn, closeKind) {
2434
+ if (this.expectOptionalToken(openKind)) {
2435
+ const nodes = [];
2436
+ do {
2437
+ nodes.push(parseFn.call(this));
2438
+ } while (!this.expectOptionalToken(closeKind));
2439
+ return nodes;
2440
+ }
2441
+ return [];
2442
+ }
2443
+ /**
2444
+ * Returns a non-empty list of parse nodes, determined by the parseFn.
2445
+ * This list begins with a lex token of openKind and ends with a lex token of closeKind.
2446
+ * Advances the parser to the next lex token after the closing token.
2447
+ */
2448
+ many(openKind, parseFn, closeKind) {
2449
+ this.expectToken(openKind);
2450
+ const nodes = [];
2451
+ do {
2452
+ nodes.push(parseFn.call(this));
2453
+ } while (!this.expectOptionalToken(closeKind));
2454
+ return nodes;
2455
+ }
2456
+ /**
2457
+ * Returns a non-empty list of parse nodes, determined by the parseFn.
2458
+ * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
2459
+ * Advances the parser to the next lex token after last item in the list.
2460
+ */
2461
+ delimitedMany(delimiterKind, parseFn) {
2462
+ this.expectOptionalToken(delimiterKind);
2463
+ const nodes = [];
2464
+ do {
2465
+ nodes.push(parseFn.call(this));
2466
+ } while (this.expectOptionalToken(delimiterKind));
2467
+ return nodes;
2468
+ }
2469
+ advanceLexer() {
2470
+ const { maxTokens } = this._options;
2471
+ const token = this._lexer.advance();
2472
+ if (token.kind !== TokenKind.EOF) {
2473
+ ++this._tokenCounter;
2474
+ if (maxTokens !== void 0 && this._tokenCounter > maxTokens) {
2475
+ throw syntaxError(
2476
+ this._lexer.source,
2477
+ token.start,
2478
+ `Document contains more that ${maxTokens} tokens. Parsing aborted.`
2479
+ );
2480
+ }
2481
+ }
2482
+ }
2483
+ }
2484
+ function getTokenDesc(token) {
2485
+ const value = token.value;
2486
+ return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : "");
2487
+ }
2488
+ function getTokenKindDesc(kind) {
2489
+ return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind;
2490
+ }
2491
+ function stripIgnoredCharacters(source) {
2492
+ const sourceObj = isSource(source) ? source : new Source(source);
2493
+ const body = sourceObj.body;
2494
+ const lexer = new Lexer(sourceObj);
2495
+ let strippedBody = "";
2496
+ let wasLastAddedTokenNonPunctuator = false;
2497
+ while (lexer.advance().kind !== TokenKind.EOF) {
2498
+ const currentToken = lexer.token;
2499
+ const tokenKind = currentToken.kind;
2500
+ const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);
2501
+ if (wasLastAddedTokenNonPunctuator) {
2502
+ if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {
2503
+ strippedBody += " ";
2504
+ }
2505
+ }
2506
+ const tokenBody = body.slice(currentToken.start, currentToken.end);
2507
+ if (tokenKind === TokenKind.BLOCK_STRING) {
2508
+ strippedBody += printBlockString(currentToken.value, {
2509
+ minimize: true
2510
+ });
2511
+ } else {
2512
+ strippedBody += tokenBody;
2513
+ }
2514
+ wasLastAddedTokenNonPunctuator = isNonPunctuator;
2515
+ }
2516
+ return strippedBody;
2517
+ }
2518
+ const docMap = /* @__PURE__ */ new Map();
2519
+ const referenceMap = /* @__PURE__ */ new WeakMap();
2520
+ function operationKeyBuilder(inputString) {
2521
+ return stripIgnoredCharacters(inputString);
2522
+ }
2523
+ function parseDocument(inputString) {
2524
+ const operationKey = operationKeyBuilder(inputString);
2525
+ const cachedDoc = docMap.get(operationKey);
2526
+ if (cachedDoc !== void 0) {
2527
+ return cachedDoc;
2528
+ }
2529
+ const parsedDoc = parse(inputString, { noLocation: true });
2530
+ if (!parsedDoc || parsedDoc.kind !== "Document") {
2531
+ if (process.env.NODE_ENV !== "production") {
2532
+ throw new Error("Invalid graphql doc");
2533
+ }
2534
+ return null;
2535
+ }
2536
+ docMap.set(operationKey, parsedDoc);
2537
+ return parsedDoc;
2538
+ }
2539
+ function insertFragments(doc, fragments) {
2540
+ fragments.forEach((fragment) => {
2541
+ doc.definitions.push(fragment);
2542
+ });
2543
+ return doc;
2544
+ }
2545
+ function updateReferenceMapWithKnownKey(doc, key) {
2546
+ referenceMap.set(key, doc);
2547
+ }
2548
+ function updateReferenceMapAndGetKey(doc) {
2549
+ const key = new String();
2550
+ updateReferenceMapWithKnownKey(doc, key);
2551
+ return key;
2552
+ }
2553
+ function processSubstitutions(inputString, substitutions) {
2554
+ let outputString = "";
2555
+ const fragments = [];
2556
+ const subLength = substitutions.length;
2557
+ for (let i = 0; i < subLength; i++) {
2558
+ const substitution = substitutions[i];
2559
+ outputString += inputString[i];
2560
+ if (typeof substitution === "string" || typeof substitution === "number") {
2561
+ outputString += substitution;
2562
+ } else if (typeof substitution === "object") {
2563
+ const doc = referenceMap.get(substitution);
2564
+ if (doc === void 0) {
2565
+ if (process.env.NODE_ENV !== "production") {
2566
+ throw new Error("Invalid substitution fragment");
2567
+ }
2568
+ return null;
2569
+ }
2570
+ for (const def of doc.definitions) {
2571
+ fragments.push(def);
2572
+ }
2573
+ } else {
2574
+ if (process.env.NODE_ENV !== "production") {
2575
+ throw new Error("Unsupported substitution type");
2576
+ }
2577
+ return null;
2578
+ }
2579
+ }
2580
+ return {
2581
+ operationString: outputString + inputString[subLength],
2582
+ fragments
2583
+ };
2584
+ }
2585
+ const astResolver = function(astReference) {
2586
+ return referenceMap.get(astReference);
2587
+ };
2588
+ function gql(literals, ...subs) {
2589
+ let inputString;
2590
+ let inputSubstitutionFragments;
2591
+ if (!literals) {
2592
+ if (process.env.NODE_ENV !== "production") {
2593
+ throw new Error("Invalid query");
2594
+ }
2595
+ return null;
2596
+ } else if (typeof literals === "string") {
2597
+ inputString = literals.trim();
2598
+ inputSubstitutionFragments = [];
2599
+ } else {
2600
+ const sub = processSubstitutions(literals, subs);
2601
+ if (sub === null) {
2602
+ return null;
2603
+ }
2604
+ const { operationString, fragments } = sub;
2605
+ inputString = operationString.trim();
2606
+ inputSubstitutionFragments = fragments;
2607
+ }
2608
+ if (inputString.length === 0) {
2609
+ if (process.env.NODE_ENV !== "production") {
2610
+ throw new Error("Invalid query");
2611
+ }
2612
+ return null;
2613
+ }
2614
+ const document = parseDocument(inputString);
2615
+ if (document === null) {
2616
+ return null;
2617
+ }
2618
+ if (inputSubstitutionFragments.length === 0) {
2619
+ return updateReferenceMapAndGetKey(document);
2620
+ }
2621
+ return updateReferenceMapAndGetKey(insertFragments(document, inputSubstitutionFragments));
2622
+ }
2623
+ export {
2624
+ Kind,
2625
+ astResolver,
2626
+ gql,
2627
+ parse
2628
+ };
2629
+ //# sourceMappingURL=index.js.map