import { Group, GroupFieldType, NestableFieldTypes, NestedGroup } from "@prismicio/types-internal/lib/customtypes" import { either } from "fp-ts" import { pipe } from "fp-ts/lib/function" import * as t from "io-ts" import { Definition, isFieldDef, WithKey } from "../utils" import { NestableDef } from "./nestable/NestableDef" export const NestedGroupDef = createGroupDef(NestedGroup, NestableDef) export const GroupDef = createGroupDef(Group, t.union([NestableDef, NestedGroupDef])) const GroupDefType = "Group" function createGroupDef< GroupCodec extends typeof Group | typeof NestedGroup, FieldsDefA extends WithKey>, FieldsDefO, >(groupCodec: GroupCodec, fieldsDef: t.Type) { return new t.Type>>( "GroupDef", (u: unknown): u is WithKey> => isFieldDef(u) && groupCodec.is(u.def), (u: unknown) => { const codec = t.strict({ name: t.string, fields: t.array(fieldsDef), }) return pipe( codec.decode(u), either.map( ({ name, fields }): WithKey> => ({ key: name, def: { type: GroupDefType, config: { fields: fields.reduce((acc, field) => ({ ...acc, [field.key]: field.def }), {}), }, }, }), ), ) }, (n) => n, ) }