@distilled.cloud/core 1.0.0-rc.3 → 1.0.0-rc.5

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