Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
2320 lines (2204 loc) · 110 KB
/
Copy pathindex.ts
File metadata and controls
2320 lines (2204 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { isAbsolute, join } from "node:path"
import { Context, Effect, FileSystem, PlatformError, Schema, SchemaAST, SchemaRepresentation } from "effect"
import { HttpMethod, type HttpRouter } from "effect/http"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api"
import { format } from "prettier"
export type InputField = {
readonly name: string
readonly source: "params" | "query" | "headers" | "payload"
}
export type OperationInputField = {
readonly name: string
readonly source: InputField["source"] | "wildcard"
}
export type Operation = {
readonly group: string
readonly name: string
readonly input: ReadonlyArray<OperationInputField>
readonly inputMode: "none" | "optional" | "required"
readonly success: "value" | "void" | "stream"
readonly errors: ReadonlyArray<string>
}
export type Output = {
readonly operations: ReadonlyArray<Operation>
readonly files: ReadonlyArray<{
readonly path: string
readonly content: string
}>
}
export type Contract = {
readonly groups: ReadonlyArray<Group>
readonly aliases?: ReadonlyArray<Alias>
}
/** A namespaced endpoint's pre-namespace client path and group, kept as a deprecated alias of its new location. */
export type Alias = {
readonly from: ReadonlyArray<string>
readonly to: ReadonlyArray<string>
readonly fromGroup: string
readonly group: Group
readonly endpoint: Endpoint
}
export type EffectTypeReference = {
readonly schema: Schema.Top
readonly name: string
readonly import: string
}
export type EffectOutputType = {
readonly name: string
readonly import: string
}
type ResolvedEffectTypeReference = Omit<EffectTypeReference, "schema"> & {
readonly ast: SchemaAST.AST
readonly type: string | undefined
}
export class GenerationError extends Schema.TaggedError<GenerationError>()("GenerationError", {
reason: Schema.String,
}) {
override get message() {
return this.reason
}
}
export type Endpoint = {
readonly group: string
readonly groupPath: ReadonlyArray<string>
readonly sourceGroup: string
readonly topLevel: boolean
readonly endpoint: HttpApiEndpoint.Top
readonly params: Schema.Top | undefined
readonly query: Schema.Top | undefined
readonly headers: Schema.Top | undefined
readonly payloads: ReadonlyArray<Schema.Top>
readonly operation: Operation
readonly clientPath: readonly [string, ...Array<string>]
readonly input: ReadonlyArray<InputField & { readonly optional: boolean }>
readonly unwrapData: boolean
readonly errors: ReadonlyArray<{ readonly status: number; readonly schema: Schema.Top }>
readonly successes: ReadonlyArray<Schema.Top>
readonly effectPortable: boolean
}
export type Group = {
readonly identifier: string
/** Where the group's methods live on the client; empty for top-level groups outside a namespace. */
readonly path: ReadonlyArray<string>
readonly sourceIdentifier: string
readonly module: string
readonly endpoints: ReadonlyArray<Endpoint>
}
type Slot = {
readonly name: string
readonly schema: Schema.Top
}
type PromiseInputField =
| (InputField & { readonly optional: boolean })
| { readonly name: string; readonly source: "wildcard"; readonly optional: false }
const resolveHttpApiStatus = (ast: SchemaAST.AST) =>
SchemaAST.resolveAt<number>("httpApiStatus")(ast) ??
(ast.checks === undefined ? ast.context?.annotations?.httpApiStatus : undefined)
const resolveHttpApiEncoding = SchemaAST.resolveAt<HttpApiSchema.Encoding>("~httpApiEncoding")
const Manifest = Schema.fromJsonString(Schema.Array(Schema.String))
const manifestName = ".httpapi-codegen.json"
export function compile<Id extends string, Groups extends HttpApiGroup.Constraint>(
api: HttpApi.HttpApi<Id, Groups>,
options?: {
readonly groupNames?: Readonly<Record<string, string>>
readonly omitEndpoints?: ReadonlySet<string>
/**
* Nests an endpoint's group under a client namespace, so `client.<group>.<method>` becomes
* `client.<namespace>.<group>.<method>`. A group whose name equals the namespace is not repeated.
*/
readonly namespace?: (endpoint: HttpApiEndpoint.Top) => string | undefined
/**
* Keeps each namespaced endpoint's pre-namespace client path and generated type names as deprecated aliases of
* the namespaced ones, so moving an endpoint into a namespace does not break callers.
*/
readonly aliases?: boolean
},
): Contract {
const endpoints: Array<Endpoint> = []
const portable = new Map<SchemaAST.AST, boolean>()
// Where each namespaced endpoint would sit without its namespace.
const unnamespaced = new Map<Endpoint, { readonly group: string; readonly path: ReadonlyArray<string> }>()
HttpApi.reflect(api, {
onGroup() {},
onEndpoint({ endpoint, errors, group, middleware }) {
if (options?.omitEndpoints?.has(endpoint.identifier)) return
const sourceName = options?.groupNames?.[group.identifier] ?? group.identifier
const namespace = options?.namespace?.(endpoint)
if (namespace === "" || namespace === "__proto__") {
throw new GenerationError({ reason: `Invalid client namespace: ${JSON.stringify(namespace)}` })
}
const groupName = namespace === undefined || namespace === sourceName ? sourceName : `${namespace}.${sourceName}`
const groupPath =
namespace === undefined
? group.topLevel
? []
: [sourceName]
: group.topLevel || namespace === sourceName
? [namespace]
: [namespace, sourceName]
const name = `${groupName}.${endpoint.identifier}`
const required = Array.from(middleware).find((item) => item.requiredForClient)
if (required !== undefined) {
throw new GenerationError({ reason: `Client middleware requires adapter: ${required.key}` })
}
const successSchemas = Array.from(endpoint.success)
if (successSchemas.length === 0) successSchemas.push(HttpApiSchema.NoContent)
if (successSchemas.length > 1) throw new GenerationError({ reason: `Multiple success schemas: ${name}` })
const params = normalizeTransport(endpoint.params, "params", endpoint, name)
const query = normalizeTransport(endpoint.query, "query", endpoint, name)
const headers = normalizeTransport(endpoint.headers, "headers", endpoint, name)
const sourcePayloads = Array.from(endpoint.payload.values()).flatMap(({ schemas }) => schemas)
if (sourcePayloads.length > 1) {
throw new GenerationError({ reason: `Multiple payload schemas: ${name}` })
}
const payloads = sourcePayloads.map((schema) => normalizeTransport(schema, "payload", endpoint, name)!)
const success = normalizeTransport(successSchemas[0], "success", endpoint, name)!
// Sort by status so output does not churn when middleware changes the declaration order.
const errorSchemas = Array.from(errors)
.toSorted(([a], [b]) => a - b)
.flatMap(([status, schemas]) =>
schemas.map((schema) => ({ status, ...normalizeTransport(schema, "error", endpoint, name)! })),
)
const inputs = [
...inputFields(params?.schema, "params", name),
...inputFields(query?.schema, "query", name),
...inputFields(headers?.schema, "headers", name),
...payloads.flatMap((item) => inputFields(item.schema, "payload", name)),
]
const names = new Map<string, InputField["source"]>()
for (const field of inputs) {
const existing = names.get(field.name)
if (existing !== undefined) {
if (field.source === "payload" && payloads[0] !== undefined && !isFlattenableStruct(payloads[0].schema)) {
throw new GenerationError({
reason: `Opaque payload field collision: ${name}.payload conflicts with ${existing}.${field.name}`,
})
}
throw new GenerationError({ reason: `Input field collision: ${field.name}` })
}
names.set(field.name, field.source)
}
const schemaPaths: Array<readonly [string, Schema.Top]> = [
...(params === undefined ? [] : [[`${name}.params`, params.schema] as const]),
...(query === undefined ? [] : [[`${name}.query`, query.schema] as const]),
...(headers === undefined ? [] : [[`${name}.headers`, headers.schema] as const]),
...payloads.map((item) => [`${name}.payload`, item.schema] as const),
...responseSchemas(success.schema, `${name}.success`),
...errorSchemas.map((item) => [`${name}.error.${item.status}`, item.schema] as const),
]
const effectPortable =
[params, query, headers, ...payloads, success, ...errorSchemas].every(
(item) => item?.effectPortable !== false,
) && streamEffectPortable(success.schema)
if (effectPortable) {
for (const [path, schema] of schemaPaths) assertPortable(schema, path, portable)
}
const clientPath = clientEndpointPath(
group.identifier,
Context.getOrElse(endpoint.annotations, OpenApi.Identifier, () =>
group.topLevel ? endpoint.identifier : `${group.identifier}.${endpoint.identifier}`,
),
)
const compiled: Endpoint = {
group: groupName,
groupPath,
sourceGroup: group.identifier,
topLevel: group.topLevel,
endpoint,
params: params?.schema,
query: query?.schema,
headers: headers?.schema,
payloads: payloads.map((item) => item.schema),
input: inputs,
clientPath,
unwrapData: isDataEnvelope(success.schema),
successes: [success.schema],
errors: errorSchemas.map((item) => ({ status: item.status, schema: item.schema })),
effectPortable,
operation: {
group: groupName,
name: clientPath.join("."),
input: inputs.map(({ name, source }) => ({ name, source })),
inputMode: inputs.length === 0 ? "none" : inputs.every((field) => field.optional) ? "optional" : "required",
success: isStreamSchema(success.schema)
? "stream"
: HttpApiSchema.isNoContent(success.schema.ast)
? "void"
: "value",
errors: [
...new Set([
...errorSchemas.flatMap((item) => {
const identifier = SchemaAST.resolveIdentifier(item.schema.ast)
return identifier === undefined ? [] : [identifier]
}),
"ClientError",
]),
],
},
}
endpoints.push(compiled)
if (namespace !== undefined && namespace !== sourceName) {
unnamespaced.set(compiled, { group: sourceName, path: group.topLevel ? [] : [sourceName] })
}
},
})
const modules = new Set(["client", "client-error", "index"])
const groups = Array.from(
Map.groupBy(endpoints, (endpoint) => endpoint.group),
([identifier, endpoints]) => {
if (new Set(endpoints.map((endpoint) => endpoint.sourceGroup)).size > 1) {
throw new GenerationError({ reason: `Client group name collision: ${identifier}` })
}
const path = endpoints[0].groupPath
if (endpoints.some((endpoint) => endpoint.groupPath.join("\0") !== path.join("\0"))) {
throw new GenerationError({ reason: `Client group path conflict: ${identifier}` })
}
// Module names derive from the group identifier so unrelated groups never rename.
const sanitized = identifier.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "")
const reserved = /^(aux|client|client-error|con|index|nul|prn|com[1-9]|lpt[1-9])$/i.test(sanitized)
const module = sanitized === "" || reserved ? `group-${sanitized}` : sanitized
if (modules.has(module.toLowerCase())) {
throw new GenerationError({ reason: `Client module name collision: ${module}` })
}
modules.add(module.toLowerCase())
return { identifier, path, sourceIdentifier: endpoints[0].sourceGroup, module, endpoints }
},
)
const groupTypeNames = new Set<string>()
const endpointTypeNames = new Set<string>()
const operationKeys = new Set<string>()
for (const group of groups) {
if (group.identifier === "__proto__") {
throw new GenerationError({ reason: "Client group name cannot be __proto__" })
}
const groupTypeName = identifierPart(group.identifier)
if (groupTypeNames.has(groupTypeName)) {
throw new GenerationError({ reason: `Client group type collision: ${groupTypeName}` })
}
groupTypeNames.add(groupTypeName)
assertUniqueClientPaths(
group.endpoints.map((endpoint) => endpoint.clientPath),
(path) => `Client endpoint name collision: ${group.identifier}.${path.join(".")}`,
)
const typeNames = new Set<string>()
for (const endpoint of group.endpoints) {
const operationKey = clientOperationKey(group, endpoint)
if (operationKeys.has(operationKey)) {
throw new GenerationError({ reason: `Client operation key collision: ${operationKey}` })
}
operationKeys.add(operationKey)
const name = endpoint.clientPath.map(identifierPart).join("")
const endpointTypeName = `${groupTypeName}${name}`
if (endpointTypeNames.has(endpointTypeName)) {
throw new GenerationError({ reason: `Client endpoint type collision: ${endpointTypeName}` })
}
endpointTypeNames.add(endpointTypeName)
if (typeNames.has(name)) {
throw new GenerationError({ reason: `Client endpoint type collision: ${group.identifier}.${name}` })
}
typeNames.add(name)
}
}
const visit = (node: GroupNode, path: ReadonlyArray<string>) => {
const keys = new Set<string>()
for (const entry of node.entries) {
const names =
typeof entry === "string" ? [entry] : [...new Set(entry.endpoints.map((item) => item.clientPath[0]))]
for (const name of names) {
if (keys.has(name)) throw new GenerationError({ reason: `Client name collision: ${[...path, name].join(".")}` })
keys.add(name)
}
}
for (const [name, child] of node.children) visit(child, [...path, name])
}
visit(groupTree(groups), [])
if (options?.aliases !== true) return { groups }
const aliases = groups.flatMap((group) =>
group.endpoints.flatMap((endpoint): Array<Alias> => {
const previous = unnamespaced.get(endpoint)
if (previous === undefined) return []
return [
{
from: [...previous.path, ...endpoint.clientPath],
to: [...group.path, ...endpoint.clientPath],
fromGroup: previous.group,
group,
endpoint,
},
]
}),
)
const paths = groups.flatMap((group) => group.endpoints.map((endpoint) => [...group.path, ...endpoint.clientPath]))
for (const alias of aliases) {
const key = alias.from.join("\0")
const conflict = paths.some((path) => {
const other = path.join("\0")
return other === key || other.startsWith(`${key}\0`) || key.startsWith(`${other}\0`)
})
if (conflict) throw new GenerationError({ reason: `Client alias collision: ${alias.from.join(".")}` })
}
assertUniqueClientPaths(
aliases.map((alias) => alias.from),
(path) => `Client alias collision: ${path.join(".")}`,
)
return { groups, aliases }
}
export function emitEffect(contract: Contract): Output {
const endpoint = contract.groups.flatMap((group) => group.endpoints).find((endpoint) => !endpoint.effectPortable)
if (endpoint !== undefined) {
throw new GenerationError({
reason: `Effect schema requires authoritative import: ${endpoint.group}.${endpoint.endpoint.identifier}`,
})
}
return { operations: operations(contract.groups), files: renderEffectFiles(contract.groups, contract.aliases ?? []) }
}
export function emitEffectImported(
contract: Contract,
options:
| { readonly module: string; readonly api: string; readonly shapeModule?: string }
| { readonly module: string; readonly group: string; readonly shapeModule?: string }
| {
readonly module: string
readonly endpoints: Readonly<Record<string, string>>
readonly shapeModule?: string
},
): Output {
return {
operations: operations(contract.groups),
files: renderImportedEffectFiles(contract.groups, contract.aliases ?? [], options),
}
}
export function emitEffectShape(
contract: Contract,
options?: {
readonly typeReferences?: ReadonlyArray<EffectTypeReference>
readonly outputTypes?: Readonly<Record<string, EffectOutputType>>
},
): Output {
return {
operations: operations(contract.groups),
files: [
{
path: "api.ts",
content: renderEffectShape(
contract.groups,
options?.typeReferences ?? [],
options?.outputTypes,
contract.aliases ?? [],
),
},
],
}
}
export function emitPromise(
contract: Contract,
options?: {
readonly outputTypes?: Readonly<Record<string, { readonly name: string; readonly import: string }>>
readonly mutableOutputs?: boolean
},
): Output {
const groups = contract.groups
for (const group of groups) {
for (const endpoint of group.endpoints) assertPromiseEndpoint(endpoint)
}
return {
operations: promiseOperations(groups),
files: [
{
path: "types.ts",
content: renderPromiseTypes(groups, options?.outputTypes, options?.mutableOutputs ?? false, contract.aliases),
},
{
path: "client-error.ts",
content: `export type ClientErrorReason = "Transport" | "UnexpectedStatus" | "UnsupportedContentType" | "MalformedResponse" | "SseEventTooLarge"\n\nexport class ClientError extends Error {\n override readonly name = "ClientError"\n constructor(readonly reason: ClientErrorReason, options?: ErrorOptions & { readonly detail?: string | null }) {\n const detail = options?.detail ?? (options?.cause instanceof Error ? options.cause.message : undefined)\n super(detail ? \`\${reason}: \${detail}\` : reason, options)\n }\n}\n`,
},
{
path: "client.ts",
content: normalizePromiseClientContent(renderPromiseClient(groups, contract.aliases), groups),
},
{
path: "index.ts",
content:
'export { ClientError, type ClientErrorReason } from "./client-error.js"\nexport * as OpenCode from "./client.js"\nexport * from "./types.js"\n',
},
],
}
}
function renderEffectShape(
groups: ReadonlyArray<Group>,
typeReferences: ReadonlyArray<EffectTypeReference>,
outputTypes: Readonly<Record<string, EffectOutputType>> | undefined,
aliases: ReadonlyArray<Alias>,
) {
const references = effectTypeReferences(typeReferences)
const imports = new Set<string>()
const externalNames = new Set([
"AppApi",
"Effect",
"Stream",
...typeReferences.flatMap((reference) => reference.name.match(/^[A-Za-z_$][A-Za-z0-9_$]*/) ?? []),
...Object.values(outputTypes ?? {}).flatMap((output) => output.name.match(/^[A-Za-z_$][A-Za-z0-9_$]*/) ?? []),
])
const generatedNames = groups.flatMap((group) => [
groupShapeName(group),
...group.endpoints.flatMap((endpoint) => [
...(endpoint.operation.inputMode === "none" ? [] : [`${endpointTypeName(group, endpoint)}Input`]),
`${endpointTypeName(group, endpoint)}Output`,
groupShapeTypeName(group, endpoint),
]),
])
const collision = generatedNames.find((name) => externalNames.has(name))
if (collision !== undefined) {
throw new GenerationError({ reason: `Generated Effect type collides with imported type: ${collision}` })
}
// An alias joins the interface of the deepest group above its old path, so code typed against that group keeps
// compiling; an alias with no such group becomes a field of AppApi.
type AliasField = { readonly path: ReadonlyArray<string>; readonly value: string; readonly alias: Alias }
const groupAliases = new Map<Group, Array<AliasField>>()
const rootAliases: Array<AliasField> = []
for (const alias of aliases) {
const value = `${groupShapeTypeName(alias.group, alias.endpoint)}<E>`
const owner = groups
.filter(
(group) =>
group.path.length > 0 &&
group.path.length < alias.from.length &&
group.path.every((name, index) => alias.from[index] === name),
)
.toSorted((a, b) => b.path.length - a.path.length)[0]
if (owner === undefined) {
rootAliases.push({ path: alias.from, value, alias })
continue
}
groupAliases.set(owner, [
...(groupAliases.get(owner) ?? []),
{ path: alias.from.slice(owner.path.length), value, alias },
])
}
const rootNames = new Set(
groups.flatMap((group) => group.endpoints.map((endpoint) => [...group.path, ...endpoint.clientPath][0])),
)
const unowned = rootAliases.find((item) => rootNames.has(item.path[0]))
if (unowned !== undefined) {
throw new GenerationError({ reason: `Client alias has no group to join: ${unowned.alias.from.join(".")}` })
}
const aliasTypes: Array<{ readonly name: string; readonly target: string; readonly generic?: true }> =
aliases.flatMap((alias) => {
const from = `${identifierPart(alias.fromGroup)}${alias.endpoint.clientPath.map(identifierPart).join("")}`
const to = endpointTypeName(alias.group, alias.endpoint)
return [
...(alias.endpoint.operation.inputMode === "none" ? [] : [{ name: `${from}Input`, target: `${to}Input` }]),
{ name: `${from}Output`, target: `${to}Output` },
{ name: `${from}Operation`, target: `${to}Operation`, generic: true as const },
]
})
// A group whose endpoints all moved into one group keeps its interface name as an alias of that group's.
for (const fromGroup of new Set(aliases.map((alias) => alias.fromGroup))) {
if (groups.some((group) => group.identifier === fromGroup)) continue
const moved = aliases.filter((alias) => alias.fromGroup === fromGroup)
const target = moved[0].group
if (moved.some((alias) => alias.group !== target) || moved.length !== target.endpoints.length) continue
aliasTypes.push({ name: `${identifierPart(fromGroup)}Api`, target: groupShapeName(target), generic: true })
}
const takenNames = new Set([...externalNames, ...generatedNames])
for (const { name } of aliasTypes) {
if (takenNames.has(name)) throw new GenerationError({ reason: `Client type alias collision: ${name}` })
takenNames.add(name)
}
const renderedAliasTypes = aliasTypes.map(
(item) =>
`${deprecatedTypeAliasDoc(item.target)}\nexport type ${item.name}${item.generic ? "<E = never>" : ""} = ${item.target}${item.generic ? "<E>" : ""}`,
)
const endpointTypes = groups.map((group) => {
const endpoints = group.endpoints.map((endpoint) => {
const prefix = endpointTypeName(group, endpoint)
const input = endpoint.input
.map((field) => {
const schema = effectInputSchema(endpoint, field)
if (schema === undefined) {
throw new GenerationError({
reason: `Missing Effect input schema: ${endpoint.group}.${endpoint.endpoint.identifier}.${field.name}`,
})
}
return `readonly ${JSON.stringify(field.name)}${field.optional ? "?" : ""}: ${effectType(schema, references, imports)}`
})
.join("; ")
const inputType = endpoint.operation.inputMode === "none" ? "" : `export type ${prefix}Input = { ${input} }`
const output = effectOutputSchema(endpoint)
const override = outputTypes?.[clientOperationKey(group, endpoint)]
if (override !== undefined) imports.add(override.import)
const outputType = `export type ${prefix}Output = ${override?.name ?? (output === undefined ? "void" : effectType(output, references, imports))}`
return [
endpoint.operation.inputMode === "none" ? "" : inputType,
outputType,
`export type ${groupShapeTypeName(group, endpoint)}<E = never> = (${endpoint.operation.inputMode === "none" ? "" : `input${endpoint.operation.inputMode === "optional" ? "?" : ""}: ${prefix}Input`}) => ${endpoint.operation.success === "stream" ? `Stream.Stream<${prefix}Output, E>` : `Effect.Effect<${prefix}Output, E>`}`,
]
.filter(Boolean)
.join("\n")
})
const methods = renderClientTree(
group.endpoints,
(endpoint) => `${groupShapeTypeName(group, endpoint)}<E>`,
(name, value) => `readonly ${JSON.stringify(name)}: ${value}`,
"\n",
groupAliases.get(group),
)
return `${endpoints.join("\n\n")}\n\nexport interface ${groupShapeName(group)}<E = never> {\n${methods}\n}`
})
const clientFields = renderGroupTree(
groups,
(group) =>
group.endpoints[0]?.topLevel
? {
fields: renderClientTree(
group.endpoints,
(endpoint) => `${groupShapeTypeName(group, endpoint)}<E>`,
(name, value) => `readonly ${JSON.stringify(name)}: ${value}`,
"\n",
),
}
: { whole: `${groupShapeName(group)}<E>` },
(name, value) => `readonly ${JSON.stringify(name)}: ${value}`,
(wholes, fields) => [...wholes, ...(fields.length === 0 ? [] : [`{\n${fields.join("\n")}\n}`])].join(" & "),
"\n",
)
const rootAliasFields = renderClientTree(
[],
() => "",
(name, value) => `readonly ${JSON.stringify(name)}: ${value}`,
"\n",
rootAliases,
)
return `// Generated by @opencode/httpapi-codegen. Do not edit.
import type { Effect, Stream } from "effect"
${[...imports].join("\n")}
${[...endpointTypes, ...renderedAliasTypes].join("\n\n")}
export interface AppApi<E = never> {
${[clientFields, rootAliasFields].filter(Boolean).join("\n")}
}
`
}
function effectTypeReferences(input: ReadonlyArray<EffectTypeReference>) {
const names = new Map<string, ResolvedEffectTypeReference>()
const asts = new Map<SchemaAST.AST, ResolvedEffectTypeReference>()
for (const reference of input) {
if (SchemaAST.resolveIdentifier(reference.schema.ast) === undefined) continue
const projected = Schema.toType(reference.schema)
const document = SchemaRepresentation.toCodeDocument(
SchemaRepresentation.toRepresentations([codegenAst(projected.ast)]),
)
const name = document.codes[0]?.Type
const type =
name === undefined ? undefined : document.references.nonRecursives.find((item) => item.$ref === name)?.code.Type
const value = { name: reference.name, import: reference.import, ast: reference.schema.ast, type }
asts.set(reference.schema.ast, value)
asts.set(projected.ast, value)
if (name === undefined || type === undefined || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) continue
const previous = names.get(name)
if (previous !== undefined) {
if (previous.ast !== reference.schema.ast) {
throw new GenerationError({ reason: `Conflicting Effect type reference: ${name}` })
}
continue
}
names.set(name, value)
}
return { names, asts }
}
function effectType(schema: Schema.Top, references: ReturnType<typeof effectTypeReferences>, imports: Set<string>) {
const projected = Schema.toType(schema)
const direct = references.asts.get(schema.ast) ?? references.asts.get(projected.ast)
if (direct !== undefined) {
imports.add(direct.import)
return direct.name
}
const document = SchemaRepresentation.toCodeDocument(
SchemaRepresentation.toRepresentations([codegenAst(projected.ast)]),
)
const source = new Map(document.references.nonRecursives.map((reference) => [reference.$ref, reference.code.Type]))
const expand = (type: string, seen = new Set<string>()): string => {
for (const [name, value] of source) {
const pattern = new RegExp(
`(?<![A-Za-z0-9_$.'\"])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_$.'\"])`,
"g",
)
if (!pattern.test(type)) continue
// Optional/encoded occurrences can acquire a numeric suffix. Reuse the named
// type only when its definition matches; a suffix can also denote a different shape.
const candidate = references.names.get(name.replace(/_\d+$/, ""))
const reference = references.names.get(name) ?? (candidate?.type === value ? candidate : undefined)
if (reference !== undefined) {
imports.add(reference.import)
type = type.replace(pattern, reference.name)
continue
}
if (seen.has(name)) continue
type = type.replace(pattern, `(${expand(value, new Set([...seen, name]))})`)
}
return type
}
const type = expand(document.codes[0].Type)
if (type.includes("DateTime.")) imports.add('import type { DateTime } from "effect"')
if (type.includes("Schema.")) imports.add('import type { Schema } from "effect"')
return type
}
function effectInputSchema(endpoint: Endpoint, field: InputField): Schema.Top | undefined {
const schema =
field.source === "params"
? endpoint.params
: field.source === "query"
? endpoint.query
: field.source === "headers"
? endpoint.headers
: endpoint.payloads[0]
if (schema === undefined) return undefined
if (isOpaquePayload(endpoint) && field.source === "payload") return schema
const ast = Schema.toType(schema).ast
if (!SchemaAST.isObjects(ast)) return undefined
const property = ast.propertySignatures.find((property) => property.name === field.name)
return property === undefined ? undefined : Schema.make<Schema.Top>(property.type)
}
function effectOutputSchema(endpoint: Endpoint): Schema.Top | undefined {
const schema = endpoint.successes[0]
if (HttpApiSchema.isNoContent(schema.ast)) return undefined
if (isStreamSchema(schema)) {
if (schema._tag === "StreamUint8Array") return Schema.Uint8Array
return schema.sseMode === "data" ? streamDataSchema(schema) : Schema.make<Schema.Top>(schema.events.ast)
}
if (!endpoint.unwrapData) return schema
const ast = Schema.toType(schema).ast
if (!SchemaAST.isObjects(ast)) return undefined
const data = ast.propertySignatures.find((property) => property.name === "data")
return data === undefined ? undefined : Schema.make<Schema.Top>(data.type)
}
function groupShapeName(group: Group) {
return `${identifierPart(group.identifier)}Api`
}
// Generated symbol names derive from group and endpoint identity, never from traversal
// position, so adding an endpoint or group cannot rename unrelated generated code.
// Uniqueness is validated by compile (groupTypeNames/endpointTypeNames).
function groupTypeName(group: Group) {
return identifierPart(group.identifier)
}
function endpointTypeName(group: Group, endpoint: Endpoint) {
return `${groupTypeName(group)}${endpoint.clientPath.map(identifierPart).join("")}`
}
function endpointAdapterName(group: Group, endpoint: Endpoint) {
return `Endpoint${endpointTypeName(group, endpoint)}`
}
function groupShapeTypeName(group: Group, endpoint: Endpoint) {
return `${endpointTypeName(group, endpoint)}Operation`
}
function assertPromiseEndpoint(endpoint: Endpoint) {
const name = `${endpoint.group}.${endpoint.endpoint.identifier}`
const payload = endpoint.payloads[0]
const payloadEncoding =
payload === undefined
? undefined
: (resolveHttpApiEncoding(payload.ast)?._tag ??
(HttpMethod.hasBody(endpoint.endpoint.method) ? "Json" : "FormUrlEncoded"))
if (payloadEncoding !== undefined && payloadEncoding !== "Json" && payloadEncoding !== "Uint8Array") {
throw new GenerationError({ reason: `Unsupported Promise payload encoding: ${name}` })
}
const success = endpoint.successes[0]
if (isStreamSchema(success)) {
if (
success._tag !== "StreamSse" ||
success.sseMode !== "data" ||
!SchemaAST.isNever(Schema.toType(success.error).ast)
) {
throw new GenerationError({ reason: `Unsupported Promise stream: ${name}` })
}
} else if (!HttpApiSchema.isNoContent(success.ast)) {
const encoding = resolveHttpApiEncoding(success.ast)?._tag ?? "Json"
if (encoding !== "Json" && encoding !== "Uint8Array") {
throw new GenerationError({ reason: `Unsupported Promise success encoding: ${name}` })
}
}
for (const error of endpoint.errors) {
if (declaredErrorFields(error.schema) === undefined) {
throw new GenerationError({ reason: `Promise error must have a literal discriminator: ${name}` })
}
if ((resolveHttpApiEncoding(error.schema.ast)?._tag ?? "Json") !== "Json") {
throw new GenerationError({ reason: `Unsupported Promise error encoding: ${name}` })
}
}
}
function operations(groups: ReadonlyArray<Group>) {
return groups.flatMap((group) => group.endpoints.map((endpoint) => endpoint.operation))
}
function promiseOperations(groups: ReadonlyArray<Group>) {
return groups.flatMap((group) =>
group.endpoints.map((endpoint) => ({
...endpoint.operation,
input: promiseInput(endpoint).map(({ name, source }) => ({ name, source })),
inputMode: promiseInputMode(endpoint),
})),
)
}
function renderEffectFiles(groups: ReadonlyArray<Group>, aliases: ReadonlyArray<Alias>): Output["files"] {
return [
...groups.map((group) => ({ path: `${group.module}.ts`, content: renderGroup(group) })),
{
path: "client-error.ts",
content:
'import { Schema } from "effect"\n\nexport class ClientError extends Schema.TaggedError<ClientError>()("ClientError", {\n cause: Schema.Defect(),\n}) {}\n',
},
{ path: "client.ts", content: renderClient(groups, aliases) },
{
path: "index.ts",
content: 'export { ClientError } from "./client-error.js"\nexport * as OpenCode from "./client.js"\n',
},
]
}
function renderImportedEffectFiles(
groups: ReadonlyArray<Group>,
aliases: ReadonlyArray<Alias>,
options:
| { readonly module: string; readonly api: string; readonly shapeModule?: string }
| { readonly module: string; readonly group: string; readonly shapeModule?: string }
| {
readonly module: string
readonly endpoints: Readonly<Record<string, string>>
readonly shapeModule?: string
},
): Output["files"] {
// An imported Api or group keeps its source group names; a projection rebuilds groups under their client names.
const rawKey = (group: Group) => JSON.stringify("endpoints" in options ? group.identifier : group.sourceIdentifier)
const adapters = groups.map((group) => {
const rawGroup = group.endpoints[0]?.topLevel ? "RawClient" : `RawClient[${rawKey(group)}]`
const methods = group.endpoints.map((item) => {
const prefix = endpointTypeName(group, item)
const adapter = endpointAdapterName(group, item)
const schemaBySource = {
params: item.params,
query: item.query,
headers: item.headers,
payload: item.payloads[0],
}
const request = (["params", "query", "headers", "payload"] as const)
.map((source) =>
renderEffectRequestPart(
item.input,
item.operation.inputMode,
source,
isOpaquePayload(item),
schemaBySource[source] !== undefined,
),
)
.filter((part): part is string => part !== undefined)
.join(", ")
const input = item.input
.map(
(field) =>
`readonly ${JSON.stringify(field.name)}${field.optional ? "?" : ""}: ${prefix}Request[${JSON.stringify(field.source)}]${isOpaquePayload(item) && field.source === "payload" ? "" : `[${JSON.stringify(field.name)}]`}`,
)
.join("; ")
const argument =
item.operation.inputMode === "none"
? ""
: `input${item.operation.inputMode === "optional" ? "?" : ""}: ${prefix}Input`
// HttpApiClient distributes union payloads into union request objects, while rebuilding a flattened input
// produces one object containing a union value. The shapes are equivalent but TypeScript cannot correlate them.
const rawCall = `raw[${JSON.stringify(item.endpoint.identifier)}]({ ${request} }${isOpaquePayload(item) ? ` as ${prefix}Request` : ""})`
const mapped = `${rawCall}.pipe(Effect.mapError(mapClientError)${item.unwrapData ? ", Effect.map((value) => value.data)" : ""})`
const result =
item.operation.success === "stream"
? `Stream.unwrap(${rawCall}.pipe(Effect.mapError(mapClientError), Effect.map((stream) => stream.pipe(Stream.mapError(mapClientError)))))`
: mapped
const output =
options.shapeModule === undefined
? result
: `${item.operation.success === "stream" ? "preserveStream" : "preserveEffect"}<${prefix}Output>()(${result})`
const declarations =
options.shapeModule === undefined && item.operation.inputMode !== "none"
? `type ${prefix}Request = Parameters<${rawGroup}[${JSON.stringify(item.endpoint.identifier)}]>[0]\ntype ${prefix}Input = { ${input} }\n`
: isOpaquePayload(item)
? `type ${prefix}Request = Parameters<${rawGroup}[${JSON.stringify(item.endpoint.identifier)}]>[0]\n`
: ""
return `${declarations}const ${adapter} = (raw: ${rawGroup}) => (${argument}) => ${output}`
})
const fields = renderClientTree(
group.endpoints,
(item) => `${endpointAdapterName(group, item)}(raw)`,
(name, value) => `${JSON.stringify(name)}: ${value}`,
", ",
)
return `${methods.join("\n\n")}\n\nconst adaptGroup${groupTypeName(group)} = (raw: ${rawGroup}) => ({ ${fields} })`
})
const fields = renderGroupTree(
groups,
(group) =>
group.endpoints[0]?.topLevel
? { fields: `...adaptGroup${groupTypeName(group)}(raw)` }
: { whole: `adaptGroup${groupTypeName(group)}(raw[${rawKey(group)}])` },
(name, value) => `${JSON.stringify(name)}: ${value}`,
spreadObject,
", ",
)
const usesStream = groups.some((group) => group.endpoints.some((item) => item.operation.success === "stream"))
const imported = "api" in options
const projection = imported
? undefined
: "group" in options
? renderImportedGroup(options.group)
: renderImportedProjection(groups, options.endpoints)
const api = imported ? options.api : "Api"
const adapterNames = new Set(
groups.flatMap((group) => group.endpoints.map((endpoint) => endpointAdapterName(group, endpoint))),
)
const adapterCollision = (projection?.imports ?? [api]).find((name) => adapterNames.has(name))
if (adapterCollision !== undefined) {
throw new GenerationError({
reason: `Generated Effect adapter collides with imported endpoint: ${adapterCollision}`,
})
}
const imports =
projection === undefined
? `import { ${api} } from ${JSON.stringify(options.module)}`
: `import { HttpApi, HttpApiClient${"endpoints" in options ? ", HttpApiGroup" : ""} } from "effect/http-api"\nimport { ${projection.imports.join(", ")} } from ${JSON.stringify(options.module)}`
const httpApiImport = projection === undefined ? 'import { HttpApiClient } from "effect/http-api"\n' : ""
const shapeTypes = groups.flatMap((group) =>
group.endpoints.flatMap((endpoint) => [
...(endpoint.operation.inputMode === "none" ? [] : [`${endpointTypeName(group, endpoint)}Input`]),
`${endpointTypeName(group, endpoint)}Output`,
]),
)
const shapeImport =
options.shapeModule === undefined
? ""
: `import type { ${shapeTypes.join(", ")} } from ${JSON.stringify(options.shapeModule)}\n`
const preserve =
options.shapeModule === undefined
? ""
: `const preserveEffect = <A>() => <Actual extends A, E, R>(effect: Effect.Effect<Actual, E, R> & ([A] extends [Actual] ? unknown : { readonly __generatedOutputWiderThanContract: [expected: Actual, generated: A] })): Effect.Effect<A, E, R> => effect\n${usesStream ? "const preserveStream = <A>() => <Actual extends A, E, R>(stream: Stream.Stream<Actual, E, R> & ([A] extends [Actual] ? unknown : { readonly __generatedOutputWiderThanContract: [expected: Actual, generated: A] })): Stream.Stream<A, E, R> => stream\n" : ""}\n`
const client = `// Generated by @opencode/httpapi-codegen. Do not edit.\nimport { Effect${usesStream ? ", Stream" : ""}, Schema } from "effect"\nimport { Sse } from "effect/encoding"\nimport { HttpClientError } from "effect/http"\n${httpApiImport}${imports}\n${shapeImport}import { ClientError } from "./client-error.js"\n\n${projection?.source ?? ""}type RawClient = HttpApiClient.ForApi<typeof ${api}>\n\nconst mapClientError = <E>(error: E) => HttpClientError.isHttpClientError(error) || Schema.isSchemaError(error) || Sse.Retry.is(error) ? new ClientError({ cause: error }) : error\n\n${preserve}${adapters.join("\n\n")}\n\nconst adaptClient = ${aliases.length === 0 ? `(raw: RawClient) => ({ ${fields} })` : `(raw: RawClient) => {\n const client = { ${fields} }\n return ${renderAliasedClient(groups, aliases, "client")}\n}`}\n\nexport const make = (options?: { readonly baseUrl?: URL | string }) => HttpApiClient.make(${api}, options).pipe(Effect.map(adaptClient))\n`
return [
{
path: "client-error.ts",
content:
'import { Schema } from "effect"\n\nexport class ClientError extends Schema.TaggedError<ClientError>()("ClientError", {\n cause: Schema.Defect(),\n}) {}\n',
},
{ path: "client.ts", content: client },
{
path: "index.ts",
content: 'export { ClientError } from "./client-error.js"\nexport * as OpenCode from "./client.js"\n',
},
]
}
function renderImportedGroup(group: string) {
return {
imports: [group],
source: `const Api = HttpApi.make("generated").add(${group})\n\n`,
}
}
function renderImportedProjection(groups: ReadonlyArray<Group>, endpoints: Readonly<Record<string, string>>) {
const imports = groups.flatMap((group) =>
group.endpoints.map((endpoint) => {
const name = endpoints[`${group.identifier}.${endpoint.endpoint.identifier}`]
if (name === undefined) {
throw new GenerationError({
reason: `Missing imported endpoint: ${group.identifier}.${endpoint.endpoint.identifier}`,
})
}
return name
}),
)
const source = `const Api = HttpApi.make("generated").${groups
.map((group) => {
const options = group.endpoints[0]?.topLevel ? ", { topLevel: true }" : ""
return `add(HttpApiGroup.make(${JSON.stringify(group.identifier)}${options})${group.endpoints.map((endpoint) => `.add(${endpoints[`${group.identifier}.${endpoint.endpoint.identifier}`]})`).join("")})`
})
.join(".")}\n\n`
return { imports: [...new Set(imports)], source }
}
function renderPromiseTypes(
groups: ReadonlyArray<Group>,
outputTypes?: Readonly<Record<string, { readonly name: string; readonly import: string }>>,
mutableOutputs = false,
aliases: ReadonlyArray<Alias> = [],
) {
const types = new Map<SchemaAST.AST, string>()
const typeOf = (schema: Schema.Top, decoded = false) => {
const projected = decoded ? Schema.toType(schema) : Schema.toEncoded(schema)
const cached = types.get(projected.ast)
if (cached !== undefined) return cached
const type = structuralType(projected)
types.set(projected.ast, type)
return type
}
const fieldTypeOf = (schema: Schema.Top, name: string, decoded: boolean) => {
const ast = (decoded ? Schema.toType(schema) : Schema.toEncoded(schema)).ast
const property = SchemaAST.isObjects(ast)
? ast.propertySignatures.find((property) => property.name === name)
: undefined
if (property === undefined) return `(${typeOf(schema, decoded)})[${JSON.stringify(name)}]`
const type = Schema.make<Schema.Top>(property.type)
// Indexing an optional property includes undefined, so keep it when the field schema omits it.
if (!SchemaAST.isOptional(property.type) || includesUndefined(property.type)) return typeOf(type)
return typeOf(Schema.UndefinedOr(type))
}
const outputMarkers = new Map<SchemaAST.AST, string>()
const outputSchemas: Array<Schema.Top> = []
const outputTypeOf = (schema: Schema.Top) => {
const projected = Schema.toEncoded(schema)
const cached = outputMarkers.get(projected.ast)
if (cached !== undefined) return cached
const marker = `__PROMISE_TYPE_${outputSchemas.length}__`
outputSchemas.push(projected)
outputMarkers.set(projected.ast, marker)
return marker
}
const errors = new Map(
groups.flatMap((group) =>
group.endpoints.flatMap((endpoint) =>