diff --git a/packages/effect/src/unstable/httpapi/HttpApi.ts b/packages/effect/src/unstable/httpapi/HttpApi.ts index 7e50d88d99..5f0f4142a1 100644 --- a/packages/effect/src/unstable/httpapi/HttpApi.ts +++ b/packages/effect/src/unstable/httpapi/HttpApi.ts @@ -250,14 +250,14 @@ export const reflect = ( } as any) ) continue - const errors = extractMembers(endpoint.errorSchema.ast, HttpApiSchema.getStatusError) + const errors = extractMembers(endpoint.errorSchema, HttpApiSchema.getStatusError) options.onEndpoint({ group, endpoint, middleware: endpoint.middlewares as any, mergedAnnotations: ServiceMap.merge(groupAnnotations, endpoint.annotations), payloads: endpoint.payloadSchema ? extractPayloads(endpoint.payloadSchema.ast) : emptyMap, - successes: extractMembers(endpoint.successSchema.ast, HttpApiSchema.getStatusSuccess), + successes: extractMembers(endpoint.successSchema, HttpApiSchema.getStatusSuccess), errors }) } @@ -269,7 +269,7 @@ export const reflect = ( const emptyMap = new Map() const extractMembers = ( - ast: AST.AST, + schema: Schema.Top, getStatus: (ast: AST.AST) => number ): ReadonlyMap() - function process(type: AST.AST) { - if (AST.isNeverKeyword(type)) { - return - } - const annotations = HttpApiSchema.getHttpApiAnnotations(ast.annotations) - // Avoid changing the reference unless necessary - // Otherwise, deduplication of the ASTs below will not be possible - if (!Record.isEmptyRecord(annotations)) { - type = AST.annotate(type, { - ...annotations, - ...type.annotations - }) - } - const status = getStatus(type) - const isEmpty = type.annotations?.httpApiIsEmpty + function process(type: Schema.Top) { + const status = getStatus(type.ast) + const isEmpty = type.ast.annotations?.httpApiIsEmpty const current = members.get(status) members.set( status, { - description: current?.description ?? getDescriptionOrIdentifier(type), - ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type)) ?? - (!isEmpty && HttpApiSchema.isVoid(type) ? undefined : type) + description: current?.description ?? getDescriptionOrIdentifier(type.ast), + ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type.ast)) ?? + (!isEmpty && HttpApiSchema.isVoid(type.ast) ? undefined : type.ast) } ) } - HttpApiSchema.extractUnionTypes(ast).forEach(process) + HttpApiSchema.forEachMember(schema, process) return members } diff --git a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts index 1e572c40f8..3fe616233a 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts @@ -605,10 +605,10 @@ const makeSecurityMiddleware = ( const responseSchema = Schema.declare(Response.isHttpServerResponse) const makeSuccessSchema = ( - schema: Schema.Schema + schema: Schema.Top ): Schema.Codec => { const schemas = new Set>() - HttpApiSchema.deunionize(schemas, schema) + HttpApiSchema.forEachMember(schema, (_) => schemas.add(_)) return Schema.Union(Array.from(schemas, toResponseSuccess)) as any } @@ -618,10 +618,10 @@ const makeErrorSchema = ( const schemas = new Set>([HttpApiSchemaError]) for (const group of Object.values(api.groups)) { for (const endpoint of Object.values(group.endpoints)) { - HttpApiSchema.deunionize(schemas, endpoint.errorSchema) + HttpApiSchema.forEachMember(endpoint.errorSchema, (_) => schemas.add(_)) for (const middleware of endpoint.middlewares) { const key = middleware as any as HttpApiMiddleware.AnyKey - HttpApiSchema.deunionize(schemas, key.error) + HttpApiSchema.forEachMember(key.error, (_) => schemas.add(_)) } } } diff --git a/packages/effect/src/unstable/httpapi/HttpApiClient.ts b/packages/effect/src/unstable/httpapi/HttpApiClient.ts index 4eaf16c338..cd78c7bce8 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiClient.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiClient.ts @@ -521,10 +521,10 @@ const responseAsVoid = (_response: HttpClientResponse.HttpClientResponse) => Eff const HttpBodyFromSelf = Schema.declare(HttpBody.isHttpBody) -const payloadSchemaBody = (schema: Schema.Top): Schema.decodeTo => { - const members = schema.ast._tag === "UnionType" ? schema.ast.types : [schema.ast] - return Schema.Union(members.map(bodyFromPayload)) as any -} +const payloadSchemaBody = (schema: Schema.Top): Schema.decodeTo => + schema.ast._tag === "UnionType" + ? Schema.Union(schema.ast.types.map(bodyFromPayload)) as any + : bodyFromPayload(schema.ast) as any const bodyFromPayloadCache = new WeakMap() @@ -543,11 +543,12 @@ const bodyFromPayload = (ast: AST.AST) => { encode(toI: any) { switch (encoding.kind) { case "Json": { - return HttpBody.json(toI).pipe( - Effect.mapError((error) => - new Issue.InvalidValue(Option.some(toI), { message: `Could not encode as JSON: ${error}` }) - ) - ) + try { + const body = JSON.stringify(toI) + return Effect.succeed(HttpBody.text(body, encoding.contentType)) + } catch { + return Effect.fail(new Issue.InvalidValue(Option.some(toI), { message: "Could not encode as JSON" })) + } } case "Text": { if (typeof toI !== "string") { @@ -555,7 +556,7 @@ const bodyFromPayload = (ast: AST.AST) => { new Issue.InvalidValue(Option.some(toI), { message: "Expected a string" }) ) } - return Effect.succeed(HttpBody.text(toI)) + return Effect.succeed(HttpBody.text(toI, encoding.contentType)) } case "UrlParams": { return Effect.succeed(HttpBody.urlParams(UrlParams.fromInput(toI as any))) @@ -566,7 +567,7 @@ const bodyFromPayload = (ast: AST.AST) => { new Issue.InvalidValue(Option.some(toI), { message: "Expected a Uint8Array" }) ) } - return Effect.succeed(HttpBody.uint8Array(toI)) + return Effect.succeed(HttpBody.uint8Array(toI, encoding.contentType)) } } } diff --git a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts index 0133cfb9fe..674576b5bc 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts @@ -2,6 +2,7 @@ * @since 4.0.0 */ import type { YieldableError } from "../../Cause.ts" +import * as Iterable from "../../collections/Iterable.ts" import type { Brand } from "../../data/Brand.ts" import { constant, constVoid, dual, type LazyArg } from "../../Function.ts" import type * as FileSystem from "../../platform/FileSystem.ts" @@ -75,9 +76,27 @@ export const getHttpApiAnnotations = (self: Annotations.Annotations | undefined) /** * @since 4.0.0 - * @category reflection */ -export const extractUnionTypes = (ast: AST.AST): ReadonlyArray => { +export const UnionUnifyAST = (self: AST.AST, that: AST.AST): AST.AST => { + const asts = new Set([...extractUnionTypes(self), ...extractUnionTypes(that)]) + if (asts.size === 1) { + return Iterable.headUnsafe(asts) + } + return new AST.UnionType( + Array.from(asts), + "anyOf", + { + ...(AST.isUnionType(self) ? self.annotations : {}), + ...(AST.isUnionType(that) ? that.annotations : {}) + } + ) +} + +const extractUnionTypes = (ast: AST.AST): ReadonlyArray => { + const out: Array = [] + process(ast) + return out + function process(ast: AST.AST): void { if (AST.isUnionType(ast)) { for (const type of ast.types) { @@ -87,27 +106,15 @@ export const extractUnionTypes = (ast: AST.AST): ReadonlyArray => { out.push(ast) } } - const out: Array = [] - process(ast) - return out } -/** - * @since 4.0.0 - */ -export const UnionUnifyAST = (self: AST.AST, that: AST.AST): AST.AST => - new AST.UnionType( - Array.from(new Set([...extractUnionTypes(self), ...extractUnionTypes(that)])), - "anyOf" - ) - /** * @since 4.0.0 */ export const UnionUnify = < A extends Schema.Top, B extends Schema.Top ->(self: A, that: B): Schema.Union<[A, B]> => Schema.make(UnionUnifyAST(self.ast, that.ast)) as any +>(self: A, that: B): Schema.Top => Schema.make(UnionUnifyAST(self.ast, that.ast)) /** * @since 4.0.0 @@ -452,39 +459,47 @@ export const Uint8Array = (options?: { readonly contentType?: string }): Schema.Uint8Array => withEncoding(Schema.Uint8Array, { kind: "Uint8Array", ...options }) -const astCache = new WeakMap() - /** * @since 4.0.0 */ -export const deunionize = ( - schemas: Set, - schema: Schema.Top +export const forEachMember = ( + schema: Schema.Top, + f: (member: Schema.Top) => void ): void => { if (astCache.has(schema.ast)) { - schemas.add(astCache.get(schema.ast)!) + f(astCache.get(schema.ast)!) return } const ast = schema.ast if (ast._tag === "UnionType") { + let unionCache = unionCaches.get(ast) + if (!unionCache) { + unionCache = new WeakMap() + unionCaches.set(ast, unionCache) + } for (const astType of ast.types) { - if (astCache.has(astType)) { - schemas.add(astCache.get(astType)!) + if (unionCache.has(astType)) { + f(unionCache.get(astType)!) + continue + } else if (astType._tag === "NeverKeyword") { continue } const memberSchema = Schema.make(astType).annotate({ - ...ast.annotations, + ...getHttpApiAnnotations(ast.annotations), ...astType.annotations }) - astCache.set(astType, memberSchema) - schemas.add(memberSchema) + unionCache.set(astType, memberSchema) + f(memberSchema) } - } else { + } else if (ast._tag !== "NeverKeyword") { astCache.set(ast, schema) - schemas.add(schema) + f(schema) } } +const astCache = new WeakMap() +const unionCaches = new WeakMap>() + /** * @since 4.0.0 * @category empty errors