@distilled.cloud/core 1.0.0-rc.12 → 1.0.0-rc.14

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 (276) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts +8 -8
  9. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  10. package/lib/codegen/boolean-string-enums.js +83 -30
  11. package/lib/codegen/boolean-string-enums.js.map +1 -1
  12. package/lib/codegen/boolean-string-enums.test.js +130 -2
  13. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  14. package/lib/codegen/cli.d.ts +5 -4
  15. package/lib/codegen/cli.d.ts.map +1 -1
  16. package/lib/codegen/cli.js +12 -9
  17. package/lib/codegen/cli.js.map +1 -1
  18. package/lib/codegen/defer-naming.test.d.ts +2 -0
  19. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  20. package/lib/codegen/defer-naming.test.js +105 -0
  21. package/lib/codegen/defer-naming.test.js.map +1 -0
  22. package/lib/codegen/emit.d.ts.map +1 -1
  23. package/lib/codegen/emit.js +1 -3
  24. package/lib/codegen/emit.js.map +1 -1
  25. package/lib/codegen/format.d.ts +0 -12
  26. package/lib/codegen/format.d.ts.map +1 -1
  27. package/lib/codegen/format.js +10 -6
  28. package/lib/codegen/format.js.map +1 -1
  29. package/lib/codegen/generated-at.d.ts +29 -0
  30. package/lib/codegen/generated-at.d.ts.map +1 -0
  31. package/lib/codegen/generated-at.js +78 -0
  32. package/lib/codegen/generated-at.js.map +1 -0
  33. package/lib/codegen/generated-at.test.d.ts +2 -0
  34. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  35. package/lib/codegen/generated-at.test.js +81 -0
  36. package/lib/codegen/generated-at.test.js.map +1 -0
  37. package/lib/codegen/generator.d.ts +24 -5
  38. package/lib/codegen/generator.d.ts.map +1 -1
  39. package/lib/codegen/generator.js +69 -80
  40. package/lib/codegen/generator.js.map +1 -1
  41. package/lib/codegen/generator.test.d.ts +2 -0
  42. package/lib/codegen/generator.test.d.ts.map +1 -0
  43. package/lib/codegen/generator.test.js +121 -0
  44. package/lib/codegen/generator.test.js.map +1 -0
  45. package/lib/codegen/graphql-client.d.ts +7 -1
  46. package/lib/codegen/graphql-client.d.ts.map +1 -1
  47. package/lib/codegen/graphql-client.js +264 -148
  48. package/lib/codegen/graphql-client.js.map +1 -1
  49. package/lib/codegen/graphql-client.test.js +98 -238
  50. package/lib/codegen/graphql-client.test.js.map +1 -1
  51. package/lib/codegen/graphql.d.ts.map +1 -1
  52. package/lib/codegen/graphql.js +7 -20
  53. package/lib/codegen/graphql.js.map +1 -1
  54. package/lib/codegen/model-diff.d.ts +10 -0
  55. package/lib/codegen/model-diff.d.ts.map +1 -0
  56. package/lib/codegen/model-diff.js +67 -0
  57. package/lib/codegen/model-diff.js.map +1 -0
  58. package/lib/codegen/naming.d.ts.map +1 -1
  59. package/lib/codegen/naming.js.map +1 -1
  60. package/lib/codegen/openapi-binary.test.d.ts +2 -0
  61. package/lib/codegen/openapi-binary.test.d.ts.map +1 -0
  62. package/lib/codegen/openapi-binary.test.js +67 -0
  63. package/lib/codegen/openapi-binary.test.js.map +1 -0
  64. package/lib/codegen/openapi-cli.d.ts +11 -11
  65. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  66. package/lib/codegen/openapi-cli.js +26 -51
  67. package/lib/codegen/openapi-cli.js.map +1 -1
  68. package/lib/codegen/openapi.d.ts +16 -2
  69. package/lib/codegen/openapi.d.ts.map +1 -1
  70. package/lib/codegen/openapi.js +56 -39
  71. package/lib/codegen/openapi.js.map +1 -1
  72. package/lib/codegen/operations.d.ts.map +1 -1
  73. package/lib/codegen/operations.js.map +1 -1
  74. package/lib/codegen/pagination.d.ts.map +1 -1
  75. package/lib/codegen/pagination.js +2 -4
  76. package/lib/codegen/pagination.js.map +1 -1
  77. package/lib/codegen/patch-audit.d.ts +84 -0
  78. package/lib/codegen/patch-audit.d.ts.map +1 -0
  79. package/lib/codegen/patch-audit.js +366 -0
  80. package/lib/codegen/patch-audit.js.map +1 -0
  81. package/lib/codegen/patch-audit.test.d.ts +2 -0
  82. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  83. package/lib/codegen/patch-audit.test.js +141 -0
  84. package/lib/codegen/patch-audit.test.js.map +1 -0
  85. package/lib/codegen/patches.d.ts +75 -11
  86. package/lib/codegen/patches.d.ts.map +1 -1
  87. package/lib/codegen/patches.js +301 -65
  88. package/lib/codegen/patches.js.map +1 -1
  89. package/lib/codegen/patches.test.js +55 -5
  90. package/lib/codegen/patches.test.js.map +1 -1
  91. package/lib/codegen/prelude.js +1 -1
  92. package/lib/codegen/prelude.js.map +1 -1
  93. package/lib/codegen/proto.d.ts.map +1 -1
  94. package/lib/codegen/proto.js +2 -4
  95. package/lib/codegen/proto.js.map +1 -1
  96. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  97. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  98. package/lib/codegen/protocol-imports.test.js +36 -0
  99. package/lib/codegen/protocol-imports.test.js.map +1 -0
  100. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  101. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  102. package/lib/codegen/rewrite-operation-ids.js +97 -59
  103. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  104. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  105. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  106. package/lib/codegen/spec-path.d.ts +1 -1
  107. package/lib/codegen/spec-path.d.ts.map +1 -1
  108. package/lib/codegen/spec-path.js +1 -1
  109. package/lib/codegen/spec-path.js.map +1 -1
  110. package/lib/codegen/untagged-unions.test.d.ts +2 -0
  111. package/lib/codegen/untagged-unions.test.d.ts.map +1 -0
  112. package/lib/codegen/untagged-unions.test.js +80 -0
  113. package/lib/codegen/untagged-unions.test.js.map +1 -0
  114. package/lib/error-category.d.ts.map +1 -1
  115. package/lib/error-category.js.map +1 -1
  116. package/lib/errors.d.ts +2 -1
  117. package/lib/errors.d.ts.map +1 -1
  118. package/lib/errors.js +9 -4
  119. package/lib/errors.js.map +1 -1
  120. package/lib/fixtures/xml/upstream-validator.json +397 -0
  121. package/lib/graphql.d.ts +292 -205
  122. package/lib/graphql.d.ts.map +1 -1
  123. package/lib/graphql.js +945 -636
  124. package/lib/graphql.js.map +1 -1
  125. package/lib/graphql.test.js +135 -764
  126. package/lib/graphql.test.js.map +1 -1
  127. package/lib/graphql.types.d.ts +10 -0
  128. package/lib/graphql.types.d.ts.map +1 -1
  129. package/lib/graphql.types.js +4 -44
  130. package/lib/graphql.types.js.map +1 -1
  131. package/lib/index.d.ts +27 -0
  132. package/lib/index.d.ts.map +1 -0
  133. package/lib/index.js +27 -0
  134. package/lib/index.js.map +1 -0
  135. package/lib/json-patch.d.ts +13 -6
  136. package/lib/json-patch.d.ts.map +1 -1
  137. package/lib/json-patch.js +34 -19
  138. package/lib/json-patch.js.map +1 -1
  139. package/lib/json-patch.test.d.ts +2 -0
  140. package/lib/json-patch.test.d.ts.map +1 -0
  141. package/lib/json-patch.test.js +65 -0
  142. package/lib/json-patch.test.js.map +1 -0
  143. package/lib/pagination.d.ts +2 -1
  144. package/lib/pagination.d.ts.map +1 -1
  145. package/lib/pagination.js +28 -30
  146. package/lib/pagination.js.map +1 -1
  147. package/lib/pagination.test.d.ts +2 -0
  148. package/lib/pagination.test.d.ts.map +1 -0
  149. package/lib/pagination.test.js +131 -0
  150. package/lib/pagination.test.js.map +1 -0
  151. package/lib/protocol-http.d.ts +30 -16
  152. package/lib/protocol-http.d.ts.map +1 -1
  153. package/lib/protocol-http.js +133 -84
  154. package/lib/protocol-http.js.map +1 -1
  155. package/lib/protocol-http.test.js +141 -1
  156. package/lib/protocol-http.test.js.map +1 -1
  157. package/lib/protocol-rest.d.ts +18 -1
  158. package/lib/protocol-rest.d.ts.map +1 -1
  159. package/lib/protocol-rest.js +32 -21
  160. package/lib/protocol-rest.js.map +1 -1
  161. package/lib/protocol-rest.test.d.ts +2 -0
  162. package/lib/protocol-rest.test.d.ts.map +1 -0
  163. package/lib/protocol-rest.test.js +498 -0
  164. package/lib/protocol-rest.test.js.map +1 -0
  165. package/lib/query.d.ts +29 -0
  166. package/lib/query.d.ts.map +1 -0
  167. package/lib/query.js +27 -0
  168. package/lib/query.js.map +1 -0
  169. package/lib/response-validation.d.ts +67 -0
  170. package/lib/response-validation.d.ts.map +1 -0
  171. package/lib/response-validation.js +76 -0
  172. package/lib/response-validation.js.map +1 -0
  173. package/lib/response-validation.test.d.ts +2 -0
  174. package/lib/response-validation.test.d.ts.map +1 -0
  175. package/lib/response-validation.test.js +72 -0
  176. package/lib/response-validation.test.js.map +1 -0
  177. package/lib/retry-after.d.ts.map +1 -1
  178. package/lib/retry-after.js +1 -1
  179. package/lib/retry-after.js.map +1 -1
  180. package/lib/retry-after.test.d.ts +2 -0
  181. package/lib/retry-after.test.d.ts.map +1 -0
  182. package/lib/retry-after.test.js +204 -0
  183. package/lib/retry-after.test.js.map +1 -0
  184. package/lib/retry.d.ts.map +1 -1
  185. package/lib/retry.js +1 -2
  186. package/lib/retry.js.map +1 -1
  187. package/lib/retry.test.d.ts +2 -0
  188. package/lib/retry.test.d.ts.map +1 -0
  189. package/lib/retry.test.js +407 -0
  190. package/lib/retry.test.js.map +1 -0
  191. package/lib/sdks.test.d.ts +2 -0
  192. package/lib/sdks.test.d.ts.map +1 -0
  193. package/lib/sdks.test.js +76 -0
  194. package/lib/sdks.test.js.map +1 -0
  195. package/lib/testing.d.ts +39 -0
  196. package/lib/testing.d.ts.map +1 -0
  197. package/lib/testing.js +41 -0
  198. package/lib/testing.js.map +1 -0
  199. package/lib/trait.d.ts +29 -9
  200. package/lib/trait.d.ts.map +1 -1
  201. package/lib/trait.js +8 -0
  202. package/lib/trait.js.map +1 -1
  203. package/lib/xml.d.ts +44 -0
  204. package/lib/xml.d.ts.map +1 -0
  205. package/lib/xml.js +311 -0
  206. package/lib/xml.js.map +1 -0
  207. package/lib/xml.test.d.ts +2 -0
  208. package/lib/xml.test.d.ts.map +1 -0
  209. package/lib/xml.test.js +210 -0
  210. package/lib/xml.test.js.map +1 -0
  211. package/package.json +8 -11
  212. package/src/api.ts +38 -55
  213. package/src/category.ts +21 -50
  214. package/src/codegen/boolean-string-enums.test.ts +148 -17
  215. package/src/codegen/boolean-string-enums.ts +81 -32
  216. package/src/codegen/cli.ts +29 -47
  217. package/src/codegen/defer-naming.test.ts +113 -0
  218. package/src/codegen/emit.ts +2 -5
  219. package/src/codegen/format.ts +12 -10
  220. package/src/codegen/generated-at.test.ts +89 -0
  221. package/src/codegen/generated-at.ts +88 -0
  222. package/src/codegen/generator.test.ts +137 -0
  223. package/src/codegen/generator.ts +132 -193
  224. package/src/codegen/graphql-client.test.ts +100 -297
  225. package/src/codegen/graphql-client.ts +302 -210
  226. package/src/codegen/graphql.ts +22 -94
  227. package/src/codegen/model-diff.ts +67 -0
  228. package/src/codegen/naming.ts +1 -2
  229. package/src/codegen/openapi-binary.test.ts +91 -0
  230. package/src/codegen/openapi-cli.ts +38 -79
  231. package/src/codegen/openapi.ts +98 -133
  232. package/src/codegen/operations.ts +2 -5
  233. package/src/codegen/pagination.ts +4 -11
  234. package/src/codegen/patch-audit.test.ts +160 -0
  235. package/src/codegen/patch-audit.ts +480 -0
  236. package/src/codegen/patches.test.ts +73 -15
  237. package/src/codegen/patches.ts +389 -99
  238. package/src/codegen/prelude.ts +1 -1
  239. package/src/codegen/proto.ts +18 -54
  240. package/src/codegen/protocol-imports.test.ts +39 -0
  241. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  242. package/src/codegen/rewrite-operation-ids.ts +111 -98
  243. package/src/codegen/spec-path.ts +3 -6
  244. package/src/codegen/untagged-unions.test.ts +85 -0
  245. package/src/error-category.ts +5 -17
  246. package/src/errors.ts +18 -30
  247. package/src/fixtures/xml/upstream-validator.json +397 -0
  248. package/src/graphql.test.ts +173 -949
  249. package/src/graphql.ts +1468 -1186
  250. package/src/graphql.types.ts +78 -164
  251. package/src/index.ts +26 -0
  252. package/src/json-patch.test.ts +77 -0
  253. package/src/json-patch.ts +54 -60
  254. package/src/pagination.test.ts +169 -0
  255. package/src/pagination.ts +46 -103
  256. package/src/protocol-http.test.ts +178 -9
  257. package/src/protocol-http.ts +174 -163
  258. package/src/protocol-rest.test.ts +703 -0
  259. package/src/protocol-rest.ts +76 -65
  260. package/src/query.ts +39 -0
  261. package/src/response-validation.test.ts +89 -0
  262. package/src/response-validation.ts +107 -0
  263. package/src/retry-after.test.ts +267 -0
  264. package/src/retry-after.ts +4 -10
  265. package/src/retry.test.ts +566 -0
  266. package/src/retry.ts +6 -21
  267. package/src/sdks.test.ts +87 -0
  268. package/src/testing.ts +72 -0
  269. package/src/trait.ts +48 -63
  270. package/src/xml.test.ts +251 -0
  271. package/src/xml.ts +323 -0
  272. package/lib/graphql.fixture.d.ts +0 -249
  273. package/lib/graphql.fixture.d.ts.map +0 -1
  274. package/lib/graphql.fixture.js +0 -240
  275. package/lib/graphql.fixture.js.map +0 -1
  276. package/src/graphql.fixture.ts +0 -371
@@ -46,8 +46,7 @@ export interface GraphQLModel {
46
46
 
47
47
  export const graphqlTypeString = (ref: TypeRef): string => {
48
48
  if (ref.kind === "NON_NULL" || ref.kind === "LIST") {
49
- if (!ref.ofType)
50
- throw new Error(`Incomplete GraphQL ${ref.kind} reference`);
49
+ if (!ref.ofType) throw new Error(`Incomplete GraphQL ${ref.kind} reference`);
51
50
  const inner = graphqlTypeString(ref.ofType);
52
51
  return ref.kind === "NON_NULL" ? `${inner}!` : `[${inner}]`;
53
52
  }
@@ -79,9 +78,7 @@ export const convertGraphQLClient = (
79
78
  ...(value.defaultValue != null ? { defaultValue: value.defaultValue } : {}),
80
79
  });
81
80
  const types: Record<string, GraphQLType> = {};
82
- for (const type of [...schema.types].sort((a, b) =>
83
- a.name.localeCompare(b.name),
84
- )) {
81
+ for (const type of [...schema.types].sort((a, b) => a.name.localeCompare(b.name))) {
85
82
  if (type.name.startsWith("__")) continue;
86
83
  types[type.name] = {
87
84
  kind: type.kind,
@@ -98,13 +95,9 @@ export const convertGraphQLClient = (
98
95
  field.name,
99
96
  {
100
97
  type: graphqlTypeString(field.type),
101
- args: Object.fromEntries(
102
- field.args.map((arg) => [arg.name, argument(arg)]),
103
- ),
98
+ args: Object.fromEntries(field.args.map((arg) => [arg.name, argument(arg)])),
104
99
  errors: [],
105
- ...(field.description
106
- ? { description: field.description }
107
- : {}),
100
+ ...(field.description ? { description: field.description } : {}),
108
101
  ...(field.isDeprecated
109
102
  ? {
110
103
  deprecated:
@@ -127,17 +120,11 @@ export const convertGraphQLClient = (
127
120
  ),
128
121
  }
129
122
  : {}),
130
- ...(type.enumValues
131
- ? { enumValues: type.enumValues.map((value) => value.name) }
132
- : {}),
133
- ...(type.possibleTypes
134
- ? { possibleTypes: type.possibleTypes.map((ref) => ref.name!) }
135
- : {}),
123
+ ...(type.enumValues ? { enumValues: type.enumValues.map((value) => value.name) } : {}),
124
+ ...(type.possibleTypes ? { possibleTypes: type.possibleTypes.map((ref) => ref.name!) } : {}),
136
125
  ...("interfaces" in type && Array.isArray(type.interfaces)
137
126
  ? {
138
- interfaces: type.interfaces.map(
139
- (ref: { name: string }) => ref.name,
140
- ),
127
+ interfaces: type.interfaces.map((ref: { name: string }) => ref.name),
141
128
  }
142
129
  : {}),
143
130
  };
@@ -146,9 +133,7 @@ export const convertGraphQLClient = (
146
133
  version: 1,
147
134
  queryType: schema.queryType.name,
148
135
  ...(schema.mutationType ? { mutationType: schema.mutationType.name } : {}),
149
- ...(schema.subscriptionType
150
- ? { subscriptionType: schema.subscriptionType.name }
151
- : {}),
136
+ ...(schema.subscriptionType ? { subscriptionType: schema.subscriptionType.name } : {}),
152
137
  types,
153
138
  errors: {},
154
139
  globalErrors: [],
@@ -158,21 +143,14 @@ export const convertGraphQLClient = (
158
143
  /** Reject dangling schema/error references after patches, before generating code. */
159
144
  export const validateGraphQLModel = (model: GraphQLModel): void => {
160
145
  const checkType = (ref: string, coordinate: string) => {
161
- const name = ref.replace(/[\[\]!]/g, "");
162
- if (!model.types[name])
163
- throw new Error(`${coordinate}: unknown GraphQL type ${name}`);
146
+ const name = ref.replace(/[[\]!]/g, "");
147
+ if (!model.types[name]) throw new Error(`${coordinate}: unknown GraphQL type ${name}`);
164
148
  };
165
149
  const checkError = (error: string, coordinate: string) => {
166
- if (!model.errors[error])
167
- throw new Error(`${coordinate}: unknown GraphQL error ${error}`);
150
+ if (!model.errors[error]) throw new Error(`${coordinate}: unknown GraphQL error ${error}`);
168
151
  };
169
- for (const name of [
170
- model.queryType,
171
- model.mutationType,
172
- model.subscriptionType,
173
- ]) {
174
- if (name && !model.types[name])
175
- throw new Error(`Unknown GraphQL root ${name}`);
152
+ for (const name of [model.queryType, model.mutationType, model.subscriptionType]) {
153
+ if (name && !model.types[name]) throw new Error(`Unknown GraphQL root ${name}`);
176
154
  }
177
155
  for (const error of model.globalErrors) checkError(error, "globalErrors");
178
156
  for (const [name, type] of Object.entries(model.types)) {
@@ -185,17 +163,13 @@ export const validateGraphQLModel = (model: GraphQLModel): void => {
185
163
  }
186
164
  for (const [fieldName, field] of Object.entries(type.inputFields ?? {}))
187
165
  checkType(field.type, `${name}.${fieldName}`);
188
- for (const member of [
189
- ...(type.possibleTypes ?? []),
190
- ...(type.interfaces ?? []),
191
- ])
166
+ for (const member of [...(type.possibleTypes ?? []), ...(type.interfaces ?? [])])
192
167
  checkType(member, name);
193
168
  }
194
169
  };
195
170
 
196
171
  const literal = (value: unknown): string => JSON.stringify(value);
197
- const union = (values: readonly string[]): string =>
198
- values.length ? values.join(" | ") : "never";
172
+ const union = (values: readonly string[]): string => (values.length ? values.join(" | ") : "never");
199
173
  const documentation = (description?: string): string =>
200
174
  description ? `/** ${description.replaceAll("*/", "* /")} */\n` : "";
201
175
 
@@ -206,114 +180,219 @@ export interface GenerateGraphQLClientOptions {
206
180
  readonly requirementsImport: string;
207
181
  /** Optional legacy-name aliases, e.g. createProject -> projectCreate. */
208
182
  readonly operationAliases?: Readonly<Record<string, string>>;
183
+ /** Export name for the root object (`Railway`, `Eas`, …). Default `"Sdk"`. */
184
+ readonly sdkName?: string;
209
185
  }
210
186
 
211
- /** Emit schema-indexed types and the matching runtime graph from one patched model. */
187
+ const peelRef = (ref: string): { name: string; list: boolean; nonNull: boolean } => {
188
+ let text = ref;
189
+ let nonNull = false;
190
+ let list = false;
191
+ if (text.endsWith("!")) {
192
+ nonNull = true;
193
+ text = text.slice(0, -1);
194
+ }
195
+ if (text.startsWith("[") && text.endsWith("]")) {
196
+ list = true;
197
+ text = text.slice(1, -1);
198
+ if (text.endsWith("!")) text = text.slice(0, -1);
199
+ }
200
+ return { name: text, list, nonNull };
201
+ };
202
+
203
+ /**
204
+ * Emit a Query-algebra SDK: TypeMeta + TS types + named roots
205
+ * (`me`, `project`, …). Combinators stay in `@distilled.cloud/core/query`;
206
+ * this file only describes the schema as lazy lenses.
207
+ */
212
208
  export const generateGraphQLClient = (
213
209
  model: GraphQLModel,
214
210
  options: GenerateGraphQLClientOptions,
215
211
  ): string => {
216
212
  validateGraphQLModel(model);
217
- const inputType = (ref: string): string => {
218
- if (ref.endsWith("!")) return requiredInput(ref.slice(0, -1));
219
- return `${requiredInput(ref)} | null`;
213
+ const sdkName = options.sdkName ?? "Sdk";
214
+ const skipRoots = new Set(
215
+ [model.queryType, model.mutationType, model.subscriptionType].filter(
216
+ (name): name is string => typeof name === "string",
217
+ ),
218
+ );
219
+ const tsNamed = (name: string): string => {
220
+ const type = model.types[name];
221
+ if (!type) return "unknown";
222
+ if (type.kind === "SCALAR") return type.scalar ?? "unknown";
223
+ if (type.kind === "ENUM")
224
+ return (type.enumValues ?? []).map((value) => JSON.stringify(value)).join(" | ") || "string";
225
+ if (type.kind === "UNION")
226
+ return (type.possibleTypes ?? []).filter(Boolean).join(" | ") || "unknown";
227
+ return name;
220
228
  };
221
- const requiredInput = (ref: string): string => {
222
- if (ref.startsWith("["))
223
- return `ReadonlyArray<${inputType(ref.slice(1, -1))}>`;
224
- const type = model.types[ref]!;
225
- return type.kind === "INPUT_OBJECT"
226
- ? `Inputs[${literal(ref)}]`
227
- : `Scalars[${literal(ref)}]`;
229
+ /** Relay `edges { node }` → node type name, else undefined. */
230
+ const connectionNode = (typeName: string): string | undefined => {
231
+ const type = model.types[typeName];
232
+ const edges = type?.fields?.edges;
233
+ if (!edges) return undefined;
234
+ const edgeRef = peelRef(edges.type);
235
+ if (!edgeRef.list) return undefined;
236
+ const node = model.types[edgeRef.name]?.fields?.node;
237
+ if (!node) return undefined;
238
+ const nodeName = peelRef(node.type).name;
239
+ const kind = model.types[nodeName]?.kind;
240
+ if (kind !== "OBJECT" && kind !== "INTERFACE" && kind !== "UNION") {
241
+ return undefined;
242
+ }
243
+ return nodeName;
228
244
  };
229
- const argsType = (args: Record<string, GraphQLArgument>): string =>
230
- `{ ${Object.entries(args)
231
- .map(
232
- ([name, arg]) =>
233
- `${literal(name)}${arg.type.endsWith("!") && arg.defaultValue === undefined ? "" : "?"}: ${inputType(arg.type)}`,
234
- )
235
- .join("; ")} }`;
236
- // GraphQL names are not necessarily valid or unoccupied TypeScript symbols.
237
- // Schema names remain quoted map keys; exported values get stable safe names.
238
- const occupied = new Set([
239
- ..."await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval abstract any as asserts async bigint boolean constructor declare from get global infer intrinsic is keyof module namespace never number object of override readonly require satisfies set string symbol type undefined unique unknown using".split(
240
- " ",
241
- ),
242
- "G",
243
- "S",
244
- "Category",
245
- "Scalars",
246
- "Inputs",
247
- "Errors",
248
- "Types",
249
- "PossibleTypes",
250
- "Schema",
251
- "Selection",
252
- "Result",
253
- "SelectedErrors",
254
- "GraphQLIssue",
255
- "Report",
256
- "catchTags",
257
- "isErrorTag",
258
- "GraphQLFailure",
259
- "GraphQLTransportError",
260
- "GraphQLDecodeError",
261
- "GraphQLRequestError",
262
- "UnknownGraphQLError",
263
- "query",
264
- "mutation",
265
- "report",
266
- "client",
267
- "schema",
268
- "errorClasses",
269
- options.transportName ?? "transport",
270
- options.requirementsType,
245
+ /** Input type: nullable GraphQL inputs (no `!`) accept `null`. */
246
+ const tsArg = (ref: string): string => {
247
+ const nonNull = ref.endsWith("!");
248
+ const inner = nonNull ? ref.slice(0, -1) : ref;
249
+ const ts =
250
+ inner.startsWith("[") && inner.endsWith("]")
251
+ ? `ReadonlyArray<${tsArg(inner.slice(1, -1))}>`
252
+ : tsNamed(inner);
253
+ return nonNull ? ts : `${ts} | null`;
254
+ };
255
+ /** Response type: nullable GraphQL types (no `!`) include `null`. */
256
+ const tsOutput = (ref: string): string => {
257
+ const nonNull = ref.endsWith("!");
258
+ const inner = nonNull ? ref.slice(0, -1) : ref;
259
+ let ts: string;
260
+ if (inner.startsWith("[") && inner.endsWith("]")) {
261
+ ts = `ReadonlyArray<${tsOutput(inner.slice(1, -1))}>`;
262
+ } else {
263
+ const node = connectionNode(inner);
264
+ ts = node ? `ReadonlyArray<${tsNamed(node)}>` : tsNamed(inner);
265
+ }
266
+ return nonNull ? ts : `${ts} | null`;
267
+ };
268
+ const isObjectLike = (name: string): boolean => {
269
+ const kind = model.types[name]?.kind;
270
+ return kind === "OBJECT" || kind === "INTERFACE";
271
+ };
272
+ const fieldMeta = (fieldName: string, field: GraphQLField): string => {
273
+ const { name, list } = peelRef(field.type);
274
+ const argTypes = Object.keys(field.args).length
275
+ ? `{ ${Object.entries(field.args)
276
+ .map(([argName, arg]) => `${argName}: ${JSON.stringify(arg.type)}`)
277
+ .join(", ")} }`
278
+ : undefined;
279
+ const node = !list ? connectionNode(name) : undefined;
280
+ if (node) {
281
+ return argTypes
282
+ ? `connectionField(${JSON.stringify(fieldName)}, ${node}, ${argTypes})`
283
+ : `connectionField(${JSON.stringify(fieldName)}, ${node})`;
284
+ }
285
+ if (list && isObjectLike(name)) {
286
+ return argTypes
287
+ ? `listField(${JSON.stringify(fieldName)}, ${name}, ${argTypes})`
288
+ : `listField(${JSON.stringify(fieldName)}, ${name})`;
289
+ }
290
+ if (isObjectLike(name) || model.types[name]?.kind === "UNION") {
291
+ return `objectField(${JSON.stringify(fieldName)}, ${name})`;
292
+ }
293
+ return `scalarField(${JSON.stringify(fieldName)})`;
294
+ };
295
+ // Errors: one tagged class per declared error, a runtime spec per class,
296
+ // and per-root error unions (field errors ∪ global errors).
297
+ const errorTags = Object.keys(model.errors).sort();
298
+ const globalErrorType = `${sdkName}GlobalError`;
299
+ const reserved = new Set([
300
+ ...Object.keys(model.types),
301
+ sdkName,
302
+ `${sdkName}Error`,
303
+ globalErrorType,
271
304
  ]);
272
- const identifier = (name: string) =>
273
- name.replace(/[^A-Za-z0-9_$]/g, "_").replace(/^(?=[0-9])/, "_") ||
274
- "generated";
275
- const allocate = (preferred: string, fallback: string): string => {
276
- let name = identifier(preferred);
277
- if (occupied.has(name)) name = identifier(fallback);
278
- const base = name;
279
- for (let suffix = 2; occupied.has(name); suffix++)
280
- name = `${base}${suffix}`;
281
- occupied.add(name);
282
- return name;
305
+ for (const tag of errorTags) {
306
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tag))
307
+ throw new Error(`GraphQL error tag ${tag} is not a valid identifier`);
308
+ for (const name of [tag, `${tag}Spec`])
309
+ if (reserved.has(name)) throw new Error(`GraphQL error ${tag} collides with ${name}`);
310
+ }
311
+ const globalErrors = [...model.globalErrors].sort();
312
+ const rootErrors = (field: GraphQLField) => {
313
+ const fieldOnly = [...new Set(field.errors)]
314
+ .filter((tag) => !globalErrors.includes(tag))
315
+ .sort();
316
+ const type = union([...fieldOnly, globalErrorType]);
317
+ const specs = fieldOnly.length
318
+ ? `[${fieldOnly.map((tag) => `${tag}Spec`).join(", ")}, ...globalErrors]`
319
+ : "globalErrors";
320
+ return { type, specs };
283
321
  };
284
- const errorNames = new Map(
285
- Object.keys(model.errors).map((tag) => [
286
- tag,
287
- allocate(tag, `${identifier(tag)}Error`),
288
- ]),
289
- );
322
+ const rootFn = (kind: "query" | "mutation", fieldName: string, field: GraphQLField): string => {
323
+ const errors = rootErrors(field);
324
+ const { name, list } = peelRef(field.type);
325
+ const node = !list ? connectionNode(name) : undefined;
326
+ const resultTs = tsOutput(field.type);
327
+ const argEntries = Object.entries(field.args);
328
+ const argTypes =
329
+ argEntries.length > 0
330
+ ? `{ ${argEntries.map(([argName, arg]) => `${argName}: ${JSON.stringify(arg.type)}`).join(", ")} }`
331
+ : undefined;
332
+ const required = argEntries.filter(([, arg]) => arg.type.endsWith("!"));
333
+ const optional = argEntries.filter(([, arg]) => !arg.type.endsWith("!"));
334
+ const argFields = [
335
+ ...required.map(([argName, arg]) => `readonly ${argName}: ${tsArg(arg.type)}`),
336
+ ...optional.map(([argName, arg]) => `readonly ${argName}?: ${tsArg(arg.type)}`),
337
+ ].join("; ");
338
+ const sig =
339
+ argEntries.length === 0
340
+ ? ""
341
+ : required.length === 0
342
+ ? `args?: { ${argFields} }`
343
+ : `args: { ${argFields} }`;
344
+ const argsExpr = argEntries.length === 0 ? ", undefined" : ", args";
345
+ const argTypesExpr = argTypes ? `, ${argTypes}` : ", undefined";
346
+ const rest = `${argsExpr}${argTypesExpr}, ${errors.specs}`;
347
+ const result = `Query<${resultTs}, ${errors.type}>`;
348
+ const call = (helper: string, target: string) =>
349
+ `${helper}(${JSON.stringify(kind)}, ${JSON.stringify(fieldName)}, ${target}${rest})`;
350
+ const body = node
351
+ ? call("rootConnection", node)
352
+ : isObjectLike(name)
353
+ ? call(list ? "rootList" : "root", name)
354
+ : call("rootLeaf", String(list));
355
+ return ` ${fieldName}: (${sig}): ${result} =>\n ${body},`;
356
+ };
357
+
358
+ const objects: string[] = [];
359
+ const enums: string[] = [];
360
+ const inputs: string[] = [];
361
+ const unions: string[] = [];
362
+ for (const [name, type] of Object.entries(model.types)) {
363
+ if (name.startsWith("__") || skipRoots.has(name)) continue;
364
+ if (type.kind === "OBJECT" || type.kind === "INTERFACE") objects.push(name);
365
+ else if (type.kind === "ENUM") enums.push(name);
366
+ else if (type.kind === "INPUT_OBJECT") inputs.push(name);
367
+ else if (type.kind === "UNION") unions.push(name);
368
+ }
369
+ objects.sort();
370
+ enums.sort();
371
+ inputs.sort();
372
+ unions.sort();
373
+
290
374
  const lines: string[] = [
291
375
  "// Generated by @distilled.cloud/core/codegen/graphql-client. DO NOT EDIT.",
292
- 'import * as G from "@distilled.cloud/core/graphql";',
293
- 'import * as S from "effect/Schema";',
294
- 'import * as Category from "@distilled.cloud/core/category";',
295
- `import { ${options.transportName ?? "transport"} } from ${literal(options.transportImport)};`,
296
- `import type { ${options.requirementsType} } from ${literal(options.requirementsImport)};`,
297
- `export type { ${options.requirementsType} } from ${literal(options.requirementsImport)};`,
298
- 'export { catchTags, isErrorTag, GraphQLFailure, GraphQLTransportError, GraphQLDecodeError, GraphQLRequestError, UnknownGraphQLError, type GraphQLIssue, type Report } from "@distilled.cloud/core/graphql";',
376
+ `import * as S from "effect/Schema";`,
377
+ `import * as Category from "@distilled.cloud/core/category";`,
378
+ `import {`,
379
+ ` connectionField,`,
380
+ ` errorFields,`,
381
+ ` errorSpec,`,
382
+ ` listField,`,
383
+ ` objectField,`,
384
+ ` root,`,
385
+ ` rootConnection,`,
386
+ ` rootLeaf,`,
387
+ ` rootList,`,
388
+ ` scalarField,`,
389
+ ` type ErrorSpec,`,
390
+ ` type Query,`,
391
+ ` type TypeMeta,`,
392
+ `} from "@distilled.cloud/core/graphql";`,
299
393
  "",
300
- "export type Scalars = {",
301
394
  ];
302
- for (const [name, type] of Object.entries(model.types)) {
303
- if (type.kind === "SCALAR" || type.kind === "ENUM")
304
- lines.push(
305
- `${literal(name)}: ${type.kind === "SCALAR" ? (type.scalar ?? "unknown") : union(type.enumValues!.map(literal))};`,
306
- );
307
- }
308
- lines.push("}", "export type Inputs = {");
309
- for (const [name, type] of Object.entries(model.types)) {
310
- if (type.kind === "INPUT_OBJECT")
311
- lines.push(
312
- documentation(type.description),
313
- `${literal(name)}: ${argsType(type.inputFields ?? {})};`,
314
- );
315
- }
316
- lines.push("}");
395
+
317
396
  const categories: Record<string, string> = {
318
397
  auth: "withAuthError",
319
398
  badRequest: "withBadRequestError",
@@ -323,97 +402,110 @@ export const generateGraphQLClient = (
323
402
  server: "withServerError",
324
403
  conflict: "withConflictError",
325
404
  };
326
- for (const [tag, error] of Object.entries(model.errors)) {
327
- const name = errorNames.get(tag)!;
405
+ for (const tag of errorTags) {
406
+ const error = model.errors[tag]!;
407
+ if (error.category && !categories[error.category])
408
+ throw new Error(`GraphQL error ${tag}: unknown category ${error.category}`);
328
409
  const pipes = [
329
- error.category
330
- ? categories[error.category] && `Category.${categories[error.category]}`
331
- : undefined,
410
+ error.category ? `Category.${categories[error.category]}` : undefined,
332
411
  error.retryable
333
412
  ? `Category.withRetryable(${error.category === "throttling" ? "{ throttling: true }" : ""})`
334
413
  : undefined,
335
414
  ].filter(Boolean);
415
+ const options = [
416
+ error.retryable ? "retryable: true" : undefined,
417
+ globalErrors.includes(tag) ? "global: true" : undefined,
418
+ ].filter(Boolean);
336
419
  lines.push(
337
- documentation(error.description),
338
- `export class ${name} extends S.TaggedError<${name}>()(${literal(tag)}, G.errorFields)${pipes.length ? `.pipe(${pipes.join(", ")})` : ""} {}`,
420
+ documentation(error.description) +
421
+ `export class ${tag} extends S.TaggedError<${tag}>()(${literal(tag)}, errorFields)${pipes.length ? `.pipe(${pipes.join(", ")})` : ""} {}`,
422
+ `const ${tag}Spec: ErrorSpec<${tag}> = errorSpec(${tag}, ${literal(tag)}, ${JSON.stringify(error.matchers)}${options.length ? `, { ${options.join(", ")} }` : ""});`,
423
+ "",
339
424
  );
340
425
  }
341
- lines.push("export type Errors = {");
342
- for (const [tag, name] of errorNames) lines.push(`${literal(tag)}: ${name};`);
343
- lines.push("}", "export type Types = {");
344
- for (const [name, type] of Object.entries(model.types)) {
345
- if (!["OBJECT", "INTERFACE", "UNION"].includes(type.kind)) continue;
346
- lines.push(documentation(type.description), `${literal(name)}: {`);
426
+ lines.push(
427
+ `/** Errors every ${sdkName} root field can return. */`,
428
+ `export type ${globalErrorType} = ${union(globalErrors)};`,
429
+ `const globalErrors: ReadonlyArray<ErrorSpec> = [${globalErrors.map((tag) => `${tag}Spec`).join(", ")}];`,
430
+ "",
431
+ `/** Every typed error the ${sdkName} SDK declares. */`,
432
+ `export type ${sdkName}Error = ${union(errorTags)};`,
433
+ "",
434
+ );
435
+
436
+ for (const name of enums) {
437
+ const type = model.types[name]!;
438
+ lines.push(
439
+ documentation(type.description) +
440
+ `export type ${name} = ${union((type.enumValues ?? []).map(literal))};`,
441
+ "",
442
+ );
443
+ }
444
+
445
+ for (const name of inputs) {
446
+ const type = model.types[name]!;
447
+ const fields = Object.entries(type.inputFields ?? {}).map(
448
+ ([fieldName, field]) =>
449
+ ` readonly ${fieldName}${field.type.endsWith("!") ? "" : "?"}: ${tsArg(field.type)};`,
450
+ );
451
+ lines.push(documentation(type.description) + `export interface ${name} {`, ...fields, "}", "");
452
+ }
453
+
454
+ for (const name of unions) {
455
+ const type = model.types[name]!;
456
+ lines.push(
457
+ documentation(type.description) +
458
+ `export type ${name} = ${(type.possibleTypes ?? []).join(" | ") || "unknown"};`,
459
+ "",
460
+ );
461
+ }
462
+
463
+ for (const name of objects) {
464
+ const type = model.types[name]!;
465
+ const fields = Object.entries(type.fields ?? {}).map(
466
+ ([fieldName, field]) => ` readonly ${fieldName}: ${tsOutput(field.type)};`,
467
+ );
468
+ lines.push(documentation(type.description) + `export interface ${name} {`, ...fields, "}", "");
469
+ }
470
+
471
+ for (const name of [...objects, ...unions]) {
472
+ lines.push(`export const ${name}: TypeMeta = { name: ${JSON.stringify(name)}, fields: {} };`);
473
+ }
474
+ lines.push("");
475
+
476
+ for (const name of objects) {
477
+ const type = model.types[name]!;
478
+ lines.push(`Object.assign(${name}.fields, {`);
347
479
  for (const [fieldName, field] of Object.entries(type.fields ?? {})) {
348
- lines.push(
349
- documentation(field.description),
350
- `${literal(fieldName)}: G.Field<${argsType(field.args)}, ${literal(field.type)}, ${union(field.errors.map(literal))}>;`,
351
- );
480
+ lines.push(` ${fieldName}: ${fieldMeta(fieldName, field)},`);
352
481
  }
353
- lines.push("};");
482
+ lines.push("});", "");
354
483
  }
355
- lines.push("}", "export type PossibleTypes = {");
356
- for (const [name, type] of Object.entries(model.types)) {
357
- if (type.kind === "INTERFACE" || type.kind === "UNION")
358
- lines.push(
359
- `${literal(name)}: ${union((type.possibleTypes ?? []).map(literal))};`,
360
- );
484
+ for (const name of unions) {
485
+ lines.push(`Object.assign(${name}.fields, { __typename: scalarField("__typename") });`, "");
361
486
  }
362
- lines.push(
363
- "}",
364
- "export type Schema = {",
365
- "types: Types; scalars: Scalars; errors: Errors; possibleTypes: PossibleTypes;",
366
- `query: ${literal(model.queryType)};`,
367
- `mutation: ${model.mutationType ? literal(model.mutationType) : "never"};`,
368
- `subscription: ${model.subscriptionType ? literal(model.subscriptionType) : "never"};`,
369
- `globalErrors: ${union(model.globalErrors.map(literal))};`,
370
- "};",
371
- );
372
- lines.push(
373
- "export type Selection<Name extends keyof Types> = G.Selection<Schema, Name>;",
374
- "export type Result<Name extends string, Select> = G.Result<Schema, Name, Select>;",
375
- "export type SelectedErrors<Name extends keyof Types, Select> = G.Errors<Schema, Name, Select>;",
376
- );
377
- lines.push(`export const schema: G.GraphQLModel = ${JSON.stringify(model)};`);
378
- lines.push(
379
- `export const errorClasses = { ${[...errorNames].map(([tag, name]) => `${literal(tag)}: ${name}`).join(", ")} };`,
380
- );
381
- lines.push(
382
- `export const client = G.makeClient<Schema, ${options.requirementsType}>(schema, ${options.transportName ?? "transport"}, errorClasses);`,
383
- "export const query = client.query;",
384
- "export const mutation = client.mutation;",
385
- "export const report = client.report;",
386
- );
387
- const operationNames = new Map<string, string>();
388
- for (const [kind, name] of [
389
- ["query", model.queryType],
390
- ["mutation", model.mutationType],
391
- ] as const) {
392
- for (const field of Object.keys(model.types[name ?? ""]?.fields ?? {})) {
393
- const exportName = allocate(
394
- field,
395
- `${kind}${field[0]!.toUpperCase()}${field.slice(1)}`,
396
- );
397
- if (!operationNames.has(field)) operationNames.set(field, exportName);
398
- lines.push(
399
- `export const ${exportName} = client.operation(${literal(kind)}, ${literal(field)});`,
400
- );
487
+
488
+ lines.push(`export const ${sdkName} = {`);
489
+ const queryNames = new Set<string>();
490
+ const queryType = model.types[model.queryType];
491
+ if (queryType?.fields) {
492
+ for (const [fieldName, field] of Object.entries(queryType.fields)) {
493
+ queryNames.add(fieldName);
494
+ lines.push(rootFn("query", fieldName, field));
401
495
  }
402
496
  }
403
- for (const [alias, target] of Object.entries(
404
- options.operationAliases ?? {},
405
- )) {
406
- const targetName = operationNames.get(target);
407
- // Legacy aliases are optional conveniences; never displace a real export.
408
- if (
409
- targetName &&
410
- alias !== target &&
411
- identifier(alias) === alias &&
412
- !occupied.has(alias)
413
- ) {
414
- occupied.add(alias);
415
- lines.push(`export const ${alias} = ${targetName};`);
497
+ if (model.mutationType) {
498
+ const mutationType = model.types[model.mutationType];
499
+ if (mutationType?.fields) {
500
+ for (const [fieldName, field] of Object.entries(mutationType.fields)) {
501
+ const exportName = queryNames.has(fieldName) ? `${fieldName}Mutation` : fieldName;
502
+ const line = rootFn("mutation", fieldName, field);
503
+ lines.push(
504
+ exportName === fieldName ? line : line.replace(` ${fieldName}:`, ` ${exportName}:`),
505
+ );
506
+ }
416
507
  }
417
508
  }
509
+ lines.push("};", "");
418
510
  return lines.join("\n") + "\n";
419
511
  };