introspection.lua 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. local path = (...):gsub('%.[^%.]+$', '')
  2. local types = require(path .. '.types')
  3. local util = require(path .. '.util')
  4. local cjson = require 'cjson' -- needs to be cloned from here https://github.com/openresty/lua-cjson for cjson.empty_array feature
  5. local function instanceof(t, s)
  6. return t.__type == s
  7. end
  8. local function trim(s)
  9. return s:gsub('^%s+', ''):gsub('%s$', ''):gsub('%s%s+', ' ')
  10. end
  11. local __Directive, __DirectiveLocation, __Type, __Field, __InputValue,__EnumValue, __TypeKind, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, astFromValue, printAst, printers
  12. local __Schema = types.object({
  13. name = '__Schema',
  14. description = trim [[
  15. A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types
  16. and directives on the server, as well as the entry points for query and mutation operations.
  17. ]],
  18. fields = function()
  19. return {
  20. types = {
  21. description = 'A list of all types supported by this server.',
  22. kind = types.nonNull(types.list(types.nonNull(__Type))),
  23. resolve = function(schema)
  24. return util.values(schema:getTypeMap())
  25. end
  26. },
  27. queryType = {
  28. description = 'The type that query operations will be rooted at.',
  29. kind = types.nonNull(__Type),
  30. resolve = function(schema)
  31. return schema:getQueryType()
  32. end
  33. },
  34. mutationType = {
  35. description = 'If this server supports mutation, the type that mutation operations will be rooted at.',
  36. kind = __Type,
  37. resolve = function(schema)
  38. return schema:getMutationType()
  39. end
  40. },
  41. directives = {
  42. description = 'A list of all directives supported by this server.',
  43. kind = types.nonNull(types.list(types.nonNull(__Directive))),
  44. resolve = function(schema)
  45. return schema.directives
  46. end
  47. }
  48. }
  49. end
  50. })
  51. __Directive = types.object({
  52. name = '__Directive',
  53. description = trim [[
  54. A Directive provides a way to describe alternate runtime execution and type validation behavior
  55. in a GraphQL document.
  56. In some cases, you need to provide options to alter GraphQL’s execution
  57. behavior in ways field arguments will not suffice, such as conditionally including or skipping a
  58. field. Directives provide this by describing additional information to the executor.
  59. ]],
  60. fields = function()
  61. return {
  62. name = types.nonNull(types.string),
  63. description = types.string,
  64. locations = {
  65. kind = types.nonNull(types.list(types.nonNull(
  66. __DirectiveLocation
  67. )))
  68. },
  69. args = {
  70. kind = types.nonNull(types.list(types.nonNull(__InputValue))),
  71. resolve = function(field)
  72. local args = {}
  73. local transform = function(a, n)
  74. if a.__type then
  75. return { kind = a, name = n }
  76. else
  77. if a.name then return a end
  78. local r = { name = n }
  79. for k,v in pairs(a) do
  80. r[k] = v
  81. end
  82. return r
  83. end
  84. end
  85. for k, v in pairs(field.arguments or {}) do
  86. table.insert(args, transform(v, k))
  87. end
  88. if #args > 0 then
  89. return args
  90. else
  91. return cjson.empty_array
  92. end
  93. end
  94. }
  95. }
  96. end
  97. })
  98. __DirectiveLocation = types.enum({
  99. name = '__DirectiveLocation',
  100. description = trim [[
  101. A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation
  102. describes one such possible adjacencies.
  103. ]],
  104. values = {
  105. QUERY = {
  106. value = 'QUERY',
  107. description = 'Location adjacent to a query operation.'
  108. },
  109. MUTATION = {
  110. value = 'MUTATION',
  111. description = 'Location adjacent to a mutation operation.'
  112. },
  113. FIELD = {
  114. value = 'FIELD',
  115. description = 'Location adjacent to a field.'
  116. },
  117. FRAGMENT_DEFINITION = {
  118. value = 'FRAGMENT_DEFINITION',
  119. description = 'Location adjacent to a fragment definition.'
  120. },
  121. FRAGMENT_SPREAD = {
  122. value = 'FRAGMENT_SPREAD',
  123. description = 'Location adjacent to a fragment spread.'
  124. },
  125. INLINE_FRAGMENT = {
  126. value = 'INLINE_FRAGMENT',
  127. description = 'Location adjacent to an inline fragment.'
  128. }
  129. }
  130. })
  131. __Type = types.object({
  132. name = '__Type',
  133. description = trim [[
  134. The fundamental unit of any GraphQL Schema is the type. There are
  135. many kinds of types in GraphQL as represented by the `__TypeKind` enum.
  136. Depending on the kind of a type, certain fields describe
  137. information about that type. Scalar types provide no information
  138. beyond a name and description, while Enum types provide their values.
  139. Object and Interface types provide the fields they describe. Abstract
  140. types, Union and Interface, provide the Object types possible
  141. at runtime. List and NonNull types compose other types.
  142. ]],
  143. fields = function()
  144. return {
  145. kind = {
  146. kind = __TypeKind.nonNull,
  147. resolve = function (type)
  148. if instanceof(type, 'Scalar') then
  149. return 'SCALAR'
  150. elseif instanceof(type, 'Object') then
  151. return 'OBJECT'
  152. elseif instanceof(type, 'Interface') then
  153. return 'INTERFACE'
  154. elseif instanceof(type, 'Union') then
  155. return 'UNION'
  156. elseif instanceof(type, 'Enum') then
  157. return 'ENUM'
  158. elseif instanceof(type, 'InputObject') then
  159. return 'INPUT_OBJECT'
  160. elseif instanceof(type, 'List') then
  161. return 'LIST'
  162. elseif instanceof(type, 'NonNull') then
  163. return 'NON_NULL'
  164. end
  165. error('Unknown kind of kind = ' .. type)
  166. end
  167. },
  168. name = types.string,
  169. description = types.string,
  170. fields = {
  171. kind = types.list(types.nonNull(__Field)),
  172. arguments = {
  173. includeDeprecated = { kind = types.boolean, defaultValue = false }
  174. },
  175. resolve = function(t, args)
  176. if instanceof(t, 'Object') or instanceof(t, 'Interface') then
  177. local fieldMap = t.fields
  178. local fields = {}
  179. for k,v in pairs(fieldMap) do
  180. table.insert(fields, fieldMap[k])
  181. end
  182. if not args.includeDeprecated then
  183. fields = util.filter(fields, function(field) return not field.deprecationReason end)
  184. end
  185. if #fields > 0 then
  186. return fields
  187. else
  188. return cjson.empty_array
  189. end
  190. end
  191. return nil
  192. end
  193. },
  194. interfaces = {
  195. kind = types.list(types.nonNull(__Type)),
  196. resolve = function(type)
  197. if instanceof(type, 'Object') then
  198. return type.interfaces and type.interfaces or cjson.empty_array
  199. end
  200. end
  201. },
  202. possibleTypes = {
  203. kind = types.list(types.nonNull(__Type)),
  204. resolve = function(type, args, context, obj)
  205. if instanceof(type, 'Interface') or instanceof(type, 'Union') then
  206. return context.schema:getPossibleTypes(type)
  207. end
  208. end
  209. },
  210. enumValues = {
  211. kind = types.list(types.nonNull(__EnumValue)),
  212. arguments = {
  213. includeDeprecated = { kind = types.boolean, defaultValue = false }
  214. },
  215. resolve = function(type, args)
  216. if instanceof(type, 'Enum') then
  217. local values = type.values
  218. if not args.includeDeprecated then
  219. values = util.filter(values, function(value) return not value.deprecationReason end)
  220. end
  221. return util.values(values)
  222. end
  223. end
  224. },
  225. inputFields = {
  226. kind = types.list(types.nonNull(__InputValue)),
  227. resolve = function(type)
  228. if instanceof(type, 'InputObject') then
  229. local fieldMap = type.fields
  230. local fields = {}
  231. for k, v in pairs(fieldMap) do
  232. table.insert(fields, fieldMap[k])
  233. end
  234. return fields
  235. end
  236. end
  237. },
  238. ofType = {
  239. kind = __Type
  240. }
  241. }
  242. end
  243. })
  244. __Field = types.object({
  245. name = '__Field',
  246. description =
  247. 'Object and Interface types are described by a list of Fields, each of ' ..
  248. 'which has a name, potentially a list of arguments, and a return type.',
  249. fields = function()
  250. return {
  251. name = types.nonNull(types.string),
  252. description = types.string,
  253. args = {
  254. -- kind = types.list(__InputValue),
  255. kind = types.nonNull(types.list(types.nonNull(__InputValue))),
  256. resolve = function(field)
  257. local args = {}
  258. local transform = function(a, n)
  259. if a.__type then
  260. return {kind = a, name = n}
  261. else
  262. if not a.name then
  263. local r = {name = n}
  264. for k,v in pairs(a) do
  265. r[k] = v
  266. end
  267. return r
  268. else
  269. return a
  270. end
  271. end
  272. end
  273. for k, v in pairs(field.arguments or {}) do table.insert(args, transform(v, k)) end
  274. -- return args
  275. if #args > 0 then return args else return cjson.empty_array end
  276. end
  277. },
  278. type = {
  279. kind = types.nonNull(__Type),
  280. resolve = function(field)
  281. return field.kind
  282. end
  283. },
  284. isDeprecated = {
  285. kind = types.nonNull(types.boolean),
  286. resolve = function(field)
  287. return field.deprecationReason ~= nil
  288. end
  289. },
  290. deprecationReason = types.string
  291. }
  292. end
  293. })
  294. __InputValue = types.object({
  295. name = '__InputValue',
  296. description = trim [[
  297. Arguments provided to Fields or Directives and the input fields of an
  298. InputObject are represented as Input Values which describe their type
  299. and optionally a default value.
  300. ]],
  301. fields = function()
  302. return {
  303. name = types.nonNull(types.string),
  304. description = types.string,
  305. type = { kind = types.nonNull(__Type), resolve = function(field) return field.kind end },
  306. defaultValue = {
  307. kind = types.string,
  308. description = 'A GraphQL-formatted string representing the default value for this ' ..
  309. 'input value.',
  310. resolve = function(inputVal)
  311. return inputVal.defaultValue and printAst(astFromValue(inputVal.defaultValue, inputVal)) or nil
  312. end
  313. }
  314. }
  315. end
  316. })
  317. __EnumValue = types.object({
  318. name = '__EnumValue',
  319. description = [[
  320. One possible value for a given Enum. Enum values are unique values, not
  321. a placeholder for a string or numeric value. However an Enum value is
  322. returned in a JSON response as a string.
  323. ]],
  324. fields = function()
  325. return {
  326. name = types.string.nonNull,
  327. description = types.string,
  328. isDeprecated = {
  329. kind = types.boolean.nonNull,
  330. resolve = function(enumValue) return enumValue.deprecationReason ~= nil end
  331. },
  332. deprecationReason = types.string
  333. }
  334. end
  335. })
  336. __TypeKind = types.enum({
  337. name = '__TypeKind',
  338. description = 'An enum describing what kind of type a given `__Type` is.',
  339. values = {
  340. SCALAR = {
  341. value = 'SCALAR',
  342. description = 'Indicates this type is a scalar.'
  343. },
  344. OBJECT = {
  345. value = 'OBJECT',
  346. description = 'Indicates this type is an object. `fields` and `interfaces` are valid fields.'
  347. },
  348. INTERFACE = {
  349. value = 'INTERFACE',
  350. description = 'Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.'
  351. },
  352. UNION = {
  353. value = 'UNION',
  354. description = 'Indicates this type is a union. `possibleTypes` is a valid field.'
  355. },
  356. ENUM = {
  357. value = 'ENUM',
  358. description = 'Indicates this type is an enum. `enumValues` is a valid field.'
  359. },
  360. INPUT_OBJECT = {
  361. value = 'INPUT_OBJECT',
  362. description = 'Indicates this type is an input object. `inputFields` is a valid field.'
  363. },
  364. LIST = {
  365. value = 'LIST',
  366. description = 'Indicates this type is a list. `ofType` is a valid field.'
  367. },
  368. NON_NULL = {
  369. value = 'NON_NULL',
  370. description = 'Indicates this type is a non-null. `ofType` is a valid field.'
  371. }
  372. }
  373. })
  374. --
  375. -- Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig,
  376. -- so the format for args is different.
  377. --
  378. SchemaMetaFieldDef = {
  379. name = '__schema',
  380. kind = __Schema.nonNull,
  381. description = 'Access the current type schema of this server.',
  382. arguments = {},
  383. resolve = function(source, args, context, obj) return context.schema end
  384. }
  385. TypeMetaFieldDef = {
  386. name = '__type',
  387. kind = __Type,
  388. description = 'Request the type information of a single type.',
  389. arguments = {
  390. name = types.string.nonNull
  391. }
  392. --,resolve = function(source, { name } = { name = string }, context, { schema })
  393. -- return schema.getType(name) end
  394. }
  395. TypeNameMetaFieldDef = {
  396. name = '__typename',
  397. kind = types.string.nonNull,
  398. description = 'The name of the current Object type at runtime.',
  399. arguments = {},
  400. resolve = function(source, args, context, obj) return obj.parentType.name end
  401. }
  402. -- Produces a GraphQL Value AST given a lua value.
  403. -- Optionally, a GraphQL type may be provided, which will be used to
  404. -- disambiguate between value primitives.
  405. -- | JSON Value | GraphQL Value |
  406. -- | ------------- | -------------------- |
  407. -- | Object | Input Object |
  408. -- | Array | List |
  409. -- | Boolean | Boolean |
  410. -- | String | String / Enum Value |
  411. -- | Number | Int / Float |
  412. local Kind = {
  413. LIST = 'ListValue',
  414. BOOLEAN = 'BooleanValue',
  415. FLOAT = 'FloatValue',
  416. INT = 'IntValue',
  417. FLOAT = 'FloatValue',
  418. ENUM = 'EnumValue',
  419. STRING = 'StringValue',
  420. OBJECT_FIELD = 'ObjectField',
  421. NAME = 'Name',
  422. OBJECT = 'ObjectValue'
  423. }
  424. printers = {
  425. IntValue = function(v) return v.value end,
  426. FloatValue = function(v) return v.value end,
  427. StringValue = function(v) return cjson.encode(v.value) end,
  428. BooleanValue = function(v) return cjson.encode(v.value) end,
  429. EnumValue = function(v) return v.value end,
  430. ListValue = function(v) return '[' .. table.concat(util.map(v.values, printAst), ', ') .. ']' end,
  431. ObjectValue = function(v) return '{' .. table.concat(util.map(v.fields, printAst), ', ') .. '}' end,
  432. ObjectField = function(v) return v.name .. ': ' .. v.value end
  433. }
  434. printAst = function(v)
  435. return printers[v.kind](v)
  436. end
  437. astFromValue = function(value, tt)
  438. -- Ensure flow knows that we treat function params as const.
  439. local _value = value
  440. if instanceof(tt,'NonNull') then
  441. -- Note: we're not checking that the result is non-null.
  442. -- This function is not responsible for validating the input value.
  443. return astFromValue(_value, tt.ofType)
  444. end
  445. if value == nil then
  446. return nil
  447. end
  448. -- Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
  449. -- the value is not an array, convert the value using the list's item type.
  450. if type(_value) == 'table' and #_value > 0 then
  451. local itemType = instanceof(tt, 'List') and tt.ofType or nil
  452. return {
  453. kind = Kind.LIST,
  454. values = util.map(_value, function(item)
  455. local itemValue = astFromValue(item, itemType)
  456. assert(itemValue, 'Could not create AST item.')
  457. return itemValue
  458. end)
  459. }
  460. elseif instanceof(tt, 'List') then
  461. -- Because GraphQL will accept single values as a "list of one" when
  462. -- expecting a list, if there's a non-array value and an expected list type,
  463. -- create an AST using the list's item type.
  464. return astFromValue(_value, tt.ofType)
  465. end
  466. if type(_value) == 'boolean' then
  467. return { kind = Kind.BOOLEAN, value = _value }
  468. end
  469. -- JavaScript numbers can be Float or Int values. Use the GraphQLType to
  470. -- differentiate if available, otherwise prefer Int if the value is a
  471. -- valid Int.
  472. if type(_value) == 'number' then
  473. local stringNum = String(_value)
  474. local isIntValue = _value%1 == 0
  475. if isIntValue then
  476. if tt == types.float then
  477. return { kind = Kind.FLOAT, value = stringNum .. '.0' }
  478. end
  479. return { kind = Kind.INT, value = stringNum }
  480. end
  481. return { kind = Kind.FLOAT, value = stringNum }
  482. end
  483. -- JavaScript strings can be Enum values or String values. Use the
  484. -- GraphQLType to differentiate if possible.
  485. if type(_value) == 'string' then
  486. if instanceof(tt, 'Enum') and _value:match('/^[_a-zA-Z][_a-zA-Z0-9]*$/') then
  487. return { kind =Kind.ENUM, value = _value }
  488. end
  489. -- Use JSON stringify, which uses the same string encoding as GraphQL,
  490. -- then remove the quotes.
  491. return {
  492. kind = Kind.STRING,
  493. value = (cjson.encode(_value)):sub(1, -1)
  494. }
  495. end
  496. -- last remaining possible typeof
  497. assert(type(_value) == 'table')
  498. assert(_value ~= nil)
  499. -- Populate the fields of the input object by creating ASTs from each value
  500. -- in the JavaScript object.
  501. local fields = {}
  502. for fieldName,v in pairs(_value) do
  503. local fieldType
  504. if instanceof(tt, 'InputObject') then
  505. local fieldDef = tt.fields[fieldName]
  506. fieldType = fieldDef and fieldDef.kind
  507. end
  508. local fieldValue = astFromValue(_value[fieldName], fieldType)
  509. if fieldValue then
  510. table.insert(fields, {
  511. kind = Kind.OBJECT_FIELD,
  512. name = { kind = Kind.NAME, value = fieldName },
  513. value = fieldValue
  514. })
  515. end
  516. end
  517. return { kind = Kind.OBJECT, fields = fields }
  518. end
  519. return {
  520. __Schema = __Schema,
  521. __Directive = __Directive,
  522. __DirectiveLocation = __DirectiveLocation,
  523. __Type = __Type,
  524. __Field = __Field,
  525. __EnumValue = __EnumValue,
  526. __TypeKind = __TypeKind,
  527. SchemaMetaFieldDef = SchemaMetaFieldDef,
  528. TypeMetaFieldDef = TypeMetaFieldDef,
  529. TypeNameMetaFieldDef = TypeNameMetaFieldDef
  530. }