index.ts 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. import { isAbsolute, join } from "node:path"
  2. import { Effect, FileSystem, PlatformError, Schema, SchemaAST, SchemaRepresentation } from "effect"
  3. import { HttpMethod, type HttpRouter } from "effect/unstable/http"
  4. import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/unstable/httpapi"
  5. import { format } from "prettier"
  6. export type InputField = {
  7. readonly name: string
  8. readonly source: "params" | "query" | "headers" | "payload"
  9. }
  10. export type Operation = {
  11. readonly group: string
  12. readonly name: string
  13. readonly input: ReadonlyArray<InputField>
  14. readonly inputMode: "none" | "optional" | "required"
  15. readonly success: "value" | "void" | "stream"
  16. readonly errors: ReadonlyArray<string>
  17. }
  18. export type Output = {
  19. readonly operations: ReadonlyArray<Operation>
  20. readonly files: ReadonlyArray<{
  21. readonly path: string
  22. readonly content: string
  23. }>
  24. }
  25. export type Contract = {
  26. readonly groups: ReadonlyArray<Group>
  27. }
  28. export class GenerationError extends Schema.TaggedErrorClass<GenerationError>()("GenerationError", {
  29. reason: Schema.String,
  30. }) {
  31. override get message() {
  32. return this.reason
  33. }
  34. }
  35. export type Endpoint = {
  36. readonly group: string
  37. readonly sourceGroup: string
  38. readonly topLevel: boolean
  39. readonly endpoint: HttpApiEndpoint.AnyWithProps
  40. readonly params: Schema.Top | undefined
  41. readonly query: Schema.Top | undefined
  42. readonly headers: Schema.Top | undefined
  43. readonly payloads: ReadonlyArray<Schema.Top>
  44. readonly operation: Operation
  45. readonly input: ReadonlyArray<InputField & { readonly optional: boolean }>
  46. readonly unwrapData: boolean
  47. readonly errors: ReadonlyArray<Schema.Top>
  48. readonly successes: ReadonlyArray<Schema.Top>
  49. readonly effectPortable: boolean
  50. }
  51. export type Group = {
  52. readonly identifier: string
  53. readonly sourceIdentifier: string
  54. readonly module: string
  55. readonly endpoints: ReadonlyArray<Endpoint>
  56. }
  57. type Slot = {
  58. readonly name: string
  59. readonly schema: Schema.Top
  60. }
  61. const resolveHttpApiStatus = SchemaAST.resolveAt<number>("httpApiStatus")
  62. const resolveHttpApiEncoding = SchemaAST.resolveAt<HttpApiSchema.Encoding>("~httpApiEncoding")
  63. const Manifest = Schema.fromJsonString(Schema.Array(Schema.String))
  64. const manifestName = ".httpapi-codegen.json"
  65. export function compile<Id extends string, Groups extends HttpApiGroup.Any>(
  66. api: HttpApi.HttpApi<Id, Groups>,
  67. options?: { readonly groupNames?: Readonly<Record<string, string>> },
  68. ): Contract {
  69. const endpoints: Array<Endpoint> = []
  70. const portable = new Map<SchemaAST.AST, boolean>()
  71. HttpApi.reflect(api, {
  72. onGroup() {},
  73. onEndpoint({ endpoint, errors, group, middleware }) {
  74. const groupName = options?.groupNames?.[group.identifier] ?? group.identifier
  75. const name = `${groupName}.${endpoint.name}`
  76. const required = Array.from(middleware).find((item) => item.requiredForClient)
  77. if (required !== undefined) {
  78. throw new GenerationError({ reason: `Client middleware requires adapter: ${required.key}` })
  79. }
  80. const successSchemas = Array.from(endpoint.success)
  81. if (successSchemas.length === 0) successSchemas.push(HttpApiSchema.NoContent)
  82. if (successSchemas.length > 1) throw new GenerationError({ reason: `Multiple success schemas: ${name}` })
  83. const params = normalizeTransport(endpoint.params, "params", endpoint, name)
  84. const query = normalizeTransport(endpoint.query, "query", endpoint, name)
  85. const headers = normalizeTransport(endpoint.headers, "headers", endpoint, name)
  86. const sourcePayloads = Array.from(endpoint.payload.values()).flatMap(({ schemas }) => schemas)
  87. if (sourcePayloads.length > 1) {
  88. throw new GenerationError({ reason: `Multiple payload schemas: ${name}` })
  89. }
  90. const payloads = sourcePayloads.map((schema) => normalizeTransport(schema, "payload", endpoint, name)!)
  91. const success = normalizeTransport(successSchemas[0], "success", endpoint, name)!
  92. const errorSchemas = Array.from(errors.values()).flatMap((schemas) =>
  93. schemas.map((schema) => normalizeTransport(schema, "error", endpoint, name)!),
  94. )
  95. const inputs = [
  96. ...inputFields(params?.schema, "params", name),
  97. ...inputFields(query?.schema, "query", name),
  98. ...inputFields(headers?.schema, "headers", name),
  99. ...payloads.flatMap((item) => inputFields(item.schema, "payload", name)),
  100. ]
  101. const names = new Set<string>()
  102. for (const field of inputs) {
  103. if (names.has(field.name)) throw new GenerationError({ reason: `Input field collision: ${field.name}` })
  104. names.add(field.name)
  105. }
  106. const schemaPaths: Array<readonly [string, Schema.Top]> = [
  107. ...(params === undefined ? [] : [[`${name}.params`, params.schema] as const]),
  108. ...(query === undefined ? [] : [[`${name}.query`, query.schema] as const]),
  109. ...(headers === undefined ? [] : [[`${name}.headers`, headers.schema] as const]),
  110. ...payloads.map((item) => [`${name}.payload`, item.schema] as const),
  111. ...responseSchemas(success.schema, `${name}.success`),
  112. ...errorSchemas.map((item) => [`${name}.error`, item.schema] as const),
  113. ]
  114. const effectPortable = [params, query, headers, ...payloads, success, ...errorSchemas].every(
  115. (item) => item?.effectPortable !== false,
  116. )
  117. if (effectPortable) {
  118. for (const [path, schema] of schemaPaths) assertPortable(schema, path, portable)
  119. }
  120. endpoints.push({
  121. group: groupName,
  122. sourceGroup: group.identifier,
  123. topLevel: group.topLevel,
  124. endpoint,
  125. params: params?.schema,
  126. query: query?.schema,
  127. headers: headers?.schema,
  128. payloads: payloads.map((item) => item.schema),
  129. input: inputs,
  130. unwrapData: isDataEnvelope(success.schema),
  131. successes: [success.schema],
  132. errors: errorSchemas.map((item) => item.schema),
  133. effectPortable,
  134. operation: {
  135. group: groupName,
  136. name: clientEndpointName(endpoint.name),
  137. input: inputs.map(({ name, source }) => ({ name, source })),
  138. inputMode: inputs.length === 0 ? "none" : inputs.every((field) => field.optional) ? "optional" : "required",
  139. success: isStreamSchema(success.schema)
  140. ? "stream"
  141. : HttpApiSchema.isNoContent(success.schema.ast)
  142. ? "void"
  143. : "value",
  144. errors: [
  145. ...new Set([
  146. ...errorSchemas.flatMap((item) => {
  147. const identifier = SchemaAST.resolveIdentifier(item.schema.ast)
  148. return identifier === undefined ? [] : [identifier]
  149. }),
  150. "ClientError",
  151. ]),
  152. ],
  153. },
  154. })
  155. },
  156. })
  157. const modules = new Set(["client", "client-error", "index"])
  158. const groups = Array.from(
  159. Map.groupBy(endpoints, (endpoint) => endpoint.group),
  160. ([identifier, endpoints], index) => {
  161. if (new Set(endpoints.map((endpoint) => endpoint.sourceGroup)).size > 1) {
  162. throw new GenerationError({ reason: `Client group name collision: ${identifier}` })
  163. }
  164. const base = /^[A-Za-z0-9_-]+$/.test(identifier) ? identifier : `group-${index}`
  165. const module = uniqueModule(base, index, modules)
  166. modules.add(module.toLowerCase())
  167. return { identifier, sourceIdentifier: endpoints[0].sourceGroup, module, endpoints }
  168. },
  169. )
  170. const publicNames = new Set<string>()
  171. for (const group of groups) {
  172. const endpointNames = new Set<string>()
  173. for (const endpoint of group.endpoints) {
  174. if (endpointNames.has(endpoint.operation.name)) {
  175. throw new GenerationError({
  176. reason: `Client endpoint name collision: ${group.identifier}.${endpoint.operation.name}`,
  177. })
  178. }
  179. endpointNames.add(endpoint.operation.name)
  180. }
  181. const names = group.endpoints[0]?.topLevel ? group.endpoints.map((item) => item.operation.name) : [group.identifier]
  182. for (const name of names) {
  183. if (publicNames.has(name)) throw new GenerationError({ reason: `Client name collision: ${name}` })
  184. publicNames.add(name)
  185. }
  186. }
  187. return {
  188. groups,
  189. }
  190. }
  191. export function emitEffect(contract: Contract): Output {
  192. const endpoint = contract.groups.flatMap((group) => group.endpoints).find((endpoint) => !endpoint.effectPortable)
  193. if (endpoint !== undefined) {
  194. throw new GenerationError({
  195. reason: `Effect schema requires authoritative import: ${endpoint.group}.${endpoint.endpoint.name}`,
  196. })
  197. }
  198. return { operations: operations(contract.groups), files: renderEffectFiles(contract.groups) }
  199. }
  200. export function emitEffectImported(
  201. contract: Contract,
  202. options:
  203. | { readonly module: string; readonly api: string }
  204. | { readonly module: string; readonly group: string }
  205. | { readonly module: string; readonly endpoints: Readonly<Record<string, string>> },
  206. ): Output {
  207. return {
  208. operations: operations(contract.groups),
  209. files: renderImportedEffectFiles(contract.groups, options),
  210. }
  211. }
  212. export function emitPromise(contract: Contract): Output {
  213. const groups = contract.groups
  214. for (const group of groups) {
  215. for (const endpoint of group.endpoints) assertPromiseEndpoint(endpoint)
  216. }
  217. return {
  218. operations: operations(groups),
  219. files: [
  220. { path: "types.ts", content: renderPromiseTypes(groups) },
  221. {
  222. path: "client-error.ts",
  223. content: `export type ClientErrorReason = "Transport" | "UnexpectedStatus" | "UnsupportedContentType" | "MalformedResponse"\n\nexport class ClientError extends Error {\n override readonly name = "ClientError"\n constructor(readonly reason: ClientErrorReason, options?: ErrorOptions) {\n super(reason, options)\n }\n}\n`,
  224. },
  225. {
  226. path: "client.ts",
  227. content: renderPromiseClient(groups).replace("let next: ReadableStreamReadResult<Uint8Array>", "let next"),
  228. },
  229. {
  230. path: "index.ts",
  231. content:
  232. 'export { ClientError, type ClientErrorReason } from "./client-error"\nexport * as OpenCode from "./client"\nexport * from "./types"\n',
  233. },
  234. ],
  235. }
  236. }
  237. function assertPromiseEndpoint(endpoint: Endpoint) {
  238. const name = `${endpoint.group}.${endpoint.endpoint.name}`
  239. const payload = endpoint.payloads[0]
  240. const payloadEncoding = payload === undefined ? undefined : resolveHttpApiEncoding(payload.ast)
  241. if (
  242. payload !== undefined &&
  243. (payloadEncoding?._tag ?? (HttpMethod.hasBody(endpoint.endpoint.method) ? "Json" : "FormUrlEncoded")) !== "Json"
  244. ) {
  245. throw new GenerationError({ reason: `Unsupported Promise payload encoding: ${name}` })
  246. }
  247. const success = endpoint.successes[0]
  248. if (isStreamSchema(success)) {
  249. if (
  250. success._tag !== "StreamSse" ||
  251. success.sseMode !== "data" ||
  252. !SchemaAST.isNever(Schema.toType(success.error).ast)
  253. ) {
  254. throw new GenerationError({ reason: `Unsupported Promise stream: ${name}` })
  255. }
  256. } else if (
  257. !HttpApiSchema.isNoContent(success.ast) &&
  258. (resolveHttpApiEncoding(success.ast)?._tag ?? "Json") !== "Json"
  259. ) {
  260. throw new GenerationError({ reason: `Unsupported Promise success encoding: ${name}` })
  261. }
  262. for (const error of endpoint.errors) {
  263. if (taggedErrorFields(error) === undefined) {
  264. throw new GenerationError({ reason: `Promise error must be tagged: ${name}` })
  265. }
  266. if ((resolveHttpApiEncoding(error.ast)?._tag ?? "Json") !== "Json") {
  267. throw new GenerationError({ reason: `Unsupported Promise error encoding: ${name}` })
  268. }
  269. }
  270. }
  271. function operations(groups: ReadonlyArray<Group>) {
  272. return groups.flatMap((group) => group.endpoints.map((endpoint) => endpoint.operation))
  273. }
  274. function renderEffectFiles(groups: ReadonlyArray<Group>): Output["files"] {
  275. return [
  276. ...groups.map((group, index) => ({ path: `${group.module}.ts`, content: renderGroup(group, index) })),
  277. {
  278. path: "client-error.ts",
  279. content:
  280. 'import { Schema } from "effect"\n\nexport class ClientError extends Schema.TaggedErrorClass<ClientError>()("ClientError", {\n cause: Schema.Defect(),\n}) {}\n',
  281. },
  282. { path: "client.ts", content: renderClient(groups) },
  283. {
  284. path: "index.ts",
  285. content: 'export { ClientError } from "./client-error"\nexport * as OpenCode from "./client"\n',
  286. },
  287. ]
  288. }
  289. function renderImportedEffectFiles(
  290. groups: ReadonlyArray<Group>,
  291. options:
  292. | { readonly module: string; readonly api: string }
  293. | { readonly module: string; readonly group: string }
  294. | { readonly module: string; readonly endpoints: Readonly<Record<string, string>> },
  295. ): Output["files"] {
  296. const adapters = groups.map((group, groupIndex) => {
  297. const rawGroup = group.endpoints[0]?.topLevel ? "RawClient" : `RawClient[${JSON.stringify(group.sourceIdentifier)}]`
  298. const methods = group.endpoints.map((item, endpointIndex) => {
  299. const prefix = `Endpoint${groupIndex}_${endpointIndex}`
  300. const request = (["params", "query", "headers", "payload"] as const)
  301. .flatMap((source) => {
  302. const fields = item.input.filter((field) => field.source === source)
  303. if (fields.length === 0) return []
  304. return [
  305. `${source}: { ${fields.map((field) => `${JSON.stringify(field.name)}: input${item.operation.inputMode === "optional" ? "?." : "."}${field.name}`).join(", ")} }`,
  306. ]
  307. })
  308. .join(", ")
  309. const input = item.input
  310. .map(
  311. (field) =>
  312. `readonly ${JSON.stringify(field.name)}${field.optional ? "?" : ""}: ${prefix}Request[${JSON.stringify(field.source)}][${JSON.stringify(field.name)}]`,
  313. )
  314. .join("; ")
  315. const argument =
  316. item.operation.inputMode === "none"
  317. ? ""
  318. : `input${item.operation.inputMode === "optional" ? "?" : ""}: ${prefix}Input`
  319. const rawCall = `raw[${JSON.stringify(item.endpoint.name)}]({ ${request} })`
  320. const mapped = `${rawCall}.pipe(Effect.mapError(mapClientError)${item.unwrapData ? ", Effect.map((value) => value.data)" : ""})`
  321. return `${item.operation.inputMode === "none" ? "" : `type ${prefix}Request = Parameters<${rawGroup}[${JSON.stringify(item.endpoint.name)}]>[0]\ntype ${prefix}Input = { ${input} }\n`}const ${prefix} = (raw: ${rawGroup}) => (${argument}) => ${item.operation.success === "stream" ? `Stream.unwrap(${rawCall}.pipe(Effect.mapError(mapClientError), Effect.map((stream) => stream.pipe(Stream.mapError(mapClientError)))))` : mapped}`
  322. })
  323. return `${methods.join("\n\n")}\n\nconst adaptGroup${groupIndex} = (raw: ${rawGroup}) => ({ ${group.endpoints.map((item, endpointIndex) => `${JSON.stringify(item.operation.name)}: Endpoint${groupIndex}_${endpointIndex}(raw)`).join(", ")} })`
  324. })
  325. const fields = groups.flatMap((group, index) =>
  326. group.endpoints[0]?.topLevel
  327. ? [`...adaptGroup${index}(raw)`]
  328. : [`${JSON.stringify(group.identifier)}: adaptGroup${index}(raw[${JSON.stringify(group.sourceIdentifier)}])`],
  329. )
  330. const usesStream = groups.some((group) => group.endpoints.some((item) => item.operation.success === "stream"))
  331. const imported = "api" in options
  332. const projection = imported
  333. ? undefined
  334. : "group" in options
  335. ? renderImportedGroup(options.group)
  336. : renderImportedProjection(groups, options.endpoints)
  337. const api = imported ? options.api : "Api"
  338. const imports =
  339. projection === undefined
  340. ? `import { ${api} } from ${JSON.stringify(options.module)}`
  341. : `import { HttpApi, HttpApiClient${"endpoints" in options ? ", HttpApiGroup" : ""} } from "effect/unstable/httpapi"\nimport { ${projection.imports.join(", ")} } from ${JSON.stringify(options.module)}`
  342. const httpApiImport = projection === undefined ? 'import { HttpApiClient } from "effect/unstable/httpapi"\n' : ""
  343. const client = `// Generated by @opencode-ai/httpapi-codegen. Do not edit.\nimport { Effect${usesStream ? ", Stream" : ""}, Schema } from "effect"\nimport { Sse } from "effect/unstable/encoding"\nimport { HttpClientError } from "effect/unstable/http"\n${httpApiImport}${imports}\nimport { ClientError } from "./client-error"\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${adapters.join("\n\n")}\n\nconst adaptClient = (raw: RawClient) => ({ ${fields.join(", ")} })\n\nexport const make = (options?: { readonly baseUrl?: URL | string }) => HttpApiClient.make(${api}, options).pipe(Effect.map(adaptClient))\n`
  344. return [
  345. {
  346. path: "client-error.ts",
  347. content:
  348. 'import { Schema } from "effect"\n\nexport class ClientError extends Schema.TaggedErrorClass<ClientError>()("ClientError", {\n cause: Schema.Defect(),\n}) {}\n',
  349. },
  350. { path: "client.ts", content: client },
  351. {
  352. path: "index.ts",
  353. content: 'export { ClientError } from "./client-error"\nexport * as OpenCode from "./client"\n',
  354. },
  355. ]
  356. }
  357. function renderImportedGroup(group: string) {
  358. return {
  359. imports: [group],
  360. source: `const Api = HttpApi.make("generated").add(${group})\n\n`,
  361. }
  362. }
  363. function renderImportedProjection(groups: ReadonlyArray<Group>, endpoints: Readonly<Record<string, string>>) {
  364. const imports = groups.flatMap((group) =>
  365. group.endpoints.map((endpoint) => {
  366. const name = endpoints[`${group.identifier}.${endpoint.endpoint.name}`]
  367. if (name === undefined) {
  368. throw new GenerationError({
  369. reason: `Missing imported endpoint: ${group.identifier}.${endpoint.endpoint.name}`,
  370. })
  371. }
  372. return name
  373. }),
  374. )
  375. const source = `const Api = HttpApi.make("generated").${groups
  376. .map((group) => {
  377. const options = group.endpoints[0]?.topLevel ? ", { topLevel: true }" : ""
  378. return `add(HttpApiGroup.make(${JSON.stringify(group.identifier)}${options})${group.endpoints.map((endpoint) => `.add(${endpoints[`${group.identifier}.${endpoint.endpoint.name}`]})`).join("")})`
  379. })
  380. .join(".")}\n\n`
  381. return { imports: [...new Set(imports)], source }
  382. }
  383. function renderPromiseTypes(groups: ReadonlyArray<Group>) {
  384. const types = new Map<SchemaAST.AST, string>()
  385. const typeOf = (schema: Schema.Top) => {
  386. const encoded = Schema.toEncoded(schema)
  387. const cached = types.get(encoded.ast)
  388. if (cached !== undefined) return cached
  389. const type = structuralType(encoded)
  390. types.set(encoded.ast, type)
  391. return type
  392. }
  393. const errors = new Map(
  394. groups.flatMap((group) =>
  395. group.endpoints.flatMap((endpoint) =>
  396. endpoint.errors.flatMap((schema) => {
  397. const tagged = taggedErrorFields(schema)
  398. return tagged === undefined ? [] : [[tagged.tag, tagged] as const]
  399. }),
  400. ),
  401. ),
  402. )
  403. const errorTypes = Array.from(errors.values()).map((error) => {
  404. const fields = error.fields
  405. .map(([name, schema, optional]) => `readonly ${JSON.stringify(name)}${optional ? "?" : ""}: ${typeOf(schema)}`)
  406. .join("; ")
  407. return `export type ${error.identifier} = { readonly _tag: ${JSON.stringify(error.tag)}; ${fields} }\nexport const is${error.identifier} = (value: unknown): value is ${error.identifier} => typeof value === "object" && value !== null && "_tag" in value && value._tag === ${JSON.stringify(error.tag)}`
  408. })
  409. const operations = groups
  410. .flatMap((group) =>
  411. group.endpoints.flatMap((endpoint) => {
  412. const prefix = promiseTypePrefix(group.identifier, endpoint.operation.name)
  413. const schemas = {
  414. params: endpoint.params,
  415. query: endpoint.query,
  416. headers: endpoint.headers,
  417. payload: endpoint.payloads[0],
  418. }
  419. const input = endpoint.input
  420. .map((field) => {
  421. const schema = schemas[field.source]
  422. if (schema === undefined)
  423. throw new GenerationError({ reason: `Missing input schema: ${prefix}.${field.name}` })
  424. return `readonly ${JSON.stringify(field.name)}${field.optional ? "?" : ""}: (${typeOf(schema)})[${JSON.stringify(field.name)}]`
  425. })
  426. .join("; ")
  427. const successSchema = endpoint.successes[0]
  428. const success = typeOf(
  429. isStreamSchema(successSchema) && successSchema._tag === "StreamSse"
  430. ? successSchema.sseMode === "data"
  431. ? streamDataSchema(successSchema)
  432. : successSchema.events
  433. : successSchema,
  434. )
  435. return [
  436. ...(endpoint.operation.inputMode === "none" ? [] : [`export type ${prefix}Input = { ${input} }`]),
  437. `export type ${prefix}Output = ${endpoint.unwrapData ? `(${success})["data"]` : success}`,
  438. ]
  439. }),
  440. )
  441. .join("\n\n")
  442. const json = operations.includes("JsonValue")
  443. ? "export type JsonValue = null | boolean | number | string | ReadonlyArray<JsonValue> | { readonly [key: string]: JsonValue }"
  444. : ""
  445. return [json, ...errorTypes, operations].filter(Boolean).join("\n\n")
  446. }
  447. function renderPromiseClient(groups: ReadonlyArray<Group>) {
  448. const imports = groups.flatMap((group) =>
  449. group.endpoints.flatMap((endpoint) => {
  450. const prefix = promiseTypePrefix(group.identifier, endpoint.operation.name)
  451. return [...(endpoint.operation.inputMode === "none" ? [] : [`${prefix}Input`]), `${prefix}Output`]
  452. }),
  453. )
  454. const fields = groups.map((group) => {
  455. const methods = group.endpoints.map((endpoint) => {
  456. const prefix = promiseTypePrefix(group.identifier, endpoint.operation.name)
  457. const argument =
  458. endpoint.operation.inputMode === "none"
  459. ? "requestOptions?: RequestOptions"
  460. : `input${endpoint.operation.inputMode === "optional" ? "?" : ""}: ${prefix}Input, requestOptions?: RequestOptions`
  461. const path = promisePath(endpoint.endpoint.path, endpoint.input)
  462. const access = (name: string) => `input${endpoint.operation.inputMode === "optional" ? "?." : "."}${name}`
  463. const part = (source: InputField["source"]) => {
  464. const inputs = endpoint.input.filter((field) => field.source === source)
  465. return inputs.length === 0
  466. ? undefined
  467. : `{ ${inputs.map((field) => `${JSON.stringify(field.name)}: ${access(field.name)}`).join(", ")} }`
  468. }
  469. const parts = [
  470. endpoint.query === undefined ? undefined : `query: ${part("query")}`,
  471. endpoint.headers === undefined ? undefined : `headers: ${part("headers")}`,
  472. endpoint.payloads.length === 0 ? undefined : `body: ${part("payload")}`,
  473. ].filter((value): value is string => value !== undefined)
  474. const declaredStatuses = [
  475. ...new Set(
  476. endpoint.errors.map((schema) => resolveHttpApiStatus(schema.ast)).filter((status) => status !== undefined),
  477. ),
  478. ]
  479. const descriptor = `{ method: ${JSON.stringify(endpoint.endpoint.method)}, path: ${path}${parts.length === 0 ? "" : `, ${parts.join(", ")}`}, successStatus: ${resolveHttpApiStatus(endpoint.successes[0].ast) ?? 200}, declaredStatuses: [${declaredStatuses.join(", ")}], empty: ${endpoint.operation.success === "void"} }`
  480. if (endpoint.operation.success === "stream") {
  481. const success = endpoint.successes[0]
  482. if (!isStreamSchema(success) || success._tag !== "StreamSse" || success.sseMode !== "data") {
  483. throw new GenerationError({
  484. reason: `Promise stream emission is not implemented: ${group.identifier}.${endpoint.endpoint.name}`,
  485. })
  486. }
  487. return `${JSON.stringify(endpoint.operation.name)}: (${argument}): AsyncIterable<${prefix}Output> => sse<${prefix}Output>(${descriptor}, requestOptions)`
  488. }
  489. const unwrap = endpoint.unwrapData ? ".then((value) => value.data)" : ""
  490. return `${JSON.stringify(endpoint.operation.name)}: (${argument}) => request<${endpoint.unwrapData ? `{ readonly data: ${prefix}Output }` : `${prefix}Output`}>(${descriptor}, requestOptions)${unwrap}`
  491. })
  492. if (group.endpoints[0]?.topLevel) return methods.join(", ")
  493. return `${JSON.stringify(group.identifier)}: { ${methods.join(", ")} }`
  494. })
  495. return `import type { ${imports.join(", ")} } from "./types"\nimport { ClientError } from "./client-error"\n\nexport interface ClientOptions {\n readonly baseUrl: string\n readonly fetch?: typeof globalThis.fetch\n readonly headers?: HeadersInit\n}\n\nexport interface RequestOptions {\n readonly signal?: AbortSignal\n readonly headers?: HeadersInit\n}\n\ninterface RequestDescriptor {\n readonly method: string\n readonly path: string\n readonly query?: Record<string, unknown>\n readonly headers?: Record<string, unknown>\n readonly body?: unknown\n readonly successStatus: number\n readonly declaredStatuses: ReadonlyArray<number>\n readonly empty: boolean\n}\n\nexport function make(options: ClientOptions) {\n const fetch = options.fetch ?? globalThis.fetch\n\n const prepare = (descriptor: RequestDescriptor, requestOptions?: RequestOptions) => {\n const url = new URL(descriptor.path, options.baseUrl)\n for (const [key, value] of Object.entries(descriptor.query ?? {})) appendQuery(url.searchParams, key, value)\n const headers = new Headers(options.headers)\n for (const [key, value] of Object.entries(descriptor.headers ?? {})) {\n if (value !== undefined && value !== null) headers.set(key, String(value))\n }\n for (const [key, value] of new Headers(requestOptions?.headers)) headers.set(key, value)\n if (descriptor.body !== undefined && !headers.has("content-type")) headers.set("content-type", "application/json")\n return {\n url,\n init: {\n method: descriptor.method,\n signal: requestOptions?.signal,\n headers,\n body: descriptor.body === undefined ? undefined : JSON.stringify(descriptor.body),\n } satisfies RequestInit,\n }\n }\n\n const execute = async (descriptor: RequestDescriptor, requestOptions?: RequestOptions) => {\n try {\n const prepared = prepare(descriptor, requestOptions)\n return await fetch(prepared.url, prepared.init)\n } catch (cause) {\n throw new ClientError("Transport", { cause })\n }\n }\n\n const responseError = async (response: Response, descriptor: RequestDescriptor): Promise<never> => {\n if (descriptor.declaredStatuses.includes(response.status)) throw await json(response)\n try {\n await response.body?.cancel()\n } catch {}\n throw new ClientError("UnexpectedStatus", { cause: { status: response.status } })\n }\n\n const request = async <A>(descriptor: RequestDescriptor, requestOptions?: RequestOptions): Promise<A> => {\n const response = await execute(descriptor, requestOptions)\n if (response.status !== descriptor.successStatus) return responseError(response, descriptor)\n if (descriptor.empty) {\n try {\n await response.body?.cancel()\n } catch {}\n return undefined as A\n }\n return await json(response) as A\n }\n\n const sse = <A>(descriptor: RequestDescriptor, requestOptions?: RequestOptions): AsyncIterable<A> => ({\n async *[Symbol.asyncIterator]() {\n const response = await execute(descriptor, requestOptions)\n if (response.status !== descriptor.successStatus) await responseError(response, descriptor)\n if (!isContentType(response, "text/event-stream")) {\n try {\n await response.body?.cancel()\n } catch {}\n throw new ClientError("UnsupportedContentType")\n }\n if (response.body === null) throw new ClientError("MalformedResponse")\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ""\n try {\n while (true) {\n let next: ReadableStreamReadResult<Uint8Array>\n try {\n next = await reader.read()\n } catch (cause) {\n throw new ClientError("Transport", { cause })\n }\n buffer += decoder.decode(next.value, { stream: !next.done })\n if (buffer.length > 1_048_576) throw new ClientError("MalformedResponse")\n const trailingCarriageReturn = !next.done && buffer.endsWith("\\r")\n if (trailingCarriageReturn) buffer = buffer.slice(0, -1)\n buffer = buffer.replaceAll("\\r\\n", "\\n").replaceAll("\\r", "\\n")\n if (trailingCarriageReturn) buffer += "\\r"\n if (next.done && buffer !== "") buffer += "\\n\\n"\n let boundary = buffer.indexOf("\\n\\n")\n while (boundary >= 0) {\n const block = buffer.slice(0, boundary)\n buffer = buffer.slice(boundary + 2)\n const data = block.split("\\n").flatMap((line) => line.startsWith("data:") ? [line.slice(5).trimStart()] : []).join("\\n")\n if (data !== "") {\n try {\n yield JSON.parse(data) as A\n } catch (cause) {\n throw new ClientError("MalformedResponse", { cause })\n }\n }\n boundary = buffer.indexOf("\\n\\n")\n }\n if (next.done) return\n }\n } finally {\n try {\n await reader.cancel()\n } catch {}\n reader.releaseLock()\n }\n },\n })\n\n return { ${fields.join(", ")} }\n}\n\nfunction appendQuery(params: URLSearchParams, key: string, value: unknown): void {\n if (value === undefined || value === null) return\n if (Array.isArray(value)) {\n for (const item of value) appendQuery(params, key, item)\n return\n }\n if (typeof value === "object") {\n for (const [child, item] of Object.entries(value)) appendQuery(params, \`\${key}[\${child}]\`, item)\n return\n }\n params.append(key, String(value))\n}\n\nasync function json(response: Response): Promise<unknown> {\n if (!isContentType(response, "application/json") && !response.headers.get("content-type")?.includes("+json")) {\n try {\n await response.body?.cancel()\n } catch {}\n throw new ClientError("UnsupportedContentType")\n }\n let text: string\n try {\n text = await response.text()\n } catch (cause) {\n throw new ClientError("Transport", { cause })\n }\n if (text === "") throw new ClientError("MalformedResponse")\n try {\n return JSON.parse(text)\n } catch (cause) {\n throw new ClientError("MalformedResponse", { cause })\n }\n}\n\nfunction isContentType(response: Response, expected: string) {\n return response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === expected\n}\n`
  496. }
  497. function promiseTypePrefix(group: string, endpoint: string) {
  498. return `${identifierPart(group)}${identifierPart(endpoint)}`
  499. }
  500. function clientEndpointName(name: string) {
  501. return name.slice(name.lastIndexOf(".") + 1)
  502. }
  503. function identifierPart(value: string) {
  504. return value
  505. .split(/[^A-Za-z0-9]+/)
  506. .filter(Boolean)
  507. .map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`)
  508. .join("")
  509. }
  510. function structuralType(schema: Schema.Top) {
  511. const document = SchemaRepresentation.toCodeDocument(SchemaRepresentation.fromASTs([schema.ast]))
  512. if (
  513. document.artifacts.some(
  514. (artifact) =>
  515. artifact._tag !== "Import" || artifact.importDeclaration !== 'import type * as Brand from "effect/Brand"',
  516. ) ||
  517. Object.keys(document.references.recursives).length > 0
  518. ) {
  519. throw new GenerationError({ reason: "Referenced Promise types are not implemented" })
  520. }
  521. const references = new Map(
  522. document.references.nonRecursives.map((reference) => [reference.$ref, reference.code.Type]),
  523. )
  524. const expand = (type: string, seen = new Set<string>()): string => {
  525. for (const [reference, value] of references) {
  526. if (!type.includes(reference)) continue
  527. if (seen.has(reference)) throw new GenerationError({ reason: "Recursive Promise types are not implemented" })
  528. type = type.replaceAll(reference, `(${expand(value, new Set([...seen, reference]))})`)
  529. }
  530. return type
  531. }
  532. return expand(document.codes[0].Type)
  533. .replaceAll(/ & Brand\.Brand<"[^"]+">/g, "")
  534. .replaceAll("Schema.Json", "JsonValue")
  535. }
  536. function promisePath(path: string, input: ReadonlyArray<InputField>) {
  537. const fields = new Set(input.filter((field) => field.source === "params").map((field) => field.name))
  538. const segments = path.split(/(:[A-Za-z_][A-Za-z0-9_]*)/g).filter(Boolean)
  539. const template = segments
  540. .map((segment) => {
  541. if (!segment.startsWith(":")) return segment.replaceAll("`", "\\`")
  542. const name = segment.slice(1)
  543. if (!fields.has(name)) throw new GenerationError({ reason: `Missing path parameter: ${name}` })
  544. return `\${encodeURIComponent(input.${name})}`
  545. })
  546. .join("")
  547. return `\`${template}\``
  548. }
  549. function uniqueModule(base: string, index: number, modules: ReadonlySet<string>) {
  550. if (!modules.has(base.toLowerCase())) return base
  551. const seed = `${base}-${index}`
  552. let suffix = 0
  553. while (modules.has(`${seed}${suffix === 0 ? "" : `-${suffix}`}`.toLowerCase())) suffix++
  554. return `${seed}${suffix === 0 ? "" : `-${suffix}`}`
  555. }
  556. function normalizeTransport(
  557. schema: Schema.Top | undefined,
  558. source: InputField["source"] | "success" | "error",
  559. endpoint: HttpApiEndpoint.AnyWithProps,
  560. operation: string,
  561. ) {
  562. if (schema === undefined) return undefined
  563. if (isStreamSchema(schema)) return { schema, effectPortable: true } as const
  564. if (!metadataPortable(schema.ast, new Set())) {
  565. throw new GenerationError({ reason: `Unportable schema: ${operation}.${source}` })
  566. }
  567. const decoded = Schema.toType(schema)
  568. if (!isPathInput(endpoint.path)) {
  569. throw new GenerationError({ reason: `Invalid endpoint path: ${operation}` })
  570. }
  571. const rebuilt = HttpApiEndpoint.make(endpoint.method)(endpoint.name, endpoint.path, {
  572. ...(source === "params" ? { params: decoded } : undefined),
  573. ...(source === "query" ? { query: decoded } : undefined),
  574. ...(source === "headers" ? { headers: decoded } : undefined),
  575. ...(source === "payload" ? { payload: decoded } : undefined),
  576. ...(source === "success" ? { success: decoded } : { success: Schema.String }),
  577. ...(source === "error" ? { error: decoded } : undefined),
  578. })
  579. const normalized =
  580. source === "params"
  581. ? rebuilt.params
  582. : source === "query"
  583. ? rebuilt.query
  584. : source === "headers"
  585. ? rebuilt.headers
  586. : source === "payload"
  587. ? Array.from(rebuilt.payload.values())[0]?.schemas[0]
  588. : source === "success"
  589. ? Array.from(rebuilt.success)[0]
  590. : Array.from(rebuilt.error)[0]
  591. if (normalized === undefined) throw new GenerationError({ reason: `Unportable schema: ${operation}.${source}` })
  592. if (!sameEncoding(schema.ast, normalized.ast)) return { schema, effectPortable: false } as const
  593. return { schema: decoded, effectPortable: true } as const
  594. }
  595. function isPathInput(path: string): path is HttpRouter.PathInput {
  596. return path === "*" || path.startsWith("/")
  597. }
  598. function sameEncoding(left: SchemaAST.AST, right: SchemaAST.AST): boolean {
  599. if (left._tag !== right._tag || left.encoding?.length !== right.encoding?.length) return false
  600. if (
  601. left.encoding?.some((link, index) => {
  602. const other = right.encoding?.[index]
  603. return other === undefined || link.transformation !== other.transformation || !sameEncoding(link.to, other.to)
  604. })
  605. )
  606. return false
  607. if (!sameChecks(left.checks, right.checks) || !sameContext(left.context, right.context)) return false
  608. if (SchemaAST.isSuspend(left) && SchemaAST.isSuspend(right)) return sameEncoding(left.thunk(), right.thunk())
  609. if (SchemaAST.isUnion(left) && SchemaAST.isUnion(right)) {
  610. return (
  611. left.types.length === right.types.length &&
  612. left.types.every((ast, index) => sameEncoding(ast, right.types[index]))
  613. )
  614. }
  615. if (SchemaAST.isArrays(left) && SchemaAST.isArrays(right)) {
  616. return (
  617. left.elements.length === right.elements.length &&
  618. left.rest.length === right.rest.length &&
  619. left.elements.every((ast, index) => sameEncoding(ast, right.elements[index])) &&
  620. left.rest.every((ast, index) => sameEncoding(ast, right.rest[index]))
  621. )
  622. }
  623. if (SchemaAST.isObjects(left) && SchemaAST.isObjects(right)) {
  624. return (
  625. left.propertySignatures.length === right.propertySignatures.length &&
  626. left.indexSignatures.length === right.indexSignatures.length &&
  627. left.propertySignatures.every((field, index) => sameEncoding(field.type, right.propertySignatures[index].type)) &&
  628. left.indexSignatures.every(
  629. (field, index) =>
  630. sameEncoding(field.parameter, right.indexSignatures[index].parameter) &&
  631. sameEncoding(field.type, right.indexSignatures[index].type),
  632. )
  633. )
  634. }
  635. return true
  636. }
  637. function sameChecks(left: SchemaAST.Checks | undefined, right: SchemaAST.Checks | undefined): boolean {
  638. if (left?.length !== right?.length) return false
  639. if (left === undefined || right === undefined) return true
  640. return left.every((check, index) => {
  641. const other = right[index]
  642. if (other === undefined || check._tag !== other._tag) return false
  643. if (check._tag === "Filter" && other._tag === "Filter") {
  644. return check.run === other.run && check.aborted === other.aborted
  645. }
  646. return check._tag === "FilterGroup" && other._tag === "FilterGroup" && sameChecks(check.checks, other.checks)
  647. })
  648. }
  649. function sameContext(left: SchemaAST.Context | undefined, right: SchemaAST.Context | undefined) {
  650. return left?.isOptional === right?.isOptional && left?.isMutable === right?.isMutable
  651. }
  652. export function write(
  653. output: Output,
  654. directory: string,
  655. ): Effect.Effect<void, GenerationError | PlatformError.PlatformError, FileSystem.FileSystem> {
  656. return Effect.gen(function* () {
  657. const paths = new Set<string>()
  658. const normalizedPaths = new Set<string>()
  659. for (const file of output.files) {
  660. if (!isSafeOutputPath(file.path)) yield* new GenerationError({ reason: `Unsafe output path: ${file.path}` })
  661. const path = file.path.toLowerCase()
  662. if (normalizedPaths.has(path)) yield* new GenerationError({ reason: `Duplicate output path: ${file.path}` })
  663. normalizedPaths.add(path)
  664. paths.add(file.path)
  665. }
  666. const fs = yield* FileSystem.FileSystem
  667. yield* fs.makeDirectory(directory, { recursive: true })
  668. const manifest = join(directory, manifestName)
  669. const previous = (yield* fs.exists(manifest))
  670. ? yield* fs.readFileString(manifest).pipe(
  671. Effect.flatMap(Schema.decodeUnknownEffect(Manifest)),
  672. Effect.mapError(() => new GenerationError({ reason: `Invalid generated file manifest: ${manifest}` })),
  673. )
  674. : []
  675. if (previous.some((path) => !isSafeOutputPath(path))) {
  676. yield* new GenerationError({ reason: `Invalid generated file manifest: ${manifest}` })
  677. }
  678. yield* Effect.forEach(
  679. previous.filter((path) => !paths.has(path)),
  680. (path) => fs.remove(join(directory, path), { force: true }),
  681. { concurrency: 8, discard: true },
  682. )
  683. yield* Effect.forEach(
  684. output.files,
  685. (file) =>
  686. fs.exists(join(directory, file.path)).pipe(
  687. Effect.flatMap((exists) => (exists ? fs.stat(join(directory, file.path)) : Effect.succeed(undefined))),
  688. Effect.flatMap((info) =>
  689. info?.type === "SymbolicLink"
  690. ? new GenerationError({ reason: `Unsafe output path: ${file.path}` })
  691. : Effect.void,
  692. ),
  693. ),
  694. { concurrency: 8, discard: true },
  695. )
  696. yield* Effect.forEach(
  697. output.files,
  698. (file) =>
  699. Effect.tryPromise({
  700. try: () => format(file.content, { filepath: file.path, parser: "typescript", semi: false, printWidth: 120 }),
  701. catch: (error) => new GenerationError({ reason: `Failed to format ${file.path}: ${String(error)}` }),
  702. }).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
  703. { concurrency: 8, discard: true },
  704. )
  705. yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
  706. })
  707. }
  708. function isSafeOutputPath(path: string) {
  709. return path !== manifestName && !isAbsolute(path) && path !== "." && path !== ".." && !/[\\/]/.test(path)
  710. }
  711. export function generate<Id extends string, Groups extends HttpApiGroup.Any>(
  712. api: HttpApi.HttpApi<Id, Groups>,
  713. options: { readonly directory: string },
  714. ): Effect.Effect<void, GenerationError | PlatformError.PlatformError, FileSystem.FileSystem> {
  715. return Effect.try({
  716. try: () => emitEffect(compile(api)),
  717. catch: (error) => (error instanceof GenerationError ? error : new GenerationError({ reason: String(error) })),
  718. }).pipe(Effect.flatMap((output) => write(output, options.directory)))
  719. }
  720. function inputFields(schema: Schema.Top | undefined, source: InputField["source"], operation: string) {
  721. if (schema === undefined) return []
  722. const ast = Schema.toType(schema).ast
  723. if (!SchemaAST.isObjects(ast) || ast.indexSignatures.length > 0) {
  724. throw new GenerationError({ reason: `Input schema must be a struct: ${operation}.${source}` })
  725. }
  726. return ast.propertySignatures.map((field) => {
  727. if (typeof field.name !== "string") {
  728. throw new GenerationError({ reason: `Input field must have a string name: ${operation}.${source}` })
  729. }
  730. return {
  731. name: field.name,
  732. source,
  733. optional: SchemaAST.isOptional(field.type),
  734. }
  735. })
  736. }
  737. function responseSchemas(schema: Schema.Top, path: string): Array<readonly [string, Schema.Top]> {
  738. if (HttpApiSchema.isNoContent(schema.ast)) return []
  739. if (!isStreamSchema(schema)) return [[path, schema]]
  740. if (schema._tag === "StreamUint8Array") return []
  741. const value = schema.sseMode === "data" ? streamDataSchema(schema) : schema.events
  742. const rebuilt =
  743. schema.sseMode === "data"
  744. ? HttpApiSchema.StreamSse({ data: value, error: schema.error, contentType: schema.contentType })
  745. : HttpApiSchema.StreamSse({
  746. events: schema.events,
  747. error: schema.error,
  748. contentType: schema.contentType,
  749. })
  750. if (!sameEncoding(schema.events.ast, rebuilt.events.ast)) {
  751. throw new GenerationError({ reason: `Unportable schema: ${path}.${schema.sseMode}` })
  752. }
  753. return [
  754. [`${path}.${schema.sseMode}`, value],
  755. [`${path}.error`, schema.error],
  756. ]
  757. }
  758. function assertPortable(schema: Schema.Top, path: string, portable: Map<SchemaAST.AST, boolean>) {
  759. const visiting = new Set<SchemaAST.AST>()
  760. const taggedError = taggedErrorFields(schema)
  761. const visit = (ast: SchemaAST.AST): boolean => {
  762. const cached = portable.get(ast)
  763. if (cached !== undefined) return cached
  764. if (visiting.has(ast)) return true
  765. visiting.add(ast)
  766. const result = visitCurrent(ast)
  767. visiting.delete(ast)
  768. portable.set(ast, result)
  769. return result
  770. }
  771. const visitCurrent = (ast: SchemaAST.AST): boolean => {
  772. if (!annotationsPortable(ast.annotations)) return false
  773. if (!checksPortable(ast.checks) || ("encodingChecks" in ast && !checksPortable(ast.encodingChecks))) return false
  774. if (SchemaAST.isDeclaration(ast)) {
  775. return generationPortable(ast.annotations?.generation) && ast.typeParameters.every(visit)
  776. }
  777. if (ast.encoding !== undefined && ast.annotations?.generation === undefined) return false
  778. if (SchemaAST.isSuspend(ast)) return visit(ast.thunk())
  779. if (SchemaAST.isUnion(ast)) return ast.types.every(visit)
  780. if (SchemaAST.isArrays(ast)) {
  781. return ast.elements.every(visit) && ast.rest.every(visit)
  782. }
  783. if (SchemaAST.isObjects(ast)) {
  784. return (
  785. ast.propertySignatures.every((field) => visit(field.type)) &&
  786. ast.indexSignatures.every((index) => visit(index.parameter) && visit(index.type))
  787. )
  788. }
  789. if (SchemaAST.isTemplateLiteral(ast)) return ast.parts.every(visit)
  790. return true
  791. }
  792. if (taggedError !== undefined && SchemaAST.isDeclaration(schema.ast)) {
  793. if (
  794. schema.ast.checks !== undefined ||
  795. ("encodingChecks" in schema.ast && !checksPortable(schema.ast.encodingChecks)) ||
  796. schema.ast.typeParameters.some((ast) => ast.checks !== undefined) ||
  797. !schema.ast.typeParameters.every(visit)
  798. ) {
  799. throw new GenerationError({ reason: `Unportable schema: ${path}` })
  800. }
  801. return
  802. }
  803. if (!visit(schema.ast)) throw new GenerationError({ reason: `Unportable schema: ${path}` })
  804. }
  805. function checksPortable(checks: SchemaAST.Checks | undefined): boolean {
  806. if (checks === undefined) return true
  807. return checks.every((check) =>
  808. check._tag === "Filter"
  809. ? !check.aborted &&
  810. check.annotations?.meta !== undefined &&
  811. typeof check.annotations.arbitrary === "object" &&
  812. check.annotations.arbitrary !== null &&
  813. "constraint" in check.annotations.arbitrary
  814. : checksPortable(check.checks),
  815. )
  816. }
  817. function metadataPortable(ast: SchemaAST.AST, seen: Set<SchemaAST.AST>): boolean {
  818. if (seen.has(ast)) return true
  819. seen.add(ast)
  820. if (!annotationsPortable(ast.annotations) || !checksPortable(ast.checks)) return false
  821. if ("encodingChecks" in ast && !checksPortable(ast.encodingChecks)) return false
  822. if (ast.encoding?.some((link) => !metadataPortable(link.to, seen))) return false
  823. if (SchemaAST.isDeclaration(ast)) return ast.typeParameters.every((item) => metadataPortable(item, seen))
  824. if (SchemaAST.isSuspend(ast)) return metadataPortable(ast.thunk(), seen)
  825. if (SchemaAST.isUnion(ast)) return ast.types.every((item) => metadataPortable(item, seen))
  826. if (SchemaAST.isArrays(ast)) {
  827. return (
  828. ast.elements.every((item) => metadataPortable(item, seen)) &&
  829. ast.rest.every((item) => metadataPortable(item, seen))
  830. )
  831. }
  832. if (SchemaAST.isObjects(ast)) {
  833. return (
  834. ast.propertySignatures.every((field) => metadataPortable(field.type, seen)) &&
  835. ast.indexSignatures.every(
  836. (field) => metadataPortable(field.parameter, seen) && metadataPortable(field.type, seen),
  837. )
  838. )
  839. }
  840. return true
  841. }
  842. function generationPortable(generation: unknown): boolean {
  843. if (typeof generation !== "object" || generation === null) return false
  844. const value = generation as {
  845. readonly runtime?: unknown
  846. readonly Type?: unknown
  847. readonly importDeclaration?: unknown
  848. }
  849. if (typeof value.runtime !== "string" || typeof value.Type !== "string") return false
  850. if (value.importDeclaration !== undefined) {
  851. if (
  852. typeof value.importDeclaration !== "string" ||
  853. !/from ["']effect(?:\/[^"']+)?["']$/.test(value.importDeclaration)
  854. ) {
  855. return false
  856. }
  857. }
  858. const namespace =
  859. typeof value.importDeclaration === "string"
  860. ? /import(?: type)? \* as ([A-Za-z_$][\w$]*)/.exec(value.importDeclaration)?.[1]
  861. : undefined
  862. return value.runtime.startsWith("Schema.") || (namespace !== undefined && value.runtime.startsWith(`${namespace}.`))
  863. }
  864. function annotationsPortable(annotations: Schema.Annotations.Annotations | undefined) {
  865. if (annotations === undefined) return true
  866. return Object.entries(annotations).every(([key, value]) => {
  867. if (
  868. ["toCodec", "toCodecJson", "toArbitrary", "toFormatter", "toEquivalence", "~effect/Schema/Class"].includes(key)
  869. ) {
  870. return true
  871. }
  872. if (key === "generation") return generationPortable(value)
  873. return serializable(value)
  874. })
  875. }
  876. function serializable(value: unknown): boolean {
  877. if (value === null || ["string", "number", "boolean"].includes(typeof value)) return true
  878. if (Array.isArray(value)) return value.every(serializable)
  879. if (typeof value !== "object") return false
  880. return Object.values(value).every(serializable)
  881. }
  882. function taggedErrorFields(schema: Schema.Top) {
  883. if (!SchemaAST.isDeclaration(schema.ast) || schema.ast.annotations?.["~effect/Schema/Class"] === undefined) {
  884. return undefined
  885. }
  886. const fields = schema.ast.typeParameters[0]
  887. if (!SchemaAST.isObjects(fields) || fields.indexSignatures.length > 0) return undefined
  888. const tag = fields.propertySignatures.find((field) => field.name === "_tag")?.type
  889. if (tag === undefined || !SchemaAST.isLiteral(tag) || typeof tag.literal !== "string") return undefined
  890. return {
  891. tag: tag.literal,
  892. identifier: SchemaAST.resolveIdentifier(schema.ast) ?? tag.literal,
  893. fields: fields.propertySignatures.flatMap((field) =>
  894. field.name === "_tag" || typeof field.name !== "string"
  895. ? []
  896. : [[field.name, Schema.make(field.type), SchemaAST.isOptional(field.type)] as const],
  897. ),
  898. }
  899. }
  900. function isDataEnvelope(schema: Schema.Top) {
  901. if (isStreamSchema(schema) || HttpApiSchema.isNoContent(schema.ast)) return false
  902. const ast = Schema.toType(schema).ast
  903. return (
  904. SchemaAST.isObjects(ast) &&
  905. ast.indexSignatures.length === 0 &&
  906. ast.propertySignatures.length === 1 &&
  907. ast.propertySignatures[0]?.name === "data"
  908. )
  909. }
  910. function isStreamSchema(schema: Schema.Top): schema is HttpApiSchema.StreamSchema {
  911. return "_tag" in schema && (schema._tag === "StreamSse" || schema._tag === "StreamUint8Array")
  912. }
  913. function streamDataSchema(schema: Extract<HttpApiSchema.StreamSchema, { readonly _tag: "StreamSse" }>) {
  914. const ast = Schema.toType(schema.events).ast
  915. if (!SchemaAST.isObjects(ast)) throw new GenerationError({ reason: "Invalid SSE data schema" })
  916. const data = ast.propertySignatures.find((field) => field.name === "data")?.type
  917. if (data === undefined) throw new GenerationError({ reason: "Invalid SSE data schema" })
  918. return Schema.make(data)
  919. }
  920. function renderGroup(group: Group, groupIndex: number) {
  921. const slots: Array<Slot> = []
  922. const adapters: Array<string> = []
  923. const endpointSources = group.endpoints.map((operation, endpointIndex) => {
  924. const {
  925. endpoint,
  926. errors,
  927. headers: endpointHeaders,
  928. params: endpointParams,
  929. payloads: endpointPayloads,
  930. query: endpointQuery,
  931. successes,
  932. } = operation
  933. const prefix = `Endpoint${endpointIndex}`
  934. const params = addSlot(endpointParams, `${prefix}Params`)
  935. const query = addSlot(endpointQuery, `${prefix}Query`)
  936. const headers = addSlot(endpointHeaders, `${prefix}Headers`)
  937. const payloads = endpointPayloads.map((schema, index) => addSlot(schema, `${prefix}Payload${index}`)!)
  938. const success = renderSuccess(successes[0], `${prefix}Success`)
  939. const errorSlots = errors.map((schema, index) => addSlot(schema, `${prefix}Error${index}`)!)
  940. const options = [
  941. params === undefined ? undefined : `params: ${params.name}`,
  942. query === undefined ? undefined : `query: ${query.name}`,
  943. headers === undefined ? undefined : `headers: ${headers.name}`,
  944. payloads.length === 0
  945. ? undefined
  946. : `payload: ${payloads.length === 1 ? payloads[0].name : `[${payloads.map((slot) => slot.name).join(", ")}]`}`,
  947. `success: ${success.source}`,
  948. errorSlots.length === 0
  949. ? undefined
  950. : `error: ${errorSlots.length === 1 ? errorSlots[0].name : `[${errorSlots.map((slot) => slot.name).join(", ")}]`}`,
  951. ].filter((option): option is string => option !== undefined)
  952. const schemaBySource = { params, query, headers, payload: payloads[0] }
  953. const inputType = operation.input
  954. .map((field) => {
  955. const slot = schemaBySource[field.source]
  956. if (slot === undefined) {
  957. throw new GenerationError({ reason: `Missing input schema: ${group.identifier}.${endpoint.name}` })
  958. }
  959. return `readonly ${JSON.stringify(field.name)}${field.optional ? "?" : ""}: (typeof ${slot.name}.Type)[${JSON.stringify(field.name)}]`
  960. })
  961. .join("; ")
  962. const argument =
  963. operation.operation.inputMode === "none"
  964. ? ""
  965. : `input${operation.operation.inputMode === "optional" ? "?" : ""}: ${prefix}Input`
  966. const request = (["params", "query", "headers", "payload"] as const)
  967. .flatMap((source) => {
  968. const slot = schemaBySource[source]
  969. if (slot === undefined) return []
  970. const fields = operation.input
  971. .filter((field) => field.source === source)
  972. .map(
  973. (field) =>
  974. `${JSON.stringify(field.name)}: input${operation.operation.inputMode === "optional" ? "?." : ""}[${JSON.stringify(field.name)}]`,
  975. )
  976. return [`${source}: { ${fields.join(", ")} }`]
  977. })
  978. .join(", ")
  979. const declared = [...errorSlots, ...(success.streamError === undefined ? [] : [success.streamError])]
  980. const declaredSchema =
  981. declared.length === 0 ? "Schema.Never" : `Schema.Union([${declared.map((slot) => slot.name).join(", ")}])`
  982. const rawCall = `raw[${JSON.stringify(endpoint.name)}]({ ${request} })`
  983. const mapped = `${rawCall}.pipe(Effect.mapError(map${prefix}Error)${operation.unwrapData ? ", Effect.map((value) => value.data)" : ""})`
  984. const inputDeclaration = operation.operation.inputMode === "none" ? "" : `type ${prefix}Input = { ${inputType} }\n`
  985. adapters.push(
  986. `${inputDeclaration}const ${prefix}DeclaredError = ${declaredSchema}\nconst map${prefix}Error = (error: unknown) => HttpClientError.isHttpClientError(error) || Schema.isSchemaError(error) || Sse.Retry.is(error) ? new ClientError({ cause: error }) : Schema.is(${prefix}DeclaredError)(error) ? error : new ClientError({ cause: error })\nconst ${prefix} = (raw: RawGroup) => (${argument}) => ${operation.operation.success === "stream" ? `Stream.unwrap(${rawCall}.pipe(Effect.mapError(map${prefix}Error), Effect.map((stream) => stream.pipe(Stream.mapError(map${prefix}Error)))))` : mapped}`,
  987. )
  988. return `HttpApiEndpoint.make(${JSON.stringify(endpoint.method)})(${JSON.stringify(endpoint.name)}, ${JSON.stringify(endpoint.path)}, { ${options.join(", ")} })`
  989. })
  990. function addSlot(schema: Schema.Top | undefined, name: string) {
  991. if (schema === undefined) return undefined
  992. const slot = { name, schema }
  993. slots.push(slot)
  994. return slot
  995. }
  996. function renderSuccess(schema: Schema.Top, name: string) {
  997. if (!isStreamSchema(schema)) return { source: addSlot(schema, name)!.name }
  998. const status = resolveHttpApiStatus(schema.ast) ?? 200
  999. const annotate = status === 200 ? "" : `.pipe(HttpApiSchema.status(${status}))`
  1000. if (schema._tag === "StreamUint8Array") {
  1001. return {
  1002. source: `HttpApiSchema.StreamUint8Array({ contentType: ${JSON.stringify(schema.contentType)} })${annotate}`,
  1003. }
  1004. }
  1005. const value = addSlot(
  1006. schema.sseMode === "data" ? streamDataSchema(schema) : schema.events,
  1007. `${name}${schema.sseMode === "data" ? "Data" : "Events"}`,
  1008. )!
  1009. const error = addSlot(schema.error, `${name}Error`)!
  1010. return {
  1011. source: `HttpApiSchema.StreamSse({ ${schema.sseMode}: ${value.name}, error: ${error.name}, contentType: ${JSON.stringify(schema.contentType)} })${annotate}`,
  1012. streamError: error,
  1013. }
  1014. }
  1015. const declarations = renderSchemas(slots)
  1016. const groupSource = `HttpApiGroup.make(${JSON.stringify(group.identifier)}, { topLevel: ${group.endpoints[0]?.topLevel ?? false} })${endpointSources.map((endpoint) => `.add(${endpoint})`).join("")}`
  1017. const usesHttpApiSchema = endpointSources.some((source) => source.includes("HttpApiSchema."))
  1018. const methods = group.endpoints
  1019. .map((item, index) => `${JSON.stringify(item.operation.name)}: Endpoint${index}(raw)`)
  1020. .join(", ")
  1021. const rawGroup = group.endpoints[0]?.topLevel
  1022. ? `HttpApiClient.Client<typeof Group${groupIndex}>`
  1023. : `HttpApiClient.Client.Group<typeof Group${groupIndex}, ${JSON.stringify(group.identifier)}, never, never>`
  1024. const usesStream = group.endpoints.some((item) => item.operation.success === "stream")
  1025. return `// Generated by @opencode-ai/httpapi-codegen. Do not edit.\nimport { Effect, Schema${usesStream ? ", Stream" : ""} } from "effect"\nimport { Sse } from "effect/unstable/encoding"\nimport { HttpClientError } from "effect/unstable/http"\nimport { HttpApiClient, HttpApiEndpoint, HttpApiGroup${usesHttpApiSchema ? ", HttpApiSchema" : ""} } from "effect/unstable/httpapi"\nimport { ClientError } from "./client-error"\n\n${declarations}\n\nexport const Group${groupIndex} = ${groupSource}\n\ntype RawGroup = ${rawGroup}\n\n${adapters.join("\n\n")}\n\nexport const adaptGroup${groupIndex} = (raw: RawGroup) => ({ ${methods} })\n`
  1026. }
  1027. function renderSchemas(slots: ReadonlyArray<Slot>) {
  1028. if (slots.length === 0) return ""
  1029. const classes = new Map(
  1030. slots.flatMap((slot, index) => {
  1031. const tagged = taggedErrorFields(slot.schema)
  1032. return tagged === undefined ? [] : [[index, tagged] as const]
  1033. }),
  1034. )
  1035. const expanded = [
  1036. ...slots.map((slot, index) => (classes.has(index) ? { name: slot.name, schema: Schema.Never } : slot)),
  1037. ...Array.from(classes.values()).flatMap((tagged, classIndex) =>
  1038. tagged.fields.map(([name, schema]) => ({ name: `Class${classIndex}${name}`, schema })),
  1039. ),
  1040. ]
  1041. const [first, ...rest] = expanded
  1042. const document = SchemaRepresentation.toCodeDocument(
  1043. SchemaRepresentation.fromASTs([first.schema.ast, ...rest.map((slot) => slot.schema.ast)]),
  1044. )
  1045. const artifacts = document.artifacts.flatMap((artifact) => {
  1046. if (artifact._tag === "Import") return [artifact.importDeclaration]
  1047. if (artifact._tag === "Enum") return [artifact.generation.runtime]
  1048. return [`const ${artifact.identifier} = ${artifact.generation.runtime}`]
  1049. })
  1050. const references = [
  1051. ...document.references.nonRecursives.map(({ $ref, code }) => `const ${$ref} = ${code.runtime}`),
  1052. ...Object.entries(document.references.recursives).map(
  1053. ([$ref, code]) => `type ${$ref} = ${code.Type}\nconst ${$ref}: Schema.Codec<${$ref}> = ${code.runtime}`,
  1054. ),
  1055. ]
  1056. let fieldIndex = slots.length
  1057. const declarations = slots.map((slot, index) => {
  1058. const tagged = classes.get(index)
  1059. if (tagged === undefined) return `const ${slot.name} = ${document.codes[index].runtime}`
  1060. const fields = tagged.fields
  1061. .map(([name]) => `${JSON.stringify(name)}: ${document.codes[fieldIndex++].runtime}`)
  1062. .join(", ")
  1063. const annotations = Object.entries({
  1064. httpApiStatus: resolveHttpApiStatus(slot.schema.ast),
  1065. "~httpApiEncoding": resolveHttpApiEncoding(slot.schema.ast),
  1066. }).filter((entry) => entry[1] !== undefined)
  1067. const annotate =
  1068. annotations.length === 0
  1069. ? ""
  1070. : `.annotate({ ${annotations.map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(value)}`).join(", ")} })`
  1071. return `class ${slot.name}Class extends Schema.TaggedErrorClass<${slot.name}Class>(${JSON.stringify(tagged.identifier)})(${JSON.stringify(tagged.tag)}, { ${fields} }) {}\nconst ${slot.name} = ${slot.name}Class${annotate}`
  1072. })
  1073. return [...artifacts, ...references, ...declarations].join("\n\n")
  1074. }
  1075. function renderClient(groups: ReadonlyArray<Group>) {
  1076. const imports = groups
  1077. .map((group, index) => `import { adaptGroup${index}, Group${index} } from ${JSON.stringify(`./${group.module}`)}`)
  1078. .join("\n")
  1079. const api = `HttpApi.make("generated")${groups.map((_, index) => `.add(Group${index})`).join("")}`
  1080. const fields = groups.flatMap((group, index) => {
  1081. if (!group.endpoints[0]?.topLevel) {
  1082. return [`${JSON.stringify(group.identifier)}: adaptGroup${index}(raw[${JSON.stringify(group.identifier)}])`]
  1083. }
  1084. const raw = `{ ${group.endpoints.map((item) => `${JSON.stringify(item.endpoint.name)}: raw[${JSON.stringify(item.endpoint.name)}]`).join(", ")} }`
  1085. return [`...adaptGroup${index}(${raw})`]
  1086. })
  1087. return `// Generated by @opencode-ai/httpapi-codegen. Do not edit.\nimport { Effect } from "effect"\nimport { HttpApi, HttpApiClient } from "effect/unstable/httpapi"\n${imports}\n\nconst Api = ${api}\nconst adaptClient = (raw: HttpApiClient.ForApi<typeof Api>) => ({ ${fields.join(", ")} })\n\nexport const make = (options?: { readonly baseUrl?: URL | string }) =>\n HttpApiClient.make(Api, options).pipe(Effect.map(adaptClient))\n`
  1088. }