import type { z } from "zod/mini" import type { FieldOrSliceType } from "../../model/widget" interface LegacyContentCtxParams { fieldKey: string contentKey?: string fieldPath?: Array contentPath?: Array allTypes?: Map allKeys?: Map } export class LegacyContentCtx { fieldKey: string prefixedKey: string keyOfType: string keyOfKey: string fieldPath: Array fieldType?: FieldOrSliceType | undefined allTypes: Map allKeys: Map contentKey: string contentPath: Array fieldContentKey: string constructor({ fieldKey, contentKey, contentPath, fieldPath, allTypes, allKeys, }: LegacyContentCtxParams) { this.fieldKey = fieldKey this.contentKey = contentKey || fieldKey this.fieldPath = fieldPath || [] this.contentPath = contentPath || [] this.allTypes = allTypes || new Map() this.allKeys = allKeys || new Map() const prefixedKey = Array.of(this.fieldPath, [this.fieldKey]).flat().join(".") const prefixedContentKey = Array.of(this.contentPath, [this.contentKey]).flat().join(".") this.prefixedKey = prefixedKey this.keyOfType = `${prefixedKey}_TYPE` this.keyOfKey = `${prefixedContentKey}_KEY` this.fieldType = this.allTypes.get(this.prefixedKey) this.fieldContentKey = this.allKeys.get(prefixedContentKey) ?? crypto.randomUUID() } withContentKey(contentKey: string): LegacyContentCtx { return new LegacyContentCtx({ ...this, contentPath: [...this.contentPath, this.contentKey], contentKey, }) } } interface GetFieldCtxParams { fieldKey: string contentKey?: string ctx: LegacyContentCtx prefixes?: Array } export function getFieldCtx({ fieldKey, contentKey: contentKeyParam, ctx, prefixes, }: GetFieldCtxParams): LegacyContentCtx { const contentKey = contentKeyParam || fieldKey return new LegacyContentCtx({ fieldKey, contentKey, contentPath: [...ctx.contentPath, ctx.contentKey, ...(prefixes || [])], fieldPath: [...ctx.fieldPath, ctx.fieldKey, ...(prefixes || [])], allTypes: ctx.allTypes, allKeys: ctx.allKeys, }) } export function defaultCtx( key: string, allTypes: Map = new Map(), allKeys: Map = new Map(), ): LegacyContentCtx { return new LegacyContentCtx({ fieldKey: key, contentKey: key, contentPath: [], fieldPath: [], allTypes, allKeys, }) } type WithTypes = { keys: Record types: Record content: T } export type LegacyCodec = { name: string is(input: unknown): input is A toContent( input: unknown, ): z.core.util.SafeParseSuccess | z.core.util.SafeParseError fromContent( value: A, ): AllowUndefined extends false ? WithTypes : WithTypes | undefined }