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

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 (259) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/rest.js +1 -1
  6. package/lib/_bundle/rest.js.map +1 -1
  7. package/lib/annotations.d.ts +15 -0
  8. package/lib/annotations.d.ts.map +1 -0
  9. package/lib/annotations.js +2 -0
  10. package/lib/annotations.js.map +1 -0
  11. package/lib/api.d.ts +15 -0
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -1
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/config.d.ts +54 -13
  16. package/lib/config.d.ts.map +1 -1
  17. package/lib/config.js +1 -1
  18. package/lib/debug.d.ts.map +1 -1
  19. package/lib/error-category.d.ts.map +1 -1
  20. package/lib/errors.d.ts +2 -13
  21. package/lib/errors.d.ts.map +1 -1
  22. package/lib/errors.js +1 -1
  23. package/lib/graphql.d.ts +14 -0
  24. package/lib/graphql.d.ts.map +1 -1
  25. package/lib/index.d.ts +3 -2
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +1 -0
  28. package/lib/pagination.d.ts +34 -2
  29. package/lib/pagination.d.ts.map +1 -1
  30. package/lib/pagination.js +1 -1
  31. package/lib/protocol-http.d.ts +30 -6
  32. package/lib/protocol-http.d.ts.map +1 -1
  33. package/lib/protocol-http.js +1 -1
  34. package/lib/protocol-rest.d.ts +53 -39
  35. package/lib/protocol-rest.d.ts.map +1 -1
  36. package/lib/protocol-rest.js +1 -1
  37. package/lib/response-validation.d.ts +4 -3
  38. package/lib/response-validation.d.ts.map +1 -1
  39. package/lib/schema-lite-typed.js +1 -2
  40. package/lib/telemetry-debug.d.ts +14 -0
  41. package/lib/telemetry-debug.d.ts.map +1 -0
  42. package/lib/telemetry-debug.js +2 -0
  43. package/lib/telemetry-debug.js.map +1 -0
  44. package/lib/telemetry-hooks.d.ts +32 -0
  45. package/lib/telemetry-hooks.d.ts.map +1 -0
  46. package/lib/telemetry-hooks.js +2 -0
  47. package/lib/telemetry-hooks.js.map +1 -0
  48. package/lib/telemetry-host-rules.d.ts +23 -0
  49. package/lib/telemetry-host-rules.d.ts.map +1 -0
  50. package/lib/telemetry-host-rules.js +2 -0
  51. package/lib/telemetry-host-rules.js.map +1 -0
  52. package/lib/telemetry-lambda-context.d.ts +17 -0
  53. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  54. package/lib/telemetry-lambda-context.js +2 -0
  55. package/lib/telemetry-lambda-context.js.map +1 -0
  56. package/lib/telemetry-message-context.d.ts +52 -0
  57. package/lib/telemetry-message-context.d.ts.map +1 -0
  58. package/lib/telemetry-message-context.js +2 -0
  59. package/lib/telemetry-message-context.js.map +1 -0
  60. package/lib/telemetry-metrics.d.ts +6 -0
  61. package/lib/telemetry-metrics.d.ts.map +1 -0
  62. package/lib/telemetry-metrics.js +2 -0
  63. package/lib/telemetry-metrics.js.map +1 -0
  64. package/lib/telemetry-name-template.d.ts +13 -0
  65. package/lib/telemetry-name-template.d.ts.map +1 -0
  66. package/lib/telemetry-name-template.js +2 -0
  67. package/lib/telemetry-name-template.js.map +1 -0
  68. package/lib/telemetry-stream.d.ts +9 -0
  69. package/lib/telemetry-stream.d.ts.map +1 -0
  70. package/lib/telemetry-stream.js +2 -0
  71. package/lib/telemetry-stream.js.map +1 -0
  72. package/lib/telemetry-xray.d.ts +28 -0
  73. package/lib/telemetry-xray.d.ts.map +1 -0
  74. package/lib/telemetry-xray.js +2 -0
  75. package/lib/telemetry-xray.js.map +1 -0
  76. package/lib/telemetry.d.ts +269 -0
  77. package/lib/telemetry.d.ts.map +1 -0
  78. package/lib/telemetry.js +3 -0
  79. package/lib/telemetry.js.map +1 -0
  80. package/package.json +1 -3
  81. package/src/annotations.ts +37 -0
  82. package/src/api.ts +123 -24
  83. package/src/category.ts +21 -22
  84. package/src/config.ts +58 -29
  85. package/src/debug.ts +9 -6
  86. package/src/error-category.ts +12 -14
  87. package/src/errors.ts +7 -7
  88. package/src/graphql.ts +123 -18
  89. package/src/index.ts +3 -2
  90. package/src/pagination.ts +119 -6
  91. package/src/protocol-http.ts +63 -43
  92. package/src/protocol-rest.ts +201 -140
  93. package/src/response-validation.ts +4 -3
  94. package/src/telemetry-debug.ts +135 -0
  95. package/src/telemetry-hooks.ts +33 -0
  96. package/src/telemetry-host-rules.ts +39 -0
  97. package/src/telemetry-lambda-context.ts +46 -0
  98. package/src/telemetry-message-context.ts +170 -0
  99. package/src/telemetry-metrics.ts +69 -0
  100. package/src/telemetry-name-template.ts +26 -0
  101. package/src/telemetry-stream.ts +91 -0
  102. package/src/telemetry-xray.ts +66 -0
  103. package/src/telemetry.ts +768 -0
  104. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  105. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  106. package/lib/codegen/boolean-string-enums.js +0 -147
  107. package/lib/codegen/boolean-string-enums.js.map +0 -1
  108. package/lib/codegen/chunk.d.ts +0 -7
  109. package/lib/codegen/chunk.d.ts.map +0 -1
  110. package/lib/codegen/chunk.js +0 -139
  111. package/lib/codegen/chunk.js.map +0 -1
  112. package/lib/codegen/cli.d.ts +0 -80
  113. package/lib/codegen/cli.d.ts.map +0 -1
  114. package/lib/codegen/cli.js +0 -166
  115. package/lib/codegen/cli.js.map +0 -1
  116. package/lib/codegen/datafy.d.ts +0 -14
  117. package/lib/codegen/datafy.d.ts.map +0 -1
  118. package/lib/codegen/datafy.js +0 -853
  119. package/lib/codegen/datafy.js.map +0 -1
  120. package/lib/codegen/dedupe.d.ts +0 -5
  121. package/lib/codegen/dedupe.d.ts.map +0 -1
  122. package/lib/codegen/dedupe.js +0 -153
  123. package/lib/codegen/dedupe.js.map +0 -1
  124. package/lib/codegen/emit.d.ts +0 -125
  125. package/lib/codegen/emit.d.ts.map +0 -1
  126. package/lib/codegen/emit.js +0 -99
  127. package/lib/codegen/emit.js.map +0 -1
  128. package/lib/codegen/format.d.ts +0 -11
  129. package/lib/codegen/format.d.ts.map +0 -1
  130. package/lib/codegen/format.js +0 -32
  131. package/lib/codegen/format.js.map +0 -1
  132. package/lib/codegen/generated-at.d.ts +0 -29
  133. package/lib/codegen/generated-at.d.ts.map +0 -1
  134. package/lib/codegen/generated-at.js +0 -78
  135. package/lib/codegen/generated-at.js.map +0 -1
  136. package/lib/codegen/generator.d.ts +0 -353
  137. package/lib/codegen/generator.d.ts.map +0 -1
  138. package/lib/codegen/generator.js +0 -810
  139. package/lib/codegen/generator.js.map +0 -1
  140. package/lib/codegen/graph.d.ts +0 -36
  141. package/lib/codegen/graph.d.ts.map +0 -1
  142. package/lib/codegen/graph.js +0 -136
  143. package/lib/codegen/graph.js.map +0 -1
  144. package/lib/codegen/graphql-client.d.ts +0 -70
  145. package/lib/codegen/graphql-client.d.ts.map +0 -1
  146. package/lib/codegen/graphql-client.js +0 -439
  147. package/lib/codegen/graphql-client.js.map +0 -1
  148. package/lib/codegen/graphql.d.ts +0 -207
  149. package/lib/codegen/graphql.d.ts.map +0 -1
  150. package/lib/codegen/graphql.js +0 -786
  151. package/lib/codegen/graphql.js.map +0 -1
  152. package/lib/codegen/latin1.d.ts +0 -3
  153. package/lib/codegen/latin1.d.ts.map +0 -1
  154. package/lib/codegen/latin1.js +0 -126
  155. package/lib/codegen/latin1.js.map +0 -1
  156. package/lib/codegen/members.d.ts +0 -32
  157. package/lib/codegen/members.d.ts.map +0 -1
  158. package/lib/codegen/members.js +0 -62
  159. package/lib/codegen/members.js.map +0 -1
  160. package/lib/codegen/model-diff.d.ts +0 -10
  161. package/lib/codegen/model-diff.d.ts.map +0 -1
  162. package/lib/codegen/model-diff.js +0 -67
  163. package/lib/codegen/model-diff.js.map +0 -1
  164. package/lib/codegen/naming.d.ts +0 -29
  165. package/lib/codegen/naming.d.ts.map +0 -1
  166. package/lib/codegen/naming.js +0 -74
  167. package/lib/codegen/naming.js.map +0 -1
  168. package/lib/codegen/openapi-cli.d.ts +0 -52
  169. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  170. package/lib/codegen/openapi-cli.js +0 -84
  171. package/lib/codegen/openapi-cli.js.map +0 -1
  172. package/lib/codegen/openapi.d.ts +0 -209
  173. package/lib/codegen/openapi.d.ts.map +0 -1
  174. package/lib/codegen/openapi.js +0 -1548
  175. package/lib/codegen/openapi.js.map +0 -1
  176. package/lib/codegen/operations.d.ts +0 -24
  177. package/lib/codegen/operations.d.ts.map +0 -1
  178. package/lib/codegen/operations.js +0 -56
  179. package/lib/codegen/operations.js.map +0 -1
  180. package/lib/codegen/pagination.d.ts +0 -39
  181. package/lib/codegen/pagination.d.ts.map +0 -1
  182. package/lib/codegen/pagination.js +0 -31
  183. package/lib/codegen/pagination.js.map +0 -1
  184. package/lib/codegen/patch-audit.d.ts +0 -84
  185. package/lib/codegen/patch-audit.d.ts.map +0 -1
  186. package/lib/codegen/patch-audit.js +0 -366
  187. package/lib/codegen/patch-audit.js.map +0 -1
  188. package/lib/codegen/patches.d.ts +0 -129
  189. package/lib/codegen/patches.d.ts.map +0 -1
  190. package/lib/codegen/patches.js +0 -472
  191. package/lib/codegen/patches.js.map +0 -1
  192. package/lib/codegen/prelude.d.ts +0 -15
  193. package/lib/codegen/prelude.d.ts.map +0 -1
  194. package/lib/codegen/prelude.js +0 -60
  195. package/lib/codegen/prelude.js.map +0 -1
  196. package/lib/codegen/privatize.d.ts +0 -21
  197. package/lib/codegen/privatize.d.ts.map +0 -1
  198. package/lib/codegen/privatize.js +0 -176
  199. package/lib/codegen/privatize.js.map +0 -1
  200. package/lib/codegen/proto.d.ts +0 -121
  201. package/lib/codegen/proto.d.ts.map +0 -1
  202. package/lib/codegen/proto.js +0 -960
  203. package/lib/codegen/proto.js.map +0 -1
  204. package/lib/codegen/pure.d.ts +0 -6
  205. package/lib/codegen/pure.d.ts.map +0 -1
  206. package/lib/codegen/pure.js +0 -91
  207. package/lib/codegen/pure.js.map +0 -1
  208. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  209. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  210. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  211. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  212. package/lib/codegen/spec-path.d.ts +0 -16
  213. package/lib/codegen/spec-path.d.ts.map +0 -1
  214. package/lib/codegen/spec-path.js +0 -101
  215. package/lib/codegen/spec-path.js.map +0 -1
  216. package/lib/codegen/table.d.ts +0 -5
  217. package/lib/codegen/table.d.ts.map +0 -1
  218. package/lib/codegen/table.js +0 -249
  219. package/lib/codegen/table.js.map +0 -1
  220. package/lib/json-patch.d.ts +0 -58
  221. package/lib/json-patch.d.ts.map +0 -1
  222. package/lib/json-patch.js +0 -2
  223. package/lib/json-patch.js.map +0 -1
  224. package/lib/schema-lite-typed.js.map +0 -1
  225. package/lib/testing.d.ts +0 -40
  226. package/lib/testing.d.ts.map +0 -1
  227. package/lib/testing.js +0 -2
  228. package/lib/testing.js.map +0 -1
  229. package/src/codegen/boolean-string-enums.ts +0 -155
  230. package/src/codegen/chunk.ts +0 -147
  231. package/src/codegen/cli.ts +0 -293
  232. package/src/codegen/datafy.ts +0 -874
  233. package/src/codegen/dedupe.ts +0 -173
  234. package/src/codegen/emit.ts +0 -200
  235. package/src/codegen/format.ts +0 -49
  236. package/src/codegen/generated-at.ts +0 -88
  237. package/src/codegen/generator.ts +0 -1229
  238. package/src/codegen/graph.ts +0 -151
  239. package/src/codegen/graphql-client.ts +0 -545
  240. package/src/codegen/graphql.ts +0 -1145
  241. package/src/codegen/latin1.ts +0 -131
  242. package/src/codegen/members.ts +0 -79
  243. package/src/codegen/model-diff.ts +0 -67
  244. package/src/codegen/naming.ts +0 -85
  245. package/src/codegen/openapi-cli.ts +0 -141
  246. package/src/codegen/openapi.ts +0 -1845
  247. package/src/codegen/operations.ts +0 -73
  248. package/src/codegen/pagination.ts +0 -64
  249. package/src/codegen/patch-audit.ts +0 -480
  250. package/src/codegen/patches.ts +0 -581
  251. package/src/codegen/prelude.ts +0 -70
  252. package/src/codegen/privatize.ts +0 -200
  253. package/src/codegen/proto.ts +0 -1092
  254. package/src/codegen/pure.ts +0 -94
  255. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  256. package/src/codegen/spec-path.ts +0 -112
  257. package/src/codegen/table.ts +0 -254
  258. package/src/json-patch.ts +0 -273
  259. package/src/testing.ts +0 -74
@@ -1,151 +0,0 @@
1
- /**
2
- * Shared shape-graph utilities for the SDK generators (dev-time only).
3
- *
4
- * Works over plain Smithy-JSON shape maps (`{ "ns#Name": { type, members,
5
- * … } }`). Providers supply the shape map and (optionally) a custom
6
- * dependency extractor; reachability, topological ordering, and cycle
7
- * analysis are generic.
8
- */
9
- import { isPrelude } from "./naming.ts";
10
-
11
- export type ShapeMap = Record<string, any>;
12
-
13
- /**
14
- * Direct dependencies of a shape: structure/union member targets, list
15
- * member, map key/value. Operations/services are not traversed here —
16
- * providers seed reachability from operation I/O explicitly.
17
- */
18
- export const shapeDeps = (def: any): string[] => {
19
- if (!def) return [];
20
- if (def.type === "structure" || def.type === "union") {
21
- return Object.values(def.members ?? {}).map((m: any) => m.target);
22
- }
23
- if (def.type === "list") return [def.member.target];
24
- if (def.type === "map") {
25
- return def.key ? [def.key.target, def.value.target] : [def.value.target];
26
- }
27
- return [];
28
- };
29
-
30
- /**
31
- * Every shape reachable from `roots` through `deps`, excluding prelude
32
- * shapes and ids missing from the map.
33
- */
34
- export const reachableFrom = (
35
- shapes: ShapeMap,
36
- roots: Iterable<string>,
37
- deps: (def: any) => string[] = shapeDeps,
38
- ): Set<string> => {
39
- const reachable = new Set<string>();
40
- const visit = (id: string) => {
41
- if (isPrelude(id) || reachable.has(id) || !shapes[id]) return;
42
- reachable.add(id);
43
- for (const dep of deps(shapes[id])) visit(dep);
44
- };
45
- for (const r of roots) visit(r);
46
- return reachable;
47
- };
48
-
49
- /**
50
- * Dependencies-first topological order over `ids`. Cycles are tolerated:
51
- * a back-edge is simply skipped, so mutually-recursive shapes come out in
52
- * discovery order and emitters break the cycle with `S.suspend` at
53
- * forward references (see {@link forwardRef}).
54
- */
55
- export const topoOrder = (
56
- shapes: ShapeMap,
57
- ids: Iterable<string>,
58
- deps: (def: any) => string[] = shapeDeps,
59
- ): string[] => {
60
- const order: string[] = [];
61
- const done = new Set<string>();
62
- const stack = new Set<string>();
63
- const walk = (id: string) => {
64
- if (done.has(id) || stack.has(id) || isPrelude(id) || !shapes[id]) return;
65
- stack.add(id);
66
- for (const dep of deps(shapes[id])) walk(dep);
67
- stack.delete(id);
68
- done.add(id);
69
- order.push(id);
70
- };
71
- for (const id of ids) walk(id);
72
- return order;
73
- };
74
-
75
- /** Position index for {@link forwardRef} decisions. */
76
- export const orderIndex = (order: readonly string[]): Map<string, number> => {
77
- const indexOf = new Map<string, number>();
78
- order.forEach((id, i) => indexOf.set(id, i));
79
- return indexOf;
80
- };
81
-
82
- /**
83
- * Whether a reference from the shape at `selfIdx` to `target` points
84
- * forward in emission order (including into a cycle) and therefore needs
85
- * `S.suspend(() => …)` to defer evaluation.
86
- */
87
- export const isForwardRef = (
88
- indexOf: ReadonlyMap<string, number>,
89
- target: string,
90
- selfIdx: number,
91
- ): boolean => {
92
- const ti = indexOf.get(target);
93
- return ti !== undefined && ti > selfIdx;
94
- };
95
-
96
- /**
97
- * All shape ids that participate in a dependency cycle (Tarjan SCC —
98
- * components of size > 1, plus direct self-loops). Used by generators
99
- * that must know cyclicity independent of emission position (e.g. to add
100
- * an explicit `S.Schema<T>` return type on suspended thunks and break
101
- * circular type inference).
102
- */
103
- export const cyclicShapeIds = (
104
- shapes: ShapeMap,
105
- ids: Iterable<string>,
106
- deps: (def: any) => string[] = shapeDeps,
107
- ): Set<string> => {
108
- const idSet = new Set(ids);
109
- const index = new Map<string, number>();
110
- const low = new Map<string, number>();
111
- const onStack = new Set<string>();
112
- const stack: string[] = [];
113
- const cyclic = new Set<string>();
114
- let counter = 0;
115
-
116
- const strongConnect = (v: string) => {
117
- index.set(v, counter);
118
- low.set(v, counter);
119
- counter++;
120
- stack.push(v);
121
- onStack.add(v);
122
-
123
- for (const w of deps(shapes[v])) {
124
- if (!idSet.has(w) || !shapes[w]) continue;
125
- if (!index.has(w)) {
126
- strongConnect(w);
127
- low.set(v, Math.min(low.get(v)!, low.get(w)!));
128
- } else if (onStack.has(w)) {
129
- low.set(v, Math.min(low.get(v)!, index.get(w)!));
130
- }
131
- }
132
-
133
- if (low.get(v) === index.get(v)) {
134
- const component: string[] = [];
135
- let w: string;
136
- do {
137
- w = stack.pop()!;
138
- onStack.delete(w);
139
- component.push(w);
140
- } while (w !== v);
141
- if (component.length > 1 || deps(shapes[v]).some((d) => d === v)) {
142
- for (const c of component) cyclic.add(c);
143
- }
144
- }
145
- };
146
-
147
- for (const id of idSet) {
148
- if (!index.has(id) && shapes[id]) strongConnect(id);
149
- }
150
- return cyclic;
151
- };
@@ -1,545 +0,0 @@
1
- /** GraphQL-native introspection compiler. No traversal limits or RPC projection. */
2
- import { readIntrospection, type TypeRef } from "./graphql.ts";
3
-
4
- export interface GraphQLArgument {
5
- readonly type: string;
6
- readonly description?: string;
7
- readonly defaultValue?: string;
8
- }
9
- export interface GraphQLField {
10
- readonly type: string;
11
- readonly args: Record<string, GraphQLArgument>;
12
- readonly errors: readonly string[];
13
- readonly description?: string;
14
- readonly deprecated?: string | true;
15
- /** The value is a secret: typed `Redacted<string>` and wrapped at runtime. Set by patch. */
16
- readonly sensitive?: true;
17
- }
18
- export interface GraphQLType {
19
- readonly kind: string;
20
- readonly description?: string;
21
- readonly fields?: Record<string, GraphQLField>;
22
- readonly inputFields?: Record<string, GraphQLArgument>;
23
- readonly enumValues?: readonly string[];
24
- readonly possibleTypes?: readonly string[];
25
- readonly interfaces?: readonly string[];
26
- /** TypeScript scalar representation; custom JSON scalars default to unknown. */
27
- readonly scalar?: string;
28
- }
29
- export interface GraphQLErrorDefinition {
30
- readonly description?: string;
31
- readonly category?: string;
32
- readonly retryable?: boolean;
33
- readonly matchers: readonly {
34
- readonly code?: string;
35
- readonly message?: string;
36
- readonly messageIncludes?: string;
37
- }[];
38
- }
39
- export interface GraphQLModel {
40
- readonly version: 1;
41
- readonly queryType: string;
42
- readonly mutationType?: string;
43
- readonly subscriptionType?: string;
44
- readonly types: Record<string, GraphQLType>;
45
- readonly errors: Record<string, GraphQLErrorDefinition>;
46
- readonly globalErrors: readonly string[];
47
- }
48
-
49
- export const graphqlTypeString = (ref: TypeRef): string => {
50
- if (ref.kind === "NON_NULL" || ref.kind === "LIST") {
51
- if (!ref.ofType) throw new Error(`Incomplete GraphQL ${ref.kind} reference`);
52
- const inner = graphqlTypeString(ref.ofType);
53
- return ref.kind === "NON_NULL" ? `${inner}!` : `[${inner}]`;
54
- }
55
- if (!ref.name) throw new Error("Unnamed GraphQL type reference");
56
- return ref.name;
57
- };
58
-
59
- /** Retain every schema coordinate, wrapper, default and abstract-type relationship. */
60
- export const convertGraphQLClient = (
61
- introspection: unknown,
62
- options: { readonly scalars?: Readonly<Record<string, string>> } = {},
63
- ): GraphQLModel => {
64
- const schema = readIntrospection(introspection);
65
- const scalars = {
66
- String: "string",
67
- ID: "string",
68
- Int: "number",
69
- Float: "number",
70
- Boolean: "boolean",
71
- ...options.scalars,
72
- };
73
- const argument = (value: {
74
- type: TypeRef;
75
- description?: string | null;
76
- defaultValue?: string | null;
77
- }): GraphQLArgument => ({
78
- type: graphqlTypeString(value.type),
79
- ...(value.description ? { description: value.description } : {}),
80
- ...(value.defaultValue != null ? { defaultValue: value.defaultValue } : {}),
81
- });
82
- const types: Record<string, GraphQLType> = {};
83
- for (const type of [...schema.types].sort((a, b) => a.name.localeCompare(b.name))) {
84
- if (type.name.startsWith("__")) continue;
85
- types[type.name] = {
86
- kind: type.kind,
87
- ...(type.description ? { description: type.description } : {}),
88
- ...(type.kind === "SCALAR"
89
- ? { scalar: scalars[type.name as keyof typeof scalars] ?? "unknown" }
90
- : {}),
91
- ...(type.fields
92
- ? {
93
- fields: Object.fromEntries(
94
- [...type.fields]
95
- .sort((a, b) => a.name.localeCompare(b.name))
96
- .map((field) => [
97
- field.name,
98
- {
99
- type: graphqlTypeString(field.type),
100
- args: Object.fromEntries(field.args.map((arg) => [arg.name, argument(arg)])),
101
- errors: [],
102
- ...(field.description ? { description: field.description } : {}),
103
- ...(field.isDeprecated
104
- ? {
105
- deprecated:
106
- (
107
- field as typeof field & {
108
- deprecationReason?: string;
109
- }
110
- ).deprecationReason || true,
111
- }
112
- : {}),
113
- },
114
- ]),
115
- ),
116
- }
117
- : {}),
118
- ...(type.inputFields
119
- ? {
120
- inputFields: Object.fromEntries(
121
- type.inputFields.map((field) => [field.name, argument(field)]),
122
- ),
123
- }
124
- : {}),
125
- ...(type.enumValues ? { enumValues: type.enumValues.map((value) => value.name) } : {}),
126
- ...(type.possibleTypes ? { possibleTypes: type.possibleTypes.map((ref) => ref.name!) } : {}),
127
- ...("interfaces" in type && Array.isArray(type.interfaces)
128
- ? {
129
- interfaces: type.interfaces.map((ref: { name: string }) => ref.name),
130
- }
131
- : {}),
132
- };
133
- }
134
- return {
135
- version: 1,
136
- queryType: schema.queryType.name,
137
- ...(schema.mutationType ? { mutationType: schema.mutationType.name } : {}),
138
- ...(schema.subscriptionType ? { subscriptionType: schema.subscriptionType.name } : {}),
139
- types,
140
- errors: {},
141
- globalErrors: [],
142
- };
143
- };
144
-
145
- /** Reject dangling schema/error references after patches, before generating code. */
146
- export const validateGraphQLModel = (model: GraphQLModel): void => {
147
- const checkType = (ref: string, coordinate: string) => {
148
- const name = ref.replace(/[[\]!]/g, "");
149
- if (!model.types[name]) throw new Error(`${coordinate}: unknown GraphQL type ${name}`);
150
- };
151
- const checkError = (error: string, coordinate: string) => {
152
- if (!model.errors[error]) throw new Error(`${coordinate}: unknown GraphQL error ${error}`);
153
- };
154
- const checkInput = (input: GraphQLArgument, coordinate: string) => {
155
- checkType(input.type, coordinate);
156
- if ("sensitive" in input) throw new Error(`${coordinate}: only output fields can be sensitive`);
157
- };
158
- for (const name of [model.queryType, model.mutationType, model.subscriptionType]) {
159
- if (name && !model.types[name]) throw new Error(`Unknown GraphQL root ${name}`);
160
- }
161
- for (const error of model.globalErrors) checkError(error, "globalErrors");
162
- for (const [name, type] of Object.entries(model.types)) {
163
- for (const [fieldName, field] of Object.entries(type.fields ?? {})) {
164
- const coordinate = `${name}.${fieldName}`;
165
- checkType(field.type, coordinate);
166
- for (const [argName, arg] of Object.entries(field.args))
167
- checkInput(arg, `${coordinate}(${argName})`);
168
- for (const error of field.errors) checkError(error, coordinate);
169
- if (field.sensitive && model.types[peelRef(field.type).name]?.scalar !== "string")
170
- throw new Error(`${coordinate}: only string scalar fields can be sensitive`);
171
- }
172
- for (const [fieldName, field] of Object.entries(type.inputFields ?? {}))
173
- checkInput(field, `${name}.${fieldName}`);
174
- for (const member of [...(type.possibleTypes ?? []), ...(type.interfaces ?? [])])
175
- checkType(member, name);
176
- }
177
- };
178
-
179
- const literal = (value: unknown): string => JSON.stringify(value);
180
- const union = (values: readonly string[]): string => (values.length ? values.join(" | ") : "never");
181
- const documentation = (description?: string): string =>
182
- description ? `/** ${description.replaceAll("*/", "* /")} */\n` : "";
183
-
184
- export interface GenerateGraphQLClientOptions {
185
- readonly transportImport: string;
186
- readonly transportName?: string;
187
- readonly requirementsType: string;
188
- readonly requirementsImport: string;
189
- /** Optional legacy-name aliases, e.g. createProject -> projectCreate. */
190
- readonly operationAliases?: Readonly<Record<string, string>>;
191
- /** Export name for the root object (`Railway`, `Eas`, …). Default `"Sdk"`. */
192
- readonly sdkName?: string;
193
- }
194
-
195
- const peelRef = (ref: string): { name: string; list: boolean; nonNull: boolean } => {
196
- let text = ref;
197
- let nonNull = false;
198
- let list = false;
199
- if (text.endsWith("!")) {
200
- nonNull = true;
201
- text = text.slice(0, -1);
202
- }
203
- if (text.startsWith("[") && text.endsWith("]")) {
204
- list = true;
205
- text = text.slice(1, -1);
206
- if (text.endsWith("!")) text = text.slice(0, -1);
207
- }
208
- return { name: text, list, nonNull };
209
- };
210
-
211
- /**
212
- * Emit a Query-algebra SDK: TypeMeta + TS types + named roots
213
- * (`me`, `project`, …). Combinators stay in `@distilled.cloud/core/query`;
214
- * this file only describes the schema as lazy lenses.
215
- */
216
- export const generateGraphQLClient = (
217
- model: GraphQLModel,
218
- options: GenerateGraphQLClientOptions,
219
- ): string => {
220
- validateGraphQLModel(model);
221
- const sdkName = options.sdkName ?? "Sdk";
222
- const skipRoots = new Set(
223
- [model.queryType, model.mutationType, model.subscriptionType].filter(
224
- (name): name is string => typeof name === "string",
225
- ),
226
- );
227
- const tsNamed = (name: string): string => {
228
- const type = model.types[name];
229
- if (!type) return "unknown";
230
- if (type.kind === "SCALAR") return type.scalar ?? "unknown";
231
- if (type.kind === "ENUM")
232
- return (type.enumValues ?? []).map((value) => JSON.stringify(value)).join(" | ") || "string";
233
- if (type.kind === "UNION")
234
- return (type.possibleTypes ?? []).filter(Boolean).join(" | ") || "unknown";
235
- return name;
236
- };
237
- /** Relay `edges { node }` → node type name, else undefined. */
238
- const connectionNode = (typeName: string): string | undefined => {
239
- const type = model.types[typeName];
240
- const edges = type?.fields?.edges;
241
- if (!edges) return undefined;
242
- const edgeRef = peelRef(edges.type);
243
- if (!edgeRef.list) return undefined;
244
- const node = model.types[edgeRef.name]?.fields?.node;
245
- if (!node) return undefined;
246
- const nodeName = peelRef(node.type).name;
247
- const kind = model.types[nodeName]?.kind;
248
- if (kind !== "OBJECT" && kind !== "INTERFACE" && kind !== "UNION") {
249
- return undefined;
250
- }
251
- return nodeName;
252
- };
253
- /** Input type: nullable GraphQL inputs (no `!`) accept `null`. */
254
- const tsArg = (ref: string): string => {
255
- const nonNull = ref.endsWith("!");
256
- const inner = nonNull ? ref.slice(0, -1) : ref;
257
- const ts =
258
- inner.startsWith("[") && inner.endsWith("]")
259
- ? `ReadonlyArray<${tsArg(inner.slice(1, -1))}>`
260
- : tsNamed(inner);
261
- return nonNull ? ts : `${ts} | null`;
262
- };
263
- /** Response type: nullable GraphQL types (no `!`) include `null`. */
264
- const tsOutput = (ref: string, sensitive = false): string => {
265
- const nonNull = ref.endsWith("!");
266
- const inner = nonNull ? ref.slice(0, -1) : ref;
267
- let ts: string;
268
- if (inner.startsWith("[") && inner.endsWith("]")) {
269
- ts = `ReadonlyArray<${tsOutput(inner.slice(1, -1), sensitive)}>`;
270
- } else if (sensitive) {
271
- ts = "Redacted.Redacted<string>";
272
- } else {
273
- const node = connectionNode(inner);
274
- ts = node ? `ReadonlyArray<${tsNamed(node)}>` : tsNamed(inner);
275
- }
276
- return nonNull ? ts : `${ts} | null`;
277
- };
278
- const isObjectLike = (name: string): boolean => {
279
- const kind = model.types[name]?.kind;
280
- return kind === "OBJECT" || kind === "INTERFACE";
281
- };
282
- const fieldMeta = (fieldName: string, field: GraphQLField): string => {
283
- const { name, list } = peelRef(field.type);
284
- const argTypes = Object.keys(field.args).length
285
- ? `{ ${Object.entries(field.args)
286
- .map(([argName, arg]) => `${argName}: ${JSON.stringify(arg.type)}`)
287
- .join(", ")} }`
288
- : undefined;
289
- const node = !list ? connectionNode(name) : undefined;
290
- if (node) {
291
- return argTypes
292
- ? `connectionField(${JSON.stringify(fieldName)}, ${node}, ${argTypes})`
293
- : `connectionField(${JSON.stringify(fieldName)}, ${node})`;
294
- }
295
- if (list && isObjectLike(name)) {
296
- return argTypes
297
- ? `listField(${JSON.stringify(fieldName)}, ${name}, ${argTypes})`
298
- : `listField(${JSON.stringify(fieldName)}, ${name})`;
299
- }
300
- if (isObjectLike(name) || model.types[name]?.kind === "UNION") {
301
- return `objectField(${JSON.stringify(fieldName)}, ${name})`;
302
- }
303
- return field.sensitive
304
- ? `scalarField(${JSON.stringify(fieldName)}, { sensitive: true })`
305
- : `scalarField(${JSON.stringify(fieldName)})`;
306
- };
307
- // Errors: one tagged class per declared error, a runtime spec per class,
308
- // and per-root error unions (field errors ∪ global errors).
309
- const errorTags = Object.keys(model.errors).sort();
310
- const globalErrorType = `${sdkName}GlobalError`;
311
- const reserved = new Set([
312
- ...Object.keys(model.types),
313
- sdkName,
314
- `${sdkName}Error`,
315
- globalErrorType,
316
- "S",
317
- "Category",
318
- "Redacted",
319
- "errorFields",
320
- ]);
321
- for (const tag of errorTags) {
322
- if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tag))
323
- throw new Error(`GraphQL error tag ${tag} is not a valid identifier`);
324
- for (const name of [tag, `${tag}Spec`])
325
- if (reserved.has(name)) throw new Error(`GraphQL error ${tag} collides with ${name}`);
326
- }
327
- const globalErrors = [...model.globalErrors].sort();
328
- const rootErrors = (field: GraphQLField) => {
329
- const fieldOnly = [...new Set(field.errors)]
330
- .filter((tag) => !globalErrors.includes(tag))
331
- .sort();
332
- const type = union([...fieldOnly, globalErrorType]);
333
- const specs = fieldOnly.length
334
- ? `[${fieldOnly.map((tag) => `${tag}Spec`).join(", ")}, ...globalErrors]`
335
- : "globalErrors";
336
- return { type, specs };
337
- };
338
- const rootFn = (kind: "query" | "mutation", fieldName: string, field: GraphQLField): string => {
339
- const errors = rootErrors(field);
340
- const { name, list } = peelRef(field.type);
341
- const node = !list ? connectionNode(name) : undefined;
342
- const resultTs = tsOutput(field.type, field.sensitive);
343
- const argEntries = Object.entries(field.args);
344
- const argTypes =
345
- argEntries.length > 0
346
- ? `{ ${argEntries.map(([argName, arg]) => `${argName}: ${JSON.stringify(arg.type)}`).join(", ")} }`
347
- : undefined;
348
- const required = argEntries.filter(([, arg]) => arg.type.endsWith("!"));
349
- const optional = argEntries.filter(([, arg]) => !arg.type.endsWith("!"));
350
- const argFields = [
351
- ...required.map(([argName, arg]) => `readonly ${argName}: ${tsArg(arg.type)}`),
352
- ...optional.map(([argName, arg]) => `readonly ${argName}?: ${tsArg(arg.type)}`),
353
- ].join("; ");
354
- const sig =
355
- argEntries.length === 0
356
- ? ""
357
- : required.length === 0
358
- ? `args?: { ${argFields} }`
359
- : `args: { ${argFields} }`;
360
- const argsExpr = argEntries.length === 0 ? ", undefined" : ", args";
361
- const argTypesExpr = argTypes ? `, ${argTypes}` : ", undefined";
362
- const rest = `${argsExpr}${argTypesExpr}, ${errors.specs}${field.sensitive ? ", { sensitive: true }" : ""}`;
363
- const result = `Query<${resultTs}, ${errors.type}>`;
364
- const call = (helper: string, target: string) =>
365
- `${helper}(${JSON.stringify(kind)}, ${JSON.stringify(fieldName)}, ${target}${rest})`;
366
- const body = node
367
- ? call("rootConnection", node)
368
- : isObjectLike(name)
369
- ? call(list ? "rootList" : "root", name)
370
- : call("rootLeaf", String(list));
371
- return ` ${fieldName}: (${sig}): ${result} =>\n ${body},`;
372
- };
373
-
374
- const objects: string[] = [];
375
- const enums: string[] = [];
376
- const inputs: string[] = [];
377
- const unions: string[] = [];
378
- for (const [name, type] of Object.entries(model.types)) {
379
- if (name.startsWith("__") || skipRoots.has(name)) continue;
380
- if (type.kind === "OBJECT" || type.kind === "INTERFACE") objects.push(name);
381
- else if (type.kind === "ENUM") enums.push(name);
382
- else if (type.kind === "INPUT_OBJECT") inputs.push(name);
383
- else if (type.kind === "UNION") unions.push(name);
384
- }
385
- objects.sort();
386
- enums.sort();
387
- inputs.sort();
388
- unions.sort();
389
- // Field tables are module-private, so a taken name gets a suffix rather than an error.
390
- const taken = new Set([...reserved, ...errorTags.flatMap((tag) => [tag, `${tag}Spec`])]);
391
- const tables = new Map<string, string>();
392
- for (const name of objects) {
393
- let table = `${name}Fields`;
394
- while (taken.has(table)) table += "_";
395
- taken.add(table);
396
- tables.set(name, table);
397
- }
398
-
399
- const lines: string[] = [
400
- "// Generated by @distilled.cloud/core/codegen/graphql-client. DO NOT EDIT.",
401
- `import * as S from "effect/Schema";`,
402
- ...(Object.values(model.types).some((type) =>
403
- Object.values(type.fields ?? {}).some((field) => field.sensitive),
404
- )
405
- ? [`import type * as Redacted from "effect/Redacted";`]
406
- : []),
407
- `import * as Category from "@distilled.cloud/core/category";`,
408
- `import {`,
409
- ` connectionField,`,
410
- ` errorFields,`,
411
- ` errorSpec,`,
412
- ` listField,`,
413
- ` objectField,`,
414
- ` root,`,
415
- ` rootConnection,`,
416
- ` rootLeaf,`,
417
- ` rootList,`,
418
- ` scalarField,`,
419
- ` type ErrorSpec,`,
420
- ` type Query,`,
421
- ` type TypeMeta,`,
422
- `} from "@distilled.cloud/core/graphql";`,
423
- "",
424
- ];
425
-
426
- const categories: Record<string, string> = {
427
- auth: "withAuthError",
428
- badRequest: "withBadRequestError",
429
- notFound: "withNotFoundError",
430
- throttling: "withThrottlingError",
431
- quota: "withQuotaError",
432
- server: "withServerError",
433
- conflict: "withConflictError",
434
- };
435
- for (const tag of errorTags) {
436
- const error = model.errors[tag]!;
437
- if (error.category && !categories[error.category])
438
- throw new Error(`GraphQL error ${tag}: unknown category ${error.category}`);
439
- const pipes = [
440
- error.category ? `Category.${categories[error.category]}` : undefined,
441
- error.retryable
442
- ? `Category.withRetryable(${error.category === "throttling" ? "{ throttling: true }" : ""})`
443
- : undefined,
444
- ].filter(Boolean);
445
- const options = [
446
- error.retryable ? "retryable: true" : undefined,
447
- globalErrors.includes(tag) ? "global: true" : undefined,
448
- ].filter(Boolean);
449
- lines.push(
450
- documentation(error.description) +
451
- `export class ${tag} extends S.TaggedError<${tag}>()(${literal(tag)}, errorFields)${pipes.length ? `.pipe(${pipes.join(", ")})` : ""} {}`,
452
- `const ${tag}Spec: ErrorSpec<${tag}> = errorSpec(${tag}, ${literal(tag)}, ${JSON.stringify(error.matchers)}${options.length ? `, { ${options.join(", ")} }` : ""});`,
453
- "",
454
- );
455
- }
456
- lines.push(
457
- `/** Errors every ${sdkName} root field can return. */`,
458
- `export type ${globalErrorType} = ${union(globalErrors)};`,
459
- `const globalErrors: ReadonlyArray<ErrorSpec> = [${globalErrors.map((tag) => `${tag}Spec`).join(", ")}];`,
460
- "",
461
- `/** Every typed error the ${sdkName} SDK declares. */`,
462
- `export type ${sdkName}Error = ${union(errorTags)};`,
463
- "",
464
- );
465
-
466
- for (const name of enums) {
467
- const type = model.types[name]!;
468
- lines.push(
469
- documentation(type.description) +
470
- `export type ${name} = ${union((type.enumValues ?? []).map(literal))};`,
471
- "",
472
- );
473
- }
474
-
475
- for (const name of inputs) {
476
- const type = model.types[name]!;
477
- const fields = Object.entries(type.inputFields ?? {}).map(
478
- ([fieldName, field]) =>
479
- ` readonly ${fieldName}${field.type.endsWith("!") ? "" : "?"}: ${tsArg(field.type)};`,
480
- );
481
- lines.push(documentation(type.description) + `export interface ${name} {`, ...fields, "}", "");
482
- }
483
-
484
- for (const name of unions) {
485
- const type = model.types[name]!;
486
- lines.push(
487
- documentation(type.description) +
488
- `export type ${name} = ${(type.possibleTypes ?? []).join(" | ") || "unknown"};`,
489
- "",
490
- );
491
- }
492
-
493
- for (const name of objects) {
494
- const type = model.types[name]!;
495
- const fields = Object.entries(type.fields ?? {}).map(
496
- ([fieldName, field]) => ` readonly ${fieldName}: ${tsOutput(field.type, field.sensitive)};`,
497
- );
498
- lines.push(documentation(type.description) + `export interface ${name} {`, ...fields, "}", "");
499
- }
500
-
501
- for (const name of objects) {
502
- lines.push(
503
- `export const ${name}: TypeMeta = { name: ${JSON.stringify(name)}, get fields() { return ${tables.get(name)}; } };`,
504
- );
505
- }
506
- for (const name of unions) {
507
- lines.push(
508
- `export const ${name}: TypeMeta = { name: ${JSON.stringify(name)}, fields: { __typename: scalarField("__typename") } };`,
509
- );
510
- }
511
- lines.push("");
512
-
513
- for (const name of objects) {
514
- const type = model.types[name]!;
515
- lines.push(`const ${tables.get(name)}: TypeMeta["fields"] = {`);
516
- for (const [fieldName, field] of Object.entries(type.fields ?? {})) {
517
- lines.push(` ${fieldName}: ${fieldMeta(fieldName, field)},`);
518
- }
519
- lines.push("};", "");
520
- }
521
-
522
- lines.push(`export const ${sdkName} = {`);
523
- const queryNames = new Set<string>();
524
- const queryType = model.types[model.queryType];
525
- if (queryType?.fields) {
526
- for (const [fieldName, field] of Object.entries(queryType.fields)) {
527
- queryNames.add(fieldName);
528
- lines.push(rootFn("query", fieldName, field));
529
- }
530
- }
531
- if (model.mutationType) {
532
- const mutationType = model.types[model.mutationType];
533
- if (mutationType?.fields) {
534
- for (const [fieldName, field] of Object.entries(mutationType.fields)) {
535
- const exportName = queryNames.has(fieldName) ? `${fieldName}Mutation` : fieldName;
536
- const line = rootFn("mutation", fieldName, field);
537
- lines.push(
538
- exportName === fieldName ? line : line.replace(` ${fieldName}:`, ` ${exportName}:`),
539
- );
540
- }
541
- }
542
- }
543
- lines.push("};", "");
544
- return lines.join("\n") + "\n";
545
- };