@distilled.cloud/core 1.0.0-rc.1 → 1.0.0-rc.11

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 (148) hide show
  1. package/LICENSE +201 -0
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +16 -4
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts +4 -4
  6. package/lib/category.js +4 -4
  7. package/lib/codegen/boolean-string-enums.d.ts +36 -0
  8. package/lib/codegen/boolean-string-enums.d.ts.map +1 -0
  9. package/lib/codegen/boolean-string-enums.js +94 -0
  10. package/lib/codegen/boolean-string-enums.js.map +1 -0
  11. package/lib/codegen/boolean-string-enums.test.d.ts +2 -0
  12. package/lib/codegen/boolean-string-enums.test.d.ts.map +1 -0
  13. package/lib/codegen/boolean-string-enums.test.js +147 -0
  14. package/lib/codegen/boolean-string-enums.test.js.map +1 -0
  15. package/lib/codegen/cli.d.ts +56 -6
  16. package/lib/codegen/cli.d.ts.map +1 -1
  17. package/lib/codegen/cli.js +59 -75
  18. package/lib/codegen/cli.js.map +1 -1
  19. package/lib/codegen/emit.d.ts +3 -7
  20. package/lib/codegen/emit.d.ts.map +1 -1
  21. package/lib/codegen/emit.js +6 -10
  22. package/lib/codegen/emit.js.map +1 -1
  23. package/lib/codegen/generator.d.ts.map +1 -1
  24. package/lib/codegen/generator.js +142 -20
  25. package/lib/codegen/generator.js.map +1 -1
  26. package/lib/codegen/graphql-client.d.ts +62 -0
  27. package/lib/codegen/graphql-client.d.ts.map +1 -0
  28. package/lib/codegen/graphql-client.js +294 -0
  29. package/lib/codegen/graphql-client.js.map +1 -0
  30. package/lib/codegen/graphql-client.test.d.ts +2 -0
  31. package/lib/codegen/graphql-client.test.d.ts.map +1 -0
  32. package/lib/codegen/graphql-client.test.js +311 -0
  33. package/lib/codegen/graphql-client.test.js.map +1 -0
  34. package/lib/codegen/graphql.d.ts +207 -0
  35. package/lib/codegen/graphql.d.ts.map +1 -0
  36. package/lib/codegen/graphql.js +799 -0
  37. package/lib/codegen/graphql.js.map +1 -0
  38. package/lib/codegen/openapi-cli.d.ts +17 -3
  39. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  40. package/lib/codegen/openapi-cli.js +50 -48
  41. package/lib/codegen/openapi-cli.js.map +1 -1
  42. package/lib/codegen/openapi.d.ts +69 -6
  43. package/lib/codegen/openapi.d.ts.map +1 -1
  44. package/lib/codegen/openapi.js +173 -16
  45. package/lib/codegen/openapi.js.map +1 -1
  46. package/lib/codegen/patches.d.ts +65 -0
  47. package/lib/codegen/patches.d.ts.map +1 -0
  48. package/lib/codegen/patches.js +236 -0
  49. package/lib/codegen/patches.js.map +1 -0
  50. package/lib/codegen/patches.test.d.ts +2 -0
  51. package/lib/codegen/patches.test.d.ts.map +1 -0
  52. package/lib/codegen/patches.test.js +105 -0
  53. package/lib/codegen/patches.test.js.map +1 -0
  54. package/lib/codegen/proto.d.ts +121 -0
  55. package/lib/codegen/proto.d.ts.map +1 -0
  56. package/lib/codegen/proto.js +962 -0
  57. package/lib/codegen/proto.js.map +1 -0
  58. package/lib/codegen/rewrite-operation-ids.d.ts +131 -0
  59. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -0
  60. package/lib/codegen/rewrite-operation-ids.js +1079 -0
  61. package/lib/codegen/rewrite-operation-ids.js.map +1 -0
  62. package/lib/codegen/rewrite-operation-ids.test.d.ts +2 -0
  63. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +1 -0
  64. package/lib/codegen/rewrite-operation-ids.test.js +533 -0
  65. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -0
  66. package/lib/codegen/spec-path.d.ts +16 -0
  67. package/lib/codegen/spec-path.d.ts.map +1 -0
  68. package/lib/codegen/spec-path.js +101 -0
  69. package/lib/codegen/spec-path.js.map +1 -0
  70. package/lib/errors.d.ts.map +1 -1
  71. package/lib/errors.js +17 -13
  72. package/lib/errors.js.map +1 -1
  73. package/lib/graphql.d.ts +284 -0
  74. package/lib/graphql.d.ts.map +1 -0
  75. package/lib/graphql.fixture.d.ts +249 -0
  76. package/lib/graphql.fixture.d.ts.map +1 -0
  77. package/lib/graphql.fixture.js +240 -0
  78. package/lib/graphql.fixture.js.map +1 -0
  79. package/lib/graphql.js +718 -0
  80. package/lib/graphql.js.map +1 -0
  81. package/lib/graphql.test.d.ts +2 -0
  82. package/lib/graphql.test.d.ts.map +1 -0
  83. package/lib/graphql.test.js +780 -0
  84. package/lib/graphql.test.js.map +1 -0
  85. package/lib/graphql.types.d.ts +2 -0
  86. package/lib/graphql.types.d.ts.map +1 -0
  87. package/lib/graphql.types.js +45 -0
  88. package/lib/graphql.types.js.map +1 -0
  89. package/lib/json-patch.d.ts +18 -11
  90. package/lib/json-patch.d.ts.map +1 -1
  91. package/lib/json-patch.js +63 -25
  92. package/lib/json-patch.js.map +1 -1
  93. package/lib/pagination.d.ts +43 -3
  94. package/lib/pagination.d.ts.map +1 -1
  95. package/lib/pagination.js +91 -5
  96. package/lib/pagination.js.map +1 -1
  97. package/lib/protocol-http.d.ts.map +1 -1
  98. package/lib/protocol-http.js +62 -26
  99. package/lib/protocol-http.js.map +1 -1
  100. package/lib/protocol-http.test.d.ts +2 -0
  101. package/lib/protocol-http.test.d.ts.map +1 -0
  102. package/lib/protocol-http.test.js +88 -0
  103. package/lib/protocol-http.test.js.map +1 -0
  104. package/lib/protocol-rest.d.ts +12 -2
  105. package/lib/protocol-rest.d.ts.map +1 -1
  106. package/lib/protocol-rest.js +17 -3
  107. package/lib/protocol-rest.js.map +1 -1
  108. package/lib/retry.js +1 -1
  109. package/lib/schema.d.ts +1 -1
  110. package/lib/schema.d.ts.map +1 -1
  111. package/lib/schema.js +1 -1
  112. package/lib/schema.js.map +1 -1
  113. package/lib/trait.d.ts +27 -3
  114. package/lib/trait.d.ts.map +1 -1
  115. package/lib/trait.js +17 -1
  116. package/lib/trait.js.map +1 -1
  117. package/package.json +13 -10
  118. package/src/api.ts +18 -4
  119. package/src/category.ts +4 -4
  120. package/src/codegen/boolean-string-enums.test.ts +168 -0
  121. package/src/codegen/boolean-string-enums.ts +106 -0
  122. package/src/codegen/cli.ts +127 -110
  123. package/src/codegen/emit.ts +6 -10
  124. package/src/codegen/generator.ts +151 -21
  125. package/src/codegen/graphql-client.test.ts +386 -0
  126. package/src/codegen/graphql-client.ts +419 -0
  127. package/src/codegen/graphql.ts +1217 -0
  128. package/src/codegen/openapi-cli.ts +75 -59
  129. package/src/codegen/openapi.ts +255 -16
  130. package/src/codegen/patches.test.ts +130 -0
  131. package/src/codegen/patches.ts +291 -0
  132. package/src/codegen/proto.ts +1128 -0
  133. package/src/codegen/rewrite-operation-ids.test.ts +563 -0
  134. package/src/codegen/rewrite-operation-ids.ts +1206 -0
  135. package/src/codegen/spec-path.ts +115 -0
  136. package/src/errors.ts +20 -25
  137. package/src/graphql.fixture.ts +371 -0
  138. package/src/graphql.test.ts +974 -0
  139. package/src/graphql.ts +1321 -0
  140. package/src/graphql.types.ts +185 -0
  141. package/src/json-patch.ts +82 -25
  142. package/src/pagination.ts +134 -7
  143. package/src/protocol-http.test.ts +107 -0
  144. package/src/protocol-http.ts +67 -31
  145. package/src/protocol-rest.ts +28 -4
  146. package/src/retry.ts +1 -1
  147. package/src/schema.ts +2 -2
  148. package/src/trait.ts +39 -3
@@ -0,0 +1,799 @@
1
+ /**
2
+ * Shared GraphQL → Smithy 2.0 converter (dev-time only).
3
+ *
4
+ * A GraphQL endpoint has no per-operation URLs, no path/query/header bindings
5
+ * and no response shapes to speak of: there is one POST, one request envelope
6
+ * (`{ query, operationName, variables }`) and one response envelope
7
+ * (`{ data, errors }`). What varies per operation is the *document* — which
8
+ * root field is called, which variables it takes, and which selection set
9
+ * comes back. This module turns an introspection schema into a Smithy model
10
+ * carrying exactly that:
11
+ *
12
+ * • operation → `smithy.api#http` (POST <endpoint>) + the op shape
13
+ * • input struct → `<traits.operation>` { query, operationName, type } —
14
+ * the baked GraphQL document for the op
15
+ * • output struct → `<traits.responsePath>` ("account.byId") — the path
16
+ * under `data` the protocol unwraps
17
+ * • nullability → `<traits.nullable>` on members,
18
+ * `<traits.nullableItems>` on list shapes (GraphQL
19
+ * nullability is not Smithy optionality: a selected
20
+ * field is always *delivered*, it just may be `null`)
21
+ * • bare results → `<traits.payload>` on the sole `result` member when
22
+ * the leaf returns a list/scalar (the response IS that
23
+ * value)
24
+ * • connections → `smithy.api#paginated` when a root field looks like a
25
+ * Relay connection (see {@link RelayOptions})
26
+ *
27
+ * Trait *ids* are caller-supplied so each SDK keeps its own vocabulary
28
+ * namespace; the generator side maps them back to that SDK's trait module.
29
+ *
30
+ * ─── Operation discovery ────────────────────────────────────────────────────
31
+ * Most schemas put operations directly on Query/Mutation, but some namespace
32
+ * them behind objects whose fields are the real operations (`account.byId`).
33
+ * `maxNamespaceDepth` bounds how far that expansion goes; set it to 1 for a
34
+ * flat schema. Selection sets are expanded to `maxDepth` levels, cycles
35
+ * short-circuit, and fields that themselves take arguments are not selected
36
+ * (we have no value to pass them).
37
+ *
38
+ * Originally distilled v0's `core/scripts/generate-graphql.ts`, generalized
39
+ * out of packages/expo-eas.
40
+ */
41
+ import { toVerbNoun } from "./rewrite-operation-ids.js";
42
+ /**
43
+ * Pull the `__schema` out of an introspection response, accepting either the
44
+ * bare schema, `{ __schema }`, or a full `{ data: { __schema } }` envelope —
45
+ * all three are shipped by real mirrors.
46
+ */
47
+ export const readIntrospection = (json) => {
48
+ const j = json;
49
+ const schema = j?.data?.__schema ?? j?.__schema ?? (j?.types ? j : undefined);
50
+ if (!schema) {
51
+ throw new Error("introspection JSON has none of `data.__schema`, `__schema`, or a top-level `types`");
52
+ }
53
+ return schema;
54
+ };
55
+ // ============================================================================
56
+ // Smithy prelude targets
57
+ // ============================================================================
58
+ export const PRELUDE = {
59
+ String: "smithy.api#String",
60
+ Boolean: "smithy.api#Boolean",
61
+ Integer: "smithy.api#Integer",
62
+ Long: "smithy.api#Long",
63
+ Double: "smithy.api#Double",
64
+ Timestamp: "smithy.api#Timestamp",
65
+ Document: "smithy.api#Document",
66
+ };
67
+ /** The five scalars every GraphQL schema has. */
68
+ const BUILTIN_SCALARS = {
69
+ String: PRELUDE.String,
70
+ ID: PRELUDE.String,
71
+ Int: PRELUDE.Integer,
72
+ Float: PRELUDE.Double,
73
+ Boolean: PRELUDE.Boolean,
74
+ };
75
+ // ============================================================================
76
+ // Small helpers
77
+ // ============================================================================
78
+ const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
79
+ const toPascalCase = (s) => capitalize(s.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()));
80
+ const unwrapNonNull = (t) => t.kind === "NON_NULL" && t.ofType
81
+ ? { type: t.ofType, nonNull: true }
82
+ : { type: t, nonNull: false };
83
+ /** Render a GraphQL type ref back to its SDL form (e.g. `[ID!]!`). */
84
+ const renderTypeRef = (t) => {
85
+ if (t.kind === "NON_NULL" && t.ofType)
86
+ return `${renderTypeRef(t.ofType)}!`;
87
+ if (t.kind === "LIST" && t.ofType)
88
+ return `[${renderTypeRef(t.ofType)}]`;
89
+ return t.name ?? "Unknown";
90
+ };
91
+ const local = (id) => id.split("#")[1] ?? id;
92
+ const memberIdent = (name) => {
93
+ let out = name.replace(/[^A-Za-z0-9_]/g, "_");
94
+ if (/^[0-9]/.test(out))
95
+ out = `_${out}`;
96
+ return out || "_";
97
+ };
98
+ const enumMemberName = (value) => {
99
+ let out = value
100
+ .toUpperCase()
101
+ .replace(/[^A-Z0-9]+/g, "_")
102
+ .replace(/^_+|_+$/g, "");
103
+ if (out === "")
104
+ out = "VALUE";
105
+ if (/^[0-9]/.test(out))
106
+ out = `_${out}`;
107
+ return out;
108
+ };
109
+ const oneLineDoc = (s) => {
110
+ const t = s?.replace(/\s+/g, " ").trim();
111
+ return t ? t : undefined;
112
+ };
113
+ /** Strip NON_NULL and LIST wrappers down to the named type underneath. */
114
+ const namedType = (ref) => {
115
+ let t = unwrapNonNull(ref).type;
116
+ while (t.kind === "LIST" && t.ofType)
117
+ t = unwrapNonNull(t.ofType).type;
118
+ return t;
119
+ };
120
+ const RELAY_DEFAULTS = {
121
+ after: "after",
122
+ first: "first",
123
+ edges: "edges",
124
+ node: "node",
125
+ pageInfo: "pageInfo",
126
+ endCursor: "endCursor",
127
+ hasNextPage: "hasNextPage",
128
+ mode: "relay",
129
+ };
130
+ const makeRelayCtx = (cfg, typeMap) => {
131
+ const connections = new Map();
132
+ const edges = new Set();
133
+ const pageInfos = new Set();
134
+ const isConnection = (name) => {
135
+ if (!name)
136
+ return false;
137
+ const cached = connections.get(name);
138
+ if (cached !== undefined)
139
+ return cached;
140
+ // Register `false` first: a connection whose node type circles back to
141
+ // the connection must not recurse forever.
142
+ connections.set(name, false);
143
+ const t = typeMap.get(name);
144
+ const fields = t?.kind === "OBJECT" ? (t.fields ?? []) : [];
145
+ const edgesField = fields.find((f) => f.name === cfg.edges);
146
+ const pageInfoField = fields.find((f) => f.name === cfg.pageInfo);
147
+ if (!edgesField || !pageInfoField)
148
+ return false;
149
+ const edgeName = namedType(edgesField.type).name;
150
+ const edgeType = edgeName ? typeMap.get(edgeName) : undefined;
151
+ const hasNode = (edgeType?.fields ?? []).some((f) => f.name === cfg.node);
152
+ if (!hasNode)
153
+ return false;
154
+ const pageInfoName = namedType(pageInfoField.type).name;
155
+ const pageInfoType = pageInfoName ? typeMap.get(pageInfoName) : undefined;
156
+ const hasCursor = (pageInfoType?.fields ?? []).some((f) => f.name === cfg.endCursor);
157
+ if (!hasCursor)
158
+ return false;
159
+ connections.set(name, true);
160
+ if (edgeName)
161
+ edges.add(edgeName);
162
+ if (pageInfoName)
163
+ pageInfos.add(pageInfoName);
164
+ return true;
165
+ };
166
+ // `edges`/`pageInfo` sets are populated as a side effect of recognizing
167
+ // their connection, so classify every object type once up front.
168
+ for (const t of typeMap.values()) {
169
+ if (t.kind === "OBJECT")
170
+ isConnection(t.name);
171
+ }
172
+ return {
173
+ cfg,
174
+ isConnection,
175
+ isEdge: (name) => (name ? edges.has(name) : false),
176
+ isPageInfo: (name) => (name ? pageInfos.has(name) : false),
177
+ };
178
+ };
179
+ /**
180
+ * Whether stepping from `parentTypeName` into `fieldName` should spend a
181
+ * level of the depth budget.
182
+ *
183
+ * A Relay connection is pure plumbing: `edges { node { … } }` is three
184
+ * nesting levels that carry one level of *meaning*. Charging them against
185
+ * `maxDepth` would leave nothing for the node itself, so the connection
186
+ * wrapper is traversed transparently and the node lands at the depth the
187
+ * connection occupied.
188
+ */
189
+ const isTransparentHop = (ctx, parentTypeName, fieldName) => {
190
+ const relay = ctx.relay;
191
+ if (!relay || !parentTypeName)
192
+ return false;
193
+ if (relay.isConnection(parentTypeName)) {
194
+ return fieldName === relay.cfg.edges || fieldName === relay.cfg.pageInfo;
195
+ }
196
+ if (relay.isEdge(parentTypeName))
197
+ return fieldName === relay.cfg.node;
198
+ return false;
199
+ };
200
+ /**
201
+ * Recursively expand the selection set for an object/interface return type up
202
+ * to `maxDepth` levels. Scalars/enums become leaves. Cycles short-circuit by
203
+ * tracking type names through `seen`.
204
+ */
205
+ const expandSelection = (ref, ctx, depth, maxDepth, seen) => {
206
+ const { type } = unwrapNonNull(ref);
207
+ if (type.kind === "LIST" && type.ofType) {
208
+ return expandSelection(type.ofType, ctx, depth, maxDepth, seen);
209
+ }
210
+ if (type.kind !== "OBJECT" && type.kind !== "INTERFACE")
211
+ return undefined;
212
+ if (!type.name)
213
+ return undefined;
214
+ if (seen.has(type.name))
215
+ return undefined;
216
+ if (depth > maxDepth)
217
+ return undefined;
218
+ const concrete = ctx.typeMap.get(type.name);
219
+ if (!concrete?.fields)
220
+ return undefined;
221
+ const nextSeen = new Set([...seen, type.name]);
222
+ const result = [];
223
+ for (const field of concrete.fields) {
224
+ // Skip fields that themselves require args — without user input we can't
225
+ // safely populate them, so we just don't select them.
226
+ if (field.args && field.args.length > 0)
227
+ continue;
228
+ const { type: fieldType } = unwrapNonNull(field.type);
229
+ let actualType = fieldType;
230
+ if (actualType.kind === "LIST" && actualType.ofType) {
231
+ actualType = unwrapNonNull(actualType.ofType).type;
232
+ }
233
+ let children;
234
+ if (actualType.kind === "OBJECT" || actualType.kind === "INTERFACE") {
235
+ const transparent = isTransparentHop(ctx, type.name, field.name);
236
+ children = expandSelection(field.type, ctx, transparent ? depth : depth + 1, maxDepth, nextSeen);
237
+ if (!children || children.length === 0) {
238
+ // Can't recurse further — skip nested object fields beyond depth.
239
+ continue;
240
+ }
241
+ }
242
+ else if (actualType.kind === "UNION") {
243
+ // Unions need fragments to select fields — skip for the generic walker.
244
+ continue;
245
+ }
246
+ result.push({ name: field.name, type: field.type, children });
247
+ }
248
+ return result;
249
+ };
250
+ /** Render a SelectionField list as a GraphQL selection-set string. */
251
+ const renderSelectionSet = (fields, indent) => fields
252
+ .map((f) => f.children && f.children.length > 0
253
+ ? `${indent}${f.name} {\n${renderSelectionSet(f.children, indent + " ")}\n${indent}}`
254
+ : `${indent}${f.name}`)
255
+ .join("\n");
256
+ /**
257
+ * Decide how to emit operations for a top-level Query/Mutation field.
258
+ *
259
+ * - If selection-set expansion produces real subfields, emit a single op for
260
+ * this path.
261
+ * - If the field's return type is an OBJECT/INTERFACE whose subfields all
262
+ * require args (a "namespace" pattern), recurse into each subfield and
263
+ * emit one op per leaf.
264
+ * - Otherwise emit one op for the field directly (scalar/enum return types).
265
+ */
266
+ const collectOperationPaths = (field, parentChain, ctx, maxNamespaceDepth, skipDeprecated) => {
267
+ const step = {
268
+ name: field.name,
269
+ args: field.args ?? [],
270
+ returnType: field.type,
271
+ };
272
+ const chain = [...parentChain, step];
273
+ // Try to expand the selection set on this field's return type. If we get a
274
+ // real selection, emit a single op terminating here.
275
+ const selection = expandSelection(field.type, ctx, 1, 3, new Set());
276
+ if (selection && selection.length > 0) {
277
+ return [chain];
278
+ }
279
+ // No selection: this is either a namespace-style field or a scalar leaf.
280
+ const { type: returnType } = unwrapNonNull(field.type);
281
+ let actualReturn = returnType;
282
+ if (actualReturn.kind === "LIST" && actualReturn.ofType) {
283
+ actualReturn = unwrapNonNull(actualReturn.ofType).type;
284
+ }
285
+ const isObject = (actualReturn.kind === "OBJECT" || actualReturn.kind === "INTERFACE") &&
286
+ !!actualReturn.name;
287
+ if (!isObject || chain.length >= maxNamespaceDepth) {
288
+ return [chain];
289
+ }
290
+ const namespaceType = ctx.typeMap.get(actualReturn.name);
291
+ if (!namespaceType?.fields || namespaceType.fields.length === 0) {
292
+ return [chain];
293
+ }
294
+ const paths = [];
295
+ for (const subfield of namespaceType.fields) {
296
+ if (skipDeprecated && subfield.isDeprecated)
297
+ continue;
298
+ paths.push(...collectOperationPaths(subfield, chain, ctx, maxNamespaceDepth, skipDeprecated));
299
+ }
300
+ return paths.length > 0 ? paths : [chain];
301
+ };
302
+ /**
303
+ * Build the operation function name from a path: `channels.byId` →
304
+ * `channelsById`.
305
+ */
306
+ const pathToFunctionName = (opPath) => {
307
+ if (opPath.length === 0)
308
+ throw new Error("empty path");
309
+ if (opPath.length === 1)
310
+ return opPath[0].name;
311
+ return (opPath[0].name +
312
+ opPath
313
+ .slice(1)
314
+ .map((s) => toPascalCase(s.name))
315
+ .join(""));
316
+ };
317
+ /**
318
+ * Resolve variable-name collisions across path segments: a later segment's
319
+ * clashing arg is renamed `<stepName><ArgName>` (then numbered).
320
+ */
321
+ const buildArgRenames = (opPath) => {
322
+ const argRenames = new Map();
323
+ const usedVarNames = new Set();
324
+ for (const step of opPath) {
325
+ for (const arg of step.args) {
326
+ let varName = arg.name;
327
+ if (usedVarNames.has(varName)) {
328
+ varName = `${step.name}${toPascalCase(arg.name)}`;
329
+ let i = 2;
330
+ while (usedVarNames.has(varName)) {
331
+ varName = `${step.name}${toPascalCase(arg.name)}${i++}`;
332
+ }
333
+ }
334
+ usedVarNames.add(varName);
335
+ argRenames.set(`${step.name}.${arg.name}`, varName);
336
+ }
337
+ }
338
+ return argRenames;
339
+ };
340
+ /**
341
+ * Build the GraphQL document string for an operation walking through `path`.
342
+ * Variables are scoped to the OUTER operation; each step that has args
343
+ * references those variables by (renamed) name.
344
+ */
345
+ const buildPathDocument = (type, operationName, opPath, selection, argRenames) => {
346
+ const varDefs = [];
347
+ for (const step of opPath) {
348
+ for (const arg of step.args) {
349
+ const varName = argRenames.get(`${step.name}.${arg.name}`) ?? arg.name;
350
+ varDefs.push(`$${varName}: ${renderTypeRef(arg.type)}`);
351
+ }
352
+ }
353
+ const header = varDefs.length
354
+ ? `${type} ${operationName}(${varDefs.join(", ")})`
355
+ : `${type} ${operationName}`;
356
+ const renderStep = (step, inner, indent) => {
357
+ const argList = step.args
358
+ .map((arg) => {
359
+ const varName = argRenames.get(`${step.name}.${arg.name}`) ?? arg.name;
360
+ return `${arg.name}: $${varName}`;
361
+ })
362
+ .join(", ");
363
+ const call = argList ? `${step.name}(${argList})` : step.name;
364
+ return `${indent}${call} {\n${inner}\n${indent}}`;
365
+ };
366
+ let body;
367
+ const innerIndent = " ".repeat(opPath.length + 1);
368
+ if (selection && selection.length > 0) {
369
+ body = renderSelectionSet(selection, innerIndent);
370
+ }
371
+ else {
372
+ // No selectable subfields — fall back to __typename so the document is
373
+ // always syntactically valid.
374
+ body = `${innerIndent}__typename`;
375
+ }
376
+ let nested = body;
377
+ for (let i = opPath.length - 1; i >= 0; i--) {
378
+ const indent = " ".repeat(i + 1);
379
+ nested = renderStep(opPath[i], nested, indent);
380
+ }
381
+ return `${header} {\n${nested}\n}`;
382
+ };
383
+ /** Add a shape under a unique PascalCase-ish name; returns its shape id. */
384
+ const addShape = (bag, base, def) => {
385
+ let want = memberIdent(base);
386
+ want = capitalize(want);
387
+ let name = want;
388
+ let n = 2;
389
+ while (bag.names.has(name))
390
+ name = `${want}${n++}`;
391
+ bag.names.add(name);
392
+ const id = `${bag.namespace}#${name}`;
393
+ bag.shapes[id] = def;
394
+ return id;
395
+ };
396
+ /** Add a shape under an exact (pre-reserved) name. */
397
+ const addExact = (bag, name, def) => {
398
+ const id = `${bag.namespace}#${name}`;
399
+ bag.shapes[id] = def;
400
+ return id;
401
+ };
402
+ const makeConverter = (bag, ctx, traits, customScalars) => {
403
+ const enumMemo = new Map();
404
+ const inputMemo = new Map();
405
+ const inputListMemo = new Map();
406
+ const scalarTarget = (name) => BUILTIN_SCALARS[name] ?? customScalars[name] ?? PRELUDE.Document;
407
+ const enumShape = (name) => {
408
+ const cached = enumMemo.get(name);
409
+ if (cached)
410
+ return cached;
411
+ const t = ctx.typeMap.get(name);
412
+ const members = {};
413
+ const used = new Set();
414
+ for (const v of t?.enumValues ?? []) {
415
+ let mn = enumMemberName(v.name);
416
+ let k = 2;
417
+ while (used.has(mn))
418
+ mn = `${enumMemberName(v.name)}_${k++}`;
419
+ used.add(mn);
420
+ members[mn] = {
421
+ target: "smithy.api#Unit",
422
+ traits: { "smithy.api#enumValue": v.name },
423
+ };
424
+ }
425
+ const id = addShape(bag, name, { type: "enum", members });
426
+ enumMemo.set(name, id);
427
+ return id;
428
+ };
429
+ const inputTypeTarget = (ref) => {
430
+ const { type, nonNull } = unwrapNonNull(ref);
431
+ const nullable = !nonNull;
432
+ if (type.kind === "LIST" && type.ofType) {
433
+ const elem = inputTypeTarget(type.ofType);
434
+ const key = `${elem.target}|${elem.nullable}`;
435
+ let listId = inputListMemo.get(key);
436
+ if (!listId) {
437
+ listId = addShape(bag, `${local(elem.target)}List`, {
438
+ type: "list",
439
+ member: { target: elem.target },
440
+ ...(elem.nullable ? { traits: { [traits.nullableItems]: {} } } : {}),
441
+ });
442
+ inputListMemo.set(key, listId);
443
+ }
444
+ return { target: listId, nullable };
445
+ }
446
+ if (type.kind === "SCALAR" && type.name) {
447
+ return { target: scalarTarget(type.name), nullable };
448
+ }
449
+ if (type.kind === "ENUM" && type.name) {
450
+ return { target: enumShape(type.name), nullable };
451
+ }
452
+ if (type.kind === "INPUT_OBJECT" && type.name) {
453
+ return { target: inputObjectShape(type.name), nullable };
454
+ }
455
+ return { target: PRELUDE.Document, nullable };
456
+ };
457
+ const inputObjectShape = (name) => {
458
+ const cached = inputMemo.get(name);
459
+ if (cached)
460
+ return cached;
461
+ const t = ctx.typeMap.get(name);
462
+ // Register before filling members so input-object cycles resolve to the
463
+ // shared shape (named smithy shapes reference each other naturally).
464
+ const def = { type: "structure", members: {} };
465
+ const id = addShape(bag, name, def);
466
+ inputMemo.set(name, id);
467
+ const doc = oneLineDoc(t?.description);
468
+ if (doc)
469
+ def.traits = { "smithy.api#documentation": doc };
470
+ for (const f of t?.inputFields ?? []) {
471
+ const { nonNull } = unwrapNonNull(f.type);
472
+ const { target, nullable } = inputTypeTarget(f.type);
473
+ const memberTraits = {};
474
+ if (nonNull)
475
+ memberTraits["smithy.api#required"] = {};
476
+ if (nullable)
477
+ memberTraits[traits.nullable] = {};
478
+ const fdoc = oneLineDoc(f.description);
479
+ if (fdoc)
480
+ memberTraits["smithy.api#documentation"] = fdoc;
481
+ def.members[memberIdent(f.name)] = {
482
+ target,
483
+ ...(Object.keys(memberTraits).length ? { traits: memberTraits } : {}),
484
+ };
485
+ }
486
+ return id;
487
+ };
488
+ return {
489
+ bag,
490
+ ctx,
491
+ traits,
492
+ scalarTarget,
493
+ enumShape,
494
+ inputObjectShape,
495
+ inputTypeTarget,
496
+ };
497
+ };
498
+ /**
499
+ * Output type ref + selection → { smithy target, GraphQL-nullability }.
500
+ * Selection structs are per-operation (hint-named); enums are shared.
501
+ */
502
+ const buildOutputTarget = (conv, ref, children, hint) => {
503
+ const { type, nonNull } = unwrapNonNull(ref);
504
+ const nullable = !nonNull;
505
+ if (type.kind === "LIST" && type.ofType) {
506
+ const elem = buildOutputTarget(conv, type.ofType, children, `${hint}Item`);
507
+ const target = addShape(conv.bag, `${hint}List`, {
508
+ type: "list",
509
+ member: { target: elem.target },
510
+ ...(elem.nullable ? { traits: { [conv.traits.nullableItems]: {} } } : {}),
511
+ });
512
+ return { target, nullable };
513
+ }
514
+ if (type.kind === "SCALAR" && type.name) {
515
+ return { target: conv.scalarTarget(type.name), nullable };
516
+ }
517
+ if (type.kind === "ENUM" && type.name) {
518
+ return { target: conv.enumShape(type.name), nullable };
519
+ }
520
+ if ((type.kind === "OBJECT" || type.kind === "INTERFACE") &&
521
+ children &&
522
+ children.length > 0) {
523
+ const members = buildSelectionMembers(conv, children, hint);
524
+ const target = addShape(conv.bag, hint, { type: "structure", members });
525
+ return { target, nullable };
526
+ }
527
+ // UNION, selection-less objects, unknowns → opaque.
528
+ return { target: PRELUDE.Document, nullable };
529
+ };
530
+ /**
531
+ * Structure members for a selection set. Every selected field is delivered
532
+ * by the server (always present), so members are `required`; GraphQL
533
+ * nullability travels as the `nullable` trait.
534
+ */
535
+ const buildSelectionMembers = (conv, fields, hint) => {
536
+ const members = {};
537
+ for (const f of fields) {
538
+ const sub = buildOutputTarget(conv, f.type, f.children, `${hint}${toPascalCase(f.name)}`);
539
+ const memberTraits = { "smithy.api#required": {} };
540
+ if (sub.nullable)
541
+ memberTraits[conv.traits.nullable] = {};
542
+ members[memberIdent(f.name)] = { target: sub.target, traits: memberTraits };
543
+ }
544
+ return members;
545
+ };
546
+ /**
547
+ * Turn a GraphQL introspection schema into a Smithy 2.0 model.
548
+ *
549
+ * Subscriptions are ignored: they are a streaming transport, not a
550
+ * `POST /graphql` request/response pair, and nothing in the generated SDK
551
+ * could speak them.
552
+ */
553
+ export const convertGraphQLToSmithy = (options) => {
554
+ const { schema, namespace, serviceName, serviceTitle, serviceDocumentation, serviceVersion = "1.0", endpoint, traits, maxDepth = 3, maxNamespaceDepth = 3, skipDeprecated = true, skipRootField = () => false, customScalars = {}, relay = false, operationNaming = "verbNoun", } = options;
555
+ const typeMap = new Map();
556
+ for (const t of schema.types)
557
+ typeMap.set(t.name, t);
558
+ const relayCfg = relay
559
+ ? { ...RELAY_DEFAULTS, ...relay }
560
+ : undefined;
561
+ const ctx = {
562
+ typeMap,
563
+ relay: relayCfg ? makeRelayCtx(relayCfg, typeMap) : undefined,
564
+ };
565
+ // ---- Discover operation paths (queries first, then mutations; names are
566
+ // deduped globally so a query and a mutation can't collide) ----
567
+ const pending = [];
568
+ const seenNames = new Set();
569
+ const collectRoot = (rootTypeName, type) => {
570
+ const rootType = typeMap.get(rootTypeName);
571
+ if (!rootType?.fields)
572
+ return;
573
+ for (const field of rootType.fields) {
574
+ if (skipDeprecated && field.isDeprecated)
575
+ continue;
576
+ if (skipRootField(field.name))
577
+ continue;
578
+ const paths = collectOperationPaths(field, [], ctx, maxNamespaceDepth, skipDeprecated);
579
+ for (const opPath of paths) {
580
+ const functionName = pathToFunctionName(opPath);
581
+ const sdkName = operationNaming === "verbNoun"
582
+ ? toVerbNoun(functionName)
583
+ : functionName;
584
+ if (seenNames.has(sdkName)) {
585
+ // Two schema fields (or the same field under two paths) map to
586
+ // one SDK name; the first wins. Silent drops hide real ops.
587
+ if (sdkName !== functionName) {
588
+ console.warn(` ⚠️ verbNoun collision: ${functionName} → ${sdkName} already taken (dropped)`);
589
+ }
590
+ continue;
591
+ }
592
+ seenNames.add(sdkName);
593
+ pending.push({
594
+ functionName,
595
+ opName: toPascalCase(sdkName),
596
+ type,
597
+ path: opPath,
598
+ description: opPath.length === 1 ? oneLineDoc(field.description) : undefined,
599
+ });
600
+ }
601
+ }
602
+ };
603
+ collectRoot(schema.queryType.name, "query");
604
+ if (schema.mutationType)
605
+ collectRoot(schema.mutationType.name, "mutation");
606
+ // ---- Build the smithy model ----
607
+ const bag = { shapes: {}, names: new Set(), namespace };
608
+ // Reserve the op-derived shape names up front so lazily-created shared
609
+ // type shapes (enums, input objects) can never steal them — the operation
610
+ // shape's local name IS the exported const name (via lowerFirst).
611
+ bag.names.add(serviceName);
612
+ for (const op of pending) {
613
+ bag.names.add(op.opName);
614
+ bag.names.add(`${op.opName}Request`);
615
+ bag.names.add(`${op.opName}Response`);
616
+ }
617
+ const conv = makeConverter(bag, ctx, traits, customScalars);
618
+ const serviceOps = [];
619
+ let converted = 0;
620
+ let failed = 0;
621
+ let paginated = 0;
622
+ for (const op of pending) {
623
+ try {
624
+ const argRenames = buildArgRenames(op.path);
625
+ const leaf = op.path[op.path.length - 1];
626
+ const selection = expandSelection(leaf.returnType, ctx, 1, maxDepth, new Set());
627
+ const document = buildPathDocument(op.type, op.functionName, op.path, selection, argRenames);
628
+ const responsePath = op.path.map((s) => s.name).join(".");
629
+ // ---- Input (the GraphQL variables) ----
630
+ const inputMembers = {};
631
+ for (const step of op.path) {
632
+ for (const arg of step.args) {
633
+ const varName = argRenames.get(`${step.name}.${arg.name}`);
634
+ const { nonNull } = unwrapNonNull(arg.type);
635
+ const { target, nullable } = conv.inputTypeTarget(arg.type);
636
+ const memberTraits = {};
637
+ if (nonNull)
638
+ memberTraits["smithy.api#required"] = {};
639
+ if (nullable)
640
+ memberTraits[traits.nullable] = {};
641
+ const adoc = oneLineDoc(arg.description);
642
+ if (adoc)
643
+ memberTraits["smithy.api#documentation"] = adoc;
644
+ inputMembers[memberIdent(varName)] = {
645
+ target,
646
+ ...(Object.keys(memberTraits).length
647
+ ? { traits: memberTraits }
648
+ : {}),
649
+ };
650
+ }
651
+ }
652
+ const inputId = addExact(bag, `${op.opName}Request`, {
653
+ type: "structure",
654
+ members: inputMembers,
655
+ traits: {
656
+ "smithy.api#input": {},
657
+ [traits.operation]: {
658
+ query: document,
659
+ operationName: op.functionName,
660
+ type: op.type,
661
+ },
662
+ },
663
+ });
664
+ // ---- Output (the selection set under `data.<responsePath>`) ----
665
+ const { type: retType } = unwrapNonNull(leaf.returnType);
666
+ const isBareObject = (retType.kind === "OBJECT" || retType.kind === "INTERFACE") &&
667
+ selection !== undefined &&
668
+ selection.length > 0;
669
+ let outputId;
670
+ if (isBareObject) {
671
+ // Object result: the response struct's members ARE the selection.
672
+ outputId = addExact(bag, `${op.opName}Response`, {
673
+ type: "structure",
674
+ members: buildSelectionMembers(conv, selection, `${op.opName}Response`),
675
+ traits: {
676
+ "smithy.api#output": {},
677
+ [traits.responsePath]: responsePath,
678
+ "smithy.api#documentation": `Selection set for \`${responsePath}\` (unwrapped from the GraphQL \`data\` envelope).`,
679
+ },
680
+ });
681
+ }
682
+ else {
683
+ // List/scalar/enum/opaque result: a sole `result` member carries the
684
+ // whole value; the payload trait makes the generated response type
685
+ // the value itself.
686
+ const inner = buildOutputTarget(conv, leaf.returnType, selection, `${op.opName}Result`);
687
+ outputId = addExact(bag, `${op.opName}Response`, {
688
+ type: "structure",
689
+ members: {
690
+ result: {
691
+ target: inner.target,
692
+ traits: {
693
+ [traits.payload]: {},
694
+ "smithy.api#required": {},
695
+ ...(inner.nullable ? { [traits.nullable]: {} } : {}),
696
+ "smithy.api#documentation": `The value of \`data.${responsePath}\`.`,
697
+ },
698
+ },
699
+ },
700
+ traits: {
701
+ "smithy.api#output": {},
702
+ [traits.responsePath]: responsePath,
703
+ },
704
+ });
705
+ }
706
+ // ---- Operation ----
707
+ const opTraits = {
708
+ "smithy.api#http": { method: "POST", uri: endpoint, code: 200 },
709
+ };
710
+ if (op.description) {
711
+ opTraits["smithy.api#documentation"] = op.description;
712
+ }
713
+ if (op.type === "query")
714
+ opTraits["smithy.api#readonly"] = {};
715
+ // Relay connections paginate. The operation must accept the cursor and
716
+ // page-size arguments AND return a connection; anything else (a plain
717
+ // list, a connection reached through a namespace hop whose leaf we
718
+ // didn't select) stays a one-shot call.
719
+ const pg = relayCfg && isBareObject
720
+ ? relayPaginatedTrait(relayCfg, ctx, leaf, argRenames)
721
+ : undefined;
722
+ if (pg) {
723
+ opTraits["smithy.api#paginated"] = pg;
724
+ paginated++;
725
+ }
726
+ const opId = addExact(bag, op.opName, {
727
+ type: "operation",
728
+ input: { target: inputId },
729
+ output: { target: outputId },
730
+ traits: opTraits,
731
+ });
732
+ serviceOps.push({ target: opId });
733
+ converted++;
734
+ }
735
+ catch (err) {
736
+ failed++;
737
+ console.error(`❌ ${op.type} ${op.functionName}:`, err);
738
+ }
739
+ }
740
+ addExact(bag, serviceName, {
741
+ type: "service",
742
+ version: serviceVersion,
743
+ operations: serviceOps,
744
+ traits: {
745
+ "smithy.api#title": serviceTitle,
746
+ ...(serviceDocumentation
747
+ ? { "smithy.api#documentation": serviceDocumentation }
748
+ : {}),
749
+ },
750
+ });
751
+ return {
752
+ model: {
753
+ smithy: "2.0",
754
+ metadata: {
755
+ suppressions: [
756
+ // Every operation is POST <endpoint> — the whole point of GraphQL.
757
+ { id: "HttpUriConflict", namespace: "*" },
758
+ { id: "HttpMethodSemantics", namespace: "*" },
759
+ { id: "UnreferencedShape", namespace: "*" },
760
+ ],
761
+ },
762
+ shapes: bag.shapes,
763
+ },
764
+ converted,
765
+ failed,
766
+ paginated,
767
+ shapeCount: Object.keys(bag.shapes).length,
768
+ };
769
+ };
770
+ /**
771
+ * The `smithy.api#paginated` trait for a Relay connection leaf, or undefined
772
+ * when the operation isn't one.
773
+ *
774
+ * `inputToken` is the *renamed* variable (namespace hops can rename a
775
+ * colliding `after`), so pagination feeds the argument the generated input
776
+ * actually exposes.
777
+ */
778
+ const relayPaginatedTrait = (cfg, ctx, leaf, argRenames) => {
779
+ const relay = ctx.relay;
780
+ if (!relay)
781
+ return undefined;
782
+ if (!relay.isConnection(namedType(leaf.returnType).name))
783
+ return undefined;
784
+ const hasArg = (name) => leaf.args.some((a) => a.name === name);
785
+ if (!hasArg(cfg.after) || !hasArg(cfg.first))
786
+ return undefined;
787
+ const inputToken = argRenames.get(`${leaf.name}.${cfg.after}`) ?? cfg.after;
788
+ const pageSize = argRenames.get(`${leaf.name}.${cfg.first}`) ?? cfg.first;
789
+ return {
790
+ mode: cfg.mode,
791
+ inputToken,
792
+ outputToken: `${cfg.pageInfo}.${cfg.endCursor}`,
793
+ hasNextPage: `${cfg.pageInfo}.${cfg.hasNextPage}`,
794
+ // Points *through* the edges so `.items()` streams nodes, not wrappers.
795
+ items: `${cfg.edges}.${cfg.node}`,
796
+ pageSize,
797
+ };
798
+ };
799
+ //# sourceMappingURL=graphql.js.map