import { Context, Effect, Either, Layer, Option, Runtime, Schema as S, } from 'effect' import { Bus, CurrentTracker, Event, Reducer, Reducers, State, type Store, type Trigger, } from '@playfast/reform' import type { AnySource, Source } from '@playfast/reform' import { getNestedValue, isPathOrParentDirty, moveAt, recalculateDirtyPaths, replaceAt, setNestedValue, type ArrayItem, type ArrayPath, type FieldPath, type PathValue, type VariantPath, type VariantValue, } from './path' import { error, errorsToRecord, firstError, normalizeErrors, routeParseError, type FormError, type FormErrors, } from './validation' export { error } export interface FieldLimitations { readonly required?: boolean readonly disabled?: boolean readonly readonly?: boolean readonly visible?: boolean readonly min?: number readonly max?: number readonly minLength?: number readonly maxLength?: number readonly minItems?: number readonly maxItems?: number readonly options?: ReadonlyArray readonly meta?: Readonly> } export type Limitations = Readonly> export interface FormState { readonly values: Values readonly initialValues: Values readonly touched: Readonly> readonly errors: FormErrors readonly dirtyPaths: ReadonlyArray readonly submitCount: number readonly validationCount: number readonly lastSubmittedValues: Option.Option readonly arrayKeys: Readonly>> } export interface FieldBinding { readonly path: string readonly value: A readonly set: (value: A | ((prev: A) => A)) => void readonly blur: () => void readonly error: Option.Option readonly dirty: boolean readonly touched: boolean readonly validating: boolean readonly limitations: FieldLimitations } export interface ArrayItemView { readonly key: string readonly index: number readonly value: Item readonly remove: () => void readonly move: (to: number) => void } export interface ArrayBinding { readonly path: string readonly items: ReadonlyArray> readonly append: (value?: Item) => void readonly remove: (index: number) => void readonly move: (from: number, to: number) => void readonly swap: (a: number, b: number) => void readonly limitations: FieldLimitations> } export interface FormView { readonly values: Values readonly inputs: Inputs readonly errors: FormErrors readonly dirty: boolean readonly canSubmit: boolean readonly submitCount: number readonly validationCount: number readonly lastSubmittedValues: Option.Option readonly submit: () => void readonly reset: () => void readonly validate: () => void readonly field:

>(path: P) => FieldBinding> readonly array:

>(path: P) => ArrayBinding> readonly variantValue:

>(path: P) => VariantValue } type InputRecord = Readonly> // Extracted structurally (`S['name']`) rather than through a `Source` conditional: `Source`'s value parameter is invariant (`in out A`), // so a concrete `StateToken<'x', V>` never matches `Source<_, unknown>` and the // conditional would erase every input's key to `never`. type SourceName = S['name'] type SourceValue = S extends Source ? A : never type InputsObject = { readonly [K in keyof Inputs as SourceName]: SourceValue } type InputStores = { [K in keyof Inputs]: Inputs[K] extends { readonly store: Context.Tag } ? Service : never }[keyof Inputs] type ValuesOfSchema = S.Schema.Encoded type DecodedOfSchema = S.Schema.Type export interface RuntimeConfig { readonly initial: Values readonly limit?: (ctx: { readonly values: Values readonly inputs: Inputs }) => Limitations readonly validate: (ctx: { readonly values: Values readonly decoded: Decoded readonly inputs: Inputs }) => Effect.Effect, never, never> readonly submit: (ctx: { readonly values: Values readonly decoded: Decoded readonly inputs: Inputs }) => Effect.Effect } export interface FormLiveConfig { readonly initial: Values readonly limit?: (ctx: { readonly values: Values readonly inputs: Inputs }) => Limitations readonly validate?: (ctx: { readonly values: Values readonly decoded: Decoded readonly inputs: Inputs }) => | void | FormError | ReadonlyArray | Effect.Effect, never, R> readonly submit?: (ctx: { readonly values: Values readonly decoded: Decoded readonly inputs: Inputs }) => void | Effect.Effect } export interface FormManifest { readonly kind: 'Form' readonly name: N readonly schema: Schema readonly inputs: Inputs } interface FormEvents { readonly set: Event.EventClass readonly blur: Event.EventClass readonly reset: Event.EventClass readonly validationFinished: Event.EventClass readonly submitAttempted: Event.EventClass readonly submitSucceeded: Event.EventClass readonly append: Event.EventClass readonly remove: Event.EventClass readonly move: Event.EventClass readonly swap: Event.EventClass } export interface FormClass< N extends string, Schema extends S.Schema.Any, Inputs extends InputRecord, > { new (): {} readonly manifest: FormManifest readonly state: State.StateClass<`${N}/state`, FormState>> readonly config: Context.Tag< RuntimeConfig, DecodedOfSchema, InputsObject>, RuntimeConfig, DecodedOfSchema, InputsObject> > readonly events: FormEvents readonly reducer: Reducer.StateReducerClass< State.StateClass<`${N}/state`, FormState>>, ReadonlyArray > } // `any` (not `InputRecord`) in the inputs slot: the inputs type flows into the // invariant `config` tag (via `InputsObject`), so a wildcard there must be `any` // for a concrete form — whose inputs object has real keys — to remain assignable // to `AnyForm`. Same Schema-variance escape the schema slot already uses. export type AnyForm = FormClass export type Values = F extends FormClass ? ValuesOfSchema : never export type Decoded = F extends FormClass ? DecodedOfSchema : never export type Inputs = F extends FormClass ? InputsObject : never export type View = FormView, Inputs> const unknownSchema = S.Unknown as S.Schema let nextArrayKey = 0 const makeArrayKey = (): string => `form-item-${nextArrayKey++}` export const arrayKeysFor = (value: unknown, path = ''): Record> => { const out: Record> = {} const visit = (current: unknown, currentPath: string): void => { if (Array.isArray(current)) { out[currentPath] = current.map(() => makeArrayKey()) current.forEach((item, index) => visit(item, `${currentPath}[${index}]`)) return } if (current !== null && typeof current === 'object') { for (const [key, child] of Object.entries(current)) { visit(child, currentPath.length === 0 ? key : `${currentPath}.${key}`) } } } visit(value, path) return out } const initialState = (initial: Values): FormState => ({ values: initial, initialValues: initial, touched: {}, errors: {}, dirtyPaths: [], submitCount: 0, validationCount: 0, lastSubmittedValues: Option.none(), arrayKeys: arrayKeysFor(initial), }) const markTouched = (touched: Readonly>, path: string): Readonly> => ({ ...touched, [path]: true }) const withValues = (state: FormState, values: Values): FormState => ({ ...state, values, dirtyPaths: recalculateDirtyPaths(state.initialValues, values), }) const currentArray = (values: unknown, path: string): ReadonlyArray => { const current = getNestedValue(values, path) return Array.isArray(current) ? current : [] } const updateKeys = ( state: FormState, path: string, f: (keys: ReadonlyArray) => ReadonlyArray, ): Readonly>> => { const existing = state.arrayKeys[path] ?? currentArray(state.values, path).map(() => makeArrayKey()) return { ...state.arrayKeys, [path]: f(existing) } } const setAtPath = (state: FormState, path: string, value: unknown): FormState => withValues(state, setNestedValue(state.values, path, value)) const appendAtPath = ( state: FormState, path: string, value: unknown, ): FormState => { const items = currentArray(state.values, path) const values = setNestedValue(state.values, path, [...items, value]) return { ...withValues(state, values), arrayKeys: updateKeys(state as FormState, path, (keys) => [...keys, makeArrayKey()]), } } const removeAtPath = ( state: FormState, path: string, index: number, ): FormState => { const items = currentArray(state.values, path) if (index < 0 || index >= items.length) return state const values = setNestedValue(state.values, path, items.filter((_, i) => i !== index)) return { ...withValues(state, values), arrayKeys: updateKeys(state as FormState, path, (keys) => keys.filter((_, i) => i !== index)), } } const moveAtPath = ( state: FormState, path: string, from: number, to: number, ): FormState => { const items = currentArray(state.values, path) const next = moveAt(items, from, to) if (next === items) return state const values = setNestedValue(state.values, path, next) return { ...withValues(state, values), arrayKeys: updateKeys(state as FormState, path, (keys) => moveAt(keys, from, to)), } } const swapAtPath = ( state: FormState, path: string, a: number, b: number, ): FormState => { const items = currentArray(state.values, path) if (a < 0 || b < 0 || a >= items.length || b >= items.length || a === b) return state const swapped = replaceAt(replaceAt(items, a, items[b]), b, items[a]) const values = setNestedValue(state.values, path, swapped) return { ...withValues(state, values), arrayKeys: updateKeys( state as FormState, path, (keys) => replaceAt(replaceAt(keys, a, keys[b] ?? makeArrayKey()), b, keys[a] ?? makeArrayKey()), ), } } export const make = < const N extends string, Schema extends S.Schema.Any, const Inputs extends InputRecord = {}, >( name: N, config: { readonly schema: Schema readonly inputs?: Inputs }, ): FormClass => { const state = State.make(`${name}/state`, unknownSchema, { title: `${name} form state`, }) as State.StateClass<`${N}/state`, FormState>> const events: FormEvents = { set: Event.make(`${name}/SetField`, S.Struct({ path: S.String, value: S.Unknown })), blur: Event.make(`${name}/BlurField`, S.Struct({ path: S.String })), reset: Event.make(`${name}/Reset`, S.Struct({})), validationFinished: Event.make(`${name}/ValidationFinished`, S.Struct({ errors: S.Record({ key: S.String, value: S.String }), })), submitAttempted: Event.make(`${name}/SubmitAttempted`, S.Struct({})), submitSucceeded: Event.make(`${name}/SubmitSucceeded`, S.Struct({ values: S.Unknown })), append: Event.make(`${name}/AppendItem`, S.Struct({ path: S.String, value: S.Unknown })), remove: Event.make(`${name}/RemoveItem`, S.Struct({ path: S.String, index: S.Number })), move: Event.make(`${name}/MoveItem`, S.Struct({ path: S.String, from: S.Number, to: S.Number })), swap: Event.make(`${name}/SwapItems`, S.Struct({ path: S.String, a: S.Number, b: S.Number })), } const reducer = Reducer.make(`${name}/FormReducer`, { states: [state], events: Object.values(events), }) const runtimeConfig = Context.GenericTag< RuntimeConfig, DecodedOfSchema, InputsObject>, RuntimeConfig, DecodedOfSchema, InputsObject> >(`reform/form/${name}/config`) const inputs = (config.inputs ?? {}) as Inputs return Object.assign(class {}, { manifest: { kind: 'Form' as const, name, schema: config.schema, inputs, }, state, config: runtimeConfig, events, reducer, }) as unknown as FormClass } export const live = < F extends AnyForm, R = never, >( form: F, config: FormLiveConfig, Decoded, Inputs, R>, ): Layer.Layer< Store>> | RuntimeConfig, Decoded, Inputs>, never, Bus | Reducers | R > => { const configTag = form.config as unknown as Context.Tag< RuntimeConfig, Decoded, Inputs>, RuntimeConfig, Decoded, Inputs> > const configLayer = Layer.effect( configTag, Effect.map(Effect.context(), (context) => { const runtimeConfig: RuntimeConfig, Decoded, Inputs> = { initial: config.initial, validate: (ctx) => { const result = config.validate?.(ctx) const effect = Effect.isEffect(result) ? result : Effect.succeed(result) return Effect.map( Effect.provide(effect, context), (value) => normalizeErrors(value), ) as Effect.Effect, never, never> }, submit: (ctx) => { const result = config.submit?.(ctx) const effect = Effect.isEffect(result) ? result : Effect.succeed(result) return Effect.asVoid(Effect.provide(effect, context)) as Effect.Effect }, } return config.limit === undefined ? runtimeConfig : { ...runtimeConfig, limit: config.limit } }), ) type InternalEvent = | { readonly _tag: string; readonly path: string; readonly value: unknown } | { readonly _tag: string; readonly path: string } | { readonly _tag: string; readonly errors: FormErrors } | { readonly _tag: string; readonly values: unknown } | { readonly _tag: string; readonly path: string; readonly index: number } | { readonly _tag: string; readonly path: string; readonly from: number; readonly to: number } | { readonly _tag: string; readonly path: string; readonly a: number; readonly b: number } | { readonly _tag: string } const reducerLayer = Reducer.live(form.reducer, (state: FormState>, event: InternalEvent): FormState> => { switch (event._tag) { case form.events.set.tag: return 'path' in event && 'value' in event ? setAtPath(state, event.path, event.value) : state case form.events.blur.tag: return 'path' in event ? { ...state, touched: markTouched(state.touched, event.path) } : state case form.events.reset.tag: return initialState(state.initialValues) case form.events.validationFinished.tag: return 'errors' in event ? { ...state, errors: event.errors, validationCount: state.validationCount + 1 } : state case form.events.submitAttempted.tag: return { ...state, submitCount: state.submitCount + 1 } case form.events.submitSucceeded.tag: return 'values' in event ? { ...state, lastSubmittedValues: Option.some(event.values as Values) } : state case form.events.append.tag: return 'path' in event && 'value' in event ? appendAtPath(state, event.path, event.value) : state case form.events.remove.tag: return 'path' in event && 'index' in event ? removeAtPath(state, event.path, event.index) : state case form.events.move.tag: return 'path' in event && 'from' in event && 'to' in event ? moveAtPath(state, event.path, event.from, event.to) : state case form.events.swap.tag: return 'path' in event && 'a' in event && 'b' in event ? swapAtPath(state, event.path, event.a, event.b) : state default: return state } }) return Layer.mergeAll(configLayer, reducerLayer).pipe( Layer.provideMerge(State.live(form.state, initialState(config.initial))), ) as Layer.Layer< Store>> | RuntimeConfig, Decoded, Inputs>, never, Bus | Reducers | R > } const readInput = ( source: Source, ): Effect.Effect, never, Store>> => Effect.gen(function* () { const store = yield* source.store const tracker = yield* Effect.serviceOption(CurrentTracker) if (Option.isSome(tracker)) tracker.value.add(store) return store.getSnapshot() }) as Effect.Effect, never, Store>> const readInputs = ( inputs: Inputs, ): Effect.Effect, never, InputStores> => Effect.gen(function* () { const out: Record = {} for (const source of Object.values(inputs)) { out[source.name] = yield* readInput(source) } return out as InputsObject }) as Effect.Effect, never, InputStores> const limitationsFor = ( limitations: Limitations, path: string, ): FieldLimitations => (limitations[path] ?? {}) as FieldLimitations const trigger =

(eventTrigger: Effect.Effect, never, Bus>): Effect.Effect, never, Bus> => eventTrigger export const view = ( form: F, ): Effect.Effect, never, Store>> | RuntimeConfig, Decoded, Inputs> | Bus | InputStores> => Effect.gen(function* () { const state = yield* form.state const runtimeConfig = yield* form.config // Erased boundary (same shape as the casts closing `live`/`readInputs`): // under the `AnyForm` constraint `form.manifest.inputs` is the wildcard // `any`, which would dissolve the generator's R to `unknown`; restate the // call at the concrete `F`'s types so R keeps the declared input stores. const inputs = (yield* readInputs(form.manifest.inputs as InputRecord)) as Inputs const limitations = runtimeConfig.limit?.({ values: state.values, inputs }) ?? {} const setField = yield* trigger(form.events.set.trigger) const blurField = yield* trigger(form.events.blur.trigger) const reset = yield* trigger(form.events.reset.trigger) const append = yield* trigger(form.events.append.trigger) const remove = yield* trigger(form.events.remove.trigger) const move = yield* trigger(form.events.move.trigger) const swap = yield* trigger(form.events.swap.trigger) const runtime = yield* Effect.runtime() const schema = form.manifest.schema as S.Schema, Values, never> const decodeEither = S.decodeUnknownEither(schema, { errors: 'all' })(state.values) const canSubmit = Either.isRight(decodeEither) && Object.keys(state.errors).length === 0 const runValidation = (publishSubmitAttempt: boolean) => Effect.gen(function* () { if (publishSubmitAttempt) yield* Event.dispatch(form.events.submitAttempted, {}) const decoded = S.decodeUnknownEither(schema, { errors: 'all' })(state.values) if (Either.isLeft(decoded)) { yield* Event.dispatch(form.events.validationFinished, { errors: routeParseError(decoded.left) }) return Option.none>() } const custom = yield* runtimeConfig.validate({ values: state.values, decoded: decoded.right, inputs }) const errors = errorsToRecord(custom) yield* Event.dispatch(form.events.validationFinished, { errors }) return Object.keys(errors).length === 0 ? Option.some(decoded.right as Decoded) : Option.none>() }) const submit = () => { Runtime.runFork(runtime)( Effect.gen(function* () { const decoded = yield* runValidation(true) if (Option.isNone(decoded)) return yield* runtimeConfig.submit({ values: state.values, decoded: decoded.value, inputs }) yield* Event.dispatch(form.events.submitSucceeded, { values: state.values }) }).pipe(Effect.catchAllCause((cause) => Effect.logError('reform form submit failed', cause))), ) } const validate = () => { Runtime.runFork(runtime)(runValidation(false)) } const field =

>>(path: P): FieldBinding, P>> => { const value = getNestedValue(state.values, path) as PathValue, P> return { path, value, set: (next) => setField({ path, value: typeof next === 'function' ? (next as (prev: PathValue, P>) => PathValue, P>)(value) : next, }), blur: () => blurField({ path }), error: firstError(state.errors, path), dirty: isPathOrParentDirty(state.dirtyPaths, path), touched: state.touched[path] === true, validating: false, limitations: limitationsFor, P>>(limitations, path), } } const array =

>>(path: P): ArrayBinding, P>> => { const values = currentArray(state.values, path) as ReadonlyArray, P>> const keys = state.arrayKeys[path] ?? values.map((_, i) => `${path}-${i}`) return { path, items: values.map((value, index) => ({ value, index, key: keys[index] ?? `${path}-${index}`, remove: () => remove({ path, index }), move: (to) => move({ path, from: index, to }), })), append: (value) => append({ path, value }), remove: (index) => remove({ path, index }), move: (from, to) => move({ path, from, to }), swap: (a, b) => swap({ path, a, b }), limitations: limitationsFor, P>>>(limitations, path), } } return { values: state.values, inputs, errors: state.errors, dirty: state.dirtyPaths.length > 0, canSubmit, submitCount: state.submitCount, validationCount: state.validationCount, lastSubmittedValues: state.lastSubmittedValues, submit, reset: () => reset({}), validate, field, array, variantValue: (path) => getNestedValue(state.values, path) as VariantValue, typeof path>, } as View })