The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,715 lines 69.6 KB
Raw
1 /**
2 * Emits per-document and shared modules from validated documents. Paths and
3 * import specifiers are supplied by the caller; output needs no formatter.
4 * Generated class names that can't be made unique produce diagnostics instead
5 * of output.
6 *
7 * @internal
8 */
9 import * as Arr from "effect/Array"
10 import type { GraphQL } from "effect/graphql"
11 import type { GeneratedFile } from "../Generator.ts"
12 import type * as Ast from "./Ast.ts"
13 import { type Diagnostic, make } from "./Diagnostic.ts"
14 import { print, template } from "./Printer.ts"
15 import * as SchemaModel from "./SchemaModel.ts"
16 import { type File, fragmentSpreads, inclusion } from "./Validate.ts"
17
18 /** One parsed document file holding only executable definitions. */
19 export interface DocumentFile extends File {
20 /** Absolute path of the `.graphql.ts` emitted for this file. */
21 readonly outputPath: string
22 /** The source file's base name, used in the header. */
23 readonly sourceName: string
24 }
25
26 /** A custom or built-in scalar mapped to a codec export. */
27 export interface ScalarMapping {
28 /** The import specifier as written in the shared module. */
29 readonly specifier: string
30 readonly exportName: string
31 }
32
33 export interface Options {
34 readonly schema: SchemaModel.Schema
35 readonly files: ReadonlyArray<DocumentFile>
36 /** Absolute path of the shared module. */
37 readonly sharedPath: string
38 readonly scalars: ReadonlyMap<string, ScalarMapping>
39 /** The import specifier one generated file uses for another, from absolute paths. */
40 readonly importSpecifier: (from: string, to: string) => string
41 }
42
43 export interface Output {
44 readonly files: ReadonlyArray<GeneratedFile>
45 readonly errors: ReadonlyArray<Diagnostic>
46 /** Custom scalars the operations reach that have no mapping, sorted by name. */
47 readonly unmappedScalars: ReadonlyArray<string>
48 }
49
50 export const emit = (options: Options): Output => {
51 const emitter = new Emitter(options)
52 const errors = emitter.check()
53 if (errors.length > 0) return { files: [], errors, unmappedScalars: [] }
54 const emitted = options.files.map((file) => emitter.emitFile(file))
55 const emitErrors = emitted.flatMap((result) => result.errors)
56 if (emitErrors.length > 0) return { files: [], errors: emitErrors, unmappedScalars: [] }
57 const shared = emitter.emitShared()
58 return { files: [shared.file, ...emitted.map((result) => result.file)], errors: [], unmappedScalars: shared.unmapped }
59 }
60
61 // -----------------------------------------------------------------------------
62 // Text helpers
63 // -----------------------------------------------------------------------------
64
65 export const header = (sourceName: string | undefined): string =>
66 `// Generated by @effect/graphql-generator${sourceName === undefined ? "" : ` from ${sourceName}`}. Do not edit.`
67
68 /** A private-use character marking class references in rendered structs (see `classRef`). */
69 const classMarker = "\uE000"
70
71 /**
72 * Escapes `*\/` so text can't end the JSDoc comment it is written into, and
73 * the class reference marker so it can't be mistaken for one.
74 */
75 const escapeComment = (text: string): string => text.replace(/\*\//g, "*\\/").replace(/\uE000/g, "\\uE000")
76
77 const deprecation = (reason: string): string => escapeComment(reason.replace(/\s*\r?\n\s*/g, " "))
78
79 const descriptionLines = (description: string | undefined): Array<string> => {
80 if (description === undefined) return []
81 const lines = description.split(/\r\n|\r|\n/).map((line) => escapeComment(line.trimEnd()))
82 while (lines.length > 0 && lines[0] === "") lines.shift()
83 while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop()
84 return lines
85 }
86
87 const docLines = (body: ReadonlyArray<string>, tags: ReadonlyArray<string>): Array<string> =>
88 body.length > 0 && tags.length > 0 ? [...body, "", ...tags] : [...body, ...tags]
89
90 const jsdoc = (lines: ReadonlyArray<string>, indent: string): string => {
91 if (lines.length === 0) return ""
92 if (lines.length === 1) return `${indent}/** ${lines[0]} */\n`
93 return `${indent}/**\n${
94 lines.map((line) => line === "" ? `${indent} *` : `${indent} * ${line}`).join("\n")
95 }\n${indent} */\n`
96 }
97
98 const deprecatedTag = (reason: string | undefined): Array<string> =>
99 reason === undefined ? [] : [`@deprecated ${deprecation(reason)}`]
100
101 const defaultTag = (value: SchemaModel.ConstValue | undefined): Array<string> =>
102 value === undefined ? [] : [`@default ${escapeComment(printConstValue(value))}`]
103
104 /** A const value in GraphQL syntax, for `@default` tags. */
105 const printConstValue = (value: SchemaModel.ConstValue): string => {
106 switch (value._tag) {
107 case "IntValue":
108 case "FloatValue":
109 case "EnumValue":
110 return value.value
111 case "StringValue":
112 return JSON.stringify(value.value)
113 case "BooleanValue":
114 return String(value.value)
115 case "NullValue":
116 return "null"
117 case "ListValue":
118 return `[${value.values.map(printConstValue).join(", ")}]`
119 case "ObjectValue":
120 return value.fields.length === 0
121 ? "{}"
122 : `{ ${value.fields.map((field) => `${field.name}: ${printConstValue(field.value)}`).join(", ")} }`
123 }
124 }
125
126 const struct = (members: ReadonlyArray<string>, indent: string, schema = "Schema"): string =>
127 members.length === 0 ? `${schema}.Struct({})` : `${schema}.Struct({\n${members.join(",\n")}\n${indent}})`
128
129 /** Writes out a type reference: `leaf` for its named type, `list` around list types, `nullable` around types without `!`. */
130 const typeRef = (
131 type: SchemaModel.TypeRef,
132 leaf: (name: string) => string,
133 list: (element: string) => string,
134 nullable: (inner: string) => string
135 ): string => {
136 const nonNull = (type: SchemaModel.NamedTypeRef | SchemaModel.ListTypeRef): string =>
137 type._tag === "ListTypeRef" ? list(typeRef(type.ofType, leaf, list, nullable)) : leaf(type.name)
138 return type._tag === "NonNullTypeRef" ? nonNull(type.ofType) : nullable(nonNull(type))
139 }
140
141 const typeSchema = (type: SchemaModel.TypeRef, leaf: (name: string) => string, schema = "Schema"): string =>
142 typeRef(type, leaf, (element) => `${schema}.Array(${element})`, (inner) => `${schema}.NullOr(${inner})`)
143
144 /**
145 * The Schema for a variable or input field: a nullable one, or a non-null one
146 * with a default, is `optional`.
147 */
148 const inputSchema = (
149 type: SchemaModel.TypeRef,
150 hasDefault: boolean,
151 ref: (name: string) => string,
152 schema = "Schema"
153 ): string => {
154 const expression = typeSchema(
155 type,
156 (name) => name === "String" || name === "Boolean" ? `${schema}.${name}` : ref(name),
157 schema
158 )
159 return hasDefault || type._tag !== "NonNullTypeRef" ? `${schema}.optional(${expression})` : expression
160 }
161
162 /**
163 * A struct key. `__proto__` is written as a computed key, because in an
164 * object literal the plain form sets the prototype instead of a field.
165 */
166 const propertyKey = (key: string): string => key === "__proto__" ? `["__proto__"]` : key
167
168 /** `issue-timeline` → `IssueTimeline`. */
169 const pascalCase = (text: string): string =>
170 text.split(/[^A-Za-z0-9]+/).map((word) => word.slice(0, 1).toUpperCase() + word.slice(1)).join("")
171
172 /** `issue-timeline.graphql` or `issue-timeline.gql` → `IssueTimelineGraphQLGroup`. */
173 const groupName = (sourceName: string): string => {
174 const name = pascalCase(sourceName.replace(/\.(?:graphql|gql)$/, ""))
175 return `${/^[0-9]/.test(name) ? `_${name}` : name}GraphQLGroup`
176 }
177
178 const reservedWords: ReadonlySet<string> = new Set([
179 "await break case catch class const continue debugger default delete do else enum export extends",
180 "false finally for function if implements import in instanceof interface let new null package private",
181 "protected public return static super switch this throw true try typeof var void while with yield",
182 "any bigint boolean never number object string symbol undefined unknown"
183 ].flatMap((line) => line.split(" ")))
184
185 /** Names unavailable for generated bindings or TypeScript type declarations. */
186 const unbindable = (name: string): boolean => reservedWords.has(name) || name === "arguments" || name === "eval"
187
188 /**
189 * An alias for each of `names` that can't be bound: `name_`, then more `_`
190 * while `taken`. Reserved words hold no `_`, so aliases never collide.
191 */
192 const underscoreAliases = (names: Iterable<string>, taken: ReadonlySet<string>): Map<string, string> => {
193 const aliases = new Map<string, string>()
194 for (const name of names) {
195 if (!unbindable(name)) continue
196 let alias = `${name}_`
197 while (taken.has(alias)) alias = `${alias}_`
198 aliases.set(name, alias)
199 }
200 return aliases
201 }
202
203 /** Names every per-file module imports, which operations and fragments can't take. */
204 const importedNames: ReadonlySet<string> = new Set(["Schema", "Shared", "GraphQL", "GraphQLGroup"])
205
206 interface BuiltInScalar {
207 readonly codec: (schema: string) => string
208 /** Whether the codec's Encoded type differs from its Type. */
209 readonly transforms: boolean
210 }
211
212 /** The scalars with a default codec in the shared module, in declaration order. */
213 const builtInSharedScalars: ReadonlyMap<string, BuiltInScalar> = new Map([
214 ["Int", { codec: (schema) => `${schema}.Number.check(${schema}.isInt32())`, transforms: false }],
215 ["Float", { codec: (schema) => `${schema}.Finite`, transforms: false }],
216 ["ID", { codec: (schema) => `${schema}.String`, transforms: false }],
217 ["DateTime", { codec: (schema) => `${schema}.DateTimeUtcFromString`, transforms: true }],
218 ["URI", { codec: (schema) => `${schema}.String`, transforms: false }]
219 ])
220
221 /**
222 * Tarjan's strongly connected components of the graph reached from `roots`,
223 * in dependency order. Each component's nodes are in the order they were
224 * reached.
225 */
226 const stronglyConnectedComponents = (
227 roots: Iterable<string>,
228 successors: (node: string) => Iterable<string>
229 ): Array<ReadonlyArray<string>> => {
230 const index = new Map<string, number>()
231 const low = new Map<string, number>()
232 const stack: Array<string> = []
233 const onStack = new Set<string>()
234 const components: Array<ReadonlyArray<string>> = []
235 const visit = (node: string): void => {
236 const nodeIndex = index.size
237 index.set(node, nodeIndex)
238 low.set(node, nodeIndex)
239 stack.push(node)
240 onStack.add(node)
241 for (const next of successors(node)) {
242 if (!index.has(next)) {
243 visit(next)
244 low.set(node, Math.min(low.get(node)!, low.get(next)!))
245 } else if (onStack.has(next)) {
246 low.set(node, Math.min(low.get(node)!, index.get(next)!))
247 }
248 }
249 if (low.get(node) !== nodeIndex) return
250 const component = stack.splice(stack.lastIndexOf(node))
251 for (const member of component) onStack.delete(member)
252 components.push(component)
253 }
254 for (const root of roots) {
255 if (!index.has(root)) visit(root)
256 }
257 return components
258 }
259
260 // -----------------------------------------------------------------------------
261 // Emitter
262 // -----------------------------------------------------------------------------
263
264 interface FragmentEntry {
265 readonly definition: Ast.FragmentDefinition
266 readonly file: DocumentFile
267 }
268
269 /**
270 * A selection together with where it came from. `via` is undefined when the
271 * selection is written in the file being emitted; otherwise it is the spread
272 * in that file through which a fragment from another file was written out
273 * inline. `conditional` is set when the selection, or a fragment it came
274 * through, has a `@skip` / `@include` with a variable condition.
275 */
276 interface Sourced<S extends Ast.Selection> {
277 readonly selection: S
278 readonly via: Ast.FragmentSpread | undefined
279 readonly conditional: boolean
280 /**
281 * The selection's index in each enclosing selection set, from the
282 * definition's root, with fragments expanded where they are spread.
283 * Comparing two orders tells which selection comes first in the document.
284 */
285 readonly order: ReadonlyArray<number>
286 }
287
288 /** A selection after inline fragments are flattened into their parent. */
289 type FlatSelection = Sourced<Ast.Field | Ast.FragmentSpread>
290
291 interface SpreadItem {
292 readonly _tag: "Spread"
293 readonly name: string
294 readonly spread: Ast.FragmentSpread
295 readonly via: Ast.FragmentSpread | undefined
296 }
297
298 type Item = { readonly _tag: "Field"; readonly key: string; readonly fields: Array<Sourced<Ast.Field>> } | SpreadItem
299
300 const written = (selections: ReadonlyArray<Ast.Selection>): Array<Sourced<Ast.Selection>> =>
301 selections.map((selection, i) => ({ selection, via: undefined, conditional: false, order: [i] }))
302
303 const isAbstract = (type: SchemaModel.NamedType): type is SchemaModel.InterfaceType | SchemaModel.UnionType =>
304 type._tag === "InterfaceType" || type._tag === "UnionType"
305
306 /** `prefix` followed by `"A" | "B"`, wrapped onto `|` lines when it doesn't fit in 120 columns. */
307 const literalUnion = (prefix: string, names: ReadonlyArray<string>, indent: string): string => {
308 if (names.length === 0) return `${prefix}never`
309 const literals = names.map((name) => JSON.stringify(name))
310 const single = `${prefix}${literals.join(" | ")}`
311 if (single.length <= 120) return single
312 const lines: Array<string> = []
313 let line = ""
314 for (const literal of literals) {
315 const next = line === "" ? `${indent} | ${literal}` : `${line} | ${literal}`
316 if (next.length > 120 && line !== "") {
317 lines.push(line)
318 line = `${indent} | ${literal}`
319 } else {
320 line = next
321 }
322 }
323 lines.push(line)
324 return `${prefix.trimEnd()}\n${lines.join("\n")}`
325 }
326
327 /**
328 * Identical nested selections share a schema and interface within a file,
329 * using the first occurrence's path for naming.
330 */
331 interface ExtractedClass {
332 readonly id: number
333 /** The type's name, or `<AbstractType>Other` for a catch-all member. */
334 readonly typeName: string
335 readonly description: string | undefined
336 /** The operation or fragment holding the selection. */
337 definition: string
338 /** Response keys from the definition's root down to the field holding the selection. */
339 path: ReadonlyArray<string>
340 /** Where the selection is written in the file being emitted. */
341 offset: number
342 /** The definition's index in the file, then the selection's place in it (see `Sourced.order`). */
343 order: ReadonlyArray<number>
344 /** The struct, with `classRef(id)` standing for each class it uses. */
345 readonly body: string
346 /** Fragments of this file the struct uses. */
347 readonly refs: ReadonlySet<string>
348 }
349
350 /**
351 * A rendered struct or struct member. `identity` stands for the selection
352 * that produced it: response keys, the fields they select, optionality and
353 * nested classes and fragments, independent of the order keys are written in.
354 */
355 interface Struct {
356 readonly code: string
357 readonly identity: string
358 }
359
360 /** A reference to a fragment or an extracted class, standing for its own selection. */
361 const refStruct = (ref: string): Struct => ({ code: ref, identity: ref })
362
363 /** Which of two `Sourced.order`s comes first in the document. */
364 const compareOrder = (a: ReadonlyArray<number>, b: ReadonlyArray<number>): number => {
365 for (let i = 0; i < Math.min(a.length, b.length); i++) {
366 if (a[i] !== b[i]) return a[i]! - b[i]!
367 }
368 return a.length - b.length
369 }
370
371 interface EmittedFile {
372 readonly file: GeneratedFile
373 readonly errors: ReadonlyArray<Diagnostic>
374 }
375
376 /**
377 * Stands for an extracted class until the file's classes are named.
378 * `escapeComment` escapes the marker in the only text from documents that
379 * structs carry.
380 */
381 const classRef = (id: number): string => `${classMarker}${id}${classMarker}`
382
383 const classRefPattern = /\uE000(\d+)\uE000/g
384
385 /** `author` → `Author`, for response keys in class names. */
386 const capitalize = (key: string): string => key.slice(0, 1).toUpperCase() + key.slice(1)
387
388 interface FileContext {
389 readonly file: DocumentFile
390 usesSchema: boolean
391 usesGraphQL: boolean
392 usesShared: boolean
393 /** Fragments imported from other files, each with the first spread in this file that led to the import. */
394 readonly imports: Map<string, Ast.FragmentSpread>
395 /** Fragments of this file referenced by the code being rendered. */
396 localRefs: Set<string>
397 /** The classes extracted so far, in order of extraction. */
398 readonly classes: Array<ExtractedClass>
399 readonly byShape: Map<string, ExtractedClass>
400 /** The name and index of the definition being rendered. */
401 definition: { readonly name: string; readonly index: number }
402 /** Response keys from the definition's root to the selection being rendered. */
403 readonly path: Array<string>
404 /** Where the field holding the selection being rendered is written. */
405 offset: number
406 /** The document order of the field holding the selection being rendered. */
407 order: ReadonlyArray<number>
408 readonly errors: Array<Diagnostic>
409 }
410
411 class Emitter {
412 readonly fragments = new Map<string, FragmentEntry>()
413 /** Named types the per-file modules reference through `Shared`. */
414 readonly reached = new Set<string>()
415 /** Interfaces and unions the per-file modules reference through `Shared.Typename`. */
416 readonly reachedAbstract = new Set<string>()
417 /** The `Shared.Typename` members whose abstract type's name can't be bound. */
418 readonly typenameAliases: ReadonlyMap<string, string>
419 readonly fragmentKeyCache = new Map<string, ReadonlyArray<string>>()
420
421 readonly options: Options
422
423 constructor(options: Options) {
424 this.options = options
425 const abstractNames = Array.from(options.schema.types.values()).filter(isAbstract).map((type) => type.name).sort()
426 this.typenameAliases = underscoreAliases(abstractNames, new Set(abstractNames))
427 for (const file of options.files) {
428 for (const definition of file.document.definitions) {
429 if (definition._tag === "FragmentDefinition") {
430 this.fragments.set(definition.name.value, { definition, file })
431 }
432 }
433 }
434 }
435
436 type(name: string): SchemaModel.NamedType {
437 const type = this.options.schema.types.get(name)
438 if (type === undefined) throw new Error(`@effect/graphql-generator: unknown type ${name} after validation`)
439 return type
440 }
441
442 fieldDefinition(parent: SchemaModel.NamedType, name: string): SchemaModel.Field {
443 const fields = parent._tag === "ObjectType" || parent._tag === "InterfaceType" ? parent.fields : []
444 const field = fields.find((field) => field.name === name)
445 if (field === undefined) {
446 throw new Error(`@effect/graphql-generator: unknown field ${parent.name}.${name} after validation`)
447 }
448 return field
449 }
450
451 /** The object types a type stands for: itself, or an abstract type's possible types. */
452 possibleTypes(name: string): ReadonlyArray<string> {
453 const type = this.type(name)
454 return isAbstract(type) ? type.possibleTypes : [name]
455 }
456
457 rootType(operation: Ast.OperationDefinition): string {
458 return SchemaModel.rootTypeName(this.options.schema, operation.operation)!
459 }
460
461 // ---------------------------------------------------------------------------
462 // Checks
463 // ---------------------------------------------------------------------------
464
465 /** Names generated code can't use and import cycles, sorted by file and position. */
466 check(): ReadonlyArray<Diagnostic> {
467 const errors: Array<{ readonly file: number; readonly offset: number; readonly message: string }> = []
468 this.options.files.forEach((file, fileIndex) => {
469 const report = (offset: number, message: string) => errors.push({ file: fileIndex, offset, message })
470 const group = groupName(file.sourceName)
471 const exportsGroup = file.document.definitions.some((definition) => definition._tag === "OperationDefinition")
472 if (exportsGroup && importedNames.has(group)) {
473 report(0, `The group name "${group}" is reserved in generated code; rename this file.`)
474 }
475 for (const definition of file.document.definitions) {
476 if (definition._tag !== "OperationDefinition" && definition._tag !== "FragmentDefinition") continue
477 const name = definition.name
478 if (name !== undefined) {
479 if (importedNames.has(name.value) || unbindable(name.value)) {
480 report(name.loc.start, `The name "${name.value}" is reserved in generated code; rename this definition.`)
481 } else if (name.value === group && exportsGroup) {
482 report(name.loc.start, `The name "${name.value}" is taken by the group this file exports.`)
483 }
484 }
485 }
486 })
487 errors.push(...this.importCycles())
488 return errors
489 .sort((a, b) => a.file - b.file || a.offset - b.offset)
490 .map((error) => make(this.options.files[error.file]!.source, error.offset, error.message))
491 }
492
493 /**
494 * Cycles in the imports between generated files. Every fragment reference
495 * is read while its module initializes, so any cycle throws for some entry
496 * point. Each cycle is reported once, at its first cross-file spread by file
497 * order and then position. Every cross-file spread counts, including ones
498 * the emitter would write out inline, so the rule doesn't depend on how a
499 * selection set is merged.
500 */
501 importCycles(): Array<{ readonly file: number; readonly offset: number; readonly message: string }> {
502 const files = this.options.files
503 const indexOf = new Map(files.map((file, i) => [file, i] as const))
504 const edges: Array<{ readonly from: number; readonly to: number; readonly spread: Ast.FragmentSpread }> = []
505 const adjacent = files.map(() => new Set<number>())
506 files.forEach((file, from) => {
507 for (const definition of file.document.definitions) {
508 if (definition._tag !== "OperationDefinition" && definition._tag !== "FragmentDefinition") continue
509 for (const spread of fragmentSpreads(definition.selectionSet)) {
510 const entry = this.fragments.get(spread.name.value)
511 if (entry === undefined || entry.file === file) continue
512 const to = indexOf.get(entry.file)!
513 edges.push({ from, to, spread })
514 adjacent[from]!.add(to)
515 }
516 }
517 })
518
519 // Tarjan's strongly connected components.
520 const index: Array<number | undefined> = files.map(() => undefined)
521 const low: Array<number> = files.map(() => 0)
522 const onStack = files.map(() => false)
523 const stack: Array<number> = []
524 const components: Array<ReadonlySet<number>> = []
525 let next = 0
526 const connect = (v: number): void => {
527 index[v] = low[v] = next++
528 stack.push(v)
529 onStack[v] = true
530 for (const w of adjacent[v]!) {
531 if (index[w] === undefined) {
532 connect(w)
533 low[v] = Math.min(low[v]!, low[w]!)
534 } else if (onStack[w]) {
535 low[v] = Math.min(low[v]!, index[w]!)
536 }
537 }
538 if (low[v] === index[v]) {
539 const component = new Set<number>()
540 let w: number
541 do {
542 w = stack.pop()!
543 onStack[w] = false
544 component.add(w)
545 } while (w !== v)
546 if (component.size > 1) components.push(component)
547 }
548 }
549 files.forEach((_, v) => {
550 if (index[v] === undefined) connect(v)
551 })
552
553 return components.map((component) => {
554 const first = edges
555 .filter((edge) => component.has(edge.from) && component.has(edge.to))
556 .sort((a, b) => a.from - b.from || a.spread.loc.start - b.spread.loc.start)[0]!
557 // The shortest way back from the spread's target to the spreading file.
558 const previous = new Map<number, number>([[first.to, -1]])
559 const queue = [first.to]
560 while (!previous.has(first.from)) {
561 const v = queue.shift()!
562 for (const w of adjacent[v]!) {
563 if (component.has(w) && !previous.has(w)) {
564 previous.set(w, v)
565 queue.push(w)
566 }
567 }
568 }
569 const path: Array<number> = []
570 for (let v = first.from; v !== -1; v = previous.get(v)!) path.unshift(v)
571 const names = [first.from, ...path].map((i) => files[i]!.source.path)
572 return {
573 file: first.from,
574 offset: first.spread.loc.start,
575 message:
576 `Fragment spread "...${first.spread.name.value}" makes the generated modules import each other in a cycle: ${
577 names.join(" -> ")
578 }. Move fragments between files so the imports don't form a cycle.`
579 }
580 })
581 }
582
583 // ---------------------------------------------------------------------------
584 // Result selections
585 // ---------------------------------------------------------------------------
586
587 /**
588 * Whether a fragment on `condition` applies to `target`. A target that is an
589 * object type is one concrete type. A target that is an interface or union
590 * stands for the possible types no fragment names, so only a fragment
591 * covering every one of its possible types applies.
592 */
593 applies(condition: string | undefined, target: string): boolean {
594 if (condition === undefined || condition === target) return true
595 const type = this.type(target)
596 if (type._tag === "ObjectType") {
597 const fragmentType = this.type(condition)
598 return isAbstract(fragmentType) && fragmentType.possibleTypes.includes(target)
599 }
600 // Only an interface the target declares contributes fields the target has.
601 return type._tag === "InterfaceType" && type.interfaces.includes(condition)
602 }
603
604 /**
605 * Flattens a selection set for `target`: inline fragments and spreads that
606 * apply to it are written into their parent and the rest are dropped,
607 * excluded selections are dropped, and variable conditions are carried down.
608 * A spread of a fragment on exactly the object type `target` is kept, unless
609 * it is conditional, since `...Frag.fields` can't make its keys optional.
610 */
611 narrow(file: DocumentFile, selections: ReadonlyArray<Sourced<Ast.Selection>>, target: string): Array<FlatSelection> {
612 const out: Array<FlatSelection> = []
613 for (const { conditional: outer, order, selection, via } of selections) {
614 const included = inclusion(selection.directives)
615 if (included === "exclude") continue
616 const conditional = outer || included === "conditional"
617 switch (selection._tag) {
618 case "Field":
619 out.push({ selection, via, conditional, order })
620 break
621 case "InlineFragment":
622 if (this.applies(selection.typeCondition?.name.value, target)) {
623 out.push(...this.narrow(
624 file,
625 selection.selectionSet.selections.map((selection, i) => ({
626 selection,
627 via,
628 conditional,
629 order: [...order, i]
630 })),
631 target
632 ))
633 }
634 break
635 case "FragmentSpread": {
636 const fragment = this.fragment(selection.name.value)
637 const condition = fragment.definition.typeCondition.name.value
638 if (condition === target && this.type(target)._tag === "ObjectType" && !conditional) {
639 out.push({ selection, via, conditional, order })
640 } else if (this.applies(condition, target)) {
641 out.push(...this.narrow(file, this.expand(file, fragment, selection, via, conditional, order), target))
642 }
643 break
644 }
645 }
646 }
647 return out
648 }
649
650 /** A fragment's selections, written out inline through `spread`. */
651 expand(
652 file: DocumentFile,
653 fragment: FragmentEntry,
654 spread: Ast.FragmentSpread,
655 via: Ast.FragmentSpread | undefined,
656 conditional: boolean,
657 order: ReadonlyArray<number>
658 ): Array<Sourced<Ast.Selection>> {
659 // A local fragment's selections are written in this file; another file's come in through this spread.
660 const through = fragment.file === file ? undefined : via ?? spread
661 return fragment.definition.selectionSet.selections.map((selection, i) => ({
662 selection,
663 via: through,
664 conditional,
665 order: [...order, i]
666 }))
667 }
668
669 group(flat: ReadonlyArray<FlatSelection>): Array<Item> {
670 const items: Array<Item> = []
671 const fields = new Map<string, Array<Sourced<Ast.Field>>>()
672 const spreads = new Set<string>()
673 for (const entry of flat) {
674 const selection = entry.selection
675 if (selection._tag === "Field") {
676 const key = (selection.alias ?? selection.name).value
677 const existing = fields.get(key)
678 const sourced = { selection, via: entry.via, conditional: entry.conditional, order: entry.order }
679 if (existing === undefined) {
680 const merged = [sourced]
681 fields.set(key, merged)
682 items.push({ _tag: "Field", key, fields: merged })
683 } else {
684 existing.push(sourced)
685 }
686 } else if (!spreads.has(selection.name.value)) {
687 spreads.add(selection.name.value)
688 items.push({ _tag: "Spread", name: selection.name.value, spread: selection, via: entry.via })
689 }
690 }
691 return items
692 }
693
694 fragment(name: string): FragmentEntry {
695 const entry = this.fragments.get(name)
696 if (entry === undefined) throw new Error(`@effect/graphql-generator: unknown fragment ${name} after validation`)
697 return entry
698 }
699
700 /** Every response key a fragment on an object type contributes, through nested spreads. */
701 fragmentKeys(name: string): ReadonlyArray<string> {
702 const cached = this.fragmentKeyCache.get(name)
703 if (cached !== undefined) return cached
704 const entry = this.fragment(name)
705 const keys = new Set<string>()
706 const flat = this.narrow(
707 entry.file,
708 written(entry.definition.selectionSet.selections),
709 entry.definition.typeCondition.name.value
710 )
711 for (const item of this.group(flat)) {
712 if (item._tag === "Field") keys.add(item.key)
713 else for (const key of this.fragmentKeys(item.name)) keys.add(key)
714 }
715 const result = Array.from(keys)
716 this.fragmentKeyCache.set(name, result)
717 return result
718 }
719
720 /**
721 * Groups a selection set for `target`, writing out inline every spread
722 * whose keys overlap a sibling's or one of `reserved`.
723 * The remaining spreads become `...Frag.fields`.
724 */
725 resolveItems(
726 file: DocumentFile,
727 selections: ReadonlyArray<Sourced<Ast.Selection>>,
728 target: string,
729 reserved: ReadonlyArray<string> = []
730 ): Array<Item> {
731 let flat = this.narrow(file, selections, target)
732 for (;;) {
733 const items = this.group(flat)
734 const overlapping = items.find((item) => {
735 if (item._tag !== "Spread") return false
736 const others = new Set<string>(reserved)
737 for (const other of items) {
738 if (other === item) continue
739 if (other._tag === "Field") others.add(other.key)
740 else for (const key of this.fragmentKeys(other.name)) others.add(key)
741 }
742 return this.fragmentKeys(item.name).some((key) => others.has(key))
743 })
744 if (overlapping === undefined || overlapping._tag !== "Spread") return items
745 const fragment = this.fragment(overlapping.name)
746 flat = flat.flatMap((entry) => {
747 const selection = entry.selection
748 if (selection._tag !== "FragmentSpread" || selection.name.value !== overlapping.name) return [entry]
749 return this.narrow(
750 file,
751 this.expand(file, fragment, selection, entry.via, entry.conditional, entry.order),
752 target
753 )
754 })
755 }
756 }
757
758 fragmentRef(ctx: FileContext, item: SpreadItem): string {
759 const name = item.name
760 if (this.fragment(name).file === ctx.file) ctx.localRefs.add(name)
761 else if (!ctx.imports.has(name)) ctx.imports.set(name, item.via ?? item.spread)
762 return name
763 }
764
765 shared(ctx: FileContext, name: string): string {
766 ctx.usesShared = true
767 this.reached.add(name)
768 return `Shared.${name}`
769 }
770
771 typename(ctx: FileContext, name: string): string {
772 ctx.usesShared = true
773 this.reachedAbstract.add(name)
774 return `Shared.Typename.${this.typenameAliases.get(name) ?? name}`
775 }
776
777 /**
778 * The Schema for a selection set on `parentName`, starting on a line
779 * indented by `indent`. A selection that is only one spread of a fragment
780 * on exactly that type references the fragment unless `alwaysStruct` is
781 * set. With `nested` set, a struct with members is extracted as a class.
782 */
783 selection(
784 ctx: FileContext,
785 parentName: string,
786 selections: ReadonlyArray<Sourced<Ast.Selection>>,
787 indent: string,
788 alwaysStruct = false,
789 nested = false
790 ): Struct {
791 const parent = this.type(parentName)
792 if (isAbstract(parent)) {
793 const only = alwaysStruct ? undefined : this.onlySpread(selections, parentName)
794 return only !== undefined
795 ? refStruct(this.fragmentRef(ctx, only))
796 : this.abstractSelection(ctx, parent, selections, indent, nested)
797 }
798 const items = this.resolveItems(ctx.file, selections, parentName)
799 const only = items[0]
800 if (!alwaysStruct && items.length === 1 && only!._tag === "Spread") {
801 return refStruct(this.fragmentRef(ctx, only!))
802 }
803 const typename = `Schema.Literal(${JSON.stringify(parent.name)})`
804 return nested && items.length > 0
805 ? refStruct(
806 this.extract(ctx, parent.name, parent.description, () => this.structOf(ctx, parent, items, "", typename, false))
807 )
808 : this.structOf(ctx, parent, items, indent, typename, false)
809 }
810
811 /**
812 * Renders a struct written at the top level as a class of the file and
813 * refers to it. A struct with the same identity reuses the class, which
814 * keeps the path of whichever occurrence comes first in the document.
815 */
816 extract(ctx: FileContext, typeName: string, description: string | undefined, render: () => Struct): string {
817 const outer = ctx.localRefs
818 ctx.localRefs = new Set()
819 const struct = render()
820 const refs = ctx.localRefs
821 ctx.localRefs = outer
822 for (const ref of refs) outer.add(ref)
823 const order = [ctx.definition.index, ...ctx.order]
824 const shape = `${typeName}\u0001${struct.identity}`
825 const existing = ctx.byShape.get(shape)
826 if (existing !== undefined) {
827 if (compareOrder(order, existing.order) < 0) {
828 existing.definition = ctx.definition.name
829 existing.path = ctx.path.slice()
830 existing.offset = ctx.offset
831 existing.order = order
832 }
833 return classRef(existing.id)
834 }
835 const extracted: ExtractedClass = {
836 id: ctx.classes.length,
837 typeName,
838 description,
839 definition: ctx.definition.name,
840 path: ctx.path.slice(),
841 offset: ctx.offset,
842 order,
843 body: struct.code,
844 refs
845 }
846 ctx.classes.push(extracted)
847 ctx.byShape.set(shape, extracted)
848 return classRef(extracted.id)
849 }
850
851 /** The one spread a selection set consists of, when it is an unconditional spread of a fragment on `parentName`. */
852 onlySpread(selections: ReadonlyArray<Sourced<Ast.Selection>>, parentName: string): SpreadItem | undefined {
853 const kept = selections.filter(({ selection }) => inclusion(selection.directives) !== "exclude")
854 const only = kept[0]
855 if (kept.length !== 1 || only!.selection._tag !== "FragmentSpread") return undefined
856 const spread = only!.selection
857 if (only!.conditional || inclusion(spread.directives) !== "include") return undefined
858 if (this.fragment(spread.name.value).definition.typeCondition.name.value !== parentName) return undefined
859 return { _tag: "Spread", name: spread.name.value, spread, via: only!.via }
860 }
861
862 /**
863 * The object types a selection on an abstract type names through fragments
864 * that don't apply to the type itself (see `applies`), in order of first
865 * mention. Each gets its own member of the union, even when it is the only
866 * possible type.
867 */
868 selectedTypes(
869 parent: SchemaModel.InterfaceType | SchemaModel.UnionType,
870 selections: ReadonlyArray<Sourced<Ast.Selection>>
871 ): Array<string> {
872 const all = parent.possibleTypes
873 const selected: Array<string> = []
874 const walk = (selections: ReadonlyArray<Ast.Selection>, scope: ReadonlyArray<string>): void => {
875 for (const selection of selections) {
876 if (selection._tag === "Field" || inclusion(selection.directives) === "exclude") continue
877 const definition = selection._tag === "FragmentSpread"
878 ? this.fragment(selection.name.value).definition
879 : selection
880 const condition = definition.typeCondition?.name.value
881 let next = scope
882 if (!this.applies(condition, parent.name)) {
883 const inScope = new Set(scope)
884 next = this.possibleTypes(condition!).filter((name) => inScope.has(name))
885 for (const name of next) if (!selected.includes(name)) selected.push(name)
886 }
887 walk(definition.selectionSet.selections, next)
888 }
889 }
890 walk(selections.map(({ selection }) => selection), all)
891 return selected
892 }
893
894 /**
895 * A selection on an interface or union: one struct per
896 * selected object type with `__typename: Schema.Literal("T")`, and one for
897 * every other possible type with `GraphQL.otherTypename`. Each member of
898 * the union is extracted as a class; without selected types the one struct
899 * is extracted only when `nested` is set. The identity ignores the order the
900 * types are mentioned in, which only decides the order members are written.
901 */
902 abstractSelection(
903 ctx: FileContext,
904 parent: SchemaModel.InterfaceType | SchemaModel.UnionType,
905 selections: ReadonlyArray<Sourced<Ast.Selection>>,
906 indent: string,
907 nested: boolean
908 ): Struct {
909 ctx.usesGraphQL = true
910 const selected = this.selectedTypes(parent, selections)
911 const others = `GraphQL.otherTypename<${this.typename(ctx, parent.name)}>()([${
912 selected.map((name) => JSON.stringify(name)).join(", ")
913 }])`
914 const othersIdentity = `GraphQL.otherTypename(${selected.slice().sort().join(",")})`
915 const member = (type: SchemaModel.NamedType, typename: string, indent: string, typenameIdentity = typename) =>
916 this.structOf(
917 ctx,
918 type,
919 this.resolveItems(ctx.file, selections, type.name, ["__typename"]),
920 indent,
921 typename,
922 true,
923 typenameIdentity
924 )
925 if (selected.length === 0) {
926 return nested
927 ? refStruct(
928 this.extract(ctx, parent.name, parent.description, () => member(parent, others, "", othersIdentity))
929 )
930 : member(parent, others, indent, othersIdentity)
931 }
932 const members = [
933 ...selected.map((name) => {
934 const type = this.type(name)
935 return this.extract(
936 ctx,
937 name,
938 type.description,
939 () => member(type, `Schema.Literal(${JSON.stringify(name)})`, "")
940 )
941 }),
942 this.extract(ctx, `${parent.name}Other`, parent.description, () => member(parent, others, "", othersIdentity))
943 ]
944 const memberIndent = `${indent} `
945 return {
946 code: `Schema.Union([\n${members.map((member) => `${memberIndent}${member}`).join(",\n")}\n${indent}])`,
947 identity: `Schema.Union(${members.slice().sort().join(",")})`
948 }
949 }
950
951 /**
952 * A struct for `items` on `parent`. `typename` is the Schema for a
953 * selected `__typename`; with `discriminated` set, `__typename` comes first
954 * whether or not it was selected. `typenameIdentity` stands for `typename`
955 * in the identity.
956 */
957 structOf(
958 ctx: FileContext,
959 parent: SchemaModel.NamedType,
960 items: ReadonlyArray<Item>,
961 indent: string,
962 typename: string,
963 discriminated: boolean,
964 typenameIdentity = typename
965 ): Struct {
966 ctx.usesSchema = true
967 const memberIndent = `${indent} `
968 const members: Array<string> = discriminated ? [`${memberIndent}__typename: ${typename}`] : []
969 const identities: Array<string> = []
970 for (const item of items) {
971 if (item._tag === "Spread") {
972 const name = this.fragmentRef(ctx, item)
973 members.push(`${memberIndent}...${name}.fields`)
974 identities.push(`...${name}`)
975 } else if (!(discriminated && item.key === "__typename")) {
976 const member = this.resultMember(ctx, parent, item.key, item.fields, memberIndent, typename, typenameIdentity)
977 members.push(member.code)
978 identities.push(member.identity)
979 }
980 }
981 return {
982 code: struct(members, indent),
983 identity: [discriminated ? typenameIdentity : "", ...identities.sort()].join("\u0002")
984 }
985 }
986
987 resultMember(
988 ctx: FileContext,
989 parent: SchemaModel.NamedType,
990 key: string,
991 fields: ReadonlyArray<Sourced<Ast.Field>>,
992 indent: string,
993 typename: string,
994 typenameIdentity: string
995 ): Struct {
996 const name = fields[0]!.selection.name.value
997 const isOptional = fields.every((field) => field.conditional)
998 const optional = (expression: string): string => isOptional ? `Schema.optionalKey(${expression})` : expression
999 const identity = (inner: string) => [key, name, isOptional ? "?" : "", inner].join("\u0003")
1000 if (name === "__typename") {
1001 return { code: `${indent}${propertyKey(key)}: ${optional(typename)}`, identity: identity(typenameIdentity) }
1002 }
1003 const definition = this.fieldDefinition(parent, name)
1004 const typeName = SchemaModel.namedTypeOf(definition.type)
1005 const type = this.type(typeName)
1006 const inner = type._tag === "ObjectType" || isAbstract(type)
1007 ? this.nestedSelection(
1008 ctx,
1009 key,
1010 fields[0]!,
1011 typeName,
1012 indent,
1013 // The parent's key covers its only occurrence's condition. With several
1014 // occurrences, the parent can be present because of another one, so
1015 // each occurrence's condition carries over to the children it adds.
1016 fields.flatMap(({ conditional, order, selection: field, via }) =>
1017 (field.selectionSet?.selections ?? []).map((selection, i) => ({
1018 selection,
1019 via,
1020 conditional: conditional && fields.length > 1,
1021 order: [...order, i]
1022 }))
1023 )
1024 )
1025 : undefined
1026 const doc = docLines(descriptionLines(definition.description), deprecatedTag(definition.deprecationReason))
1027 const expression = optional(typeSchema(definition.type, () => inner?.code ?? this.resultLeaf(ctx, type)))
1028 return {
1029 code: `${jsdoc(doc, indent)}${indent}${propertyKey(key)}: ${expression}`,
1030 // A leaf's Schema follows from the field.
1031 identity: identity(inner?.identity ?? "")
1032 }
1033 }
1034
1035 /** The selection under the field `key`, with `key` added to the path of the classes it extracts. */
1036 nestedSelection(
1037 ctx: FileContext,
1038 key: string,
1039 first: Sourced<Ast.Field>,
1040 typeName: string,
1041 indent: string,
1042 selections: ReadonlyArray<Sourced<Ast.Selection>>
1043 ): Struct {
1044 const { offset, order } = ctx
1045 ctx.path.push(key)
1046 ctx.offset = (first.via ?? first.selection).loc.start
1047 ctx.order = first.order
1048 const expression = this.selection(ctx, typeName, selections, indent, false, true)
1049 ctx.path.pop()
1050 ctx.offset = offset
1051 ctx.order = order
1052 return expression
1053 }
1054
1055 resultLeaf(ctx: FileContext, type: SchemaModel.NamedType): string {
1056 if (type.name === "String" || type.name === "Boolean") return `Schema.${type.name}`
1057 if (type._tag === "EnumType") {
1058 ctx.usesGraphQL = true
1059 return `GraphQL.enumLiterals(${this.shared(ctx, type.name)}.literals)`
1060 }
1061 return this.shared(ctx, type.name)
1062 }
1063
1064 // ---------------------------------------------------------------------------
1065 // Per-file modules
1066 // ---------------------------------------------------------------------------
1067
1068 /**
1069 * Emits one per-file module. Fails with a located error when the module
1070 * would import a fragment named like the group it exports, or when a
1071 * class can't be given a name of its own; the import is found from the
1072 * code actually emitted, so a spread written out inline counts only for
1073 * the fragments it really brings in.
1074 */
1075 emitFile(file: DocumentFile): EmittedFile {
1076 const ctx: FileContext = {
1077 file,
1078 usesSchema: false,
1079 usesGraphQL: false,
1080 usesShared: false,
1081 imports: new Map(),
1082 localRefs: new Set(),
1083 classes: [],
1084 byShape: new Map(),
1085 definition: { name: "", index: 0 },
1086 path: [],
1087 offset: 0,
1088 order: [],
1089 errors: []
1090 }
1091
1092 const fragments = new Map<string, { readonly code: string; readonly refs: ReadonlySet<string> }>()
1093 const operations: Array<string> = []
1094 const operationNames: Array<string> = []
1095 file.document.definitions.forEach((definition, index) => {
1096 if (definition._tag !== "FragmentDefinition" && definition._tag !== "OperationDefinition") return
1097 const name = definition.name!
1098 ctx.localRefs = new Set()
1099 ctx.definition = { name: name.value, index }
1100 ctx.offset = name.loc.start
1101 ctx.order = []
1102 if (definition._tag === "FragmentDefinition") {
1103 fragments.set(name.value, { code: this.emitFragment(ctx, definition), refs: ctx.localRefs })
1104 } else {
1105 operations.push(this.emitOperation(ctx, definition))
1106 operationNames.push(name.value)
1107 }
1108 })
1109
1110 const group = groupName(file.sourceName)
1111 const errors = ctx.errors
1112 const taken = new Map<string, string>()
1113 for (const name of importedNames) taken.set(name, "is reserved in generated code")
1114 for (const name of [...fragments.keys(), ...operationNames]) {
1115 taken.set(name, "is taken by a definition in this file")
1116 }
1117 for (const name of ctx.imports.keys()) taken.set(name, "is taken by a fragment this file imports")
1118 if (operationNames.length > 0) taken.set(group, "is taken by the group this file exports")
1119 const names = this.nameClasses(ctx, taken)
1120 const fill = (text: string) => text.replace(classRefPattern, (_, id: string) => names[Number(id)]!)
1121
1122 // Fragments and classes are declared before the code that uses them: each
1123 // fragment after the fragments it uses, and each class after the
1124 // fragments and classes it uses.
1125 const blocks: Array<string> = []
1126 const placedClasses = new Set<number>()
1127 const placedFragments = new Set<string>()
1128 const placeClasses = (code: string): void => {
1129 // A class only uses classes extracted before it.
1130 const used = new Set<number>()
1131 const visit = (text: string): void => {
1132 for (const match of text.matchAll(classRefPattern)) {
1133 const id = Number(match[1])
1134 if (used.has(id)) continue
1135 used.add(id)
1136 visit(ctx.classes[id]!.body)
1137 }
1138 }
1139 visit(code)
1140 for (const id of Array.from(used).sort((a, b) => a - b)) {
1141 if (placedClasses.has(id)) continue
1142 placedClasses.add(id)
1143 const extracted = ctx.classes[id]!
1144 for (const ref of extracted.refs) placeFragment(ref)
1145 const name = names[id]!
1146 blocks.push(
1147 `${jsdoc(descriptionLines(extracted.description), "")}export const ${name} = ${
1148 fill(extracted.body)
1149 }\nexport interface ${name} extends Schema.Struct.Type<typeof ${name}.fields> {}`
1150 )
1151 }
1152 }
1153 const placeFragment = (name: string): void => {
1154 if (placedFragments.has(name)) return
1155 placedFragments.add(name)
1156 const fragment = fragments.get(name)!
1157 for (const ref of fragment.refs) placeFragment(ref)
1158 placeClasses(fragment.code)
1159 blocks.push(fill(fragment.code))
1160 }
1161 for (const name of fragments.keys()) placeFragment(name)
1162 for (const operation of operations) {
1163 placeClasses(operation)
1164 blocks.push(fill(operation))
1165 }
1166
1167 if (operationNames.length > 0) {
1168 blocks.push(
1169 `/** Every operation in ${file.sourceName}. */\nexport const ${group} = GraphQLGroup.make(${
1170 operationNames.join(", ")
1171 })`
1172 )
1173 const via = ctx.imports.get(group)
1174 if (via !== undefined) {
1175 errors.push(make(
1176 file.source,
1177 via.loc.start,
1178 `Fragment "${group}" from ${
1179 this.fragment(group).file.source.path
1180 } can't be imported here: the name is taken by the group this file exports.`
1181 ))
1182 }
1183 }
1184
1185 const imports: Array<string> = []
1186 const graphql = [...(ctx.usesGraphQL ? ["GraphQL"] : []), ...(operationNames.length > 0 ? ["GraphQLGroup"] : [])]
1187 if (graphql.length > 0) imports.push(`import { ${graphql.join(", ")} } from "effect/graphql"`)
1188 if (ctx.usesSchema) imports.push(`import * as Schema from "effect/Schema"`)
1189 const bySpecifier = Arr.groupBy(
1190 Array.from(ctx.imports.keys()).sort(),
1191 (name) => this.options.importSpecifier(file.outputPath, this.fragment(name).file.outputPath)
1192 )
1193 for (const specifier of Object.keys(bySpecifier).sort()) {
1194 imports.push(`import { ${bySpecifier[specifier].join(", ")} } from ${JSON.stringify(specifier)}`)
1195 }
1196 if (ctx.usesShared) {
1197 imports.push(
1198 `import * as Shared from ${
1199 JSON.stringify(this.options.importSpecifier(file.outputPath, this.options.sharedPath))
1200 }`
1201 )
1202 }
1203
1204 return {
1205 file: {
1206 path: file.outputPath,
1207 contents: `${[header(file.sourceName), ...imports].join("\n")}\n\n${blocks.join("\n\n")}\n`
1208 },
1209 errors
1210 }
1211 }
1212
1213 /**
1214 * Names the file's classes after their types. Classes that would share a
1215 * name, and ones whose name is `taken` or can't be bound, all add their
1216 * field's response key, then parent response keys one at a time, then
1217 * their definition's name, until the names are free. Ones that run out
1218 * are reported.
1219 */
1220 nameClasses(ctx: FileContext, taken: ReadonlyMap<string, string>): Array<string> {
1221 const classes = ctx.classes
1222 const levels = classes.map(() => 0)
1223 const nameAt = (extracted: ExtractedClass, level: number): string => {
1224 const keys = extracted.path.slice(Math.max(0, extracted.path.length - level)).map(capitalize).join("")
1225 return `${level > extracted.path.length ? extracted.definition : ""}${keys}${extracted.typeName}`
1226 }
1227 let names: Array<string>
1228 let counts: Map<string, number>
1229 let conflicts: Array<number>
1230 for (;;) {
1231 names = classes.map((extracted, i) => nameAt(extracted, levels[i]!))
1232 counts = new Map()
1233 for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1)
1234 conflicts = names.flatMap((name, i) => counts.get(name)! > 1 || taken.has(name) || unbindable(name) ? [i] : [])
1235 let advanced = false
1236 for (const i of conflicts) {
1237 if (levels[i]! <= classes[i]!.path.length) {
1238 levels[i]!++
1239 advanced = true
1240 }
1241 }
1242 if (!advanced) break
1243 }
1244 for (const i of conflicts.sort((a, b) => classes[a]!.offset - classes[b]!.offset)) {
1245 const name = names[i]!
1246 ctx.errors.push(make(
1247 ctx.file.source,
1248 classes[i]!.offset,
1249 counts.get(name)! > 1
1250 ? `Different selections here would all generate the class "${name}"; alias one of the fields.`
1251 : `The generated class name "${name}" ${taken.get(name) ?? "is reserved in generated code"}; alias the field.`
1252 ))
1253 }
1254 return names
1255 }
1256
1257 emitFragment(ctx: FileContext, definition: Ast.FragmentDefinition): string {
1258 const name = definition.name.value
1259 const type = this.type(definition.typeCondition.name.value)
1260 ctx.usesSchema = true
1261 const description = definition.description?.value ?? type.description
1262 const doc = docLines([`\`fragment ${name} on ${type.name}\``], descriptionLines(description))
1263 const selections = written(definition.selectionSet.selections)
1264 if (isAbstract(type)) {
1265 const body = this.abstractSelection(ctx, type, selections, "", false).code
1266 return `${jsdoc(doc, "")}export const ${name} = ${body}\nexport type ${name} = typeof ${name}.Type`
1267 }
1268 const body = this.selection(ctx, type.name, selections, "", true).code
1269 return `${
1270 jsdoc(doc, "")
1271 }export const ${name} = ${body}\nexport interface ${name} extends Schema.Struct.Type<typeof ${name}.fields> {}`
1272 }
1273
1274 emitOperation(ctx: FileContext, definition: Ast.OperationDefinition): string {
1275 const name = definition.name!.value
1276 const root = this.rootType(definition)
1277 ctx.usesGraphQL = true
1278 const doc = docLines(
1279 [`\`${definition.operation} ${name}\``],
1280 descriptionLines(definition.description?.value)
1281 )
1282 const lines = [` document: ${this.document(definition)},`]
1283 if (definition.variableDefinitions.length > 0) {
1284 const members = definition.variableDefinitions.map((variable) => {
1285 const defaultValue = variable.defaultValue === undefined
1286 ? undefined
1287 : SchemaModel.fromAstConstValue(variable.defaultValue)
1288 const type = SchemaModel.fromAstType(variable.type)
1289 const expression = inputSchema(type, defaultValue !== undefined, (name) => this.shared(ctx, name))
1290 ctx.usesSchema ||= expression.includes("Schema.")
1291 const variableDoc = docLines(descriptionLines(variable.description?.value), defaultTag(defaultValue))
1292 return `${jsdoc(variableDoc, " ")} ${propertyKey(variable.variable.name.value)}: ${expression}`
1293 })
1294 lines.push(` variables: {\n${members.join(",\n")}\n },`)
1295 }
1296 lines.push(` result: ${this.selection(ctx, root, written(definition.selectionSet.selections), " ").code}`)
1297 return [
1298 `${jsdoc(doc, "")}export const ${name} = GraphQL.${definition.operation}(${JSON.stringify(name)}, {`,
1299 ...lines,
1300 "})",
1301 `export declare namespace ${name} {`,
1302 ` export type Variables = typeof ${name}.variables.Type`,
1303 ` export type Result = typeof ${name}.result.Type`,
1304 "}"
1305 ].join("\n")
1306 }
1307
1308 /**
1309 * The `document` expression: the operation printed compactly, followed by
1310 * every fragment it uses in order of first use, with `__typename` added to
1311 * every selection on an interface or union that doesn't already select it.
1312 * Queries and mutations get a `DocumentTemplate` of that text, subscriptions
1313 * the text itself.
1314 */
1315 document(operation: Ast.OperationDefinition): string {
1316 const names = new Set(fragmentSpreads(operation.selectionSet).map((spread) => spread.name.value))
1317 for (const name of names) {
1318 for (const spread of fragmentSpreads(this.fragment(name).definition.selectionSet)) names.add(spread.name.value)
1319 }
1320 const root = {
1321 ...operation,
1322 selectionSet: this.withTypename(operation.selectionSet, this.rootType(operation))
1323 }
1324 const fragments = Array.from(names, (name) => {
1325 const fragment = this.fragment(name).definition
1326 return { ...fragment, selectionSet: this.withTypename(fragment.selectionSet, fragment.typeCondition.name.value) }
1327 })
1328 if (operation.operation === "subscription") {
1329 return JSON.stringify(print({ _tag: "Document", definitions: [root, ...fragments], loc: operation.loc }))
1330 }
1331 return emitTemplate(template(root, fragments))
1332 }
1333
1334 /**
1335 * Adds `__typename` to a selection set on an interface or union. Inline
1336 * fragments share their parent's response object, so the one added there
1337 * covers them (`inline`).
1338 */
1339 withTypename(selectionSet: Ast.SelectionSet, parentName: string, inline = false): Ast.SelectionSet {
1340 const parent = this.type(parentName)
1341 const selections = selectionSet.selections.map((selection): Ast.Selection => {
1342 switch (selection._tag) {
1343 case "Field": {
1344 if (selection.selectionSet === undefined) return selection
1345 const definition = this.fieldDefinition(parent, selection.name.value)
1346 return {
1347 ...selection,
1348 selectionSet: this.withTypename(selection.selectionSet, SchemaModel.namedTypeOf(definition.type))
1349 }
1350 }
1351 case "InlineFragment":
1352 return {
1353 ...selection,
1354 selectionSet: this.withTypename(
1355 selection.selectionSet,
1356 selection.typeCondition?.name.value ?? parentName,
1357 true
1358 )
1359 }
1360 case "FragmentSpread":
1361 return selection
1362 }
1363 })
1364 const selectsTypename = selections.some((selection) =>
1365 selection._tag === "Field" && selection.alias === undefined && selection.name.value === "__typename" &&
1366 selection.directives.length === 0
1367 )
1368 if (inline || !isAbstract(parent) || selectsTypename) return { ...selectionSet, selections }
1369 const loc = selectionSet.loc
1370 const typename: Ast.Field = {
1371 _tag: "Field",
1372 alias: undefined,
1373 name: { _tag: "Name", value: "__typename", loc },
1374 arguments: [],
1375 directives: [],
1376 selectionSet: undefined,
1377 loc
1378 }
1379 return { ...selectionSet, selections: [typename, ...selections] }
1380 }
1381
1382 // ---------------------------------------------------------------------------
1383 // Shared module
1384 // ---------------------------------------------------------------------------
1385
1386 /** The shared module, and the custom scalars it holds without a mapping. */
1387 emitShared(): { readonly file: GeneratedFile; readonly unmapped: ReadonlyArray<string> } {
1388 // Close over input objects in dependency order, keeping each cycle's
1389 // members together.
1390 const fieldTypes = (name: string): ReadonlyArray<string> => {
1391 const type = this.type(name)
1392 return type._tag === "InputObjectType" ? type.fields.map((field) => SchemaModel.namedTypeOf(field.type)) : []
1393 }
1394 const components = stronglyConnectedComponents(Array.from(this.reached).sort(), fieldTypes)
1395 const order = components.flat()
1396 const all = new Set(order)
1397 const inputs = order.flatMap((name) => {
1398 const type = this.type(name)
1399 return type._tag === "InputObjectType" ? [type] : []
1400 })
1401 /** Each recursive input object's cycle. */
1402 const cycles = new Map<string, ReadonlySet<string>>()
1403 /** The input objects whose Encoded type differs from their Type. */
1404 const transforms = new Set<string>()
1405 // A mapped scalar codec may transform; an unmapped custom scalar is `Schema.Json`.
1406 const transformsLeaf = (name: string): boolean =>
1407 this.type(name)._tag === "ScalarType"
1408 ? this.options.scalars.has(name) || builtInSharedScalars.get(name)?.transforms === true
1409 : transforms.has(name)
1410 for (const component of components) {
1411 const members = new Set(component)
1412 const leaves = component.flatMap(fieldTypes)
1413 if (members.size > 1 || leaves.includes(component[0])) {
1414 for (const name of component) cycles.set(name, members)
1415 }
1416 if (leaves.some((leaf) => !members.has(leaf) && transformsLeaf(leaf))) {
1417 for (const name of component) transforms.add(name)
1418 }
1419 }
1420 all.delete("String")
1421 all.delete("Boolean")
1422
1423 const byName = Array.from(all).sort()
1424 const builtIns = Array.from(builtInSharedScalars.keys()).filter((name) =>
1425 all.has(name) && this.type(name)._tag === "ScalarType"
1426 )
1427 const scalars = byName.filter((name) => this.type(name)._tag === "ScalarType" && !builtInSharedScalars.has(name))
1428 const enums = byName.flatMap((name) => {
1429 const type = this.type(name)
1430 return type._tag === "EnumType" ? [type] : []
1431 })
1432
1433 // Each type is exported under its GraphQL name, which per-file modules read
1434 // as `Shared.<name>`. A name the module can't bind gets a local alias,
1435 // and the module's own imports take names no type uses.
1436 const taken = new Set<string>([...byName, "Typename"])
1437 const allocate = (candidate: string): string => {
1438 let name = candidate
1439 for (let i = 2; taken.has(name) || unbindable(name); i++) name = `${candidate}${i}`
1440 taken.add(name)
1441 return name
1442 }
1443 const aliases = underscoreAliases(byName, taken)
1444 const alias = (name: string): string => aliases.get(name) ?? name
1445 const schema = allocate("Schema")
1446
1447 let usesSchema = enums.length > 0 || inputs.length > 0
1448 const modules = new Map<string, string>()
1449 const moduleName = (specifier: string): string => {
1450 if (specifier === "effect/Schema") {
1451 usesSchema = true
1452 return schema
1453 }
1454 const existing = modules.get(specifier)
1455 if (existing !== undefined) return existing
1456 const candidate = pascalCase(specifier.split("/").pop()!.replace(/\.[^.]*$/, ""))
1457 const name = allocate(candidate === "" || /^[0-9]/.test(candidate) ? "Scalars" : candidate)
1458 modules.set(specifier, name)
1459 return name
1460 }
1461 const scalarCodec = (name: string, fallback: string): string => {
1462 const mapping = this.options.scalars.get(name)
1463 if (mapping === undefined) {
1464 usesSchema = true
1465 return fallback
1466 }
1467 return `${moduleName(mapping.specifier)}.${mapping.exportName}`
1468 }
1469 /**
1470 * A documented declaration, exported under the GraphQL name: directly, or
1471 * through `export { alias as Name }` when the name can't be bound.
1472 * `declaration` puts `exported` before each statement it writes.
1473 */
1474 const declare = (
1475 name: string,
1476 doc: ReadonlyArray<string>,
1477 declaration: (binding: string, exported: string) => string
1478 ): string => {
1479 const binding = alias(name)
1480 return binding === name
1481 ? `${jsdoc(doc, "")}${declaration(name, "export ")}`
1482 : `${jsdoc(doc, "")}${declaration(binding, "")}\nexport { ${binding} as ${name} }`
1483 }
1484
1485 const blocks: Array<string> = []
1486 for (const name of [...builtIns, ...scalars]) {
1487 const codec = scalarCodec(name, builtInSharedScalars.get(name)?.codec(schema) ?? `${schema}.Json`)
1488 blocks.push(declare(name, descriptionLines(this.type(name).description), (b, e) => `${e}const ${b} = ${codec}`))
1489 }
1490 for (const type of enums) {
1491 const values = type.values.map((value) => {
1492 const description = descriptionLines(value.description).join(" ")
1493 const deprecated = value.deprecationReason === undefined
1494 ? ""
1495 : ` Deprecated: ${deprecation(value.deprecationReason)}`
1496 return `- \`${value.name}\`${description === "" ? "" : `: ${description}`}${deprecated}`
1497 })
1498 const literals = type.values.map((value) => JSON.stringify(value.name)).join(", ")
1499 blocks.push(declare(
1500 type.name,
1501 docLines(descriptionLines(type.description), values),
1502 (b, e) => `${e}const ${b} = ${schema}.Literals([${literals}])\n${e}type ${b} = typeof ${b}.Type`
1503 ))
1504 }
1505 // Recursive input objects whose Encoded type differs from their Type.
1506 const encodedNames = new Map<string, string>()
1507 for (const type of inputs) {
1508 if (cycles.has(type.name) && transforms.has(type.name)) {
1509 encodedNames.set(type.name, allocate(`${type.name}Encoded`))
1510 }
1511 }
1512 // Enums and input objects declare a type under their name; scalars don't.
1513 const typeLeaf = (name: string): string =>
1514 this.type(name)._tag === "ScalarType" ? `typeof ${alias(name)}.Type` : alias(name)
1515 const encodedLeaf = (name: string): string =>
1516 cycles.has(name) ? encodedNames.get(name) ?? alias(name) : `typeof ${alias(name)}.Encoded`
1517 for (const type of inputs) {
1518 const doc = descriptionLines(type.description)
1519 const cycle = cycles.get(type.name)
1520 if (cycle !== undefined) {
1521 const recursion: Recursion = {
1522 encoded: encodedNames.get(type.name),
1523 ref: (name) => cycle.has(name) ? `${schema}.suspend(() => ${alias(name)})` : alias(name),
1524 typeLeaf,
1525 encodedLeaf
1526 }
1527 blocks.push(declare(type.name, doc, (b, e) => recursiveDeclaration(type, b, e, schema, recursion)))
1528 continue
1529 }
1530 if (type.oneOf) {
1531 blocks.push(declare(type.name, doc, (b, e) => oneOfDeclaration(type, b, e, schema, alias, typeLeaf)))
1532 continue
1533 }
1534 const members = type.fields.map((field) => {
1535 const fieldDoc = docLines(
1536 descriptionLines(field.description),
1537 [...deprecatedTag(field.deprecationReason), ...defaultTag(field.defaultValue)]
1538 )
1539 return `${jsdoc(fieldDoc, " ")} ${propertyKey(field.name)}: ${
1540 inputSchema(field.type, field.defaultValue !== undefined, alias, schema)
1541 }`
1542 })
1543 const body = struct(members, "", schema)
1544 blocks.push(declare(
1545 type.name,
1546 doc,
1547 (b, e) => `${e}const ${b} = ${body}\n${e}interface ${b} extends ${schema}.Struct.Type<typeof ${b}.fields> {}`
1548 ))
1549 }
1550
1551 if (this.reachedAbstract.size > 0) {
1552 const members = Array.from(this.reachedAbstract).sort().map((name) => {
1553 const kind = this.type(name)._tag === "InterfaceType" ? "interface" : "union"
1554 const doc = ` /** Every possible \`__typename\` of ${kind} \`${name}\`. */\n`
1555 return `${doc}${
1556 literalUnion(` export type ${this.typenameAliases.get(name) ?? name} = `, this.possibleTypes(name), " ")
1557 }`
1558 })
1559 blocks.push(
1560 `/** The possible \`__typename\` values of each interface and union the operations select from. */\n` +
1561 `export declare namespace Typename {\n${members.join("\n")}\n}`
1562 )
1563 }
1564
1565 const imports: Array<string> = []
1566 if (usesSchema) imports.push(`import * as ${schema} from "effect/Schema"`)
1567 for (const [specifier, name] of modules) {
1568 imports.push(`import * as ${name} from ${JSON.stringify(specifier)}`)
1569 }
1570 const body = blocks.length === 0 ? "export {}" : blocks.join("\n\n")
1571 return {
1572 file: { path: this.options.sharedPath, contents: `${[header(undefined), ...imports].join("\n")}\n\n${body}\n` },
1573 unmapped: scalars.filter((name) => !this.options.scalars.has(name))
1574 }
1575 }
1576 }
1577
1578 /**
1579 * A `@oneOf` input object: a `Schema.Union` with one
1580 * struct per field, each with that field required and non-null and every
1581 * other field `optionalKey(Never)`, so an input with two keys or none fails to
1582 * encode. A class can't extend `Opaque` over a union, so it is an Opaque const
1583 * with the type written out beside it.
1584 */
1585 const oneOfDeclaration = (
1586 type: SchemaModel.InputObjectType,
1587 binding: string,
1588 exported: string,
1589 schema: string,
1590 ref: (name: string) => string,
1591 typeLeaf: (name: string) => string
1592 ): string =>
1593 `${exported}const ${binding} = ${schema}.Opaque<${binding}>()(${schema}.Union([\n${
1594 oneOfStructs(type, schema, ref).join(",\n")
1595 }\n]))\n` +
1596 `${exported}type ${binding} =\n${oneOfAlternatives(type, typeLeaf).join("\n")}`
1597
1598 const required = (field: SchemaModel.InputValue): SchemaModel.TypeRef =>
1599 field.type._tag === "NonNullTypeRef" ? field.type : { _tag: "NonNullTypeRef", ofType: field.type }
1600
1601 const oneOfStructs = (
1602 type: SchemaModel.InputObjectType,
1603 schema: string,
1604 ref: (name: string) => string
1605 ): Array<string> =>
1606 type.fields.map((selected) => {
1607 const members = type.fields.map((field) => {
1608 if (field !== selected) return ` ${propertyKey(field.name)}: ${schema}.optionalKey(${schema}.Never)`
1609 const doc = docLines(descriptionLines(field.description), deprecatedTag(field.deprecationReason))
1610 return `${jsdoc(doc, " ")} ${propertyKey(field.name)}: ${inputSchema(required(field), false, ref, schema)}`
1611 })
1612 return ` ${struct(members, " ", schema)}`
1613 })
1614
1615 const oneOfAlternatives = (type: SchemaModel.InputObjectType, leaf: (name: string) => string): Array<string> =>
1616 type.fields.map((selected) =>
1617 ` | { ${
1618 type.fields.map((field) =>
1619 field === selected
1620 ? `readonly ${propertyKey(field.name)}: ${inputTypeText(required(field), leaf)}`
1621 : `readonly ${propertyKey(field.name)}?: never`
1622 ).join("; ")
1623 } }`
1624 )
1625
1626 /** How a recursive input object refers to the types of its fields. */
1627 interface Recursion {
1628 /** The name of the Encoded type, when it differs from the Type. */
1629 readonly encoded: string | undefined
1630 /** The Schema for a type, suspended when it is on the same cycle. */
1631 readonly ref: (name: string) => string
1632 readonly typeLeaf: (name: string) => string
1633 readonly encodedLeaf: (name: string) => string
1634 }
1635
1636 /**
1637 * An input object on a cycle. TypeScript can't infer a const read in its own
1638 * initializer, so the Type, and the Encoded type when it differs, are written
1639 * out to annotate a `Schema.Codec`. References within the cycle are
1640 * suspended, since later members aren't initialized yet.
1641 */
1642 const recursiveDeclaration = (
1643 type: SchemaModel.InputObjectType,
1644 binding: string,
1645 exported: string,
1646 schema: string,
1647 recursion: Recursion
1648 ): string => {
1649 const { encoded, encodedLeaf, ref, typeLeaf } = recursion
1650 const codec = `${schema}.Codec<${binding}${encoded === undefined ? "" : `, ${encoded}`}>`
1651 if (type.oneOf) {
1652 return `${exported}const ${binding}: ${codec} = ${schema}.Union([\n${
1653 oneOfStructs(type, schema, ref).join(",\n")
1654 }\n])\n` +
1655 `${exported}type ${binding} =\n${oneOfAlternatives(type, typeLeaf).join("\n")}` +
1656 (encoded === undefined ? "" : `\nexport type ${encoded} =\n${oneOfAlternatives(type, encodedLeaf).join("\n")}`)
1657 }
1658 const members = type.fields.map((field) =>
1659 ` ${propertyKey(field.name)}: ${inputSchema(field.type, field.defaultValue !== undefined, ref, schema)}`
1660 )
1661 const fields = (leaf: (name: string) => string, documented: boolean): string => {
1662 if (type.fields.length === 0) return "{}"
1663 const lines = type.fields.map((field) => {
1664 const doc = documented
1665 ? docLines(
1666 descriptionLines(field.description),
1667 [...deprecatedTag(field.deprecationReason), ...defaultTag(field.defaultValue)]
1668 )
1669 : []
1670 const optional = field.defaultValue !== undefined || field.type._tag !== "NonNullTypeRef"
1671 return `${jsdoc(doc, " ")} readonly ${propertyKey(field.name)}${optional ? "?" : ""}: ${
1672 inputTypeText(field.type, leaf)
1673 }${optional ? " | undefined" : ""}`
1674 })
1675 return `{\n${lines.join("\n")}\n}`
1676 }
1677 return `${exported}const ${binding}: ${codec} = ${struct(members, "", schema)}\n` +
1678 `${exported}interface ${binding} ${fields(typeLeaf, true)}` +
1679 (encoded === undefined ? "" : `\nexport interface ${encoded} ${fields(encodedLeaf, false)}`)
1680 }
1681
1682 /**
1683 * The TypeScript type of an input, with `leaf` for each named type. Lists are
1684 * `readonly T[]`, since a generated type can be named `ReadonlyArray`.
1685 */
1686 const inputTypeText = (type: SchemaModel.TypeRef, leaf: (name: string) => string): string =>
1687 typeRef(
1688 type,
1689 (name) => name === "String" || name === "Boolean" ? name.toLowerCase() : leaf(name),
1690 (element) => `readonly ${/^[\w$]+$/.test(element) ? element : `(${element})`}[]`,
1691 (inner) => `${inner} | null`
1692 )
1693
1694 /** A string or string array literal. */
1695 const literal = (value: string | ReadonlyArray<string>): string =>
1696 typeof value === "string" ? JSON.stringify(value) : `[${value.map((item) => JSON.stringify(item)).join(", ")}]`
1697
1698 /** A `DocumentTemplate` literal with one line per entry, keys in the order `Printer.template` builds them. */
1699 const emitTemplate = ({ directives, fragments, selections, variables }: GraphQL.DocumentTemplate): string => {
1700 const list = (key: string, entries: ReadonlyArray<object>) =>
1701 entries.length === 0 ?
1702 ` ${key}: []` :
1703 ` ${key}: [\n${
1704 entries.map((entry) =>
1705 ` { ${Object.entries(entry).map(([name, value]) => `${name}: ${literal(value)}`).join(", ")} }`
1706 ).join(",\n")
1707 }\n ]`
1708 const fields = [
1709 list("variables", variables),
1710 ...(directives === undefined ? [] : [` directives: ${literal(directives)}`]),
1711 list("selections", selections),
1712 list("fragments", fragments)
1713 ]
1714 return `{\n${fields.join(",\n")}\n }`
1715 }