@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.17

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 (318) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/api.d.ts +118 -13
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -188
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/category.js +1 -278
  16. package/lib/chunks.d.ts +3 -0
  17. package/lib/chunks.d.ts.map +1 -0
  18. package/lib/chunks.js +1 -0
  19. package/lib/codegen/boolean-string-enums.js +36 -36
  20. package/lib/codegen/chunk.d.ts +7 -0
  21. package/lib/codegen/chunk.d.ts.map +1 -0
  22. package/lib/codegen/chunk.js +139 -0
  23. package/lib/codegen/chunk.js.map +1 -0
  24. package/lib/codegen/cli.d.ts.map +1 -1
  25. package/lib/codegen/cli.js +28 -14
  26. package/lib/codegen/cli.js.map +1 -1
  27. package/lib/codegen/datafy.d.ts +14 -0
  28. package/lib/codegen/datafy.d.ts.map +1 -0
  29. package/lib/codegen/datafy.js +853 -0
  30. package/lib/codegen/datafy.js.map +1 -0
  31. package/lib/codegen/dedupe.d.ts +5 -0
  32. package/lib/codegen/dedupe.d.ts.map +1 -0
  33. package/lib/codegen/dedupe.js +153 -0
  34. package/lib/codegen/dedupe.js.map +1 -0
  35. package/lib/codegen/emit.js +56 -56
  36. package/lib/codegen/format.js +18 -18
  37. package/lib/codegen/generated-at.js +29 -29
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +92 -84
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/graph.js +36 -36
  42. package/lib/codegen/graphql-client.d.ts +2 -0
  43. package/lib/codegen/graphql-client.d.ts.map +1 -1
  44. package/lib/codegen/graphql-client.js +55 -26
  45. package/lib/codegen/graphql-client.js.map +1 -1
  46. package/lib/codegen/graphql.js +113 -113
  47. package/lib/codegen/latin1.d.ts +3 -0
  48. package/lib/codegen/latin1.d.ts.map +1 -0
  49. package/lib/codegen/latin1.js +126 -0
  50. package/lib/codegen/latin1.js.map +1 -0
  51. package/lib/codegen/members.d.ts +7 -0
  52. package/lib/codegen/members.d.ts.map +1 -1
  53. package/lib/codegen/members.js +26 -19
  54. package/lib/codegen/members.js.map +1 -1
  55. package/lib/codegen/model-diff.js +6 -6
  56. package/lib/codegen/naming.js +19 -19
  57. package/lib/codegen/openapi-cli.js +15 -15
  58. package/lib/codegen/openapi.d.ts +17 -0
  59. package/lib/codegen/openapi.d.ts.map +1 -1
  60. package/lib/codegen/openapi.js +323 -169
  61. package/lib/codegen/openapi.js.map +1 -1
  62. package/lib/codegen/operations.js +14 -14
  63. package/lib/codegen/pagination.js +11 -11
  64. package/lib/codegen/patch-audit.js +57 -57
  65. package/lib/codegen/patches.js +79 -79
  66. package/lib/codegen/prelude.js +19 -19
  67. package/lib/codegen/privatize.d.ts +21 -0
  68. package/lib/codegen/privatize.d.ts.map +1 -0
  69. package/lib/codegen/privatize.js +176 -0
  70. package/lib/codegen/privatize.js.map +1 -0
  71. package/lib/codegen/proto.js +25 -25
  72. package/lib/codegen/pure.d.ts +6 -0
  73. package/lib/codegen/pure.d.ts.map +1 -0
  74. package/lib/codegen/pure.js +91 -0
  75. package/lib/codegen/pure.js.map +1 -0
  76. package/lib/codegen/rewrite-operation-ids.js +108 -108
  77. package/lib/codegen/spec-path.js +57 -57
  78. package/lib/codegen/table.d.ts +5 -0
  79. package/lib/codegen/table.d.ts.map +1 -0
  80. package/lib/codegen/table.js +249 -0
  81. package/lib/codegen/table.js.map +1 -0
  82. package/lib/config.d.ts +27 -0
  83. package/lib/config.d.ts.map +1 -0
  84. package/lib/config.js +1 -0
  85. package/lib/crypto.d.ts +76 -0
  86. package/lib/crypto.d.ts.map +1 -0
  87. package/lib/crypto.js +1 -0
  88. package/lib/debug.d.ts +2 -0
  89. package/lib/debug.d.ts.map +1 -0
  90. package/lib/debug.js +1 -0
  91. package/lib/error-category.d.ts +1 -1
  92. package/lib/error-category.d.ts.map +1 -1
  93. package/lib/error-category.js +1 -46
  94. package/lib/errors.d.ts +62 -62
  95. package/lib/errors.d.ts.map +1 -1
  96. package/lib/errors.js +1 -195
  97. package/lib/graphql.d.ts +31 -20
  98. package/lib/graphql.d.ts.map +1 -1
  99. package/lib/graphql.js +1 -1027
  100. package/lib/graphql.types.js +1 -5
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +1 -15
  104. package/lib/json-patch.d.ts +2 -2
  105. package/lib/json-patch.js +1 -226
  106. package/lib/json-patch.js.map +1 -1
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +1 -266
  110. package/lib/plain-values.d.ts +10 -0
  111. package/lib/plain-values.d.ts.map +1 -0
  112. package/lib/plain-values.js +2 -0
  113. package/lib/plain-values.js.map +1 -0
  114. package/lib/protocol-http.d.ts +50 -14
  115. package/lib/protocol-http.d.ts.map +1 -1
  116. package/lib/protocol-http.js +1 -639
  117. package/lib/protocol-rest.d.ts +38 -25
  118. package/lib/protocol-rest.d.ts.map +1 -1
  119. package/lib/protocol-rest.js +1 -267
  120. package/lib/query.js +1 -27
  121. package/lib/response-validation-strict.d.ts +48 -0
  122. package/lib/response-validation-strict.d.ts.map +1 -0
  123. package/lib/response-validation-strict.js +1 -0
  124. package/lib/response-validation.d.ts +43 -25
  125. package/lib/response-validation.d.ts.map +1 -1
  126. package/lib/response-validation.js +1 -76
  127. package/lib/retry-after.d.ts +3 -3
  128. package/lib/retry-after.js +1 -112
  129. package/lib/retry.d.ts +48 -29
  130. package/lib/retry.d.ts.map +1 -1
  131. package/lib/retry.js +1 -209
  132. package/lib/schema-lite-impl.d.ts +158 -0
  133. package/lib/schema-lite-impl.d.ts.map +1 -0
  134. package/lib/schema-lite-impl.js +1 -0
  135. package/lib/schema-lite-typed.d.ts +41 -0
  136. package/lib/schema-lite-typed.d.ts.map +1 -0
  137. package/lib/schema-lite-typed.js +2 -0
  138. package/lib/schema-lite-typed.js.map +1 -0
  139. package/lib/schema-lite.d.ts +40 -0
  140. package/lib/schema-lite.d.ts.map +1 -0
  141. package/lib/schema-lite.js +1 -0
  142. package/lib/schema.d.ts +20 -6
  143. package/lib/schema.d.ts.map +1 -1
  144. package/lib/schema.js +1 -48
  145. package/lib/testing.d.ts +3 -2
  146. package/lib/testing.d.ts.map +1 -1
  147. package/lib/testing.js +1 -40
  148. package/lib/testing.js.map +1 -1
  149. package/lib/trait.d.ts +13 -13
  150. package/lib/trait.d.ts.map +1 -1
  151. package/lib/trait.js +1 -131
  152. package/lib/xml.d.ts +1 -1
  153. package/lib/xml.d.ts.map +1 -1
  154. package/lib/xml.js +1 -311
  155. package/package.json +9 -7
  156. package/src/api.ts +1080 -180
  157. package/src/category.ts +33 -33
  158. package/src/chunks.ts +30 -0
  159. package/src/codegen/chunk.ts +147 -0
  160. package/src/codegen/cli.ts +27 -1
  161. package/src/codegen/datafy.ts +874 -0
  162. package/src/codegen/dedupe.ts +173 -0
  163. package/src/codegen/generator.ts +10 -3
  164. package/src/codegen/graphql-client.ts +49 -15
  165. package/src/codegen/latin1.ts +131 -0
  166. package/src/codegen/members.ts +8 -0
  167. package/src/codegen/openapi.ts +194 -3
  168. package/src/codegen/privatize.ts +200 -0
  169. package/src/codegen/pure.ts +94 -0
  170. package/src/codegen/table.ts +254 -0
  171. package/src/config.ts +216 -0
  172. package/src/crypto.ts +202 -0
  173. package/src/debug.ts +8 -0
  174. package/src/error-category.ts +2 -1
  175. package/src/errors.ts +65 -56
  176. package/src/graphql.ts +109 -62
  177. package/src/graphql.types.ts +9 -7
  178. package/src/index.ts +3 -2
  179. package/src/json-patch.ts +2 -2
  180. package/src/pagination.ts +37 -18
  181. package/src/plain-values.ts +41 -0
  182. package/src/protocol-http.ts +378 -145
  183. package/src/protocol-rest.ts +337 -169
  184. package/src/response-validation-strict.ts +327 -0
  185. package/src/response-validation.ts +101 -50
  186. package/src/retry-after.ts +3 -3
  187. package/src/retry.ts +94 -93
  188. package/src/schema-lite-impl.ts +550 -0
  189. package/src/schema-lite-typed.ts +44 -0
  190. package/src/schema-lite.ts +44 -0
  191. package/src/schema.ts +258 -14
  192. package/src/testing.ts +4 -2
  193. package/src/trait.ts +36 -28
  194. package/src/xml.ts +31 -17
  195. package/lib/api.js.map +0 -1
  196. package/lib/category.js.map +0 -1
  197. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  198. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  199. package/lib/codegen/boolean-string-enums.test.js +0 -275
  200. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  201. package/lib/codegen/defer-naming.test.d.ts +0 -2
  202. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  203. package/lib/codegen/defer-naming.test.js +0 -105
  204. package/lib/codegen/defer-naming.test.js.map +0 -1
  205. package/lib/codegen/generated-at.test.d.ts +0 -2
  206. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  207. package/lib/codegen/generated-at.test.js +0 -81
  208. package/lib/codegen/generated-at.test.js.map +0 -1
  209. package/lib/codegen/generator.test.d.ts +0 -2
  210. package/lib/codegen/generator.test.d.ts.map +0 -1
  211. package/lib/codegen/generator.test.js +0 -121
  212. package/lib/codegen/generator.test.js.map +0 -1
  213. package/lib/codegen/graphql-client.test.d.ts +0 -2
  214. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  215. package/lib/codegen/graphql-client.test.js +0 -171
  216. package/lib/codegen/graphql-client.test.js.map +0 -1
  217. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  218. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  219. package/lib/codegen/openapi-binary.test.js +0 -67
  220. package/lib/codegen/openapi-binary.test.js.map +0 -1
  221. package/lib/codegen/patch-audit.test.d.ts +0 -2
  222. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  223. package/lib/codegen/patch-audit.test.js +0 -141
  224. package/lib/codegen/patch-audit.test.js.map +0 -1
  225. package/lib/codegen/patches.test.d.ts +0 -2
  226. package/lib/codegen/patches.test.d.ts.map +0 -1
  227. package/lib/codegen/patches.test.js +0 -155
  228. package/lib/codegen/patches.test.js.map +0 -1
  229. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  230. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  231. package/lib/codegen/protocol-imports.test.js +0 -36
  232. package/lib/codegen/protocol-imports.test.js.map +0 -1
  233. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  234. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  235. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  236. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  237. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  238. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  239. package/lib/codegen/untagged-unions.test.js +0 -80
  240. package/lib/codegen/untagged-unions.test.js.map +0 -1
  241. package/lib/error-category.js.map +0 -1
  242. package/lib/errors.js.map +0 -1
  243. package/lib/fixtures/xml/upstream-validator.json +0 -397
  244. package/lib/graphql.js.map +0 -1
  245. package/lib/graphql.test.d.ts +0 -2
  246. package/lib/graphql.test.d.ts.map +0 -1
  247. package/lib/graphql.test.js +0 -151
  248. package/lib/graphql.test.js.map +0 -1
  249. package/lib/graphql.types.js.map +0 -1
  250. package/lib/index.js.map +0 -1
  251. package/lib/json-patch.test.d.ts +0 -2
  252. package/lib/json-patch.test.d.ts.map +0 -1
  253. package/lib/json-patch.test.js +0 -65
  254. package/lib/json-patch.test.js.map +0 -1
  255. package/lib/pagination.js.map +0 -1
  256. package/lib/pagination.test.d.ts +0 -2
  257. package/lib/pagination.test.d.ts.map +0 -1
  258. package/lib/pagination.test.js +0 -131
  259. package/lib/pagination.test.js.map +0 -1
  260. package/lib/protocol-http.js.map +0 -1
  261. package/lib/protocol-http.test.d.ts +0 -2
  262. package/lib/protocol-http.test.d.ts.map +0 -1
  263. package/lib/protocol-http.test.js +0 -228
  264. package/lib/protocol-http.test.js.map +0 -1
  265. package/lib/protocol-rest.js.map +0 -1
  266. package/lib/protocol-rest.test.d.ts +0 -2
  267. package/lib/protocol-rest.test.d.ts.map +0 -1
  268. package/lib/protocol-rest.test.js +0 -498
  269. package/lib/protocol-rest.test.js.map +0 -1
  270. package/lib/query.js.map +0 -1
  271. package/lib/response-validation.js.map +0 -1
  272. package/lib/response-validation.test.d.ts +0 -2
  273. package/lib/response-validation.test.d.ts.map +0 -1
  274. package/lib/response-validation.test.js +0 -72
  275. package/lib/response-validation.test.js.map +0 -1
  276. package/lib/retry-after.js.map +0 -1
  277. package/lib/retry-after.test.d.ts +0 -2
  278. package/lib/retry-after.test.d.ts.map +0 -1
  279. package/lib/retry-after.test.js +0 -204
  280. package/lib/retry-after.test.js.map +0 -1
  281. package/lib/retry.js.map +0 -1
  282. package/lib/retry.test.d.ts +0 -2
  283. package/lib/retry.test.d.ts.map +0 -1
  284. package/lib/retry.test.js +0 -407
  285. package/lib/retry.test.js.map +0 -1
  286. package/lib/schema.js.map +0 -1
  287. package/lib/sdks.test.d.ts +0 -2
  288. package/lib/sdks.test.d.ts.map +0 -1
  289. package/lib/sdks.test.js +0 -76
  290. package/lib/sdks.test.js.map +0 -1
  291. package/lib/trait.js.map +0 -1
  292. package/lib/xml.js.map +0 -1
  293. package/lib/xml.test.d.ts +0 -2
  294. package/lib/xml.test.d.ts.map +0 -1
  295. package/lib/xml.test.js +0 -210
  296. package/lib/xml.test.js.map +0 -1
  297. package/src/codegen/boolean-string-enums.test.ts +0 -299
  298. package/src/codegen/defer-naming.test.ts +0 -113
  299. package/src/codegen/generated-at.test.ts +0 -89
  300. package/src/codegen/generator.test.ts +0 -137
  301. package/src/codegen/graphql-client.test.ts +0 -189
  302. package/src/codegen/openapi-binary.test.ts +0 -91
  303. package/src/codegen/patch-audit.test.ts +0 -160
  304. package/src/codegen/patches.test.ts +0 -188
  305. package/src/codegen/protocol-imports.test.ts +0 -39
  306. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  307. package/src/codegen/untagged-unions.test.ts +0 -85
  308. package/src/fixtures/xml/upstream-validator.json +0 -397
  309. package/src/graphql.test.ts +0 -198
  310. package/src/json-patch.test.ts +0 -77
  311. package/src/pagination.test.ts +0 -169
  312. package/src/protocol-http.test.ts +0 -276
  313. package/src/protocol-rest.test.ts +0 -703
  314. package/src/response-validation.test.ts +0 -89
  315. package/src/retry-after.test.ts +0 -267
  316. package/src/retry.test.ts +0 -566
  317. package/src/sdks.test.ts +0 -87
  318. package/src/xml.test.ts +0 -251
package/lib/graphql.js CHANGED
@@ -1,1027 +1 @@
1
- /**
2
- * GraphQL Query algebra — the runtime generated GraphQL SDKs target.
3
- *
4
- * ── Why this exists ────────────────────────────────────────────────────────
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
- * ── The two phases ─────────────────────────────────────────────────────────
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
- * ── Combinators ────────────────────────────────────────────────────────────
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
- * ── Types ──────────────────────────────────────────────────────────────────
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
- * ── Transport ──────────────────────────────────────────────────────────────
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). Compile
48
- * failures are {@link GqlError} defects.
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 Schedule from "effect/Schedule";
58
- import * as S from "effect/Schema";
59
- import * as Stream from "effect/Stream";
60
- export const QuerySymbol = Symbol.for("@distilled.cloud/graphql/Query");
61
- const inspect = Symbol.for("nodejs.util.inspect.custom");
62
- /** A plan that cannot be compiled (a programming error, raised as a defect). */
63
- export class GqlError {
64
- _tag = "GqlError";
65
- message;
66
- constructor(message) {
67
- this.message = message;
68
- }
69
- }
70
- // ── Errors ──────────────────────────────────────────────────────────────────
71
- //
72
- // Every entry of a GraphQL `errors` array becomes one typed issue. Generated
73
- // SDKs declare tagged error classes plus the matchers that recognize them,
74
- // scoped to the root fields that can return them (or global). `Query.fn`
75
- // classifies each entry against the roots its path points at, so the error
76
- // channel is the union of the errors declared by the roots the plan reads.
77
- /** Fields every classified GraphQL error carries. */
78
- export const errorFields = {
79
- message: S.String,
80
- code: S.optional(S.String),
81
- path: S.optional(S.Array(S.Union([S.String, S.Number]))),
82
- locations: S.optional(S.Array(S.Struct({ line: S.Number, column: S.Number }))),
83
- extensions: S.optional(S.Unknown),
84
- traceId: S.optional(S.String),
85
- status: S.optional(S.Number),
86
- /** Server retry hint in seconds. */
87
- retryAfter: S.optional(S.Number),
88
- };
89
- /** A GraphQL error no declared matcher recognizes. */
90
- export class UnknownGraphQLError extends S.TaggedError()("UnknownGraphQLError", {
91
- ...errorFields,
92
- /** Root field the error path points at, when the path is known. */
93
- coordinate: S.optional(S.String),
94
- }) {
95
- }
96
- /** One response carried errors with different tags; none is hidden. */
97
- export class GraphQLFailure extends Data.TaggedError("GraphQLFailure") {
98
- get message() {
99
- return this.errors
100
- .map((e) => `${e._tag}${e.path?.length ? ` at ${e.path.join(".")}` : ""}: ${e.message}`)
101
- .join("; ");
102
- }
103
- }
104
- /** The request never produced a GraphQL response (network, HTTP, non-JSON). */
105
- export class GraphQLTransportError extends Data.TaggedError("GraphQLTransportError") {
106
- }
107
- /** A paginated connection reported more pages without a new cursor. */
108
- export class GraphQLPaginationError extends Data.TaggedError("GraphQLPaginationError") {
109
- }
110
- export const errorSpec = (make, tag, matchers, options = {}) => ({
111
- tag,
112
- make: (props) => new make(props),
113
- matchers,
114
- retryable: options.retryable ?? false,
115
- global: options.global ?? false,
116
- });
117
- export const scalarField = (name) => ({
118
- name,
119
- kind: "scalar",
120
- });
121
- export const objectField = (name, objectType) => ({
122
- name,
123
- kind: "object",
124
- of: objectType,
125
- });
126
- export const listField = (name, itemType, argTypes) => ({
127
- name,
128
- kind: "list",
129
- of: itemType,
130
- argTypes,
131
- });
132
- /** Relay connection: GraphQL `edges { node }` presented as `Query<Item[]>`. */
133
- export const connectionField = (name, nodeType, argTypes) => ({
134
- name,
135
- kind: "connection",
136
- of: nodeType,
137
- argTypes,
138
- });
139
- const objectRef = (meta) => ({ tag: "object", meta });
140
- const listRef = (itemType) => ({
141
- tag: "list",
142
- of: itemType,
143
- });
144
- const fieldResult = (parent, field) => {
145
- const inner = () => {
146
- if (field.kind === "scalar")
147
- return { tag: "scalar" };
148
- if (field.kind === "object")
149
- return objectRef(field.of);
150
- return listRef(objectRef(field.of)); // list | connection
151
- };
152
- return parent.tag === "list" ? listRef(fieldResult(parent.of, field)) : inner();
153
- };
154
- const unwrapList = (typeRef) => {
155
- if (typeRef.tag !== "list")
156
- throw new GqlError("expected a list Query");
157
- return typeRef.of;
158
- };
159
- const fieldsOf = (typeRef) => {
160
- if (typeRef.tag === "object")
161
- return typeRef.meta.fields;
162
- if (typeRef.tag === "list")
163
- return fieldsOf(typeRef.of);
164
- return {};
165
- };
166
- export class GqlTransport extends Context.Service()("@distilled.cloud/graphql/Transport") {
167
- }
168
- const log = (..._args) => { };
169
- export class QueryNode {
170
- [QuerySymbol] = QuerySymbol;
171
- expr;
172
- constructor(expr) {
173
- this.expr = expr;
174
- return proxy(this);
175
- }
176
- pipe(...steps) {
177
- return steps.reduce((current, step) => step(current), this);
178
- }
179
- [inspect]() {
180
- return printExpr(this.expr);
181
- }
182
- toString() {
183
- return this[inspect]();
184
- }
185
- }
186
- export const isQuery = (value) => (typeof value === "object" || typeof value === "function") &&
187
- value !== null &&
188
- QuerySymbol in value;
189
- const make = (expr) => new QueryNode(expr);
190
- const itemQuery = (list) => new QueryNode({
191
- _tag: "Item",
192
- list: list.expr,
193
- type: unwrapList(list.expr.type),
194
- });
195
- function proxy(self) {
196
- const callable = Object.assign(function (bag) {
197
- return bag == null ? self : applyBag(self, bag);
198
- }, self);
199
- return new Proxy(callable, {
200
- has: (_, prop) => prop === QuerySymbol ||
201
- prop === inspect ||
202
- prop in self ||
203
- (typeof prop === "string" && prop in fieldsOf(self.expr.type)),
204
- get: (_target, prop) => {
205
- if (prop === QuerySymbol)
206
- return QuerySymbol;
207
- if (prop === inspect)
208
- return self[inspect].bind(self);
209
- if (prop === "pipe")
210
- return self.pipe.bind(self);
211
- if (typeof prop === "string" && prop in self) {
212
- const member = self[prop];
213
- return typeof member === "function" ? member.bind(self) : member;
214
- }
215
- if (typeof prop !== "string")
216
- return undefined;
217
- const field = fieldsOf(self.expr.type)[prop];
218
- if (!field)
219
- return undefined;
220
- return make({
221
- _tag: "Prop",
222
- parent: self.expr,
223
- field,
224
- type: fieldResult(self.expr.type, field),
225
- });
226
- },
227
- apply: (_target, _thisArg, args) => applyBag(self, args[0] ?? {}),
228
- });
229
- }
230
- const applyBag = (self, bag) => {
231
- const argTypes = self.expr._tag === "Prop"
232
- ? self.expr.field.argTypes
233
- : self.expr._tag === "Root"
234
- ? self.expr.argTypes
235
- : undefined;
236
- const args = {};
237
- for (const [argName, argValue] of Object.entries(bag)) {
238
- if (argTypes && argName in argTypes)
239
- args[argName] = argValue;
240
- }
241
- if (self.expr._tag === "Prop") {
242
- return make({
243
- ...self.expr,
244
- args: { ...self.expr.args, ...args },
245
- });
246
- }
247
- if (self.expr._tag === "Root") {
248
- return make({
249
- ...self.expr,
250
- args: { ...self.expr.args, ...args },
251
- });
252
- }
253
- return self;
254
- };
255
- export const root = (op, field, meta, args, argTypes, errors = []) => make({
256
- _tag: "Root",
257
- op,
258
- field,
259
- args,
260
- argTypes,
261
- type: objectRef(meta),
262
- errors,
263
- });
264
- export const rootList = (op, field, meta, args, argTypes, errors = []) => make({
265
- _tag: "Root",
266
- op,
267
- field,
268
- args,
269
- argTypes,
270
- type: listRef(objectRef(meta)),
271
- errors,
272
- });
273
- /** Root Relay connection: typed as `Query<Item[]>`, document uses `edges { node }`. */
274
- export const rootConnection = (op, field, meta, args, argTypes, errors = []) => make({
275
- _tag: "Root",
276
- op,
277
- field,
278
- args,
279
- argTypes,
280
- type: listRef(objectRef(meta)),
281
- connection: true,
282
- errors,
283
- });
284
- /** Root field whose GraphQL type is a scalar, enum, or list of those. */
285
- export const rootLeaf = (op, field, list, args, argTypes, errors = []) => make({
286
- _tag: "Root",
287
- op,
288
- field,
289
- args,
290
- argTypes,
291
- type: list ? listRef({ tag: "scalar" }) : { tag: "scalar" },
292
- errors,
293
- });
294
- const printExpr = (expr) => {
295
- switch (expr._tag) {
296
- case "Root":
297
- return expr.args ? `${expr.field}(${JSON.stringify(expr.args)})` : expr.field;
298
- case "Prop":
299
- return `${printExpr(expr.parent)}.${expr.field.name}`;
300
- case "Item":
301
- return "$item";
302
- case "MapValue":
303
- return `map(${printExpr(expr.parent)})`;
304
- case "MapItems":
305
- return `mapItems(${printExpr(expr.parent)})`;
306
- case "Filter":
307
- return `filter(${printExpr(expr.parent)})`;
308
- case "FlatMap":
309
- return `flatMap(${printExpr(expr.parent)})`;
310
- case "Literal":
311
- return `of(${String(expr.value)})`;
312
- }
313
- };
314
- const emptySel = (field) => ({
315
- field,
316
- alias: undefined,
317
- args: undefined,
318
- children: new Map(),
319
- isScalar: false,
320
- isList: false,
321
- });
322
- const stableStringify = (value) => {
323
- if (value === null || typeof value !== "object")
324
- return JSON.stringify(value);
325
- if (Array.isArray(value))
326
- return `[${value.map(stableStringify).join(",")}]`;
327
- const keys = Object.keys(value).sort();
328
- return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
329
- };
330
- const bindArgs = (forest, args, argTypes) => {
331
- if (args === undefined)
332
- return undefined;
333
- const bound = {};
334
- let hasArgs = false;
335
- for (const [name, value] of Object.entries(args)) {
336
- if (value === undefined)
337
- continue;
338
- forest.vars.set(`v${forest.varI}`, {
339
- type: argTypes?.[name] ?? "String",
340
- value,
341
- });
342
- bound[name] = `v${forest.varI++}`;
343
- hasArgs = true;
344
- }
345
- return hasArgs ? bound : undefined;
346
- };
347
- const ensureChild = (forest, parent, field, options) => {
348
- const key = options.args === undefined ? field : `${field}:${stableStringify(options.args)}`;
349
- const existing = parent.children.get(key);
350
- if (existing)
351
- return existing;
352
- const taken = new Set([...parent.children.values()].map((c) => c.alias ?? c.field));
353
- let alias;
354
- if (taken.has(field)) {
355
- do {
356
- alias = `${field}_${forest.aliasI++}`;
357
- } while (taken.has(alias));
358
- }
359
- const sel = {
360
- field,
361
- alias,
362
- args: bindArgs(forest, options.args, options.argTypes),
363
- children: new Map(),
364
- isScalar: options.isScalar ?? false,
365
- isList: options.isList ?? false,
366
- };
367
- parent.children.set(key, sel);
368
- return sel;
369
- };
370
- const paintConnection = (forest, connection) => {
371
- const edges = ensureChild(forest, connection, "edges", { isList: true });
372
- ensureChild(forest, edges, "node", {});
373
- return ["edges", "node"];
374
- };
375
- const paintAbs = (forest, expr) => {
376
- switch (expr._tag) {
377
- case "Root": {
378
- if (forest.kind !== undefined && forest.kind !== expr.op) {
379
- throw new GqlError(`cannot mix ${forest.kind} and ${expr.op} in one document`);
380
- }
381
- forest.kind = expr.op;
382
- const node = ensureChild(forest, forest.roots, expr.field, {
383
- args: expr.args,
384
- argTypes: expr.argTypes,
385
- // Leaf roots (`projectDelete: Boolean!`) take no sub-selection.
386
- isScalar: expr.type.tag === "scalar" || (expr.type.tag === "list" && expr.type.of.tag === "scalar"),
387
- isList: expr.type.tag === "list" && !expr.connection,
388
- });
389
- const key = node.alias ?? node.field;
390
- forest.rootAlias.set(expr, key);
391
- forest.rootErrors.set(key, { field: expr.field, errors: expr.errors });
392
- return expr.connection ? [key, ...paintConnection(forest, node)] : [key];
393
- }
394
- case "Prop": {
395
- const parentPath = paintAbs(forest, expr.parent);
396
- const parentSel = selAt(forest.roots, parentPath);
397
- const node = ensureChild(forest, parentSel, expr.field.name, {
398
- args: expr.args,
399
- argTypes: expr.field.argTypes,
400
- isScalar: expr.field.kind === "scalar",
401
- isList: expr.field.kind === "list",
402
- });
403
- const path = [...parentPath, node.alias ?? node.field];
404
- return expr.field.kind === "connection" ? [...path, ...paintConnection(forest, node)] : path;
405
- }
406
- default:
407
- throw new GqlError(`paintAbs: ${expr._tag}`);
408
- }
409
- };
410
- const selAt = (roots, path) => {
411
- let current = roots;
412
- for (const segment of path) {
413
- if (segment === "*")
414
- continue;
415
- const child = [...current.children.values()].find((candidate) => (candidate.alias ?? candidate.field) === segment);
416
- if (!child) {
417
- throw new GqlError(`internal: missing ${String(segment)}`);
418
- }
419
- current = child;
420
- }
421
- return current;
422
- };
423
- const connectionNodeSel = (connection) => {
424
- const edges = [...connection.children.values()].find((c) => c.field === "edges");
425
- const node = edges ? [...edges.children.values()].find((c) => c.field === "node") : undefined;
426
- if (!node)
427
- throw new GqlError("internal: connection missing edges.node");
428
- return node;
429
- };
430
- const relSel = (expr, listSel) => {
431
- switch (expr._tag) {
432
- case "Item":
433
- return listSel;
434
- case "Prop": {
435
- const parent = relSel(expr.parent, listSel);
436
- const child = [...parent.children.values()].find((c) => c.field === expr.field.name);
437
- if (!child) {
438
- throw new GqlError(`missing ${expr.field.name} in list selection`);
439
- }
440
- return expr.field.kind === "connection" ? connectionNodeSel(child) : child;
441
- }
442
- default:
443
- return listSel;
444
- }
445
- };
446
- const paintRel = (forest, expr, listSel) => {
447
- switch (expr._tag) {
448
- case "Item":
449
- case "Literal":
450
- return;
451
- case "Prop": {
452
- paintRel(forest, expr.parent, listSel);
453
- const child = ensureChild(forest, relSel(expr.parent, listSel), expr.field.name, {
454
- args: expr.args,
455
- argTypes: expr.field.argTypes,
456
- isScalar: expr.field.kind === "scalar",
457
- isList: expr.field.kind === "list",
458
- });
459
- if (expr.field.kind === "connection")
460
- paintConnection(forest, child);
461
- return;
462
- }
463
- case "MapValue":
464
- case "FlatMap":
465
- paintRel(forest, expr.parent, listSel);
466
- return;
467
- case "MapItems":
468
- paintRel(forest, expr.parent, listSel);
469
- visitRel(expr.mapped, forest, relSel(expr.parent, listSel));
470
- return;
471
- case "Filter":
472
- paintRel(forest, expr.parent, listSel);
473
- paintRel(forest, expr.predicate, relSel(expr.parent, listSel));
474
- return;
475
- case "Root":
476
- throw new GqlError("root inside list item");
477
- }
478
- };
479
- const visitExpr = (forest, expr) => {
480
- switch (expr._tag) {
481
- case "Root":
482
- case "Prop":
483
- paintAbs(forest, expr);
484
- return;
485
- case "Item":
486
- return;
487
- case "Literal":
488
- return;
489
- case "MapValue":
490
- case "FlatMap":
491
- visitExpr(forest, expr.parent);
492
- return;
493
- case "MapItems": {
494
- visitExpr(forest, expr.parent);
495
- const path = paintAbs(forest, graphqlBase(expr.parent));
496
- visitRel(expr.mapped, forest, selAt(forest.roots, path));
497
- return;
498
- }
499
- case "Filter": {
500
- visitExpr(forest, expr.parent);
501
- const path = paintAbs(forest, graphqlBase(expr.parent));
502
- paintRel(forest, expr.predicate, selAt(forest.roots, path));
503
- return;
504
- }
505
- }
506
- };
507
- const graphqlBase = (expr) => {
508
- switch (expr._tag) {
509
- case "Root":
510
- case "Prop":
511
- case "Item":
512
- return expr;
513
- case "MapValue":
514
- case "MapItems":
515
- case "Filter":
516
- case "FlatMap":
517
- return graphqlBase(expr.parent);
518
- case "Literal":
519
- throw new GqlError("literal has no graphql base");
520
- }
521
- };
522
- const visitRel = (plan, forest, listSel) => {
523
- if (isQuery(plan)) {
524
- paintRel(forest, plan.expr, listSel);
525
- return;
526
- }
527
- if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
528
- for (const nested of Object.values(plan)) {
529
- visitRel(nested, forest, listSel);
530
- }
531
- }
532
- };
533
- /**
534
- * Recurse through a builder return value. Query nodes contribute GraphQL
535
- * fields to `forest`; Effects are ignored until interpret (FlatMap).
536
- */
537
- const visitPlan = (plan, forest) => {
538
- if (isQuery(plan)) {
539
- log("visit", printExpr(plan.expr));
540
- visitExpr(forest, plan.expr);
541
- return;
542
- }
543
- if (Effect.isEffect(plan))
544
- return;
545
- if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
546
- for (const nested of Object.values(plan)) {
547
- visitPlan(nested, forest);
548
- }
549
- }
550
- };
551
- const validate = (node) => {
552
- for (const child of node.children.values()) {
553
- if (!child.isScalar && child.children.size === 0) {
554
- return `field "${child.field}" has no sub-selection`;
555
- }
556
- const inner = validate(child);
557
- if (inner)
558
- return inner;
559
- }
560
- return undefined;
561
- };
562
- const printChildren = (node, indent) => {
563
- const pad = " ".repeat(indent);
564
- const lines = [];
565
- for (const child of node.children.values()) {
566
- let head = child.alias ? `${child.alias}: ${child.field}` : child.field;
567
- if (child.args && Object.keys(child.args).length > 0) {
568
- const printed = Object.entries(child.args)
569
- .map(([argName, varName]) => `${argName}: $${varName}`)
570
- .join(", ");
571
- head += `(${printed})`;
572
- }
573
- if (child.isScalar)
574
- lines.push(`${pad}${head}`);
575
- else {
576
- lines.push(`${pad}${head} {`);
577
- lines.push(printChildren(child, indent + 1));
578
- lines.push(`${pad}}`);
579
- }
580
- }
581
- return lines.join("\n");
582
- };
583
- const emptyForest = () => ({
584
- kind: undefined,
585
- roots: emptySel(""),
586
- vars: new Map(),
587
- varI: 0,
588
- aliasI: 0,
589
- rootAlias: new WeakMap(),
590
- rootErrors: new Map(),
591
- });
592
- const emit = (forest) => {
593
- const err = validate(forest.roots);
594
- if (err)
595
- throw new GqlError(err);
596
- const kind = forest.kind ?? "query";
597
- const varDefs = [...forest.vars.entries()]
598
- .map(([name, binding]) => `$${name}: ${binding.type}`)
599
- .join(", ");
600
- const header = varDefs.length > 0 ? `${kind} Gql(${varDefs})` : `${kind} Gql`;
601
- const variables = {};
602
- for (const [name, binding] of forest.vars)
603
- variables[name] = binding.value;
604
- return {
605
- document: `${header} {\n${printChildren(forest.roots, 1)}\n}`,
606
- operationName: "Gql",
607
- variables,
608
- kind,
609
- tree: forest.roots,
610
- rootAlias: forest.rootAlias,
611
- rootErrors: forest.rootErrors,
612
- };
613
- };
614
- const nodesFromConnection = (value) => {
615
- if (value == null)
616
- return value;
617
- if (Array.isArray(value))
618
- return value.map(nodesFromConnection);
619
- const edges = value.edges;
620
- if (!Array.isArray(edges))
621
- return [];
622
- return edges.map((edge) => (edge == null ? edge : edge.node));
623
- };
624
- const readField = (parent, name) => {
625
- if (parent == null)
626
- return parent;
627
- if (Array.isArray(parent)) {
628
- return parent.map((item) => (item == null ? item : item[name]));
629
- }
630
- return parent[name];
631
- };
632
- const extractAbs = (expr, data, rootAlias) => {
633
- switch (expr._tag) {
634
- case "Root": {
635
- const raw = data[rootAlias.get(expr) ?? expr.field];
636
- return expr.connection ? nodesFromConnection(raw) : raw;
637
- }
638
- case "Prop": {
639
- const value = readField(extractAbs(expr.parent, data, rootAlias), expr.field.name);
640
- return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
641
- }
642
- default:
643
- throw new GqlError(`extractAbs: ${expr._tag}`);
644
- }
645
- };
646
- const extractRel = (expr, item) => {
647
- switch (expr._tag) {
648
- case "Item":
649
- return item;
650
- case "Prop": {
651
- const value = readField(extractRel(expr.parent, item), expr.field.name);
652
- return expr.field.kind === "connection" ? nodesFromConnection(value) : value;
653
- }
654
- default:
655
- throw new GqlError(`extractRel: ${expr._tag}`);
656
- }
657
- };
658
- const inItem = (expr) => {
659
- switch (expr._tag) {
660
- case "Item":
661
- return true;
662
- case "Prop":
663
- case "MapValue":
664
- case "MapItems":
665
- case "Filter":
666
- case "FlatMap":
667
- return inItem(expr.parent);
668
- default:
669
- return false;
670
- }
671
- };
672
- const interpretExpr = (expr, data, rootAlias, item) => {
673
- switch (expr._tag) {
674
- case "Literal":
675
- return expr.value;
676
- case "Item":
677
- return item;
678
- case "Root":
679
- case "Prop":
680
- return inItem(expr) ? extractRel(expr, item) : extractAbs(expr, data, rootAlias);
681
- case "MapValue":
682
- return expr.mapFn(interpretExpr(expr.parent, data, rootAlias, item));
683
- case "Filter": {
684
- const list = interpretExpr(expr.parent, data, rootAlias, item);
685
- const arr = Array.isArray(list) ? list : [];
686
- return arr.filter((row) => Boolean(interpretExpr(expr.predicate, data, rootAlias, row)));
687
- }
688
- case "MapItems": {
689
- const list = interpretExpr(expr.parent, data, rootAlias, item);
690
- if (expr.single) {
691
- return list == null ? null : interpretValueSync(expr.mapped, data, rootAlias, list);
692
- }
693
- const arr = Array.isArray(list) ? list : [];
694
- return arr.map((row) => interpretValueSync(expr.mapped, data, rootAlias, row));
695
- }
696
- case "FlatMap":
697
- throw new GqlError("FlatMap must be interpreted as Effect");
698
- }
699
- };
700
- const interpretValueSync = (plan, data, rootAlias, item) => {
701
- if (isQuery(plan)) {
702
- return interpretExpr(plan.expr, data, rootAlias, item);
703
- }
704
- if (plan !== null && typeof plan === "object" && !Effect.isEffect(plan)) {
705
- const out = {};
706
- for (const [key, nested] of Object.entries(plan)) {
707
- out[key] = interpretValueSync(nested, data, rootAlias, item);
708
- }
709
- return out;
710
- }
711
- return plan;
712
- };
713
- const interpretPlan = (plan, data, rootAlias) => Effect.gen(function* () {
714
- if (isQuery(plan)) {
715
- const expr = plan.expr;
716
- if (expr._tag === "FlatMap") {
717
- const resolved = interpretExpr(expr.parent, data, rootAlias, undefined);
718
- const next = expr.flatMapFn(resolved);
719
- if (Effect.isEffect(next))
720
- return yield* next;
721
- if (isQuery(next))
722
- return yield* interpretPlan(next, data, rootAlias);
723
- return next;
724
- }
725
- return interpretExpr(expr, data, rootAlias, undefined);
726
- }
727
- if (Effect.isEffect(plan))
728
- return yield* plan;
729
- if (plan !== null && typeof plan === "object" && !Array.isArray(plan)) {
730
- const out = {};
731
- for (const [key, nested] of Object.entries(plan)) {
732
- out[key] = yield* interpretPlan(nested, data, rootAlias);
733
- }
734
- return out;
735
- }
736
- return plan;
737
- });
738
- /**
739
- * Compile every Query in `plan` into one document, POST it, then replace
740
- * Query/Effect leaves with plain data (`UnwrapPlan`).
741
- */
742
- const evaluatePlan = (plan) => Effect.gen(function* () {
743
- const forest = emptyForest();
744
- visitPlan(plan, forest);
745
- let data = {};
746
- let rootAlias = new WeakMap();
747
- if (forest.roots.children.size > 0) {
748
- const compiled = emit(forest);
749
- log("document\n" + compiled.document);
750
- data = yield* execute(compiled);
751
- rootAlias = compiled.rootAlias;
752
- }
753
- return (yield* interpretPlan(plan, data, rootAlias));
754
- });
755
- /**
756
- * POST one compiled document and fail with its classified errors. Queries
757
- * are retried (bounded) while every failure is retryable; mutations never
758
- * are, since an error can follow a side effect that already happened.
759
- */
760
- const execute = (compiled) => {
761
- const once = Effect.gen(function* () {
762
- const transport = yield* GqlTransport;
763
- const response = yield* transport.execute(compiled);
764
- const raw = response.errors ?? [];
765
- if (raw.length === 0)
766
- return response.data;
767
- const issues = raw.map((error) => classify(compiled, error, response));
768
- const [first, ...rest] = issues;
769
- return yield* Effect.fail(rest.every((issue) => issue._tag === first._tag)
770
- ? first
771
- : new GraphQLFailure({
772
- errors: [first, ...rest],
773
- data: response.data,
774
- status: response.status,
775
- }));
776
- });
777
- return compiled.kind === "query"
778
- ? once.pipe(Effect.retry({
779
- while: (error) => isRetryable(compiled, error),
780
- times: 5,
781
- schedule: Schedule.exponential("200 millis"),
782
- }))
783
- : once;
784
- };
785
- const isRetryable = (compiled, error) => {
786
- if (error instanceof GraphQLTransportError) {
787
- return error.status === undefined || error.status === 429 || error.status >= 500;
788
- }
789
- const retryable = new Set([...compiled.rootErrors.values()].flatMap((root) => root.errors.filter((spec) => spec.retryable).map((spec) => spec.tag)));
790
- return error instanceof GraphQLFailure
791
- ? error.errors.every((issue) => retryable.has(issue._tag))
792
- : retryable.has(error._tag);
793
- };
794
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
795
- /**
796
- * Pick the most specific matcher among the errors the root at `path[0]`
797
- * declares (or the global errors for a path-less error). A tie between
798
- * different tags is ambiguous and stays {@link UnknownGraphQLError}.
799
- */
800
- const classify = (compiled, raw, response) => {
801
- const path = Array.isArray(raw.path) ? raw.path : undefined;
802
- const root = typeof path?.[0] === "string" ? compiled.rootErrors.get(path[0]) : undefined;
803
- const candidates = root
804
- ? root.errors
805
- : uniqueByTag([...compiled.rootErrors.values()].flatMap((entry) => entry.errors.filter((spec) => spec.global)));
806
- const extensions = isRecord(raw.extensions) ? raw.extensions : {};
807
- const code = typeof extensions.code === "string"
808
- ? extensions.code
809
- : typeof extensions.errorCode === "string"
810
- ? extensions.errorCode
811
- : undefined;
812
- const message = typeof raw.message === "string" ? raw.message : "";
813
- const retryHeader = response.headers?.["retry-after"];
814
- const props = {
815
- message,
816
- code,
817
- path,
818
- locations: raw.locations,
819
- extensions: raw.extensions,
820
- traceId: typeof extensions.traceId === "string"
821
- ? extensions.traceId
822
- : typeof raw.traceId === "string"
823
- ? raw.traceId
824
- : undefined,
825
- status: response.status,
826
- retryAfter: retryHeader && /^\d+(\.\d+)?$/.test(retryHeader) ? Number(retryHeader) : undefined,
827
- };
828
- const matches = candidates.flatMap((spec) => spec.matchers
829
- .filter((matcher) => (matcher.code === undefined || matcher.code === code) &&
830
- (matcher.message === undefined || matcher.message === message) &&
831
- (matcher.messageIncludes === undefined || message.includes(matcher.messageIncludes)))
832
- .map((matcher) => ({
833
- spec,
834
- score: (matcher.code ? 1 : 0) + (matcher.message ? 4 : 0) + (matcher.messageIncludes ? 2 : 0),
835
- })));
836
- matches.sort((a, b) => b.score - a.score);
837
- const best = matches[0];
838
- if (best &&
839
- !matches.some((match) => match.score === best.score && match.spec.tag !== best.spec.tag)) {
840
- return best.spec.make(props);
841
- }
842
- return new UnknownGraphQLError({
843
- ...props,
844
- coordinate: root?.field,
845
- });
846
- };
847
- const uniqueByTag = (specs) => [
848
- ...new Map(specs.map((spec) => [spec.tag, spec])).values(),
849
- ];
850
- /** `Query.of` / pure. */
851
- export const ofQuery = (value) => make({ _tag: "Literal", value, type: { tag: "scalar" } });
852
- const filterImpl = (source, predicate) => {
853
- const proto = itemQuery(source);
854
- const predicateQuery = predicate(proto);
855
- log("filter pred", printExpr(predicateQuery.expr));
856
- return make({
857
- _tag: "Filter",
858
- parent: source.expr,
859
- predicate: predicateQuery.expr,
860
- type: source.expr.type,
861
- });
862
- };
863
- export function filterQuery(sourceOrPredicate, predicate) {
864
- if (predicate === undefined) {
865
- return (source) => filterImpl(source, sourceOrPredicate);
866
- }
867
- return filterImpl(sourceOrPredicate, predicate);
868
- }
869
- const mapImpl = (source, mapFn) => {
870
- if (source.expr.type.tag === "object") {
871
- const mapped = mapFn(new QueryNode({
872
- _tag: "Item",
873
- list: source.expr,
874
- type: source.expr.type,
875
- }));
876
- log("map object", printExpr(source.expr));
877
- return make({
878
- _tag: "MapItems",
879
- parent: source.expr,
880
- mapped,
881
- single: true,
882
- type: { tag: "scalar" },
883
- });
884
- }
885
- if (source.expr.type.tag === "list") {
886
- const proto = itemQuery(source);
887
- const mapped = mapFn(proto);
888
- log("map items", printExpr(source.expr));
889
- return make({
890
- _tag: "MapItems",
891
- parent: source.expr,
892
- mapped,
893
- type: source.expr.type,
894
- });
895
- }
896
- log("map value", printExpr(source.expr));
897
- return make({
898
- _tag: "MapValue",
899
- parent: source.expr,
900
- mapFn,
901
- type: { tag: "scalar" },
902
- });
903
- };
904
- export function mapQuery(sourceOrMapFn, mapFn) {
905
- if (mapFn === undefined) {
906
- return (source) => mapImpl(source, sourceOrMapFn);
907
- }
908
- return mapImpl(sourceOrMapFn, mapFn);
909
- }
910
- const flatMapImpl = (source, flatMapFn) => {
911
- log("flatMap", printExpr(source.expr));
912
- return make({
913
- _tag: "FlatMap",
914
- parent: source.expr,
915
- flatMapFn,
916
- type: { tag: "scalar" },
917
- });
918
- };
919
- export function flatMapQuery(sourceOrFlatMapFn, flatMapFn) {
920
- if (flatMapFn === undefined) {
921
- return (source) => flatMapImpl(source, sourceOrFlatMapFn);
922
- }
923
- return flatMapImpl(sourceOrFlatMapFn, flatMapFn);
924
- }
925
- /**
926
- * Builder → Effect. The inner function is *not* a generator; it returns a
927
- * plan of Query/Effect values. Query.fn visits the plan, POSTs one document,
928
- * then interprets Map/Filter/FlatMap/Of.
929
- */
930
- export const queryFn = (build) => (...args) => {
931
- const plan = build(...args);
932
- return evaluatePlan(plan);
933
- };
934
- // ── Pagination ──────────────────────────────────────────────────────────────
935
- //
936
- // A connection lens hides `edges`/`pageInfo`. `Query.pages` re-evaluates the
937
- // query once per page: it sets the connection's `after` argument, paints
938
- // `pageInfo { hasNextPage endCursor }` next to `edges`, and stops when
939
- // `hasNextPage` is false.
940
- /** The connection a paged query reads, below any list-level Map/Filter. */
941
- const connectionOf = (expr) => {
942
- const base = graphqlBase(expr);
943
- const isConnection = (base._tag === "Root" && base.connection === true) ||
944
- (base._tag === "Prop" && base.field.kind === "connection");
945
- if (!isConnection || inItem(base)) {
946
- throw new GqlError(`Query.pages needs a Relay connection, got ${printExpr(base)}`);
947
- }
948
- const argTypes = base._tag === "Root" ? base.argTypes : base.field.argTypes;
949
- if (!argTypes || !("after" in argTypes)) {
950
- throw new GqlError(`${printExpr(base)} takes no "after" cursor`);
951
- }
952
- return base;
953
- };
954
- /** Rebuild `expr` with the connection's `after` argument set. */
955
- const withCursor = (expr, connection, after) => {
956
- if (expr === connection) {
957
- const current = expr;
958
- return { ...current, args: { ...current.args, after } };
959
- }
960
- switch (expr._tag) {
961
- case "MapItems":
962
- case "Filter":
963
- case "MapValue":
964
- case "FlatMap":
965
- return { ...expr, parent: withCursor(expr.parent, connection, after) };
966
- default:
967
- throw new GqlError(`withCursor: ${expr._tag}`);
968
- }
969
- };
970
- const readPath = (data, path) => {
971
- let current = data;
972
- for (const segment of path) {
973
- if (current == null)
974
- return undefined;
975
- if (Array.isArray(current)) {
976
- throw new GqlError("Query.pages cannot page a connection inside a list");
977
- }
978
- current = current[segment];
979
- }
980
- return current;
981
- };
982
- const fetchPage = (query, connection, state) => Effect.gen(function* () {
983
- const pageExpr = withCursor(query.expr, connection, state.after);
984
- const forest = emptyForest();
985
- visitExpr(forest, pageExpr);
986
- const nodePath = paintAbs(forest, withCursor(connection, connection, state.after));
987
- const connectionPath = nodePath.slice(0, -2);
988
- const pageInfo = ensureChild(forest, selAt(forest.roots, connectionPath), "pageInfo", {});
989
- ensureChild(forest, pageInfo, "hasNextPage", { isScalar: true });
990
- ensureChild(forest, pageInfo, "endCursor", { isScalar: true });
991
- const compiled = emit(forest);
992
- log("page\n" + compiled.document);
993
- const data = yield* execute(compiled);
994
- const items = (yield* interpretPlan(make(pageExpr), data, compiled.rootAlias));
995
- const info = readPath(data, [...connectionPath, "pageInfo"]);
996
- const cursor = info?.endCursor ?? null;
997
- if (info?.hasNextPage !== true) {
998
- return [items ?? [], Option.none()];
999
- }
1000
- if (cursor === null || cursor === state.after || state.seen.has(cursor)) {
1001
- return yield* new GraphQLPaginationError({
1002
- message: `${printExpr(connection)} returned a non-advancing cursor`,
1003
- cursor,
1004
- });
1005
- }
1006
- return [
1007
- items ?? [],
1008
- Option.some({ after: cursor, seen: new Set([...state.seen, cursor]) }),
1009
- ];
1010
- });
1011
- /**
1012
- * Every page of a Relay connection, one request per page. `query` is a
1013
- * connection lens (root or nested under objects), optionally mapped or
1014
- * filtered: `Query.pages(Railway.project({ id }).services({ first: 50 }))`.
1015
- * Starts from the query's own `after` argument, if any.
1016
- */
1017
- export const pagesQuery = (query) => Stream.unwrap(Effect.sync(() => {
1018
- const connection = connectionOf(query.expr);
1019
- const after = connection.args?.after;
1020
- return Stream.paginate({
1021
- after: typeof after === "string" ? after : undefined,
1022
- seen: new Set(),
1023
- }, (state) => fetchPage(query, connection, state).pipe(Effect.map(([items, next]) => [[items], next])));
1024
- }));
1025
- /** Every node of a Relay connection, across all pages. */
1026
- export const itemsQuery = (query) => pagesQuery(query).pipe(Stream.flatMap(Stream.fromIterable));
1027
- //# sourceMappingURL=graphql.js.map
1
+ export { graphql$GqlError as GqlError, graphql$GqlTransport as GqlTransport, graphql$GraphQLFailure as GraphQLFailure, graphql$GraphQLPaginationError as GraphQLPaginationError, graphql$GraphQLTransportError as GraphQLTransportError, graphql$QueryNode as QueryNode, graphql$QuerySymbol as QuerySymbol, graphql$UnknownGraphQLError as UnknownGraphQLError, graphql$connectionField as connectionField, graphql$errorFields as errorFields, graphql$errorSpec as errorSpec, graphql$filterQuery as filterQuery, graphql$flatMapQuery as flatMapQuery, graphql$isQuery as isQuery, graphql$itemsQuery as itemsQuery, graphql$listField as listField, graphql$mapQuery as mapQuery, graphql$objectField as objectField, graphql$ofQuery as ofQuery, graphql$pagesQuery as pagesQuery, graphql$queryFn as queryFn, graphql$root as root, graphql$rootConnection as rootConnection, graphql$rootLeaf as rootLeaf, graphql$rootList as rootList, graphql$scalarField as scalarField } from "./_bundle/graphql.js";