@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
package/src/graphql.ts ADDED
@@ -0,0 +1,1817 @@
1
+ /**
2
+ * GraphQL Query algebra -- the runtime generated GraphQL SDKs target.
3
+ *
4
+ * U+2500U+2500 Why this exists U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
5
+ * A GraphQL document is a *selection*, not an RPC. Distilled used to bake a
6
+ * max-depth selection into every operation (`Railway.me({})` downloaded the
7
+ * world). This module instead treats every field as a lazy `Query<Value>`:
8
+ * reading `user.email` records that field, and nothing is posted until
9
+ * `Query.fn` evaluates the plan you returned.
10
+ *
11
+ * U+2500U+2500 The two phases U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
12
+ * 1. Build (your function). `Railway.me()` / `user.email` / `Query.map` do
13
+ * not talk to the network. They construct an expression tree:
14
+ * Of | Map | Filter | FlatMap | Prop | Root
15
+ * The inner function of `Query.fn` is therefore a *builder*, not an
16
+ * Effect generator. No `yield*` inside it.
17
+ *
18
+ * 2. Evaluate (`Query.fn`). Walk the returned plan, paint every GraphQL
19
+ * field that appears onto one selection forest, POST that document
20
+ * once through {@link GqlTransport}, then interpret Map/Filter/FlatMap
21
+ * against the JSON. Effects reached via FlatMap (e.g.
22
+ * `usernameIsAvailable(name)`) run *after* the POST, with real values.
23
+ *
24
+ * U+2500U+2500 Combinators U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
25
+ * - `Query.of(x)` -- a literal; never selected.
26
+ * - `Query.map` on a list -- callback receives `Query<Item>` so `p.name` is
27
+ * still a Query (selected). On a scalar, callback receives the value
28
+ * after extract (`stars => stars > 5`). Relay connections (`edges { node }`)
29
+ * are lists of the node type, so `projects({ first: 20 }).pipe(Query.map)`
30
+ * maps projects, not edges.
31
+ * - `Query.filter` -- predicate is `Query<Item> => Query<boolean>`; the
32
+ * boolean Query is walked for fields, then run per row after the POST.
33
+ * - `Query.flatMap` -- after extract, run `(value) => Effect | Query`.
34
+ * - `Query.pages` / `Query.items` -- a Stream over every page / node of a
35
+ * Relay connection, one POST per page (see "Pagination").
36
+ *
37
+ * U+2500U+2500 Types U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
38
+ * `Query<Value>` is `QueryNode<Value>` plus the GraphQL fields of `Value`,
39
+ * so `user.name` type-checks. That copy is a circular type alias
40
+ * (`Query<User>` contains `Query<Project[]>` which contains `Query<User>`
41
+ * again). TypeScript leaves the cycle lazy; there is no depth cap.
42
+ *
43
+ * U+2500U+2500 Transport U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
44
+ * {@link GqlTransport.execute} posts `{ query, variables, operationName }`.
45
+ * The Effect it returns may require Credentials / HttpClient; those leak
46
+ * into `Query.fn`'s requirements. It returns the parsed `data` and raw
47
+ * `errors`; `Query.fn` classifies the errors (see "Errors" below). A plan
48
+ * that can't be compiled fails with {@link GqlError}.
49
+ *
50
+ * Generated SDKs export *roots* (`Railway.me`, `Railway.project`).
51
+ * Combinators live in `@distilled.cloud/core/query`.
52
+ */
53
+ import * as Context from "effect/Context";
54
+ import * as Data from "effect/Data";
55
+ import * as Effect from "effect/Effect";
56
+ import * as Option from "effect/Option";
57
+ import * as Redacted from "effect/Redacted";
58
+ import * as Schedule from "effect/Schedule";
59
+ import * as S from "effect/Schema";
60
+ import * as Stream from "effect/Stream";
61
+ import { unwrapRedactedDeep } from "./plain-values.ts";
62
+ import * as Telemetry from "./telemetry.ts";
63
+
64
+ export const QuerySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/graphql/Query");
65
+ const inspect = /*@__PURE__*/ Symbol.for("nodejs.util.inspect.custom");
66
+
67
+ /**
68
+ * A plan that cannot be compiled (a programming error in the query). The
69
+ * compiler throws it; `Query.fn`, `Query.pages` and `Query.items` fail with
70
+ * it (see {@link compiling}).
71
+ */
72
+ export class GqlError
73
+ extends /*@__PURE__*/ Data.TaggedError("GqlError")<{
74
+ readonly message: string;
75
+ }>
76
+ {
77
+ constructor(message: string) {
78
+ super({ message });
79
+ }
80
+ }
81
+
82
+ /** `f()`, with what the compiler throws failed as a {@link GqlError}. */
83
+ const compiling = <A>(f: () => A): Effect.Effect<A, GqlError> =>
84
+ Effect.try({
85
+ try: f,
86
+ catch: (e) =>
87
+ e instanceof GqlError ? e : new GqlError(e instanceof Error ? e.message : String(e)),
88
+ });
89
+
90
+ // U+2500U+2500 Errors U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
91
+ //
92
+ // Every entry of a GraphQL `errors` array becomes one typed issue. Generated
93
+ // SDKs declare tagged error classes plus the matchers that recognize them,
94
+ // scoped to the root fields that can return them (or global). `Query.fn`
95
+ // classifies each entry against the roots its path points at, so the error
96
+ // channel is the union of the errors declared by the roots the plan reads.
97
+
98
+ /** Fields every classified GraphQL error carries. */
99
+ export const errorFields = {
100
+ message: S.String,
101
+ code: /*@__PURE__*/ S.optional(S.String),
102
+ path: /*@__PURE__*/ S.optional(
103
+ /*@__PURE__*/ S.Array(/*@__PURE__*/ S.Union([S.String, S.Number])),
104
+ ),
105
+ locations: /*@__PURE__*/ S.optional(
106
+ /*@__PURE__*/ S.Array(/*@__PURE__*/ S.Struct({ line: S.Number, column: S.Number })),
107
+ ),
108
+ extensions: /*@__PURE__*/ S.optional(S.Unknown),
109
+ traceId: /*@__PURE__*/ S.optional(S.String),
110
+ status: /*@__PURE__*/ S.optional(S.Number),
111
+ /** Server retry hint in seconds. */
112
+ retryAfter: /*@__PURE__*/ S.optional(S.Number),
113
+ };
114
+
115
+ /** The shape shared by every classified GraphQL error. */
116
+ export interface GraphQLIssue {
117
+ readonly _tag: string;
118
+ readonly message: string;
119
+ readonly code?: string;
120
+ readonly path?: ReadonlyArray<string | number>;
121
+ readonly locations?: ReadonlyArray<{
122
+ readonly line: number;
123
+ readonly column: number;
124
+ }>;
125
+ readonly extensions?: unknown;
126
+ readonly traceId?: string;
127
+ readonly status?: number;
128
+ readonly retryAfter?: number;
129
+ }
130
+
131
+ export type GraphQLIssueProps = Omit<GraphQLIssue, "_tag">;
132
+
133
+ /** A GraphQL error no declared matcher recognizes. */
134
+ export class UnknownGraphQLError
135
+ extends /*@__PURE__*/ S.TaggedError<UnknownGraphQLError>()("UnknownGraphQLError", {
136
+ ...errorFields,
137
+ /** Root field the error path points at, when the path is known. */
138
+ coordinate: /*@__PURE__*/ S.optional(S.String),
139
+ }) {}
140
+
141
+ /** One response carried errors with different tags; none is hidden. */
142
+ export class GraphQLFailure<E extends GraphQLIssue = GraphQLIssue>
143
+ extends /*@__PURE__*/ Data.TaggedError("GraphQLFailure")<{
144
+ readonly errors: readonly [E, ...E[]];
145
+ /** The partial response data, with sensitive fields wrapped in `Redacted`. */
146
+ readonly data: unknown;
147
+ readonly status?: number;
148
+ }>
149
+ {
150
+ get message(): string {
151
+ return this.errors
152
+ .map((e) => `${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`)
153
+ .join("; ");
154
+ }
155
+ }
156
+
157
+ /** The request never produced a GraphQL response (network, HTTP, non-JSON). */
158
+ export class GraphQLTransportError
159
+ extends /*@__PURE__*/ Data.TaggedError("GraphQLTransportError")<{
160
+ readonly message: string;
161
+ readonly status?: number;
162
+ /** Server retry hint in seconds. */
163
+ readonly retryAfter?: number;
164
+ readonly cause?: unknown;
165
+ }> {}
166
+
167
+ /** A paginated connection reported more pages without a new cursor. */
168
+ export class GraphQLPaginationError
169
+ extends /*@__PURE__*/ Data.TaggedError("GraphQLPaginationError")<{
170
+ readonly message: string;
171
+ readonly cursor: string | null;
172
+ }> {}
173
+
174
+ /** Recognizes a raw GraphQL error. Every present property must match. */
175
+ export interface ErrorMatcher {
176
+ readonly code?: string;
177
+ readonly message?: string;
178
+ readonly messageIncludes?: string;
179
+ }
180
+
181
+ /** Runtime description of one generated error class. */
182
+ export interface ErrorSpec<E extends GraphQLIssue = GraphQLIssue> {
183
+ readonly tag: E["_tag"];
184
+ readonly make: (props: GraphQLIssueProps) => E;
185
+ readonly matchers: ReadonlyArray<ErrorMatcher>;
186
+ /** Queries failing only with retryable errors are retried. */
187
+ readonly retryable: boolean;
188
+ /** Applies to every root, including errors that carry no path. */
189
+ readonly global: boolean;
190
+ }
191
+
192
+ export const errorSpec = <E extends GraphQLIssue>(
193
+ make: new (props: GraphQLIssueProps) => E,
194
+ tag: E["_tag"],
195
+ matchers: ReadonlyArray<ErrorMatcher>,
196
+ options: { readonly retryable?: boolean; readonly global?: boolean } = {},
197
+ ): ErrorSpec<E> => ({
198
+ tag,
199
+ make: (props) => new make(props),
200
+ matchers,
201
+ retryable: options.retryable ?? false,
202
+ global: options.global ?? false,
203
+ });
204
+
205
+ /** An entry of a GraphQL response's `errors` array, as sent on the wire. */
206
+ export interface RawGraphQLError {
207
+ readonly message: string;
208
+ readonly path?: ReadonlyArray<string | number>;
209
+ readonly locations?: ReadonlyArray<{
210
+ readonly line: number;
211
+ readonly column: number;
212
+ }>;
213
+ readonly extensions?: Record<string, unknown>;
214
+ readonly [key: string]: unknown;
215
+ }
216
+
217
+ /** What a transport returns once it has a GraphQL response body. */
218
+ export interface GraphQLResponse {
219
+ readonly data?: unknown;
220
+ readonly errors?: ReadonlyArray<RawGraphQLError>;
221
+ readonly status?: number;
222
+ readonly headers?: Readonly<Record<string, string | undefined>>;
223
+ }
224
+
225
+ export type ArgMeta = Record<string, string>;
226
+
227
+ export type FieldMeta = {
228
+ readonly name: string;
229
+ readonly kind: "scalar" | "object" | "list" | "connection";
230
+ readonly of?: TypeMeta;
231
+ readonly argTypes?: ArgMeta;
232
+ /** The value is a secret: extracted values are wrapped in `Redacted`. */
233
+ readonly sensitive?: boolean;
234
+ };
235
+
236
+ export type TypeMeta = {
237
+ readonly name: string;
238
+ readonly fields: Record<string, FieldMeta>;
239
+ };
240
+
241
+ export const scalarField = (
242
+ name: string,
243
+ options: { readonly sensitive?: boolean; readonly argTypes?: ArgMeta } = {},
244
+ ): FieldMeta => ({
245
+ name,
246
+ kind: "scalar",
247
+ ...(options.argTypes ? { argTypes: options.argTypes } : {}),
248
+ ...(options.sensitive ? { sensitive: true } : {}),
249
+ });
250
+ export const objectField = (name: string, objectType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({
251
+ name,
252
+ kind: "object",
253
+ of: objectType,
254
+ ...(argTypes ? { argTypes } : {}),
255
+ });
256
+ export const listField = (name: string, itemType: TypeMeta, argTypes?: ArgMeta): FieldMeta => ({
257
+ name,
258
+ kind: "list",
259
+ of: itemType,
260
+ argTypes,
261
+ });
262
+ /** Relay connection: GraphQL `edges { node }` presented as `Query<Item[]>`. */
263
+ export const connectionField = (
264
+ name: string,
265
+ nodeType: TypeMeta,
266
+ argTypes?: ArgMeta,
267
+ ): FieldMeta => ({
268
+ name,
269
+ kind: "connection",
270
+ of: nodeType,
271
+ argTypes,
272
+ });
273
+
274
+ export type TypeRef =
275
+ | { readonly tag: "scalar" }
276
+ | { readonly tag: "object"; readonly meta: TypeMeta }
277
+ | { readonly tag: "list"; readonly of: TypeRef };
278
+
279
+ const objectRef = (meta: TypeMeta): TypeRef => ({ tag: "object", meta });
280
+ const listRef = (itemType: TypeRef): TypeRef => ({
281
+ tag: "list",
282
+ of: itemType,
283
+ });
284
+
285
+ const fieldResult = (parent: TypeRef, field: FieldMeta): TypeRef => {
286
+ const inner = (): TypeRef => {
287
+ if (field.kind === "scalar") return { tag: "scalar" };
288
+ if (field.kind === "object") return objectRef(field.of!);
289
+ return listRef(objectRef(field.of!)); // list | connection
290
+ };
291
+ return parent.tag === "list" ? listRef(fieldResult(parent.of, field)) : inner();
292
+ };
293
+
294
+ const unwrapList = (typeRef: TypeRef): TypeRef => {
295
+ if (typeRef.tag !== "list") throw new GqlError("expected a list Query");
296
+ return typeRef.of;
297
+ };
298
+
299
+ const fieldsOf = (typeRef: TypeRef): Record<string, FieldMeta> => {
300
+ if (typeRef.tag === "object") return typeRef.meta.fields;
301
+ if (typeRef.tag === "list") return fieldsOf(typeRef.of);
302
+ return {};
303
+ };
304
+
305
+ export interface SelNode {
306
+ field: string;
307
+ alias: string | undefined;
308
+ args: Record<string, string> | undefined;
309
+ children: Map<string, SelNode>;
310
+ isScalar: boolean;
311
+ isList: boolean;
312
+ /** The value is a secret: its strings are wrapped in `Redacted`. */
313
+ sensitive?: boolean;
314
+ }
315
+
316
+ export interface CompiledOperation {
317
+ readonly document: string;
318
+ readonly operationName: string;
319
+ readonly variables: Record<string, unknown>;
320
+ readonly kind: "query" | "mutation";
321
+ readonly tree: SelNode;
322
+ }
323
+
324
+ /**
325
+ * What a GraphQL SDK's document spans carry, generated from its GraphQL
326
+ * model's `telemetry` entry (see `packages/dev/src/codegen/telemetry-traits.md`).
327
+ * One span per document: `<prefix>.<rootField>`, or `<prefix>.<kind>` when
328
+ * the document selects several root fields.
329
+ */
330
+ export interface GraphQLTelemetry extends Telemetry.ServiceTelemetry {
331
+ readonly prefix: string;
332
+ /** `<kind>.<rootField>`, then argument name, then the attributes read from its value. */
333
+ readonly fields?: Readonly<
334
+ Record<string, Readonly<Record<string, ReadonlyArray<Telemetry.AttributeRule>>>>
335
+ >;
336
+ }
337
+
338
+ export class GqlTransport
339
+ extends /*@__PURE__*/ Context.Service<
340
+ GqlTransport,
341
+ {
342
+ readonly execute: (
343
+ req: CompiledOperation,
344
+ ) => Effect.Effect<GraphQLResponse, GraphQLTransportError, any>;
345
+ /** The SDK's span facts; no spans without it. */
346
+ readonly telemetry?: GraphQLTelemetry;
347
+ }
348
+ >()("@distilled.cloud/graphql/Transport") {}
349
+
350
+ const log = (..._args: Array<unknown>): void => {};
351
+
352
+ /**
353
+ * GraphQL fields copied onto a Query so `user.name` type-checks.
354
+ * `Query<User>` contains `projects: Query<Project[]>`, which contains
355
+ * `owner: Query<User>` again -- TypeScript leaves the cycle lazy. Fields
356
+ * inherit the errors of the root they were read from.
357
+ */
358
+ type QueryFields<Value, Error> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
359
+ ? {
360
+ readonly [Field in keyof NonNullable<Item>]: FieldQuery<
361
+ NonNullable<Item>[Field],
362
+ Nullish<Item>,
363
+ Error
364
+ >;
365
+ } & {
366
+ (args: Record<string, unknown>): Query<Value, Error>;
367
+ }
368
+ : [NonNullable<Value>] extends [object]
369
+ ? {
370
+ readonly [Field in keyof NonNullable<Value>]: FieldQuery<
371
+ NonNullable<Value>[Field],
372
+ Nullish<Value>,
373
+ Error
374
+ >;
375
+ }
376
+ : {};
377
+
378
+ /**
379
+ * A field that takes arguments, as it appears in a generated data type.
380
+ * Through a Query it is a call: `account.byId({ accountId })`. When every
381
+ * argument is optional (`Required` false) the field also reads bare.
382
+ */
383
+ export interface FieldWithArgs<Value, Args, Required extends boolean = true> {
384
+ readonly "~fieldArgs": {
385
+ readonly value: Value;
386
+ readonly args: Args;
387
+ readonly required: Required;
388
+ };
389
+ }
390
+
391
+ /** The Query for one field: a call for a field with arguments, else a property. */
392
+ type FieldQuery<Field, ParentNull, Error> = [Field] extends [
393
+ FieldWithArgs<infer Value, infer Args, infer Required>,
394
+ ]
395
+ ? [Required] extends [true]
396
+ ? (args: Args) => Query<Value | ParentNull, Error>
397
+ : Query<Value | ParentNull, Error> & ((args?: Args) => Query<Value | ParentNull, Error>)
398
+ : Query<Field | ParentNull, Error>;
399
+
400
+ /** A field read through a `null` parent is `null`. */
401
+ type Nullish<Value> = Extract<Value, null | undefined>;
402
+
403
+ /**
404
+ * A lazy GraphQL selection. `Value` is the plain data after `Query.fn` runs;
405
+ * `Error` is the union of typed errors the roots it reads can return.
406
+ */
407
+ export type Query<Value, Error = never> = QueryNode<Value, Error> & QueryFields<Value, Error>;
408
+
409
+ /** Strip Query/Effect wrappers from a returned plan down to plain data. */
410
+ export type UnwrapPlan<Plan> =
411
+ Plan extends QueryNode<infer Value, any>
412
+ ? Value
413
+ : Plan extends Effect.Effect<infer Success, any, any>
414
+ ? Success
415
+ : Plan extends ReadonlyArray<infer Element>
416
+ ? ReadonlyArray<UnwrapPlan<Element>>
417
+ : Plan extends object
418
+ ? { readonly [Key in keyof Plan]: UnwrapPlan<Plan[Key]> }
419
+ : Plan;
420
+
421
+ /** Typed errors of every Query and Effect in a returned plan. */
422
+ export type PlanError<Plan> =
423
+ Plan extends QueryNode<any, infer Error>
424
+ ? Error
425
+ : Plan extends Effect.Effect<any, infer Error, any>
426
+ ? Error
427
+ : Plan extends ReadonlyArray<infer Element>
428
+ ? PlanError<Element>
429
+ : Plan extends object
430
+ ? { readonly [Key in keyof Plan]: PlanError<Plan[Key]> }[keyof Plan]
431
+ : never;
432
+
433
+ /** Failures of evaluating a plan whose roots declare `Error`. */
434
+ export type QueryError<Error> =
435
+ | Error
436
+ | GraphQLFailure<Extract<Error, GraphQLIssue> | UnknownGraphQLError>
437
+ | UnknownGraphQLError
438
+ | GraphQLTransportError
439
+ | GqlError;
440
+
441
+ type Expr =
442
+ | RootExpr
443
+ | PropExpr
444
+ | ItemExpr
445
+ | MapValueExpr
446
+ | MapItemsExpr
447
+ | FilterExpr
448
+ | FlatMapExpr
449
+ | LiteralExpr;
450
+
451
+ type RootExpr = {
452
+ readonly _tag: "Root";
453
+ readonly op: "query" | "mutation";
454
+ readonly field: string;
455
+ readonly args: Record<string, unknown> | undefined;
456
+ readonly argTypes: ArgMeta | undefined;
457
+ readonly type: TypeRef;
458
+ /** Relay connection: paint `edges { node }`, extract an array of nodes. */
459
+ readonly connection?: boolean;
460
+ /** Errors this root field can return, including global errors. */
461
+ readonly errors: ReadonlyArray<ErrorSpec>;
462
+ /** Leaf root whose value is a secret: extracted strings are wrapped in `Redacted`. */
463
+ readonly sensitive?: boolean;
464
+ };
465
+
466
+ type PropExpr = {
467
+ readonly _tag: "Prop";
468
+ readonly parent: Expr;
469
+ readonly field: FieldMeta;
470
+ readonly type: TypeRef;
471
+ readonly args?: Record<string, unknown>;
472
+ };
473
+
474
+ type ItemExpr = {
475
+ readonly _tag: "Item";
476
+ readonly list: Expr;
477
+ readonly type: TypeRef;
478
+ };
479
+
480
+ type MapValueExpr = {
481
+ readonly _tag: "MapValue";
482
+ readonly parent: Expr;
483
+ readonly mapFn: (value: unknown) => unknown;
484
+ readonly type: TypeRef;
485
+ };
486
+
487
+ type MapItemsExpr = {
488
+ readonly _tag: "MapItems";
489
+ readonly parent: Expr;
490
+ readonly mapped: unknown;
491
+ /** Map one object (`null` stays `null`) instead of every list item. */
492
+ readonly single?: boolean;
493
+ readonly type: TypeRef;
494
+ };
495
+
496
+ type FilterExpr = {
497
+ readonly _tag: "Filter";
498
+ readonly parent: Expr;
499
+ readonly predicate: Expr;
500
+ readonly type: TypeRef;
501
+ };
502
+
503
+ type FlatMapExpr = {
504
+ readonly _tag: "FlatMap";
505
+ readonly parent: Expr;
506
+ readonly flatMapFn: (value: unknown) => unknown;
507
+ readonly type: TypeRef;
508
+ };
509
+
510
+ type LiteralExpr = {
511
+ readonly _tag: "Literal";
512
+ readonly value: unknown;
513
+ readonly type: TypeRef;
514
+ };
515
+
516
+ export class QueryNode<out Value = unknown, out Error = never> {
517
+ readonly [QuerySymbol] = QuerySymbol;
518
+ declare readonly valueType: Value;
519
+ declare readonly errorType: Error;
520
+ readonly expr: Expr;
521
+ constructor(expr: Expr) {
522
+ this.expr = expr;
523
+ return proxy(this) as QueryNode<Value, Error>;
524
+ }
525
+ pipe<Self>(this: Self): Self;
526
+ pipe<Self, Out1>(this: Self, step1: (_: Self) => Out1): Out1;
527
+ pipe<Self, Out1, Out2>(this: Self, step1: (_: Self) => Out1, step2: (_: Out1) => Out2): Out2;
528
+ pipe<Self, Out1, Out2, Out3>(
529
+ this: Self,
530
+ step1: (_: Self) => Out1,
531
+ step2: (_: Out1) => Out2,
532
+ step3: (_: Out2) => Out3,
533
+ ): Out3;
534
+ pipe<Self, Out1, Out2, Out3, Out4>(
535
+ this: Self,
536
+ step1: (_: Self) => Out1,
537
+ step2: (_: Out1) => Out2,
538
+ step3: (_: Out2) => Out3,
539
+ step4: (_: Out3) => Out4,
540
+ ): Out4;
541
+ pipe<Self, Out1, Out2, Out3, Out4, Out5>(
542
+ this: Self,
543
+ step1: (_: Self) => Out1,
544
+ step2: (_: Out1) => Out2,
545
+ step3: (_: Out2) => Out3,
546
+ step4: (_: Out3) => Out4,
547
+ step5: (_: Out4) => Out5,
548
+ ): Out5;
549
+ pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6>(
550
+ this: Self,
551
+ step1: (_: Self) => Out1,
552
+ step2: (_: Out1) => Out2,
553
+ step3: (_: Out2) => Out3,
554
+ step4: (_: Out3) => Out4,
555
+ step5: (_: Out4) => Out5,
556
+ step6: (_: Out5) => Out6,
557
+ ): Out6;
558
+ pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7>(
559
+ this: Self,
560
+ step1: (_: Self) => Out1,
561
+ step2: (_: Out1) => Out2,
562
+ step3: (_: Out2) => Out3,
563
+ step4: (_: Out3) => Out4,
564
+ step5: (_: Out4) => Out5,
565
+ step6: (_: Out5) => Out6,
566
+ step7: (_: Out6) => Out7,
567
+ ): Out7;
568
+ pipe<Self, Out1, Out2, Out3, Out4, Out5, Out6, Out7, Out8>(
569
+ this: Self,
570
+ step1: (_: Self) => Out1,
571
+ step2: (_: Out1) => Out2,
572
+ step3: (_: Out2) => Out3,
573
+ step4: (_: Out3) => Out4,
574
+ step5: (_: Out4) => Out5,
575
+ step6: (_: Out5) => Out6,
576
+ step7: (_: Out6) => Out7,
577
+ step8: (_: Out7) => Out8,
578
+ ): Out8;
579
+ pipe(...steps: Array<(_: any) => any>): unknown {
580
+ return steps.reduce((current, step) => step(current), this as never);
581
+ }
582
+ [inspect](): string {
583
+ return printExpr(this.expr);
584
+ }
585
+ toString(): string {
586
+ return this[inspect]();
587
+ }
588
+ }
589
+
590
+ export const isQuery = (value: unknown): value is Query<unknown> =>
591
+ (typeof value === "object" || typeof value === "function") &&
592
+ value !== null &&
593
+ QuerySymbol in value;
594
+
595
+ const make = <Value, Error = never>(expr: Expr): Query<Value, Error> =>
596
+ new QueryNode<Value, Error>(expr) as unknown as Query<Value, Error>;
597
+
598
+ const itemQuery = (list: QueryNode): QueryNode =>
599
+ new QueryNode({
600
+ _tag: "Item",
601
+ list: list.expr,
602
+ type: unwrapList(list.expr.type),
603
+ });
604
+
605
+ function proxy(self: QueryNode<unknown, unknown>): Query<unknown> {
606
+ const callable = Object.assign(function (bag?: Record<string, unknown>) {
607
+ return bag == null ? self : applyBag(self, bag);
608
+ }, self);
609
+ return new Proxy(callable, {
610
+ has: (_, prop) =>
611
+ prop === QuerySymbol ||
612
+ prop === inspect ||
613
+ prop in self ||
614
+ (typeof prop === "string" && prop in fieldsOf(self.expr.type)),
615
+ get: (_target, prop) => {
616
+ if (prop === QuerySymbol) return QuerySymbol;
617
+ if (prop === inspect) return self[inspect].bind(self);
618
+ if (prop === "pipe") return self.pipe.bind(self);
619
+ if (typeof prop === "string" && prop in self) {
620
+ const member = (self as unknown as Record<string, unknown>)[prop];
621
+ return typeof member === "function" ? member.bind(self) : member;
622
+ }
623
+ if (typeof prop !== "string") return undefined;
624
+ const field = fieldsOf(self.expr.type)[prop];
625
+ if (!field) return undefined;
626
+ return make({
627
+ _tag: "Prop",
628
+ parent: self.expr,
629
+ field,
630
+ type: fieldResult(self.expr.type, field),
631
+ });
632
+ },
633
+ apply: (_target, _thisArg, args) => applyBag(self, args[0] ?? {}),
634
+ }) as unknown as Query<unknown>;
635
+ }
636
+
637
+ const applyBag = <Value, Error>(
638
+ self: QueryNode<Value, Error>,
639
+ bag: Record<string, unknown>,
640
+ ): Query<Value, Error> => {
641
+ const argTypes =
642
+ self.expr._tag === "Prop"
643
+ ? self.expr.field.argTypes
644
+ : self.expr._tag === "Root"
645
+ ? self.expr.argTypes
646
+ : undefined;
647
+ const args: Record<string, unknown> = {};
648
+ for (const [argName, argValue] of Object.entries(bag)) {
649
+ if (argTypes && argName in argTypes) args[argName] = argValue;
650
+ }
651
+ if (self.expr._tag === "Prop") {
652
+ return make<Value, Error>({
653
+ ...self.expr,
654
+ args: { ...self.expr.args, ...args },
655
+ });
656
+ }
657
+ if (self.expr._tag === "Root") {
658
+ return make<Value, Error>({
659
+ ...self.expr,
660
+ args: { ...self.expr.args, ...args },
661
+ });
662
+ }
663
+ return self as unknown as Query<Value, Error>;
664
+ };
665
+
666
+ export const root = <Value, Error = never>(
667
+ op: "query" | "mutation",
668
+ field: string,
669
+ meta: TypeMeta,
670
+ args?: Record<string, unknown>,
671
+ argTypes?: ArgMeta,
672
+ errors: ReadonlyArray<ErrorSpec> = [],
673
+ ): Query<Value, Error> =>
674
+ make({
675
+ _tag: "Root",
676
+ op,
677
+ field,
678
+ args,
679
+ argTypes,
680
+ type: objectRef(meta),
681
+ errors,
682
+ });
683
+
684
+ export const rootList = <Item, Error = never>(
685
+ op: "query" | "mutation",
686
+ field: string,
687
+ meta: TypeMeta,
688
+ args?: Record<string, unknown>,
689
+ argTypes?: ArgMeta,
690
+ errors: ReadonlyArray<ErrorSpec> = [],
691
+ ): Query<ReadonlyArray<Item>, Error> =>
692
+ make({
693
+ _tag: "Root",
694
+ op,
695
+ field,
696
+ args,
697
+ argTypes,
698
+ type: listRef(objectRef(meta)),
699
+ errors,
700
+ });
701
+
702
+ /** Root Relay connection: typed as `Query<Item[]>`, document uses `edges { node }`. */
703
+ export const rootConnection = <Item, Error = never>(
704
+ op: "query" | "mutation",
705
+ field: string,
706
+ meta: TypeMeta,
707
+ args?: Record<string, unknown>,
708
+ argTypes?: ArgMeta,
709
+ errors: ReadonlyArray<ErrorSpec> = [],
710
+ ): Query<ReadonlyArray<Item>, Error> =>
711
+ make({
712
+ _tag: "Root",
713
+ op,
714
+ field,
715
+ args,
716
+ argTypes,
717
+ type: listRef(objectRef(meta)),
718
+ connection: true,
719
+ errors,
720
+ });
721
+
722
+ /** Root field whose GraphQL type is a scalar, enum, or list of those. */
723
+ export const rootLeaf = <Value, Error = never>(
724
+ op: "query" | "mutation",
725
+ field: string,
726
+ list: boolean,
727
+ args?: Record<string, unknown>,
728
+ argTypes?: ArgMeta,
729
+ errors: ReadonlyArray<ErrorSpec> = [],
730
+ options: { readonly sensitive?: boolean } = {},
731
+ ): Query<Value, Error> =>
732
+ make({
733
+ _tag: "Root",
734
+ op,
735
+ field,
736
+ args,
737
+ argTypes,
738
+ type: list ? listRef({ tag: "scalar" }) : { tag: "scalar" },
739
+ errors,
740
+ ...(options.sensitive ? { sensitive: true } : {}),
741
+ });
742
+
743
+ const printExpr = (expr: Expr): string => {
744
+ switch (expr._tag) {
745
+ case "Root":
746
+ return expr.args ? `${expr.field}(${JSON.stringify(expr.args)})` : expr.field;
747
+ case "Prop":
748
+ return `${printExpr(expr.parent)}.${expr.field.name}`;
749
+ case "Item":
750
+ return "$item";
751
+ case "MapValue":
752
+ return `map(${printExpr(expr.parent)})`;
753
+ case "MapItems":
754
+ return `mapItems(${printExpr(expr.parent)})`;
755
+ case "Filter":
756
+ return `filter(${printExpr(expr.parent)})`;
757
+ case "FlatMap":
758
+ return `flatMap(${printExpr(expr.parent)})`;
759
+ case "Literal":
760
+ return `of(${String(expr.value)})`;
761
+ }
762
+ };
763
+
764
+ const emptySel = (field: string): SelNode => ({
765
+ field,
766
+ alias: undefined,
767
+ args: undefined,
768
+ children: new Map(),
769
+ isScalar: false,
770
+ isList: false,
771
+ });
772
+
773
+ const stableStringify = (value: unknown): string => {
774
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
775
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
776
+ const keys = Object.keys(value as object).sort();
777
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify((value as Record<string, unknown>)[key])}`).join(",")}}`;
778
+ };
779
+
780
+ type Forest = {
781
+ kind: "query" | "mutation" | undefined;
782
+ roots: SelNode;
783
+ vars: Map<string, { type: string; value: unknown }>;
784
+ varI: number;
785
+ aliasI: number;
786
+ rootAlias: WeakMap<object, string>;
787
+ /** Response key of each root -> the root field and its declared errors. */
788
+ rootErrors: Map<string, RootErrors>;
789
+ };
790
+
791
+ interface RootErrors {
792
+ readonly field: string;
793
+ readonly errors: ReadonlyArray<ErrorSpec>;
794
+ }
795
+
796
+ const bindArgs = (
797
+ forest: Forest,
798
+ args: Record<string, unknown> | undefined,
799
+ argTypes: ArgMeta | undefined,
800
+ ): Record<string, string> | undefined => {
801
+ if (args === undefined) return undefined;
802
+ const bound: Record<string, string> = {};
803
+ let hasArgs = false;
804
+ for (const [name, value] of Object.entries(args)) {
805
+ if (value === undefined) continue;
806
+ forest.vars.set(`v${forest.varI}`, {
807
+ type: argTypes?.[name] ?? "String",
808
+ value,
809
+ });
810
+ bound[name] = `v${forest.varI++}`;
811
+ hasArgs = true;
812
+ }
813
+ return hasArgs ? bound : undefined;
814
+ };
815
+
816
+ const ensureChild = (
817
+ forest: Forest,
818
+ parent: SelNode,
819
+ field: string,
820
+ options: {
821
+ args?: Record<string, unknown>;
822
+ argTypes?: ArgMeta;
823
+ isScalar?: boolean;
824
+ isList?: boolean;
825
+ sensitive?: boolean;
826
+ },
827
+ ): SelNode => {
828
+ const args = unwrapRedactedDeep(options.args) as Record<string, unknown> | undefined;
829
+ const key = args === undefined ? field : `${field}:${stableStringify(args)}`;
830
+ const existing = parent.children.get(key);
831
+ if (existing) return existing;
832
+ const taken = new Set([...parent.children.values()].map((c) => c.alias ?? c.field));
833
+ let alias: string | undefined;
834
+ if (taken.has(field)) {
835
+ do {
836
+ alias = `${field}_${forest.aliasI++}`;
837
+ } while (taken.has(alias));
838
+ }
839
+ const sel: SelNode = {
840
+ field,
841
+ alias,
842
+ args: bindArgs(forest, args, options.argTypes),
843
+ children: new Map(),
844
+ isScalar: options.isScalar ?? false,
845
+ isList: options.isList ?? false,
846
+ ...(options.sensitive ? { sensitive: true } : {}),
847
+ };
848
+ parent.children.set(key, sel);
849
+ return sel;
850
+ };
851
+
852
+ type Path = Array<string | "*">;
853
+
854
+ const paintConnection = (forest: Forest, connection: SelNode): Path => {
855
+ const edges = ensureChild(forest, connection, "edges", { isList: true });
856
+ ensureChild(forest, edges, "node", {});
857
+ return ["edges", "node"];
858
+ };
859
+
860
+ const paintAbs = (forest: Forest, expr: Expr): Path => {
861
+ switch (expr._tag) {
862
+ case "Root": {
863
+ if (forest.kind !== undefined && forest.kind !== expr.op) {
864
+ throw new GqlError(`cannot mix ${forest.kind} and ${expr.op} in one document`);
865
+ }
866
+ forest.kind = expr.op;
867
+ const node = ensureChild(forest, forest.roots, expr.field, {
868
+ args: expr.args,
869
+ argTypes: expr.argTypes,
870
+ // Leaf roots (`projectDelete: Boolean!`) take no sub-selection.
871
+ isScalar:
872
+ expr.type.tag === "scalar" || (expr.type.tag === "list" && expr.type.of.tag === "scalar"),
873
+ isList: expr.type.tag === "list" && !expr.connection,
874
+ sensitive: expr.sensitive,
875
+ });
876
+ const key = node.alias ?? node.field;
877
+ forest.rootAlias.set(expr, key);
878
+ forest.rootErrors.set(key, { field: expr.field, errors: expr.errors });
879
+ return expr.connection ? [key, ...paintConnection(forest, node)] : [key];
880
+ }
881
+ case "Prop": {
882
+ const parentPath = paintAbs(forest, expr.parent);
883
+ const parentSel = selAt(forest.roots, parentPath);
884
+ const node = ensureChild(forest, parentSel, expr.field.name, {
885
+ args: expr.args,
886
+ argTypes: expr.field.argTypes,
887
+ isScalar: expr.field.kind === "scalar",
888
+ isList: expr.field.kind === "list",
889
+ sensitive: expr.field.sensitive,
890
+ });
891
+ const key = node.alias ?? node.field;
892
+ forest.rootAlias.set(expr, key);
893
+ const path = [...parentPath, key];
894
+ return expr.field.kind === "connection" ? [...path, ...paintConnection(forest, node)] : path;
895
+ }
896
+ default:
897
+ throw new GqlError(`paintAbs: ${expr._tag}`);
898
+ }
899
+ };
900
+
901
+ const selAt = (roots: SelNode, path: Path): SelNode => {
902
+ let current = roots;
903
+ for (const segment of path) {
904
+ if (segment === "*") continue;
905
+ const child = [...current.children.values()].find(
906
+ (candidate) => (candidate.alias ?? candidate.field) === segment,
907
+ );
908
+ if (!child) {
909
+ throw new GqlError(`internal: missing ${String(segment)}`);
910
+ }
911
+ current = child;
912
+ }
913
+ return current;
914
+ };
915
+
916
+ const connectionNodeSel = (connection: SelNode): SelNode => {
917
+ const edges = [...connection.children.values()].find((c) => c.field === "edges");
918
+ const node = edges ? [...edges.children.values()].find((c) => c.field === "node") : undefined;
919
+ if (!node) throw new GqlError("internal: connection missing edges.node");
920
+ return node;
921
+ };
922
+
923
+ const relSel = (forest: Forest, expr: Expr, listSel: SelNode): SelNode => {
924
+ switch (expr._tag) {
925
+ case "Item":
926
+ return listSel;
927
+ case "Prop": {
928
+ const parent = relSel(forest, expr.parent, listSel);
929
+ const key = forest.rootAlias.get(expr) ?? expr.field.name;
930
+ const child = [...parent.children.values()].find((c) => (c.alias ?? c.field) === key);
931
+ if (!child) {
932
+ throw new GqlError(`missing ${expr.field.name} in list selection`);
933
+ }
934
+ return expr.field.kind === "connection" ? connectionNodeSel(child) : child;
935
+ }
936
+ default:
937
+ return listSel;
938
+ }
939
+ };
940
+
941
+ const paintRel = (forest: Forest, expr: Expr, listSel: SelNode): void => {
942
+ switch (expr._tag) {
943
+ case "Item":
944
+ case "Literal":
945
+ return;
946
+ case "Prop": {
947
+ paintRel(forest, expr.parent, listSel);
948
+ const child = ensureChild(forest, relSel(forest, expr.parent, listSel), expr.field.name, {
949
+ args: expr.args,
950
+ argTypes: expr.field.argTypes,
951
+ isScalar: expr.field.kind === "scalar",
952
+ isList: expr.field.kind === "list",
953
+ sensitive: expr.field.sensitive,
954
+ });
955
+ forest.rootAlias.set(expr, child.alias ?? child.field);
956
+ if (expr.field.kind === "connection") paintConnection(forest, child);
957
+ return;
958
+ }
959
+ case "MapValue":
960
+ case "FlatMap":
961
+ paintRel(forest, expr.parent, listSel);
962
+ return;
963
+ case "MapItems":
964
+ paintRel(forest, expr.parent, listSel);
965
+ visitRel(expr.mapped, forest, relSel(forest, expr.parent, listSel));
966
+ return;
967
+ case "Filter":
968
+ paintRel(forest, expr.parent, listSel);
969
+ paintRel(forest, expr.predicate, relSel(forest, expr.parent, listSel));
970
+ return;
971
+ case "Root":
972
+ throw new GqlError("root inside list item");
973
+ }
974
+ };
975
+
976
+ const visitExpr = (forest: Forest, expr: Expr): void => {
977
+ switch (expr._tag) {
978
+ case "Root":
979
+ case "Prop":
980
+ paintAbs(forest, expr);
981
+ return;
982
+ case "Item":
983
+ return;
984
+ case "Literal":
985
+ return;
986
+ case "MapValue":
987
+ case "FlatMap":
988
+ visitExpr(forest, expr.parent);
989
+ return;
990
+ case "MapItems": {
991
+ visitExpr(forest, expr.parent);
992
+ const path = paintAbs(forest, graphqlBase(expr.parent));
993
+ visitRel(expr.mapped, forest, selAt(forest.roots, path));
994
+ return;
995
+ }
996
+ case "Filter": {
997
+ visitExpr(forest, expr.parent);
998
+ const path = paintAbs(forest, graphqlBase(expr.parent));
999
+ paintRel(forest, expr.predicate, selAt(forest.roots, path));
1000
+ return;
1001
+ }
1002
+ }
1003
+ };
1004
+
1005
+ const graphqlBase = (expr: Expr): Expr => {
1006
+ switch (expr._tag) {
1007
+ case "Root":
1008
+ case "Prop":
1009
+ case "Item":
1010
+ return expr;
1011
+ case "MapValue":
1012
+ case "MapItems":
1013
+ case "Filter":
1014
+ case "FlatMap":
1015
+ return graphqlBase(expr.parent);
1016
+ case "Literal":
1017
+ throw new GqlError("literal has no graphql base");
1018
+ }
1019
+ };
1020
+
1021
+ const visitRel = (plan: unknown, forest: Forest, listSel: SelNode): void => {
1022
+ if (isQuery(plan)) {
1023
+ paintRel(forest, (plan as QueryNode).expr, listSel);
1024
+ return;
1025
+ }
1026
+ if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
1027
+ for (const nested of Object.values(plan as Record<string, unknown>)) {
1028
+ visitRel(nested, forest, listSel);
1029
+ }
1030
+ }
1031
+ };
1032
+
1033
+ /**
1034
+ * Recurse through a builder return value. Query nodes contribute GraphQL
1035
+ * fields to `forest`; Effects are ignored until interpret (FlatMap).
1036
+ */
1037
+ const visitPlan = (plan: unknown, forest: Forest): void => {
1038
+ if (isQuery(plan)) {
1039
+ log("visit", printExpr((plan as QueryNode).expr));
1040
+ visitExpr(forest, (plan as QueryNode).expr);
1041
+ return;
1042
+ }
1043
+ if (Effect.isEffect(plan)) return;
1044
+ if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
1045
+ for (const nested of Object.values(plan as Record<string, unknown>)) {
1046
+ visitPlan(nested, forest);
1047
+ }
1048
+ }
1049
+ };
1050
+
1051
+ const validate = (node: SelNode): string | undefined => {
1052
+ for (const child of node.children.values()) {
1053
+ if (!child.isScalar && child.children.size === 0) {
1054
+ return `field "${child.field}" has no sub-selection`;
1055
+ }
1056
+ const inner = validate(child);
1057
+ if (inner) return inner;
1058
+ }
1059
+ return undefined;
1060
+ };
1061
+
1062
+ const printChildren = (node: SelNode, indent: number): string => {
1063
+ const pad = " ".repeat(indent);
1064
+ const lines: Array<string> = [];
1065
+ for (const child of node.children.values()) {
1066
+ let head = child.alias ? `${child.alias}: ${child.field}` : child.field;
1067
+ if (child.args && Object.keys(child.args).length > 0) {
1068
+ const printed = Object.entries(child.args)
1069
+ .map(([argName, varName]) => `${argName}: $${varName}`)
1070
+ .join(", ");
1071
+ head += `(${printed})`;
1072
+ }
1073
+ if (child.isScalar) lines.push(`${pad}${head}`);
1074
+ else {
1075
+ lines.push(`${pad}${head} {`);
1076
+ lines.push(printChildren(child, indent + 1));
1077
+ lines.push(`${pad}}`);
1078
+ }
1079
+ }
1080
+ return lines.join("\n");
1081
+ };
1082
+
1083
+ const emptyForest = (): Forest => ({
1084
+ kind: undefined,
1085
+ roots: emptySel(""),
1086
+ vars: new Map(),
1087
+ varI: 0,
1088
+ aliasI: 0,
1089
+ rootAlias: new WeakMap(),
1090
+ rootErrors: new Map(),
1091
+ });
1092
+
1093
+ const emit = (forest: Forest): Compiled => {
1094
+ const err = validate(forest.roots);
1095
+ if (err) throw new GqlError(err);
1096
+ const kind = forest.kind ?? "query";
1097
+ const varDefs = [...forest.vars.entries()]
1098
+ .map(([name, binding]) => `$${name}: ${binding.type}`)
1099
+ .join(", ");
1100
+ const header = varDefs.length > 0 ? `${kind} Gql(${varDefs})` : `${kind} Gql`;
1101
+ const variables: Record<string, unknown> = {};
1102
+ for (const [name, binding] of forest.vars) variables[name] = binding.value;
1103
+ return {
1104
+ document: `${header} {\n${printChildren(forest.roots, 1)}\n}`,
1105
+ operationName: "Gql",
1106
+ variables,
1107
+ kind,
1108
+ tree: forest.roots,
1109
+ rootAlias: forest.rootAlias,
1110
+ rootErrors: forest.rootErrors,
1111
+ };
1112
+ };
1113
+
1114
+ type Compiled = CompiledOperation & {
1115
+ readonly rootAlias: WeakMap<object, string>;
1116
+ readonly rootErrors: ReadonlyMap<string, RootErrors>;
1117
+ };
1118
+
1119
+ const nodesFromConnection = (value: unknown): unknown => {
1120
+ if (value == null) return value;
1121
+ if (Array.isArray(value)) return value.map(nodesFromConnection);
1122
+ const edges = (value as Record<string, unknown>).edges;
1123
+ if (!Array.isArray(edges)) return [];
1124
+ return edges.map((edge) => (edge == null ? edge : (edge as Record<string, unknown>).node));
1125
+ };
1126
+
1127
+ const readField = (parent: unknown, name: string): unknown => {
1128
+ if (parent == null) return parent;
1129
+ if (Array.isArray(parent)) {
1130
+ return parent.map((item) => (item == null ? item : (item as Record<string, unknown>)[name]));
1131
+ }
1132
+ return (parent as Record<string, unknown>)[name];
1133
+ };
1134
+
1135
+ /**
1136
+ * Wrap a sensitive scalar in `Redacted`: a string, a JSON object, or each
1137
+ * item of a list of them.
1138
+ */
1139
+ const redactValues = (value: unknown): unknown =>
1140
+ value === null || value === undefined
1141
+ ? value
1142
+ : Array.isArray(value)
1143
+ ? value.map(redactValues)
1144
+ : Redacted.make(value);
1145
+
1146
+ /** Copy `data` with the value of every sensitive field `sel` selects wrapped in `Redacted`. */
1147
+ const redactSelected = (sel: SelNode, data: unknown): unknown => {
1148
+ if (sel.children.size === 0 || data === null || typeof data !== "object") return data;
1149
+ if (Array.isArray(data)) return data.map((item) => redactSelected(sel, item));
1150
+ const out: Record<string, unknown> = { ...data };
1151
+ for (const child of sel.children.values()) {
1152
+ const key = child.alias ?? child.field;
1153
+ out[key] = child.sensitive ? redactValues(out[key]) : redactSelected(child, out[key]);
1154
+ }
1155
+ return out;
1156
+ };
1157
+
1158
+ const extractAbs = (expr: Expr, data: unknown, rootAlias: WeakMap<object, string>): unknown => {
1159
+ switch (expr._tag) {
1160
+ case "Root": {
1161
+ const raw = (data as Record<string, unknown>)[rootAlias.get(expr) ?? expr.field];
1162
+ return expr.connection ? nodesFromConnection(raw) : raw;
1163
+ }
1164
+ case "Prop": {
1165
+ const value = readField(
1166
+ extractAbs(expr.parent, data, rootAlias),
1167
+ rootAlias.get(expr) ?? expr.field.name,
1168
+ );
1169
+ return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
1170
+ }
1171
+ default:
1172
+ throw new GqlError(`extractAbs: ${expr._tag}`);
1173
+ }
1174
+ };
1175
+
1176
+ const extractRel = (expr: Expr, item: unknown, rootAlias: WeakMap<object, string>): unknown => {
1177
+ switch (expr._tag) {
1178
+ case "Item":
1179
+ return item;
1180
+ case "Prop": {
1181
+ const value = readField(
1182
+ extractRel(expr.parent, item, rootAlias),
1183
+ rootAlias.get(expr) ?? expr.field.name,
1184
+ );
1185
+ return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
1186
+ }
1187
+ default:
1188
+ throw new GqlError(`extractRel: ${expr._tag}`);
1189
+ }
1190
+ };
1191
+
1192
+ const inItem = (expr: Expr): boolean => {
1193
+ switch (expr._tag) {
1194
+ case "Item":
1195
+ return true;
1196
+ case "Prop":
1197
+ case "MapValue":
1198
+ case "MapItems":
1199
+ case "Filter":
1200
+ case "FlatMap":
1201
+ return inItem(expr.parent);
1202
+ default:
1203
+ return false;
1204
+ }
1205
+ };
1206
+
1207
+ const interpretExpr = (
1208
+ expr: Expr,
1209
+ data: unknown,
1210
+ rootAlias: WeakMap<object, string>,
1211
+ item: unknown,
1212
+ ): unknown => {
1213
+ switch (expr._tag) {
1214
+ case "Literal":
1215
+ return expr.value;
1216
+ case "Item":
1217
+ return item;
1218
+ case "Root":
1219
+ case "Prop":
1220
+ return inItem(expr) ? extractRel(expr, item, rootAlias) : extractAbs(expr, data, rootAlias);
1221
+ case "MapValue":
1222
+ return expr.mapFn(interpretExpr(expr.parent, data, rootAlias, item));
1223
+ case "Filter": {
1224
+ const list = interpretExpr(expr.parent, data, rootAlias, item);
1225
+ const arr = Array.isArray(list) ? list : [];
1226
+ return arr.filter((row) => Boolean(interpretExpr(expr.predicate, data, rootAlias, row)));
1227
+ }
1228
+ case "MapItems": {
1229
+ const list = interpretExpr(expr.parent, data, rootAlias, item);
1230
+ if (expr.single) {
1231
+ return list == null ? null : interpretValueSync(expr.mapped, data, rootAlias, list);
1232
+ }
1233
+ const arr = Array.isArray(list) ? list : [];
1234
+ return arr.map((row) => interpretValueSync(expr.mapped, data, rootAlias, row));
1235
+ }
1236
+ case "FlatMap":
1237
+ throw new GqlError("FlatMap must be interpreted as Effect");
1238
+ }
1239
+ };
1240
+
1241
+ const interpretValueSync = (
1242
+ plan: unknown,
1243
+ data: unknown,
1244
+ rootAlias: WeakMap<object, string>,
1245
+ item: unknown,
1246
+ ): unknown => {
1247
+ if (isQuery(plan)) {
1248
+ return interpretExpr((plan as QueryNode).expr, data, rootAlias, item);
1249
+ }
1250
+ if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
1251
+ const out: Record<string, unknown> = {};
1252
+ for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
1253
+ out[key] = interpretValueSync(nested, data, rootAlias, item);
1254
+ }
1255
+ return out;
1256
+ }
1257
+ return plan;
1258
+ };
1259
+
1260
+ const interpretPlan = (
1261
+ plan: unknown,
1262
+ data: unknown,
1263
+ rootAlias: WeakMap<object, string>,
1264
+ ): Effect.Effect<unknown, unknown, GqlTransport> =>
1265
+ Effect.gen(function* () {
1266
+ if (isQuery(plan)) {
1267
+ const expr = (plan as QueryNode).expr;
1268
+ if (expr._tag === "FlatMap") {
1269
+ const resolved = yield* compiling(() =>
1270
+ interpretExpr(expr.parent, data, rootAlias, undefined),
1271
+ );
1272
+ const next = expr.flatMapFn(resolved);
1273
+ if (Effect.isEffect(next)) return yield* next;
1274
+ if (isQuery(next)) return yield* interpretPlan(next, data, rootAlias);
1275
+ return next;
1276
+ }
1277
+ return yield* compiling(() => interpretExpr(expr, data, rootAlias, undefined));
1278
+ }
1279
+ if (Effect.isEffect(plan)) return yield* plan;
1280
+ if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
1281
+ const out: Record<string, unknown> = {};
1282
+ for (const [key, nested] of Object.entries(plan as Record<string, unknown>)) {
1283
+ out[key] = yield* interpretPlan(nested, data, rootAlias);
1284
+ }
1285
+ return out;
1286
+ }
1287
+ return plan;
1288
+ }) as Effect.Effect<unknown, unknown, GqlTransport>;
1289
+
1290
+ /**
1291
+ * Compile every Query in `plan` into one document, POST it, then replace
1292
+ * Query/Effect leaves with plain data (`UnwrapPlan`).
1293
+ */
1294
+ const evaluatePlan = <Plan>(
1295
+ plan: Plan,
1296
+ ): Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport> =>
1297
+ Effect.gen(function* () {
1298
+ const forest = emptyForest();
1299
+ const compiled = yield* compiling(() => {
1300
+ visitPlan(plan, forest);
1301
+ return forest.roots.children.size > 0 ? emit(forest) : undefined;
1302
+ });
1303
+ let data: unknown = {};
1304
+ let rootAlias: WeakMap<object, string> = new WeakMap();
1305
+ if (compiled !== undefined) {
1306
+ log("document\n" + compiled.document);
1307
+ data = yield* execute(compiled);
1308
+ rootAlias = compiled.rootAlias;
1309
+ }
1310
+ return (yield* interpretPlan(plan, data, rootAlias)) as UnwrapPlan<Plan>;
1311
+ }) as Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>;
1312
+
1313
+ /**
1314
+ * POST one compiled document and fail with its classified errors. Queries
1315
+ * are retried (bounded) while every failure is retryable; mutations never
1316
+ * are, since an error can follow a side effect that already happened.
1317
+ */
1318
+ const execute = (compiled: Compiled): Effect.Effect<unknown, ExecuteError, GqlTransport> => {
1319
+ const once = Effect.gen(function* () {
1320
+ const transport = yield* GqlTransport;
1321
+ const response = yield* transport.execute(compiled);
1322
+ const data = redactSelected(compiled.tree, response.data);
1323
+ const raw = response.errors ?? [];
1324
+ if (raw.length === 0) {
1325
+ // Without errors, a GraphQL response must carry a `data` object.
1326
+ if (!isRecord(response.data)) {
1327
+ return yield* Effect.fail(
1328
+ new GraphQLTransportError({
1329
+ message: "GraphQL response has no data object and no errors",
1330
+ status: response.status,
1331
+ }),
1332
+ );
1333
+ }
1334
+ return data;
1335
+ }
1336
+ const issues = raw.map((error) => classify(compiled, error, response));
1337
+ const [first, ...rest] = issues as [GraphQLIssue, ...GraphQLIssue[]];
1338
+ return yield* Effect.fail(
1339
+ rest.every((issue) => issue._tag === first._tag)
1340
+ ? first
1341
+ : new GraphQLFailure({
1342
+ errors: [first, ...rest],
1343
+ data,
1344
+ status: response.status,
1345
+ }),
1346
+ );
1347
+ });
1348
+ const attempts = Effect.withFiber((fiber) => {
1349
+ if (compiled.kind !== "query") return once;
1350
+ const context = fiber.context as Context.Context<any>;
1351
+ let retries = 0;
1352
+ return once.pipe(
1353
+ Effect.retry({
1354
+ while: (error) => {
1355
+ const retry = isRetryable(compiled, error) && retries < 5;
1356
+ // Schedule.exponential("200 millis"): 200 ms, then doubling.
1357
+ if (retry) Telemetry.retried(context, ++retries, error, 200 * 2 ** (retries - 1));
1358
+ return retry;
1359
+ },
1360
+ times: 5,
1361
+ schedule: Schedule.exponential("200 millis"),
1362
+ }),
1363
+ );
1364
+ });
1365
+ return Effect.withFiber((fiber) => {
1366
+ const debug = fiber.getRef(Telemetry.Debug);
1367
+ const telemetry = Context.getOrUndefined(fiber.context, GqlTransport)?.telemetry;
1368
+ if (telemetry === undefined) return attempts;
1369
+ const [info, input] = documentInfo(telemetry, compiled);
1370
+ return Telemetry.operationSpan(fiber, debug, info, undefined, input, () => attempts);
1371
+ }) as Effect.Effect<unknown, ExecuteError, GqlTransport>;
1372
+ };
1373
+
1374
+ /**
1375
+ * One document's span facts: its root fields name it, and their arguments
1376
+ * fill the attributes the SDK's `fields` rules name (an input object keyed
1377
+ * `<kind>.<field>.<argument>`).
1378
+ */
1379
+ const documentInfo = (
1380
+ telemetry: GraphQLTelemetry,
1381
+ compiled: Compiled,
1382
+ ): readonly [Telemetry.OperationInfo, Record<string, unknown>] => {
1383
+ const roots = [...new Set([...compiled.tree.children.values()].map((node) => node.field))];
1384
+ const single = roots.length === 1 ? roots[0] : undefined;
1385
+ const target = single ?? compiled.kind;
1386
+ const input: Record<string, unknown> = {};
1387
+ const rules: Record<string, ReadonlyArray<Telemetry.AttributeRule>> = {};
1388
+ for (const node of compiled.tree.children.values()) {
1389
+ const fieldRules = telemetry.fields?.[`${compiled.kind}.${node.field}`];
1390
+ if (fieldRules === undefined || node.args === undefined) continue;
1391
+ for (const arg in node.args) {
1392
+ const argRules = fieldRules[arg];
1393
+ if (argRules === undefined) continue;
1394
+ const key = `${compiled.kind}.${node.field}.${arg}`;
1395
+ input[key] = compiled.variables[node.args[arg]!];
1396
+ rules[key] = argRules;
1397
+ }
1398
+ }
1399
+ const info = Telemetry.operationInfo(
1400
+ telemetry,
1401
+ {
1402
+ name: `${telemetry.prefix}.${target}`,
1403
+ method: `${telemetry.prefix}/${target}`,
1404
+ attributes: {
1405
+ "graphql.operation.type": compiled.kind,
1406
+ ...(single !== undefined ? { "graphql.operation.name": single } : {}),
1407
+ },
1408
+ input: rules,
1409
+ },
1410
+ undefined,
1411
+ );
1412
+ return [info, input];
1413
+ };
1414
+
1415
+ type ExecuteError = GraphQLIssue | GraphQLFailure | GraphQLTransportError;
1416
+
1417
+ const isRetryable = (compiled: Compiled, error: ExecuteError): boolean => {
1418
+ if (error instanceof GraphQLTransportError) {
1419
+ return error.status === undefined || error.status === 429 || error.status >= 500;
1420
+ }
1421
+ const retryable = new Set(
1422
+ [...compiled.rootErrors.values()].flatMap((root) =>
1423
+ root.errors.filter((spec) => spec.retryable).map((spec) => spec.tag),
1424
+ ),
1425
+ );
1426
+ return error instanceof GraphQLFailure
1427
+ ? error.errors.every((issue) => retryable.has(issue._tag))
1428
+ : retryable.has(error._tag);
1429
+ };
1430
+
1431
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
1432
+ typeof value === "object" && value !== null && !Array.isArray(value);
1433
+
1434
+ /**
1435
+ * Pick the most specific matcher among the errors the root at `path[0]`
1436
+ * declares (or the global errors for a path-less error). A tie between
1437
+ * different tags is ambiguous and stays {@link UnknownGraphQLError}.
1438
+ */
1439
+ const classify = (compiled: Compiled, entry: unknown, response: GraphQLResponse): GraphQLIssue => {
1440
+ // The entry comes from the wire: anything that is not an object (`null`,
1441
+ // a bare string) is read as an error with only a message.
1442
+ const raw: Partial<RawGraphQLError> = isRecord(entry)
1443
+ ? (entry as Partial<RawGraphQLError>)
1444
+ : {
1445
+ message:
1446
+ typeof entry === "string"
1447
+ ? entry
1448
+ : `malformed GraphQL error entry (${entry === null ? "null" : typeof entry})`,
1449
+ };
1450
+ const rawPath = Array.isArray(raw.path) ? (raw.path as ReadonlyArray<unknown>) : undefined;
1451
+ const root = typeof rawPath?.[0] === "string" ? compiled.rootErrors.get(rawPath[0]) : undefined;
1452
+ // The error classes validate `path` and `locations`, so a malformed value
1453
+ // is left out instead of making the constructor throw.
1454
+ const path = rawPath?.every((key) => typeof key === "string" || typeof key === "number")
1455
+ ? (rawPath as ReadonlyArray<string | number>)
1456
+ : undefined;
1457
+ const locations =
1458
+ Array.isArray(raw.locations) &&
1459
+ raw.locations.every(
1460
+ (location: unknown) =>
1461
+ isRecord(location) &&
1462
+ typeof location.line === "number" &&
1463
+ typeof location.column === "number",
1464
+ )
1465
+ ? raw.locations
1466
+ : undefined;
1467
+ const candidates = root
1468
+ ? root.errors
1469
+ : uniqueByTag(
1470
+ [...compiled.rootErrors.values()].flatMap((entry) =>
1471
+ entry.errors.filter((spec) => spec.global),
1472
+ ),
1473
+ );
1474
+ const extensions = isRecord(raw.extensions) ? raw.extensions : {};
1475
+ const code =
1476
+ typeof extensions.code === "string"
1477
+ ? extensions.code
1478
+ : typeof extensions.errorCode === "string"
1479
+ ? extensions.errorCode
1480
+ : undefined;
1481
+ const message = typeof raw.message === "string" ? raw.message : "";
1482
+ const retryHeader = response.headers?.["retry-after"];
1483
+ const props: GraphQLIssueProps = {
1484
+ message,
1485
+ code,
1486
+ path,
1487
+ locations,
1488
+ extensions: raw.extensions,
1489
+ traceId:
1490
+ typeof extensions.traceId === "string"
1491
+ ? extensions.traceId
1492
+ : typeof raw.traceId === "string"
1493
+ ? raw.traceId
1494
+ : undefined,
1495
+ status: response.status,
1496
+ retryAfter: retryHeader && /^\d+(\.\d+)?$/.test(retryHeader) ? Number(retryHeader) : undefined,
1497
+ };
1498
+ const matches = candidates.flatMap((spec) =>
1499
+ spec.matchers
1500
+ .filter(
1501
+ (matcher) =>
1502
+ (matcher.code === undefined || matcher.code === code) &&
1503
+ (matcher.message === undefined || matcher.message === message) &&
1504
+ (matcher.messageIncludes === undefined || message.includes(matcher.messageIncludes)),
1505
+ )
1506
+ .map((matcher) => ({
1507
+ spec,
1508
+ score:
1509
+ (matcher.code ? 1 : 0) + (matcher.message ? 4 : 0) + (matcher.messageIncludes ? 2 : 0),
1510
+ })),
1511
+ );
1512
+ matches.sort((a, b) => b.score - a.score);
1513
+ const best = matches[0];
1514
+ if (
1515
+ best &&
1516
+ !matches.some((match) => match.score === best.score && match.spec.tag !== best.spec.tag)
1517
+ ) {
1518
+ return best.spec.make(props);
1519
+ }
1520
+ return new UnknownGraphQLError({
1521
+ ...props,
1522
+ coordinate: root?.field,
1523
+ });
1524
+ };
1525
+
1526
+ const uniqueByTag = (specs: ReadonlyArray<ErrorSpec>): ErrorSpec[] => [
1527
+ ...new Map(specs.map((spec) => [spec.tag, spec])).values(),
1528
+ ];
1529
+
1530
+ /** `Query.of` / pure. */
1531
+ export const ofQuery = <Value>(value: Value): Query<Value> =>
1532
+ make({ _tag: "Literal", value, type: { tag: "scalar" } });
1533
+
1534
+ const filterImpl = (
1535
+ source: QueryNode,
1536
+ predicate: (item: QueryNode) => QueryNode,
1537
+ ): Query<unknown> => {
1538
+ const proto = itemQuery(source);
1539
+ const predicateQuery = predicate(proto);
1540
+ log("filter pred", printExpr(predicateQuery.expr));
1541
+ return make({
1542
+ _tag: "Filter",
1543
+ parent: source.expr,
1544
+ predicate: predicateQuery.expr,
1545
+ type: source.expr.type,
1546
+ });
1547
+ };
1548
+
1549
+ export function filterQuery<Item, Error = never>(
1550
+ predicate: (item: Query<Item>) => QueryNode<boolean, any>,
1551
+ ): (source: QueryNode<readonly Item[] | null, Error>) => Query<readonly Item[], Error>;
1552
+ export function filterQuery<Item, Error = never>(
1553
+ source: QueryNode<readonly Item[] | null, Error>,
1554
+ predicate: (item: Query<Item>) => QueryNode<boolean, any>,
1555
+ ): Query<readonly Item[], Error>;
1556
+ export function filterQuery(sourceOrPredicate: any, predicate?: any): any {
1557
+ if (predicate === undefined) {
1558
+ return (source: QueryNode) => filterImpl(source, sourceOrPredicate);
1559
+ }
1560
+ return filterImpl(sourceOrPredicate, predicate);
1561
+ }
1562
+
1563
+ /**
1564
+ * What `Query.map`'s callback receives: a Query per item for lists, a Query
1565
+ * for an object (so its fields get selected), the plain value for scalars.
1566
+ */
1567
+ type MapInput<Value> = [NonNullable<Value>] extends [ReadonlyArray<infer Item>]
1568
+ ? Query<Item>
1569
+ : [NonNullable<Value>] extends [object]
1570
+ ? Query<NonNullable<Value>>
1571
+ : Value;
1572
+
1573
+ /** An object mapped through a `null` value stays `null`. */
1574
+ type MapOutput<Value, Mapped> = [NonNullable<Value>] extends [ReadonlyArray<unknown>]
1575
+ ? ReadonlyArray<UnwrapPlan<Mapped>>
1576
+ : [NonNullable<Value>] extends [object]
1577
+ ? UnwrapPlan<Mapped> | Nullish<Value>
1578
+ : Mapped;
1579
+
1580
+ const mapImpl = (source: QueryNode, mapFn: (value: any) => unknown): Query<unknown> => {
1581
+ if (source.expr.type.tag === "object") {
1582
+ const mapped = mapFn(
1583
+ new QueryNode({
1584
+ _tag: "Item",
1585
+ list: source.expr,
1586
+ type: source.expr.type,
1587
+ }),
1588
+ );
1589
+ log("map object", printExpr(source.expr));
1590
+ return make({
1591
+ _tag: "MapItems",
1592
+ parent: source.expr,
1593
+ mapped,
1594
+ single: true,
1595
+ type: { tag: "scalar" },
1596
+ });
1597
+ }
1598
+ if (source.expr.type.tag === "list") {
1599
+ const proto = itemQuery(source);
1600
+ const mapped = mapFn(proto);
1601
+ log("map items", printExpr(source.expr));
1602
+ return make({
1603
+ _tag: "MapItems",
1604
+ parent: source.expr,
1605
+ mapped,
1606
+ type: source.expr.type,
1607
+ });
1608
+ }
1609
+ log("map value", printExpr(source.expr));
1610
+ return make({
1611
+ _tag: "MapValue",
1612
+ parent: source.expr,
1613
+ mapFn,
1614
+ type: { tag: "scalar" },
1615
+ });
1616
+ };
1617
+
1618
+ export function mapQuery<Value, Mapped, Error = never>(
1619
+ mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
1620
+ ): (source: QueryNode<Value, Error>) => Query<MapOutput<Value, Mapped>, Error>;
1621
+ export function mapQuery<Value, Mapped, Error = never>(
1622
+ source: QueryNode<Value, Error>,
1623
+ mapFn: (value: NoInfer<MapInput<Value>>) => Mapped,
1624
+ ): Query<MapOutput<Value, Mapped>, Error>;
1625
+ export function mapQuery(sourceOrMapFn: any, mapFn?: any): any {
1626
+ if (mapFn === undefined) {
1627
+ return (source: QueryNode) => mapImpl(source, sourceOrMapFn);
1628
+ }
1629
+ return mapImpl(sourceOrMapFn, mapFn);
1630
+ }
1631
+
1632
+ const flatMapImpl = (source: QueryNode, flatMapFn: (value: unknown) => unknown): Query<unknown> => {
1633
+ log("flatMap", printExpr(source.expr));
1634
+ return make({
1635
+ _tag: "FlatMap",
1636
+ parent: source.expr,
1637
+ flatMapFn,
1638
+ type: { tag: "scalar" },
1639
+ });
1640
+ };
1641
+
1642
+ export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
1643
+ flatMapFn: (
1644
+ value: Value,
1645
+ ) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
1646
+ ): (source: QueryNode<Value, SourceError>) => Query<Result, SourceError | Error>;
1647
+ export function flatMapQuery<Value, Result, Error, Requirements, SourceError = never>(
1648
+ source: QueryNode<Value, SourceError>,
1649
+ flatMapFn: (
1650
+ value: Value,
1651
+ ) => Effect.Effect<Result, Error, Requirements> | QueryNode<Result, Error>,
1652
+ ): Query<Result, SourceError | Error>;
1653
+ export function flatMapQuery(sourceOrFlatMapFn: any, flatMapFn?: any): any {
1654
+ if (flatMapFn === undefined) {
1655
+ return (source: QueryNode) => flatMapImpl(source, sourceOrFlatMapFn);
1656
+ }
1657
+ return flatMapImpl(sourceOrFlatMapFn, flatMapFn);
1658
+ }
1659
+
1660
+ /**
1661
+ * Builder -> Effect. The inner function is *not* a generator; it returns a
1662
+ * plan of Query/Effect values. Query.fn visits the plan, POSTs one document,
1663
+ * then interprets Map/Filter/FlatMap/Of.
1664
+ */
1665
+ export const queryFn =
1666
+ <Arguments extends Array<unknown>, Plan>(
1667
+ build: (...args: Arguments) => Plan,
1668
+ ): ((
1669
+ ...args: Arguments
1670
+ ) => Effect.Effect<UnwrapPlan<Plan>, QueryError<PlanError<Plan>>, GqlTransport>) =>
1671
+ (...args) => {
1672
+ const plan = build(...args);
1673
+ return evaluatePlan(plan);
1674
+ };
1675
+
1676
+ // U+2500U+2500 Pagination U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500U+2500
1677
+ //
1678
+ // A connection lens hides `edges`/`pageInfo`. `Query.pages` re-evaluates the
1679
+ // query once per page: it sets the connection's `after` argument, paints
1680
+ // `pageInfo { hasNextPage endCursor }` next to `edges`, and stops when
1681
+ // `hasNextPage` is false.
1682
+
1683
+ /** The connection a paged query reads, below any list-level Map/Filter. */
1684
+ const connectionOf = (expr: Expr): RootExpr | PropExpr => {
1685
+ const base = graphqlBase(expr);
1686
+ const isConnection =
1687
+ (base._tag === "Root" && base.connection === true) ||
1688
+ (base._tag === "Prop" && base.field.kind === "connection");
1689
+ if (!isConnection || inItem(base)) {
1690
+ throw new GqlError(`Query.pages needs a Relay connection, got ${printExpr(base)}`);
1691
+ }
1692
+ const argTypes = base._tag === "Root" ? base.argTypes : base.field.argTypes;
1693
+ if (!argTypes || !("after" in argTypes)) {
1694
+ throw new GqlError(`${printExpr(base)} takes no "after" cursor`);
1695
+ }
1696
+ return base as RootExpr | PropExpr;
1697
+ };
1698
+
1699
+ /** Rebuild `expr` with the connection's `after` argument set. */
1700
+ const withCursor = (expr: Expr, connection: Expr, after: string | undefined): Expr => {
1701
+ if (expr === connection) {
1702
+ const current = expr as RootExpr | PropExpr;
1703
+ return { ...current, args: { ...current.args, after } } as Expr;
1704
+ }
1705
+ switch (expr._tag) {
1706
+ case "MapItems":
1707
+ case "Filter":
1708
+ case "MapValue":
1709
+ case "FlatMap":
1710
+ return { ...expr, parent: withCursor(expr.parent, connection, after) };
1711
+ default:
1712
+ throw new GqlError(`withCursor: ${expr._tag}`);
1713
+ }
1714
+ };
1715
+
1716
+ const readPath = (data: unknown, path: Path): unknown => {
1717
+ let current = data;
1718
+ for (const segment of path) {
1719
+ if (current == null) return undefined;
1720
+ if (Array.isArray(current)) {
1721
+ throw new GqlError("Query.pages cannot page a connection inside a list");
1722
+ }
1723
+ current = (current as Record<string, unknown>)[segment];
1724
+ }
1725
+ return current;
1726
+ };
1727
+
1728
+ interface PageState {
1729
+ readonly after: string | undefined;
1730
+ readonly seen: ReadonlySet<string>;
1731
+ }
1732
+
1733
+ const fetchPage = <Item>(
1734
+ query: QueryNode<ReadonlyArray<Item> | null, unknown>,
1735
+ connection: RootExpr | PropExpr,
1736
+ state: PageState,
1737
+ ) =>
1738
+ Effect.gen(function* () {
1739
+ const { pageExpr, connectionPath, compiled } = yield* compiling(() => {
1740
+ const pageExpr = withCursor(query.expr, connection, state.after);
1741
+ const forest = emptyForest();
1742
+ visitExpr(forest, pageExpr);
1743
+ const nodePath = paintAbs(forest, withCursor(connection, connection, state.after));
1744
+ const connectionPath = nodePath.slice(0, -2);
1745
+ const pageInfo = ensureChild(forest, selAt(forest.roots, connectionPath), "pageInfo", {});
1746
+ ensureChild(forest, pageInfo, "hasNextPage", { isScalar: true });
1747
+ ensureChild(forest, pageInfo, "endCursor", { isScalar: true });
1748
+ return { pageExpr, connectionPath, compiled: emit(forest) };
1749
+ });
1750
+ log("page\n" + compiled.document);
1751
+ const data = yield* execute(compiled);
1752
+ const items = (yield* interpretPlan(make(pageExpr), data, compiled.rootAlias)) as
1753
+ | ReadonlyArray<Item>
1754
+ | null
1755
+ | undefined;
1756
+ const info = readPath(data, [...connectionPath, "pageInfo"]) as
1757
+ | { hasNextPage?: boolean; endCursor?: string | null }
1758
+ | null
1759
+ | undefined;
1760
+ const cursor = info?.endCursor ?? null;
1761
+ if (info?.hasNextPage !== true) {
1762
+ return [items ?? [], Option.none<PageState>()] as const;
1763
+ }
1764
+ if (cursor === null || cursor === state.after || state.seen.has(cursor)) {
1765
+ return yield* new GraphQLPaginationError({
1766
+ message: `${printExpr(connection)} returned a non-advancing cursor`,
1767
+ cursor,
1768
+ });
1769
+ }
1770
+ return [
1771
+ items ?? [],
1772
+ Option.some({ after: cursor, seen: new Set([...state.seen, cursor]) }),
1773
+ ] as const;
1774
+ });
1775
+
1776
+ /**
1777
+ * Every page of a Relay connection, one request per page. `query` is a
1778
+ * connection lens (root or nested under objects), optionally mapped or
1779
+ * filtered: `Query.pages(Railway.project({ id }).services({ first: 50 }))`.
1780
+ * Starts from the query's own `after` argument, if any.
1781
+ */
1782
+ export const pagesQuery = <Item, Error>(
1783
+ query: QueryNode<ReadonlyArray<Item> | null, Error>,
1784
+ ): Stream.Stream<ReadonlyArray<Item>, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
1785
+ Stream.unwrap(
1786
+ Effect.map(
1787
+ compiling(() => connectionOf(query.expr)),
1788
+ (connection) => {
1789
+ const after = connection.args?.after;
1790
+ return Stream.paginate<
1791
+ PageState,
1792
+ ReadonlyArray<Item>,
1793
+ QueryError<Error> | GraphQLPaginationError,
1794
+ GqlTransport
1795
+ >(
1796
+ {
1797
+ after: typeof after === "string" ? after : undefined,
1798
+ seen: new Set(),
1799
+ },
1800
+ (state) =>
1801
+ fetchPage(query, connection, state).pipe(
1802
+ Effect.map(([items, next]) => [[items], next] as const),
1803
+ ) as Effect.Effect<
1804
+ readonly [ReadonlyArray<ReadonlyArray<Item>>, Option.Option<PageState>],
1805
+ QueryError<Error> | GraphQLPaginationError,
1806
+ GqlTransport
1807
+ >,
1808
+ );
1809
+ },
1810
+ ),
1811
+ );
1812
+
1813
+ /** Every node of a Relay connection, across all pages. */
1814
+ export const itemsQuery = <Item, Error>(
1815
+ query: QueryNode<ReadonlyArray<Item> | null, Error>,
1816
+ ): Stream.Stream<Item, QueryError<Error> | GraphQLPaginationError, GqlTransport> =>
1817
+ pagesQuery(query).pipe(Stream.flatMap(Stream.fromIterable));