printer.js.flow 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // @flow strict
  2. import { visit } from './visitor';
  3. import { type ASTNode } from './ast';
  4. import { printBlockString } from './blockString';
  5. /**
  6. * Converts an AST into a string, using one set of reasonable
  7. * formatting rules.
  8. */
  9. export function print(ast: ASTNode): string {
  10. return visit(ast, { leave: printDocASTReducer });
  11. }
  12. // TODO: provide better type coverage in future
  13. const printDocASTReducer: any = {
  14. Name: node => node.value,
  15. Variable: node => '$' + node.name,
  16. // Document
  17. Document: node => join(node.definitions, '\n\n') + '\n',
  18. OperationDefinition(node) {
  19. const op = node.operation;
  20. const name = node.name;
  21. const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
  22. const directives = join(node.directives, ' ');
  23. const selectionSet = node.selectionSet;
  24. // Anonymous queries with no directives or variable definitions can use
  25. // the query short form.
  26. return !name && !directives && !varDefs && op === 'query'
  27. ? selectionSet
  28. : join([op, join([name, varDefs]), directives, selectionSet], ' ');
  29. },
  30. VariableDefinition: ({ variable, type, defaultValue, directives }) =>
  31. variable +
  32. ': ' +
  33. type +
  34. wrap(' = ', defaultValue) +
  35. wrap(' ', join(directives, ' ')),
  36. SelectionSet: ({ selections }) => block(selections),
  37. Field: ({ alias, name, arguments: args, directives, selectionSet }) =>
  38. join(
  39. [
  40. wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'),
  41. join(directives, ' '),
  42. selectionSet,
  43. ],
  44. ' ',
  45. ),
  46. Argument: ({ name, value }) => name + ': ' + value,
  47. // Fragments
  48. FragmentSpread: ({ name, directives }) =>
  49. '...' + name + wrap(' ', join(directives, ' ')),
  50. InlineFragment: ({ typeCondition, directives, selectionSet }) =>
  51. join(
  52. ['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet],
  53. ' ',
  54. ),
  55. FragmentDefinition: ({
  56. name,
  57. typeCondition,
  58. variableDefinitions,
  59. directives,
  60. selectionSet,
  61. }) =>
  62. // Note: fragment variable definitions are experimental and may be changed
  63. // or removed in the future.
  64. `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +
  65. `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +
  66. selectionSet,
  67. // Value
  68. IntValue: ({ value }) => value,
  69. FloatValue: ({ value }) => value,
  70. StringValue: ({ value, block: isBlockString }, key) =>
  71. isBlockString
  72. ? printBlockString(value, key === 'description' ? '' : ' ')
  73. : JSON.stringify(value),
  74. BooleanValue: ({ value }) => (value ? 'true' : 'false'),
  75. NullValue: () => 'null',
  76. EnumValue: ({ value }) => value,
  77. ListValue: ({ values }) => '[' + join(values, ', ') + ']',
  78. ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}',
  79. ObjectField: ({ name, value }) => name + ': ' + value,
  80. // Directive
  81. Directive: ({ name, arguments: args }) =>
  82. '@' + name + wrap('(', join(args, ', '), ')'),
  83. // Type
  84. NamedType: ({ name }) => name,
  85. ListType: ({ type }) => '[' + type + ']',
  86. NonNullType: ({ type }) => type + '!',
  87. // Type System Definitions
  88. SchemaDefinition: ({ directives, operationTypes }) =>
  89. join(['schema', join(directives, ' '), block(operationTypes)], ' '),
  90. OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type,
  91. ScalarTypeDefinition: addDescription(({ name, directives }) =>
  92. join(['scalar', name, join(directives, ' ')], ' '),
  93. ),
  94. ObjectTypeDefinition: addDescription(
  95. ({ name, interfaces, directives, fields }) =>
  96. join(
  97. [
  98. 'type',
  99. name,
  100. wrap('implements ', join(interfaces, ' & ')),
  101. join(directives, ' '),
  102. block(fields),
  103. ],
  104. ' ',
  105. ),
  106. ),
  107. FieldDefinition: addDescription(
  108. ({ name, arguments: args, type, directives }) =>
  109. name +
  110. (hasMultilineItems(args)
  111. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  112. : wrap('(', join(args, ', '), ')')) +
  113. ': ' +
  114. type +
  115. wrap(' ', join(directives, ' ')),
  116. ),
  117. InputValueDefinition: addDescription(
  118. ({ name, type, defaultValue, directives }) =>
  119. join(
  120. [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],
  121. ' ',
  122. ),
  123. ),
  124. InterfaceTypeDefinition: addDescription(({ name, directives, fields }) =>
  125. join(['interface', name, join(directives, ' '), block(fields)], ' '),
  126. ),
  127. UnionTypeDefinition: addDescription(({ name, directives, types }) =>
  128. join(
  129. [
  130. 'union',
  131. name,
  132. join(directives, ' '),
  133. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  134. ],
  135. ' ',
  136. ),
  137. ),
  138. EnumTypeDefinition: addDescription(({ name, directives, values }) =>
  139. join(['enum', name, join(directives, ' '), block(values)], ' '),
  140. ),
  141. EnumValueDefinition: addDescription(({ name, directives }) =>
  142. join([name, join(directives, ' ')], ' '),
  143. ),
  144. InputObjectTypeDefinition: addDescription(({ name, directives, fields }) =>
  145. join(['input', name, join(directives, ' '), block(fields)], ' '),
  146. ),
  147. DirectiveDefinition: addDescription(
  148. ({ name, arguments: args, repeatable, locations }) =>
  149. 'directive @' +
  150. name +
  151. (hasMultilineItems(args)
  152. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  153. : wrap('(', join(args, ', '), ')')) +
  154. (repeatable ? ' repeatable' : '') +
  155. ' on ' +
  156. join(locations, ' | '),
  157. ),
  158. SchemaExtension: ({ directives, operationTypes }) =>
  159. join(['extend schema', join(directives, ' '), block(operationTypes)], ' '),
  160. ScalarTypeExtension: ({ name, directives }) =>
  161. join(['extend scalar', name, join(directives, ' ')], ' '),
  162. ObjectTypeExtension: ({ name, interfaces, directives, fields }) =>
  163. join(
  164. [
  165. 'extend type',
  166. name,
  167. wrap('implements ', join(interfaces, ' & ')),
  168. join(directives, ' '),
  169. block(fields),
  170. ],
  171. ' ',
  172. ),
  173. InterfaceTypeExtension: ({ name, directives, fields }) =>
  174. join(['extend interface', name, join(directives, ' '), block(fields)], ' '),
  175. UnionTypeExtension: ({ name, directives, types }) =>
  176. join(
  177. [
  178. 'extend union',
  179. name,
  180. join(directives, ' '),
  181. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  182. ],
  183. ' ',
  184. ),
  185. EnumTypeExtension: ({ name, directives, values }) =>
  186. join(['extend enum', name, join(directives, ' '), block(values)], ' '),
  187. InputObjectTypeExtension: ({ name, directives, fields }) =>
  188. join(['extend input', name, join(directives, ' '), block(fields)], ' '),
  189. };
  190. function addDescription(cb) {
  191. return node => join([node.description, cb(node)], '\n');
  192. }
  193. /**
  194. * Given maybeArray, print an empty string if it is null or empty, otherwise
  195. * print all items together separated by separator if provided
  196. */
  197. function join(maybeArray, separator) {
  198. return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';
  199. }
  200. /**
  201. * Given array, print each item on its own line, wrapped in an
  202. * indented "{ }" block.
  203. */
  204. function block(array) {
  205. return array && array.length !== 0
  206. ? '{\n' + indent(join(array, '\n')) + '\n}'
  207. : '';
  208. }
  209. /**
  210. * If maybeString is not null or empty, then wrap with start and end, otherwise
  211. * print an empty string.
  212. */
  213. function wrap(start, maybeString, end) {
  214. return maybeString ? start + maybeString + (end || '') : '';
  215. }
  216. function indent(maybeString) {
  217. return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');
  218. }
  219. function isMultiline(string) {
  220. return string.indexOf('\n') !== -1;
  221. }
  222. function hasMultilineItems(maybeArray) {
  223. return maybeArray && maybeArray.some(isMultiline);
  224. }