printer.js.flow 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. // @flow strict
  2. import type { ASTNode } from './ast';
  3. import { visit } from './visitor';
  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: addDescription(({ directives, operationTypes }) =>
  89. join(['schema', join(directives, ' '), block(operationTypes)], ' '),
  90. ),
  91. OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type,
  92. ScalarTypeDefinition: addDescription(({ name, directives }) =>
  93. join(['scalar', name, join(directives, ' ')], ' '),
  94. ),
  95. ObjectTypeDefinition: addDescription(
  96. ({ name, interfaces, directives, fields }) =>
  97. join(
  98. [
  99. 'type',
  100. name,
  101. wrap('implements ', join(interfaces, ' & ')),
  102. join(directives, ' '),
  103. block(fields),
  104. ],
  105. ' ',
  106. ),
  107. ),
  108. FieldDefinition: addDescription(
  109. ({ name, arguments: args, type, directives }) =>
  110. name +
  111. (hasMultilineItems(args)
  112. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  113. : wrap('(', join(args, ', '), ')')) +
  114. ': ' +
  115. type +
  116. wrap(' ', join(directives, ' ')),
  117. ),
  118. InputValueDefinition: addDescription(
  119. ({ name, type, defaultValue, directives }) =>
  120. join(
  121. [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],
  122. ' ',
  123. ),
  124. ),
  125. InterfaceTypeDefinition: addDescription(
  126. ({ name, interfaces, directives, fields }) =>
  127. join(
  128. [
  129. 'interface',
  130. name,
  131. wrap('implements ', join(interfaces, ' & ')),
  132. join(directives, ' '),
  133. block(fields),
  134. ],
  135. ' ',
  136. ),
  137. ),
  138. UnionTypeDefinition: addDescription(({ name, directives, types }) =>
  139. join(
  140. [
  141. 'union',
  142. name,
  143. join(directives, ' '),
  144. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  145. ],
  146. ' ',
  147. ),
  148. ),
  149. EnumTypeDefinition: addDescription(({ name, directives, values }) =>
  150. join(['enum', name, join(directives, ' '), block(values)], ' '),
  151. ),
  152. EnumValueDefinition: addDescription(({ name, directives }) =>
  153. join([name, join(directives, ' ')], ' '),
  154. ),
  155. InputObjectTypeDefinition: addDescription(({ name, directives, fields }) =>
  156. join(['input', name, join(directives, ' '), block(fields)], ' '),
  157. ),
  158. DirectiveDefinition: addDescription(
  159. ({ name, arguments: args, repeatable, locations }) =>
  160. 'directive @' +
  161. name +
  162. (hasMultilineItems(args)
  163. ? wrap('(\n', indent(join(args, '\n')), '\n)')
  164. : wrap('(', join(args, ', '), ')')) +
  165. (repeatable ? ' repeatable' : '') +
  166. ' on ' +
  167. join(locations, ' | '),
  168. ),
  169. SchemaExtension: ({ directives, operationTypes }) =>
  170. join(['extend schema', join(directives, ' '), block(operationTypes)], ' '),
  171. ScalarTypeExtension: ({ name, directives }) =>
  172. join(['extend scalar', name, join(directives, ' ')], ' '),
  173. ObjectTypeExtension: ({ name, interfaces, directives, fields }) =>
  174. join(
  175. [
  176. 'extend type',
  177. name,
  178. wrap('implements ', join(interfaces, ' & ')),
  179. join(directives, ' '),
  180. block(fields),
  181. ],
  182. ' ',
  183. ),
  184. InterfaceTypeExtension: ({ name, interfaces, directives, fields }) =>
  185. join(
  186. [
  187. 'extend interface',
  188. name,
  189. wrap('implements ', join(interfaces, ' & ')),
  190. join(directives, ' '),
  191. block(fields),
  192. ],
  193. ' ',
  194. ),
  195. UnionTypeExtension: ({ name, directives, types }) =>
  196. join(
  197. [
  198. 'extend union',
  199. name,
  200. join(directives, ' '),
  201. types && types.length !== 0 ? '= ' + join(types, ' | ') : '',
  202. ],
  203. ' ',
  204. ),
  205. EnumTypeExtension: ({ name, directives, values }) =>
  206. join(['extend enum', name, join(directives, ' '), block(values)], ' '),
  207. InputObjectTypeExtension: ({ name, directives, fields }) =>
  208. join(['extend input', name, join(directives, ' '), block(fields)], ' '),
  209. };
  210. function addDescription(cb) {
  211. return (node) => join([node.description, cb(node)], '\n');
  212. }
  213. /**
  214. * Given maybeArray, print an empty string if it is null or empty, otherwise
  215. * print all items together separated by separator if provided
  216. */
  217. function join(maybeArray: ?Array<string>, separator = '') {
  218. return maybeArray?.filter((x) => x).join(separator) ?? '';
  219. }
  220. /**
  221. * Given array, print each item on its own line, wrapped in an
  222. * indented "{ }" block.
  223. */
  224. function block(array) {
  225. return array && array.length !== 0
  226. ? '{\n' + indent(join(array, '\n')) + '\n}'
  227. : '';
  228. }
  229. /**
  230. * If maybeString is not null or empty, then wrap with start and end, otherwise
  231. * print an empty string.
  232. */
  233. function wrap(start, maybeString, end = '') {
  234. return maybeString ? start + maybeString + end : '';
  235. }
  236. function indent(maybeString) {
  237. return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');
  238. }
  239. function isMultiline(string) {
  240. return string.indexOf('\n') !== -1;
  241. }
  242. function hasMultilineItems(maybeArray) {
  243. return maybeArray && maybeArray.some(isMultiline);
  244. }