@vielzeug/forge 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_utils.cjs +1 -1
- package/dist/_utils.cjs.map +1 -1
- package/dist/_utils.d.ts.map +1 -1
- package/dist/_utils.js +1 -0
- package/dist/_utils.js.map +1 -1
- package/dist/core/array.cjs +1 -1
- package/dist/core/array.cjs.map +1 -1
- package/dist/core/array.d.ts.map +1 -1
- package/dist/core/array.js +63 -32
- package/dist/core/array.js.map +1 -1
- package/dist/core/asyncQueue.cjs.map +1 -1
- package/dist/core/asyncQueue.d.ts +2 -2
- package/dist/core/asyncQueue.js.map +1 -1
- package/dist/core/context.cjs +1 -1
- package/dist/core/context.cjs.map +1 -1
- package/dist/core/context.d.ts +2 -5
- package/dist/core/context.d.ts.map +1 -1
- package/dist/core/context.js +72 -109
- package/dist/core/context.js.map +1 -1
- package/dist/core/fields.cjs +2 -0
- package/dist/core/fields.cjs.map +1 -0
- package/dist/core/fields.d.ts +52 -0
- package/dist/core/fields.d.ts.map +1 -0
- package/dist/core/fields.js +310 -0
- package/dist/core/fields.js.map +1 -0
- package/dist/core/lifecycle.cjs +1 -1
- package/dist/core/lifecycle.cjs.map +1 -1
- package/dist/core/lifecycle.d.ts +3 -1
- package/dist/core/lifecycle.d.ts.map +1 -1
- package/dist/core/lifecycle.js +10 -14
- package/dist/core/lifecycle.js.map +1 -1
- package/dist/core/notifier.cjs +2 -0
- package/dist/core/notifier.cjs.map +1 -0
- package/dist/core/notifier.d.ts +33 -0
- package/dist/core/notifier.d.ts.map +1 -0
- package/dist/core/notifier.js +78 -0
- package/dist/core/notifier.js.map +1 -0
- package/dist/core/observe.cjs +1 -1
- package/dist/core/observe.cjs.map +1 -1
- package/dist/core/observe.d.ts +8 -6
- package/dist/core/observe.d.ts.map +1 -1
- package/dist/core/observe.js +34 -45
- package/dist/core/observe.js.map +1 -1
- package/dist/core/scope.cjs +1 -1
- package/dist/core/scope.cjs.map +1 -1
- package/dist/core/scope.d.ts +6 -3
- package/dist/core/scope.d.ts.map +1 -1
- package/dist/core/scope.js +105 -156
- package/dist/core/scope.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -2
- package/dist/errors.js.map +1 -1
- package/dist/forge.cjs +1 -1
- package/dist/forge.cjs.map +1 -1
- package/dist/forge.iife.js +1 -1
- package/dist/forge.iife.js.map +1 -1
- package/dist/forge.js +1 -1
- package/dist/forge.js.map +1 -1
- package/dist/form.cjs +1 -1
- package/dist/form.cjs.map +1 -1
- package/dist/form.d.ts.map +1 -1
- package/dist/form.js +45 -56
- package/dist/form.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +4 -4
- package/dist/types.cjs +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +53 -36
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/dist/core/validation.cjs +0 -2
- package/dist/core/validation.cjs.map +0 -1
- package/dist/core/validation.d.ts +0 -23
- package/dist/core/validation.d.ts.map +0 -1
- package/dist/core/validation.js +0 -173
- package/dist/core/validation.js.map +0 -1
- package/dist/core/values.cjs +0 -2
- package/dist/core/values.cjs.map +0 -1
- package/dist/core/values.d.ts +0 -31
- package/dist/core/values.d.ts.map +0 -1
- package/dist/core/values.js +0 -149
- package/dist/core/values.js.map +0 -1
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/** A callback to remove a subscription. */\nexport type Unsubscribe = () => void;\n\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\nexport type FieldValidator<V = unknown> = (value: V, signal?: AbortSignal) => MaybePromise<string | undefined>;\n\nexport type FormValidator<TValues extends Record<string, unknown> = Record<string, unknown>> = (\n values: TValues,\n signal?: AbortSignal,\n) => MaybePromise<Partial<Record<ErrorKeyOf<TValues>, string>> | undefined>;\n\nexport type SetOptions = {\n /** Whether to mark the field as touched. Default: false. */\n touched?: boolean;\n};\n\nexport type FormState = {\n errors: Readonly<Record<string, string> & { [FORM_ERROR]?: string }>;\n isDirty: boolean;\n /** `true` while an async `defaultValues` factory is resolving. */\n isLoading: boolean;\n isSubmitting: boolean;\n isTouched: boolean;\n isValid: boolean;\n isValidating: boolean;\n submitCount: number;\n /**\n * Field names that are currently touched, as full dot-notation paths.\n * On a scoped form these are still full paths (e.g. `\"address.city\"`, not `\"city\"`).\n * Prefer calling `scopedForm.validate()` to run scoped validation rather than\n * passing `state.touchedFields` directly — scoped `validate(fields[])` expects relative paths.\n */\n touchedFields: readonly string[];\n /** Field names that currently have an active async validation run. Useful for per-field loading indicators. */\n validatingFields: readonly string[];\n};\n\nexport type SubscribeOptions = {\n /** Call the listener immediately with the current state on subscription. Default: false. */\n sync?: boolean;\n};\n\n/** Shared field key for root-level / form-level validation errors. */\nexport const FORM_ERROR = '_form' as const;\n\nexport type ValidateResult = {\n errors: Readonly<Record<string, string>>;\n valid: boolean;\n};\n\nexport type SubmitResult<TResult = void> =\n { ok: true; value: TResult } | { errors: Record<string, string>; ok: false; type: 'validation' };\n\n/* -------------------- Utility Types -------------------- */\n\n/**\n * Recursively makes all properties optional.\n * Used by `form.patch()` to accept partial nested updates.\n */\nexport type DeepPartial<T> = T extends Record<string, unknown> ? { [K in keyof T]?: DeepPartial<T[K]> } : T;\n\n/**\n * Recursively extracts all dot-notation leaf keys from a values shape.\n * Depth-limited to 5: TypeScript compilation time grows non-linearly beyond this point.\n */\nexport type FlatKeyOf<\n T extends Record<string, unknown>,\n P extends string = '',\n D extends readonly 0[] = [],\n> = D['length'] extends 5\n ? string\n : {\n [K in keyof T & string]: T[K] extends unknown[] | File | Blob | Date\n ? P extends ''\n ? K\n : `${P}.${K}`\n : T[K] extends Record<string, unknown>\n ? FlatKeyOf<T[K] & Record<string, unknown>, P extends '' ? K : `${P}.${K}`, [...D, 0]>\n : P extends ''\n ? K\n : `${P}.${K}`;\n }[keyof T & string];\n\n/** Resolves the value type at a dot-notation path within a values shape. */\nexport type TypeAtPath<T, K extends string> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends Record<string, unknown>\n ? TypeAtPath<T[Head], Tail>\n : unknown\n : unknown\n : K extends keyof T\n ? T[K]\n : unknown;\n\n/** Field error keys include field paths plus the reserved `_form` key for root-level issues. */\nexport type ErrorKeyOf<TValues extends Record<string, unknown>> = FlatKeyOf<TValues> | typeof FORM_ERROR;\n\n/**\n * Structural interface for safeParse-compatible schemas.\n * Works with `@vielzeug/spell`, Zod, Valibot, and any Standard Schema compliant library.\n */\nexport type SafeParseSchema = {\n safeParse(\n data: unknown,\n ): { success: true } | { error: { issues: { message: string; path: (string | number)[] }[] }; success: false };\n};\n\n/** The type of values accessible at a scoped sub-form prefix. */\nexport type ScopedValues<TValues, P extends string> =\n TypeAtPath<TValues, P> extends Record<string, unknown>\n ? TypeAtPath<TValues, P> & Record<string, unknown>\n : Record<string, unknown>;\n\n/**\n * The live connection object returned by `form.connect()`.\n * Getters re-evaluate on every property access — store the object once per field, do not destructure.\n * Call `dispose()` to cancel any pending debounce timers when the field unmounts.\n */\nexport type ConnectionResult<V = unknown> = {\n [Symbol.dispose](): void;\n readonly dirty: boolean;\n /** Cancels the debounce timer owned by this specific binding. Safe to call multiple times. */\n dispose(): void;\n /** `true` after `dispose()` has been called on this binding. */\n readonly disposed: boolean;\n readonly error: string | undefined;\n onBlur(): void;\n onChange(value: V): void;\n readonly touched: boolean;\n readonly value: V;\n};\n\n/** Per-field or global validation trigger configuration. */\nexport type ConnectOptions = {\n /**\n * Debounce auto-triggered validation by this many milliseconds.\n * Each `connect()` call owns its own timer — cancelling one binding does not affect others.\n * Default: 0.\n */\n debounce?: number;\n /** Auto-mark the field as touched when it loses focus. Default: false. */\n touchOnBlur?: boolean;\n /** Validate the field automatically when it loses focus. Default: false. */\n validateOnBlur?: boolean;\n /** Validate the field automatically after each value change. Default: false. */\n validateOnChange?: boolean;\n /** Validate on change only after the field has been touched at least once. */\n validateOnTouch?: boolean;\n};\n\n// Resolves the element type of an array, or `unknown` for non-arrays.\ntype ElementOf<T> = T extends readonly (infer E)[] ? E : unknown;\n\nexport type ArrayField<T = unknown> = {\n append(value: T): void;\n insert(index: number, value: T): void;\n move(from: number, to: number): void;\n prepend(value: T): void;\n remove(index: number): void;\n replace(index: number, value: T): void;\n swap(a: number, b: number): void;\n};\n\nexport type FieldState<V = unknown> = {\n dirty: boolean;\n error: string | undefined;\n /** `true` when `error` is not `undefined`. Convenience alias for `error !== undefined`. */\n hasError: boolean;\n touched: boolean;\n value: V;\n};\n\n/**\n * Options for registering a dynamic field. Both properties are optional;\n * omitting `defaultValue` leaves the field uninitialized and omitting `validator`\n * skips field-level validation.\n */\nexport type RegisterFieldOptions<V = unknown> = {\n /** Initial value. Also becomes the baseline, so the field starts clean. */\n defaultValue?: V;\n /** Field-level validator to attach. */\n validator?: FieldValidator<V>;\n};\n\n/**\n * A complete snapshot of form state that can be restored via `form.restore()`.\n * `store` and `baseline` keys are the flattened dot-notation paths used internally.\n * Typed with `TValues` for nominal clarity — structurally both are `Record<string, unknown>`.\n */\nexport type FormSnapshot<TValues extends Record<string, unknown> = Record<string, unknown>> = {\n readonly baseline: Partial<Record<FlatKeyOf<TValues>, unknown>>;\n readonly dirty: readonly string[];\n readonly errors: Readonly<Record<string, string>>;\n readonly store: Partial<Record<FlatKeyOf<TValues>, unknown>>;\n readonly submitCount: number;\n readonly touched: readonly string[];\n};\n\nexport type FormOptions<TValues extends Record<string, unknown> = Record<string, unknown>> = {\n /**\n * Default connect behavior applied when `connect(name, config)` omits specific options.\n * Use `ValidationModes` presets for common strategies:\n * - `ValidationModes.onSubmit` (default) — validates only on submit, no touch-on-blur\n * - `ValidationModes.onBlur` — validates each field on blur\n * - `ValidationModes.onChange` — validates each field on every change\n * - `ValidationModes.onTouched` — validates on blur first, then on every change once touched\n */\n connect?: ConnectOptions;\n /**\n * Initial form values. May be a static object or an async factory function.\n * While a factory is pending, `form.isLoading` is `true` and the form is read-only.\n */\n defaultValues?: { [K in keyof TValues]: TValues[K] } | (() => Promise<{ [K in keyof TValues]: TValues[K] }>);\n /**\n * Called when an async `defaultValues` factory rejects.\n * Use to show an error UI or retry logic. In development, a warning is also emitted via `console.warn`.\n */\n onLoadError?: (error: unknown) => void;\n /**\n * Form-level validator. Accepts either:\n * - A `FormValidator` function\n * - Any `safeParse`-compatible schema (auto-detected, works with `@vielzeug/spell`, Zod, Valibot)\n */\n validator?: FormValidator<TValues> | SafeParseSchema;\n /** Field-level validators keyed by field name or dot-notation path. */\n validators?: Partial<Record<FlatKeyOf<TValues>, FieldValidator>>;\n};\n\n/**\n * Named presets for common validation trigger strategies.\n * Pass to `createForm({ connect: ValidationModes.onBlur })`.\n *\n * - `onSubmit` — no automatic validation or touch. Clean until the user submits.\n * - `onBlur` — validates and marks touched on blur.\n * - `onChange` — validates on every keystroke (marks touched on blur).\n * - `onTouched` — validates on blur first, then on every change once touched.\n */\nexport const ValidationModes = {\n onBlur: { touchOnBlur: true, validateOnBlur: true },\n onChange: { touchOnBlur: true, validateOnChange: true },\n onSubmit: {},\n onTouched: { touchOnBlur: true, validateOnBlur: true, validateOnTouch: true },\n} as const satisfies Record<string, ConnectOptions>;\n\nexport interface Form<TValues extends Record<string, unknown> = Record<string, unknown>> {\n /** Returns a cached typed `ArrayField` helper for mutating array-valued fields. */\n array<K extends FlatKeyOf<TValues>>(name: K): ArrayField<ElementOf<TypeAtPath<TValues, K>>>;\n batch(fn: () => void): void;\n /** Clear a single field error. No-op if the field has no error. */\n clearError(name: ErrorKeyOf<TValues>): void;\n /**\n * Returns a live connection object for a field (DOM event handlers + live getters).\n * Each call to `connect()` creates a new object with its own debounce timer.\n * Call `binding.dispose()` on unmount to cancel any pending debounce timer.\n * Do not destructure: getters re-evaluate on every property access.\n */\n connect<K extends FlatKeyOf<TValues>>(name: K, config?: ConnectOptions): ConnectionResult<TypeAtPath<TValues, K>>;\n dispose(): void;\n /** Aborted when `dispose()` is called. Use to cancel async work tied to this form's lifetime. */\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n field<K extends FlatKeyOf<TValues>>(name: K): FieldState<TypeAtPath<TValues, K>>;\n get<K extends FlatKeyOf<TValues>>(name: K): TypeAtPath<TValues, K>;\n /** `true` while an async `defaultValues` factory is resolving. Mirrors `state.isLoading`. */\n readonly isLoading: boolean;\n /** `true` while a `submit()` call is in progress. Mirrors `state.isSubmitting`. */\n readonly isSubmitting: boolean;\n /**\n * Merge a partial server response into the form: updates both the store and the baseline\n * for each provided field, marking them clean. Fields not included in `partial` are untouched.\n */\n patch(partial: DeepPartial<TValues>): void;\n /**\n * Field-lifecycle namespace — use to dynamically register/remove fields and manage validators.\n *\n * @example\n * const unsub = form.fields.register('email', { defaultValue: '', validator: required });\n * form.fields.setValidator('email', (v) => v ? undefined : 'Required');\n * form.fields.remove('email');\n */\n fields: {\n /**\n * Enumerate all currently-known field paths: the deduplicated union of populated store\n * keys and keys with a registered validator (the same definition `touchAll()` uses).\n * On a scoped form, paths are relative to the scope's prefix — matching `scope.state`'s\n * relative-path convention, not `state.touchedFields`'s absolute-path convention.\n */\n list(): readonly string[];\n /**\n * Declare a dynamic field with an optional default value and validator.\n * If the field does not yet exist in the store, `defaultValue` is written to both the\n * store and the baseline so the field starts clean (not dirty).\n * Returns an **unregister** callback that calls `fields.remove()` on the same field.\n */\n register<K extends FlatKeyOf<TValues>>(\n name: K,\n options?: RegisterFieldOptions<TypeAtPath<TValues, K>>,\n ): Unsubscribe;\n /** Remove a field entirely: drops value, dirty, touched, error, and any registered validator. */\n remove(name: FlatKeyOf<TValues>): void;\n /**\n * Add, replace, or remove a field validator.\n * Removing a validator (passing `undefined`) also immediately clears any existing error for that field.\n */\n setValidator(name: FlatKeyOf<TValues>, validator?: FieldValidator): void;\n };\n /** Replace values and baseline in one operation. Aborts any in-flight validation. */\n replace(newValues: TValues): void;\n /** Restore values from the current baseline and clear errors/touched/dirty. Aborts any in-flight validation. */\n reset(): void;\n resetField(name: FlatKeyOf<TValues>): void;\n /** Replace the entire error map. Use `undefined` values to omit entries. */\n resetErrors(errors?: Partial<Record<ErrorKeyOf<TValues>, string | undefined>>): void;\n /**\n * Returns a scoped sub-form whose field paths are relative to `prefix`.\n * `scopedForm.get('city')` is equivalent to `form.get('${prefix}.city')`.\n * The scoped form shares state and lifecycle with the parent — `dispose()` on a scoped\n * form is a no-op; call `parentForm.dispose()` to tear down the whole form.\n *\n * Results are memoized — calling `scope(prefix)` multiple times with the same prefix\n * returns the same object. Safe to call on every render.\n *\n * **`state`** returns a scoped projection: `errors`, `touchedFields`, `validatingFields`,\n * `isValid`, `isDirty`, and `isTouched` reflect only fields within this prefix.\n * `isSubmitting`, `isLoading`, `isValidating`, and `submitCount` reflect the full form.\n */\n scope<P extends FlatKeyOf<TValues>>(prefix: P): Form<ScopedValues<TValues, P>>;\n set<K extends FlatKeyOf<TValues>>(name: K, value: TypeAtPath<TValues, K>, options?: SetOptions): void;\n /** Set a field error. */\n setError(name: ErrorKeyOf<TValues>, message: string): void;\n /**\n * Capture the complete form state into a snapshot that can be passed to `restore()`.\n * Useful for undo/redo, draft saving, and \"discard changes\" flows.\n */\n snapshot(): FormSnapshot<TValues>;\n /**\n * Restore the form to a previously captured snapshot. Replaces all state:\n * values, baseline, errors, touched, dirty, and submitCount.\n * Aborts any in-flight validation.\n */\n restore(snapshot: FormSnapshot<TValues>): void;\n readonly state: FormState;\n submit<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<SubmitResult<TResult>>;\n /**\n * Like `submit()` but throws a `ForgeValidationError` when validation fails instead of returning\n * `{ ok: false, ... }`. Use when you prefer a throw-based control flow.\n *\n * @throws {ForgeValidationError} when validation fails.\n * @throws {Error} when `submit()` is already in progress.\n */\n submitOrThrow<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<TResult>;\n subscribe(listener: (state: FormState) => void, options?: SubscribeOptions): Unsubscribe;\n /**\n * Subscribe to form state changes filtered to this scope's prefix.\n * `errors`, `touchedFields`, and `validatingFields` are remapped to relative paths;\n * all other state flags reflect the full form.\n * The listener fires only when the scoped projection changes — unrelated field mutations\n * outside this prefix are suppressed.\n * On a root form, behaves identically to `subscribe` — no prefix filtering is applied.\n */\n subscribeScoped(listener: (state: FormState) => void, options?: SubscribeOptions): Unsubscribe;\n subscribeField<K extends FlatKeyOf<TValues>>(\n name: K,\n listener: (state: FieldState<TypeAtPath<TValues, K>>) => void,\n options?: SubscribeOptions,\n ): Unsubscribe;\n /**\n * Iterate over form state changes via `for await`.\n * Yields the current state immediately, then once per mutation until the iterator\n * is returned or the form is disposed.\n *\n * @example\n * for await (const state of form) {\n * if (state.isSubmitting) showSpinner();\n * }\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<FormState>;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n /** Mark a field as touched. */\n touch(name: FlatKeyOf<TValues>): void;\n /** Mark all known fields (store + validators) as touched. */\n touchAll(): void;\n /** Mark a field as untouched. No-op if the field is not currently touched. */\n untouch(name: FlatKeyOf<TValues>): void;\n /** Mark all fields as untouched. */\n untouchAll(): void;\n /**\n * Validate all registered field validators and the optional form validator.\n *\n * On a scoped form: validates only the fields within the scope and does not run the\n * form-level validator. Errors and `valid` reflect only scoped fields.\n */\n validate(signal?: AbortSignal): Promise<ValidateResult>;\n /**\n * Validate a single named field. Preserves other fields' errors. Does not run the form-level validator.\n * Returns a `ValidateResult` scoped to that field — `errors` contains at most one entry.\n */\n validate(name: FlatKeyOf<TValues>, signal?: AbortSignal): Promise<ValidateResult>;\n /**\n * Validate a specific set of fields. Preserves other fields' errors. Does not run the form-level validator.\n * Returns a `ValidateResult` scoped to the requested fields.\n */\n validate(fields: FlatKeyOf<TValues>[], signal?: AbortSignal): Promise<ValidateResult>;\n /**\n * Streaming validation — yields each field result as soon as its validator resolves.\n * The final item in the stream is the form-level validator result (field: '_form'), if configured.\n *\n * @example\n * for await (const result of form.validateStream()) {\n * console.log(result.field, result.error ?? 'ok');\n * }\n */\n validateStream(signal?: AbortSignal): AsyncIterableIterator<{ error: string | undefined; field: string }>;\n values(): TValues;\n}\n"],"mappings":";AA4CA,IAAa,IAAa,SAkMb,IAAkB;CAC7B,QAAQ;EAAE,aAAa;EAAM,gBAAgB;CAAK;CAClD,UAAU;EAAE,aAAa;EAAM,kBAAkB;CAAK;CACtD,UAAU,CAAC;CACX,WAAW;EAAE,aAAa;EAAM,gBAAgB;EAAM,iBAAiB;CAAK;AAC9E"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/** A callback to remove a subscription. */\nexport type Unsubscribe = () => void;\n\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\nexport type FieldValidator<V = unknown> = (value: V, signal?: AbortSignal) => MaybePromise<string | undefined>;\n\nexport type FormValidator<TValues extends Record<string, unknown> = Record<string, unknown>> = (\n values: TValues,\n signal?: AbortSignal,\n) => MaybePromise<Partial<Record<ErrorKeyOf<TValues>, string>> | undefined>;\n\nexport type SetOptions = {\n /** Whether to mark the field as touched. Default: false. */\n touched?: boolean;\n};\n\nexport type FormState = {\n errors: Readonly<Record<string, string> & { [FORM_ERROR]?: string }>;\n isDirty: boolean;\n /** `true` while an async `defaultValues` factory is resolving. */\n isLoading: boolean;\n isSubmitting: boolean;\n isTouched: boolean;\n isValid: boolean;\n isValidating: boolean;\n submitCount: number;\n /**\n * Field names that are currently touched, as full dot-notation paths.\n * On a scoped form these are still full paths (e.g. `\"address.city\"`, not `\"city\"`).\n * Prefer calling `scopedForm.validate()` to run scoped validation rather than\n * passing `state.touchedFields` directly — scoped `validate(fields[])` expects relative paths.\n */\n touchedFields: readonly string[];\n /** Field names that currently have an active async validation run. Useful for per-field loading indicators. */\n validatingFields: readonly string[];\n};\n\nexport type SubscribeOptions = {\n /** Call the listener immediately with the current state on subscription. Default: false. */\n sync?: boolean;\n};\n\n/** Shared field key for root-level / form-level validation errors. */\nexport const FORM_ERROR = '_form' as const;\n\nexport type ValidateResult = {\n errors: Readonly<Record<string, string>>;\n valid: boolean;\n};\n\nexport type SubmitResult<TResult = void> =\n { ok: true; value: TResult } | { errors: Record<string, string>; ok: false; type: 'validation' };\n\n/* -------------------- Utility Types -------------------- */\n\n/**\n * Recursively makes all properties optional.\n * Used by `form.patch()` to accept partial nested updates.\n */\nexport type DeepPartial<T> = T extends Record<string, unknown> ? { [K in keyof T]?: DeepPartial<T[K]> } : T;\n\n/**\n * Single source of truth for the typed-path depth ceiling, shared by `FlatKeyOf`'s\n * type-level cutoff below and `_utils.ts`'s matching runtime dev-warning threshold —\n * one named constant instead of two hardcoded `5`s that could silently drift apart.\n *\n * Deliberately not a per-form generic parameter (e.g. `Form<TValues, MaxDepth>`): the\n * whole point of this cutoff is protecting TypeScript compile time, which is a\n * repo-wide concern, not a per-form preference. Making it user-configurable would let\n * one form's type param silently regress compile performance for everyone who imports\n * it. If a real shape needs deeper typed paths, flatten it or accept `string` typing\n * for those leaves — `FlatKeyOf` already falls back to `string` gracefully past this\n * depth, so nothing is a hard error either way.\n */\nexport const MAX_TYPED_PATH_DEPTH = 5 as const;\n\n/**\n * Recursively extracts all dot-notation leaf keys from a values shape.\n * Depth-limited to {@link MAX_TYPED_PATH_DEPTH}: TypeScript compilation time grows\n * non-linearly beyond this point.\n */\nexport type FlatKeyOf<\n T extends Record<string, unknown>,\n P extends string = '',\n D extends readonly 0[] = [],\n> = D['length'] extends typeof MAX_TYPED_PATH_DEPTH\n ? string\n : {\n [K in keyof T & string]: T[K] extends unknown[] | File | Blob | Date\n ? P extends ''\n ? K\n : `${P}.${K}`\n : T[K] extends Record<string, unknown>\n ? FlatKeyOf<T[K] & Record<string, unknown>, P extends '' ? K : `${P}.${K}`, [...D, 0]>\n : P extends ''\n ? K\n : `${P}.${K}`;\n }[keyof T & string];\n\n/** Resolves the value type at a dot-notation path within a values shape. */\nexport type TypeAtPath<T, K extends string> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends Record<string, unknown>\n ? TypeAtPath<T[Head], Tail>\n : unknown\n : unknown\n : K extends keyof T\n ? T[K]\n : unknown;\n\n/** Field error keys include field paths plus the reserved `_form` key for root-level issues. */\nexport type ErrorKeyOf<TValues extends Record<string, unknown>> = FlatKeyOf<TValues> | typeof FORM_ERROR;\n\n/**\n * Structural interface for safeParse-compatible schemas.\n * Works with `@vielzeug/spell`, Zod, Valibot, and any Standard Schema compliant library.\n */\nexport type SafeParseSchema = {\n safeParse(\n data: unknown,\n ): { success: true } | { error: { issues: { message: string; path: (string | number)[] }[] }; success: false };\n};\n\n/** The type of values accessible at a scoped sub-form prefix. */\nexport type ScopedValues<TValues, P extends string> =\n TypeAtPath<TValues, P> extends Record<string, unknown>\n ? TypeAtPath<TValues, P> & Record<string, unknown>\n : Record<string, unknown>;\n\n/**\n * The live connection object returned by `form.connect()`.\n * Getters re-evaluate on every property access — store the object once per field, do not destructure.\n * Call `dispose()` to cancel any pending debounce timers when the field unmounts.\n */\nexport type ConnectionResult<V = unknown> = {\n [Symbol.dispose](): void;\n readonly dirty: boolean;\n /** Cancels the debounce timer owned by this specific binding. Safe to call multiple times. */\n dispose(): void;\n /** `true` after `dispose()` has been called on this binding. */\n readonly disposed: boolean;\n readonly error: string | undefined;\n onBlur(): void;\n onChange(value: V): void;\n readonly touched: boolean;\n readonly value: V;\n};\n\n/** Per-field or global validation trigger configuration. */\nexport type ConnectOptions = {\n /**\n * Debounce auto-triggered validation by this many milliseconds.\n * Each `connect()` call owns its own timer — cancelling one binding does not affect others.\n * Default: 0.\n */\n debounce?: number;\n /** Auto-mark the field as touched when it loses focus. Default: false. */\n touchOnBlur?: boolean;\n /** Validate the field automatically when it loses focus. Default: false. */\n validateOnBlur?: boolean;\n /** Validate the field automatically after each value change. Default: false. */\n validateOnChange?: boolean;\n /** Validate on change only after the field has been touched at least once. */\n validateOnTouch?: boolean;\n};\n\n// Resolves the element type of an array, or `unknown` for non-arrays.\ntype ElementOf<T> = T extends readonly (infer E)[] ? E : unknown;\n\nexport type ArrayField<T = unknown> = {\n append(value: T): void;\n insert(index: number, value: T): void;\n move(from: number, to: number): void;\n prepend(value: T): void;\n remove(index: number): void;\n replace(index: number, value: T): void;\n swap(a: number, b: number): void;\n};\n\nexport type FieldState<V = unknown> = {\n dirty: boolean;\n error: string | undefined;\n /** `true` when `error` is not `undefined`. Convenience alias for `error !== undefined`. */\n hasError: boolean;\n touched: boolean;\n value: V;\n};\n\n/**\n * Options for registering a dynamic field. Both properties are optional;\n * omitting `defaultValue` leaves the field uninitialized and omitting `validator`\n * skips field-level validation.\n */\nexport type RegisterFieldOptions<V = unknown> = {\n /** Initial value. Also becomes the baseline, so the field starts clean. */\n defaultValue?: V;\n /** Field-level validator to attach. */\n validator?: FieldValidator<V>;\n};\n\n/**\n * A complete snapshot of form state that can be restored via `form.history.restore()`.\n * `store` and `baseline` keys are the flattened dot-notation paths used internally.\n * Typed with `TValues` for nominal clarity — structurally both are `Record<string, unknown>`.\n */\nexport type FormSnapshot<TValues extends Record<string, unknown> = Record<string, unknown>> = {\n readonly baseline: Partial<Record<FlatKeyOf<TValues>, unknown>>;\n readonly dirty: readonly string[];\n readonly errors: Readonly<Record<string, string>>;\n readonly store: Partial<Record<FlatKeyOf<TValues>, unknown>>;\n readonly submitCount: number;\n readonly touched: readonly string[];\n};\n\n/**\n * Undo/redo-style snapshotting, namespaced off the main `Form<T>` surface since it's a\n * distinctly less common operation than reading/writing values — grouped the same way\n * `fields` already groups dynamic-field-lifecycle operations.\n */\nexport type FormHistory<TValues extends Record<string, unknown> = Record<string, unknown>> = {\n /**\n * Restore the form to a previously captured snapshot. Replaces all state:\n * values, baseline, errors, touched, dirty, and submitCount.\n * Aborts any in-flight validation.\n */\n restore(snapshot: FormSnapshot<TValues>): void;\n /**\n * Capture the complete form state into a snapshot that can be passed to `restore()`.\n * Useful for undo/redo, draft saving, and \"discard changes\" flows.\n */\n snapshot(): FormSnapshot<TValues>;\n};\n\nexport type FormOptions<TValues extends Record<string, unknown> = Record<string, unknown>> = {\n /**\n * Default connect behavior applied when `connect(name, config)` omits specific options.\n * Use `ValidationModes` presets for common strategies:\n * - `ValidationModes.onSubmit` (default) — validates only on submit, no touch-on-blur\n * - `ValidationModes.onBlur` — validates each field on blur\n * - `ValidationModes.onChange` — validates each field on every change\n * - `ValidationModes.onTouched` — validates on blur first, then on every change once touched\n */\n connect?: ConnectOptions;\n /**\n * Initial form values. May be a static object or an async factory function.\n * While a factory is pending, `form.isLoading` is `true` and the form is read-only.\n */\n defaultValues?: { [K in keyof TValues]: TValues[K] } | (() => Promise<{ [K in keyof TValues]: TValues[K] }>);\n /**\n * Called when an async `defaultValues` factory rejects.\n * Use to show an error UI or retry logic. In development, a warning is also emitted via `console.warn`.\n */\n onLoadError?: (error: unknown) => void;\n /**\n * Form-level validator. Accepts either:\n * - A `FormValidator` function\n * - Any `safeParse`-compatible schema (auto-detected, works with `@vielzeug/spell`, Zod, Valibot)\n */\n validator?: FormValidator<TValues> | SafeParseSchema;\n /** Field-level validators keyed by field name or dot-notation path. */\n validators?: Partial<Record<FlatKeyOf<TValues>, FieldValidator>>;\n};\n\n/**\n * Named presets for common validation trigger strategies.\n * Pass to `createForm({ connect: ValidationModes.onBlur })`.\n *\n * - `onSubmit` — no automatic validation or touch. Clean until the user submits.\n * - `onBlur` — validates and marks touched on blur.\n * - `onChange` — validates on every keystroke (marks touched on blur).\n * - `onTouched` — validates on blur first, then on every change once touched.\n */\nexport const ValidationModes = {\n onBlur: { touchOnBlur: true, validateOnBlur: true },\n onChange: { touchOnBlur: true, validateOnChange: true },\n onSubmit: {},\n onTouched: { touchOnBlur: true, validateOnBlur: true, validateOnTouch: true },\n} as const satisfies Record<string, ConnectOptions>;\n\nexport interface Form<TValues extends Record<string, unknown> = Record<string, unknown>> {\n /** Returns a cached typed `ArrayField` helper for mutating array-valued fields. */\n array<K extends FlatKeyOf<TValues>>(name: K): ArrayField<ElementOf<TypeAtPath<TValues, K>>>;\n batch(fn: () => void): void;\n /** Clear a single field error. No-op if the field has no error. */\n clearError(name: ErrorKeyOf<TValues>): void;\n /**\n * Returns a live connection object for a field (DOM event handlers + live getters).\n * Each call to `connect()` creates a new object with its own debounce timer.\n * Call `binding.dispose()` on unmount to cancel any pending debounce timer.\n * Do not destructure: getters re-evaluate on every property access.\n */\n connect<K extends FlatKeyOf<TValues>>(name: K, config?: ConnectOptions): ConnectionResult<TypeAtPath<TValues, K>>;\n dispose(): void;\n /** Aborted when `dispose()` is called. Use to cancel async work tied to this form's lifetime. */\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n field<K extends FlatKeyOf<TValues>>(name: K): FieldState<TypeAtPath<TValues, K>>;\n get<K extends FlatKeyOf<TValues>>(name: K): TypeAtPath<TValues, K>;\n /** `true` while an async `defaultValues` factory is resolving. Mirrors `state.isLoading`. */\n readonly isLoading: boolean;\n /** `true` while a `submit()` call is in progress. Mirrors `state.isSubmitting`. */\n readonly isSubmitting: boolean;\n /**\n * Merge a partial server response into the form: updates both the store and the baseline\n * for each provided field, marking them clean. Fields not included in `partial` are untouched.\n */\n patch(partial: DeepPartial<TValues>): void;\n /**\n * Field-lifecycle namespace — use to dynamically register/remove fields and manage validators.\n *\n * @example\n * const unsub = form.fields.register('email', { defaultValue: '', validator: required });\n * form.fields.setValidator('email', (v) => v ? undefined : 'Required');\n * form.fields.remove('email');\n */\n fields: {\n /**\n * Enumerate all currently-known field paths: the deduplicated union of populated store\n * keys and keys with a registered validator (the same definition `touchAll()` uses).\n * On a scoped form, paths are relative to the scope's prefix — matching `scope.state`'s\n * relative-path convention, not `state.touchedFields`'s absolute-path convention.\n */\n list(): readonly string[];\n /**\n * Declare a dynamic field with an optional default value and validator.\n * If the field does not yet exist in the store, `defaultValue` is written to both the\n * store and the baseline so the field starts clean (not dirty).\n * Returns an **unregister** callback that calls `fields.remove()` on the same field.\n */\n register<K extends FlatKeyOf<TValues>>(\n name: K,\n options?: RegisterFieldOptions<TypeAtPath<TValues, K>>,\n ): Unsubscribe;\n /** Remove a field entirely: drops value, dirty, touched, error, and any registered validator. */\n remove(name: FlatKeyOf<TValues>): void;\n /**\n * Add, replace, or remove a field validator.\n * Removing a validator (passing `undefined`) also immediately clears any existing error for that field.\n */\n setValidator(name: FlatKeyOf<TValues>, validator?: FieldValidator): void;\n };\n /**\n * Undo/redo-style snapshotting — see {@link FormHistory}. Namespaced off the main surface\n * since it's a distinctly less common operation than reading/writing values.\n *\n * @example\n * const before = form.history.snapshot();\n * form.patch({ status: 'archived' });\n * form.history.restore(before); // undo\n */\n history: FormHistory<TValues>;\n /** Replace values and baseline in one operation. Aborts any in-flight validation. */\n replace(newValues: TValues): void;\n /** Restore values from the current baseline and clear errors/touched/dirty. Aborts any in-flight validation. */\n reset(): void;\n resetField(name: FlatKeyOf<TValues>): void;\n /** Replace the entire error map. Use `undefined` values to omit entries. */\n resetErrors(errors?: Partial<Record<ErrorKeyOf<TValues>, string | undefined>>): void;\n /**\n * Returns a scoped sub-form whose field paths are relative to `prefix`.\n * `scopedForm.get('city')` is equivalent to `form.get('${prefix}.city')`.\n * The scoped form shares state and lifecycle with the parent — `dispose()` on a scoped\n * form is a no-op; call `parentForm.dispose()` to tear down the whole form.\n *\n * Results are memoized — calling `scope(prefix)` multiple times with the same prefix\n * returns the same object. Safe to call on every render.\n *\n * **`state`** returns a scoped projection: `errors`, `touchedFields`, `validatingFields`,\n * `isValid`, `isDirty`, and `isTouched` reflect only fields within this prefix.\n * `isSubmitting`, `isLoading`, `isValidating`, and `submitCount` reflect the full form.\n */\n scope<P extends FlatKeyOf<TValues>>(prefix: P): Form<ScopedValues<TValues, P>>;\n set<K extends FlatKeyOf<TValues>>(name: K, value: TypeAtPath<TValues, K>, options?: SetOptions): void;\n /** Set a field error. */\n setError(name: ErrorKeyOf<TValues>, message: string): void;\n readonly state: FormState;\n submit<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<SubmitResult<TResult>>;\n /**\n * Like `submit()` but throws a `ForgeValidationError` when validation fails instead of returning\n * `{ ok: false, ... }`. Use when you prefer a throw-based control flow.\n *\n * @throws {ForgeValidationError} when validation fails.\n * @throws {ForgeSubmitError} when `submit()` is already in progress.\n */\n submitOrThrow<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<TResult>;\n /**\n * Subscribe to form state changes.\n * On a scoped form (`form.scope(prefix)`), `errors`, `touchedFields`, and `validatingFields`\n * are remapped to relative paths, and the listener fires only when the scoped projection\n * changes — mutations outside the scope's prefix are suppressed. On a root form, no\n * filtering is applied.\n */\n subscribe(listener: (state: FormState) => void, options?: SubscribeOptions): Unsubscribe;\n subscribeField<K extends FlatKeyOf<TValues>>(\n name: K,\n listener: (state: FieldState<TypeAtPath<TValues, K>>) => void,\n options?: SubscribeOptions,\n ): Unsubscribe;\n /**\n * Iterate over form state changes via `for await`.\n * Yields the current state immediately, then once per mutation until the iterator\n * is returned or the form is disposed.\n *\n * @example\n * for await (const state of form) {\n * if (state.isSubmitting) showSpinner();\n * }\n */\n [Symbol.asyncIterator](): AsyncIterableIterator<FormState>;\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose](): void;\n /** Mark a field as touched. */\n touch(name: FlatKeyOf<TValues>): void;\n /** Mark all known fields (store + validators) as touched. */\n touchAll(): void;\n /** Mark a field as untouched. No-op if the field is not currently touched. */\n untouch(name: FlatKeyOf<TValues>): void;\n /** Mark all fields as untouched. */\n untouchAll(): void;\n /**\n * Validate all registered field validators and the optional form validator.\n *\n * On a scoped form: validates only the fields within the scope and does not run the\n * form-level validator. Errors and `valid` reflect only scoped fields.\n */\n validate(signal?: AbortSignal): Promise<ValidateResult>;\n /**\n * Validate a single named field. Preserves other fields' errors. Does not run the form-level validator.\n * Returns a `ValidateResult` scoped to that field — `errors` contains at most one entry.\n */\n validate(name: FlatKeyOf<TValues>, signal?: AbortSignal): Promise<ValidateResult>;\n /**\n * Validate a specific set of fields. Preserves other fields' errors. Does not run the form-level validator.\n * Returns a `ValidateResult` scoped to the requested fields.\n */\n validate(fields: FlatKeyOf<TValues>[], signal?: AbortSignal): Promise<ValidateResult>;\n values(): TValues;\n}\n"],"mappings":";AA4CA,IAAa,IAAa,SA+Bb,IAAuB,GAsMvB,IAAkB;CAC7B,QAAQ;EAAE,aAAa;EAAM,gBAAgB;CAAK;CAClD,UAAU;EAAE,aAAa;EAAM,kBAAkB;CAAK;CACtD,UAAU,CAAC;CACX,WAAW;EAAE,aAAa;EAAM,gBAAgB;EAAM,iBAAiB;CAAK;AAC9E"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/forge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Type-safe form state — field-level validation, submission, dirty tracking, field arrays, and async default values",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"@vielzeug/arsenal": "1.1.2",
|
|
51
|
-
"@vielzeug/ripple": "1.
|
|
51
|
+
"@vielzeug/ripple": "1.3.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@types/node": "^26.1.0",
|
package/dist/core/validation.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../errors.cjs"),t=require("../_utils.cjs"),n=require("../types.cjs"),r=require("./asyncQueue.cjs");let i=require("@vielzeug/arsenal");function a(a,o){async function s(e,t){let n=a.validators.get(e);if(!n)return;if(t.aborted)throw t.reason;let r=await n(a.store.get(e),t);return typeof r==`string`?r:void 0}async function c(e){if(!a.formValidator)return{};if(e.aborted)throw e.reason;let n=await a.formValidator(o.values(),e),r={};if(n)for(let[e,i]of Object.entries(n))t.isSafeKey(e)&&typeof i==`string`&&(r[e]=i);return r}function l(e,t,n,r){if(r===`full`){a.fieldErrors.clear();for(let[e,r]of Object.entries(n))t[e]===void 0&&(t[e]=r);for(let[e,n]of Object.entries(t))a.fieldErrors.set(e,n);a.invalidateErrors(),a.requestNotify()}else{let n=new Set;for(let r of e){let e=t[r],i=a.fieldErrors.get(r);e===void 0?a.fieldErrors.delete(r)&&n.add(r):(a.fieldErrors.set(r,e),i!==e&&n.add(r))}n.size>0&&a.invalidateErrors(),a.requestNotify(n)}}async function u(e,n,r){let o=new Set(e),u=new Map;for(let e of o){a.fieldCtrls.get(e)?.abort();let t=new AbortController;a.fieldCtrls.set(e,t),u.set(e,t)}let d=new AbortController,f=t.anySignal(d.signal,r,a.disposeController.signal);a.runCtrls.add(d);let p=Symbol();for(let e of o){let t=a.validatingRuns.get(e);t||(t=new Set,a.validatingRuns.set(e,t)),t.add(p)}a.requestNotify();try{let e=await Promise.all([...o].map(async e=>[e,await s(e,n===`partial`?t.anySignal(u.get(e).signal,f):f)]));if(f.aborted)return{aborted:!0,errors:Object.fromEntries(a.fieldErrors),valid:a.fieldErrors.size===0};let r={};for(let[t,n]of e)n!==void 0&&(r[t]=n);return l(o,r,n===`full`?await c(f):{},n),{aborted:!1,errors:Object.fromEntries(a.fieldErrors),valid:a.fieldErrors.size===0}}catch(e){if((0,i.isAbortError)(e))return{aborted:!0,errors:Object.fromEntries(a.fieldErrors),valid:a.fieldErrors.size===0};throw e}finally{a.runCtrls.delete(d);for(let e of o){let t=a.validatingRuns.get(e);t&&(t.delete(p),t.size===0&&a.validatingRuns.delete(e))}a.requestNotify();for(let[e,t]of u)a.fieldCtrls.get(e)===t&&a.fieldCtrls.delete(e)}}async function d(e,t){a.ensureNotDisposed();let n=await u(e,`partial`,t);return{errors:n.errors,valid:n.valid}}async function f(e,t){if(a.ensureNotDisposed(),e===void 0||e instanceof AbortSignal){let t=await u([...a.validators.keys()],`full`,e);return{errors:t.errors,valid:t.valid}}if(Array.isArray(e))return d(e,t);await d([e],t);let n=e,r=a.fieldErrors.get(n);return{errors:r===void 0?{}:{[n]:r},valid:r===void 0}}async function p(t){let n=await m(t);if(!n.ok)throw new e.ForgeValidationError(n.errors);return n.value}async function m(t){if(a.ensureNotDisposed(),a.isSubmittingState)throw new e.ForgeSubmitError(`submit() called while a submission is already in progress`);a.batch(()=>{a.submitCount++,a.isSubmittingState=!0,o.touchAll()});try{let e=await u([...a.validators.keys()],`full`);return a.ensureNotDisposed(),e.valid?{ok:!0,value:await t(o.values())}:{errors:e.errors,ok:!1,type:`validation`}}finally{a.isSubmittingState=!1,a.disposed||a.requestNotify()}}function h(e){a.ensureNotDisposed();let o=[...a.validators.keys()],l=new AbortController,u=e?t.anySignal(l.signal,e,a.disposeController.signal):t.anySignal(l.signal,a.disposeController.signal),d=r.createAsyncQueue(()=>l.abort());return Promise.all(o.map(async e=>{if(!u.aborted)try{let t=await s(e,u);u.aborted||d.push({error:t,field:e})}catch(e){if(!(0,i.isAbortError)(e))throw e}})).then(async()=>{if(a.formValidator&&!u.aborted)try{let e=await c(u);if(!u.aborted){let t=new Set([n.FORM_ERROR,...Object.keys(e)]);for(let n of t)d.push({error:e[n],field:n})}}catch{}}).catch(e=>{(0,i.isAbortError)(e)||(l.abort(),d.fail(e))}).finally(()=>{l.abort(),d.finish()}),d.iterator}return{runValidationCore:u,submit:m,submitOrThrow:p,validate:f,validateFields:d,validateStream:h}}exports.createValidationOps=a;
|
|
2
|
-
//# sourceMappingURL=validation.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validation.cjs","names":[],"sources":["../../src/core/validation.ts"],"sourcesContent":["import { isAbortError } from '@vielzeug/arsenal';\n\nimport type { FormContext } from './context';\nimport type { ValueOps } from './values';\n\nimport { anySignal, isSafeKey } from '../_utils';\nimport { ForgeSubmitError, ForgeValidationError } from '../errors';\nimport { type FlatKeyOf, FORM_ERROR, type MaybePromise, type SubmitResult, type ValidateResult } from '../types';\nimport { createAsyncQueue } from './asyncQueue';\n\n/**\n * Validation + submit operations: field/form validator execution, error application,\n * `validate()`/`validateFields()`/`validateStream()`, and `submit()`/`submitOrThrow()`.\n * Moved verbatim from `createForm()`'s \"Validation\" and \"Submit\" sections.\n */\nexport function createValidationOps<TValues extends Record<string, unknown>>(\n ctx: FormContext<TValues>,\n deps: Pick<ValueOps<TValues>, 'touchAll' | 'values'>,\n) {\n async function runFieldValidator(name: string, signal: AbortSignal): Promise<string | undefined> {\n const validator = ctx.validators.get(name);\n\n if (!validator) return undefined;\n\n if (signal.aborted) throw signal.reason;\n\n const result = await validator(ctx.store.get(name), signal);\n\n return typeof result === 'string' ? result : undefined;\n }\n\n async function runFormValidator(signal: AbortSignal): Promise<Record<string, string>> {\n if (!ctx.formValidator) return {};\n\n if (signal.aborted) throw signal.reason;\n\n const result = await ctx.formValidator(deps.values(), signal);\n const errors: Record<string, string> = {};\n\n if (result) {\n for (const [key, message] of Object.entries(result)) {\n // Security: a custom FormValidator function is caller-authored code — its returned\n // keys are just as untrusted as a schema's `issue.path`. Reject reserved segments.\n if (isSafeKey(key) && typeof message === 'string') errors[key] = message;\n }\n }\n\n return errors;\n }\n\n function applyFieldErrors(\n fieldSet: Set<string>,\n nextErrors: Record<string, string>,\n formErrors: Record<string, string>,\n scope: 'full' | 'partial',\n ): void {\n if (scope === 'full') {\n ctx.fieldErrors.clear();\n\n for (const [key, message] of Object.entries(formErrors)) {\n if (nextErrors[key] === undefined) nextErrors[key] = message;\n }\n\n for (const [key, message] of Object.entries(nextErrors)) ctx.fieldErrors.set(key, message);\n\n ctx.invalidateErrors();\n ctx.requestNotify();\n } else {\n const changedFields = new Set<string>();\n\n for (const name of fieldSet) {\n const next = nextErrors[name];\n const previous = ctx.fieldErrors.get(name);\n\n if (next !== undefined) {\n ctx.fieldErrors.set(name, next);\n\n if (previous !== next) changedFields.add(name);\n } else if (ctx.fieldErrors.delete(name)) {\n changedFields.add(name);\n }\n }\n\n if (changedFields.size > 0) ctx.invalidateErrors();\n\n ctx.requestNotify(changedFields);\n }\n }\n\n async function runValidationCore(\n fields: string[],\n scope: 'full' | 'partial',\n signal?: AbortSignal,\n ): Promise<ValidateResult & { aborted: boolean }> {\n const fieldSet = new Set(fields);\n const fieldRunCtrls = new Map<string, AbortController>();\n\n for (const name of fieldSet) {\n ctx.fieldCtrls.get(name)?.abort();\n\n const ctrl = new AbortController();\n\n ctx.fieldCtrls.set(name, ctrl);\n fieldRunCtrls.set(name, ctrl);\n }\n\n const runCtrl = new AbortController();\n const runSignal = anySignal(runCtrl.signal, signal, ctx.disposeController.signal)!;\n\n ctx.runCtrls.add(runCtrl);\n\n // Symbol-based ref-counting: each run gets a unique token per field.\n // The field leaves validatingFields only when its Set empties — impossible to miscount.\n const runId = Symbol();\n\n for (const name of fieldSet) {\n let runs = ctx.validatingRuns.get(name);\n\n if (!runs) {\n runs = new Set<symbol>();\n ctx.validatingRuns.set(name, runs);\n }\n\n runs.add(runId);\n }\n\n ctx.requestNotify();\n\n try {\n const results = await Promise.all(\n [...fieldSet].map(async (name) => {\n const fieldSignal = scope === 'partial' ? anySignal(fieldRunCtrls.get(name)!.signal, runSignal)! : runSignal;\n\n return [name, await runFieldValidator(name, fieldSignal)] as const;\n }),\n );\n\n if (runSignal.aborted) {\n return { aborted: true, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n }\n\n const nextErrors: Record<string, string> = {};\n\n for (const [name, message] of results) {\n if (message !== undefined) nextErrors[name] = message;\n }\n\n const formErrors = scope === 'full' ? await runFormValidator(runSignal) : {};\n\n applyFieldErrors(fieldSet, nextErrors, formErrors, scope);\n\n return { aborted: false, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n } catch (error) {\n if (isAbortError(error)) {\n return { aborted: true, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n }\n\n throw error;\n } finally {\n ctx.runCtrls.delete(runCtrl);\n\n for (const name of fieldSet) {\n const runs = ctx.validatingRuns.get(name);\n\n if (runs) {\n runs.delete(runId);\n\n if (runs.size === 0) ctx.validatingRuns.delete(name);\n }\n }\n\n ctx.requestNotify();\n\n for (const [name, ctrl] of fieldRunCtrls) {\n if (ctx.fieldCtrls.get(name) === ctrl) ctx.fieldCtrls.delete(name);\n }\n }\n }\n\n async function validateFields(\n fields: FlatKeyOf<TValues>[] | string[],\n signal?: AbortSignal,\n ): Promise<ValidateResult> {\n ctx.ensureNotDisposed();\n\n const result = await runValidationCore(fields as string[], 'partial', signal);\n\n return { errors: result.errors, valid: result.valid };\n }\n\n async function validate(\n nameOrFieldsOrSignal?: FlatKeyOf<TValues> | FlatKeyOf<TValues>[] | AbortSignal,\n signal?: AbortSignal,\n ): Promise<ValidateResult> {\n ctx.ensureNotDisposed();\n\n if (nameOrFieldsOrSignal === undefined || nameOrFieldsOrSignal instanceof AbortSignal) {\n const result = await runValidationCore(\n [...ctx.validators.keys()],\n 'full',\n nameOrFieldsOrSignal as AbortSignal | undefined,\n );\n\n return { errors: result.errors, valid: result.valid };\n }\n\n if (Array.isArray(nameOrFieldsOrSignal)) {\n return validateFields(nameOrFieldsOrSignal, signal);\n }\n\n await validateFields([nameOrFieldsOrSignal], signal);\n\n const name = nameOrFieldsOrSignal as string;\n const error = ctx.fieldErrors.get(name);\n\n return { errors: error !== undefined ? { [name]: error } : {}, valid: error === undefined };\n }\n\n /* ======== Submit ======== */\n\n async function submitOrThrow<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<TResult> {\n const result = await submit(handler);\n\n if (!result.ok) throw new ForgeValidationError(result.errors as Record<string, string>);\n\n return result.value;\n }\n\n async function submit<TResult = void>(\n handler: (values: TValues) => MaybePromise<TResult>,\n ): Promise<SubmitResult<TResult>> {\n ctx.ensureNotDisposed();\n\n if (ctx.isSubmittingState) throw new ForgeSubmitError('submit() called while a submission is already in progress');\n\n ctx.batch(() => {\n ctx.submitCount++;\n ctx.isSubmittingState = true;\n deps.touchAll();\n });\n\n try {\n const validation = await runValidationCore([...ctx.validators.keys()], 'full');\n\n ctx.ensureNotDisposed();\n\n if (!validation.valid) {\n return { errors: validation.errors, ok: false, type: 'validation' };\n }\n\n return { ok: true, value: await handler(deps.values()) };\n } finally {\n ctx.isSubmittingState = false;\n\n if (!ctx.disposed) ctx.requestNotify();\n }\n }\n\n /* ======== validateStream ======== */\n\n function validateStream(signal?: AbortSignal): AsyncIterableIterator<{ error: string | undefined; field: string }> {\n ctx.ensureNotDisposed();\n\n const fields = [...ctx.validators.keys()];\n const ctrl = new AbortController();\n const combined = signal\n ? anySignal(ctrl.signal, signal, ctx.disposeController.signal)!\n : anySignal(ctrl.signal, ctx.disposeController.signal)!;\n\n type Item = { error: string | undefined; field: string };\n\n const queue = createAsyncQueue<Item>(() => ctrl.abort());\n\n // Run validators read-only — does NOT write to fieldErrors or fire requestNotify.\n // Each result is yielded as it settles; the form-level validator is yielded last.\n Promise.all(\n fields.map(async (f) => {\n if (combined.aborted) return;\n\n try {\n const error = await runFieldValidator(f, combined);\n\n if (!combined.aborted) queue.push({ error, field: f });\n } catch (err) {\n if (!isAbortError(err)) throw err;\n\n // aborted or disposed — skip this field\n }\n }),\n )\n .then(async () => {\n // Yield the form-level validator result last (F4: streams _form key too)\n if (ctx.formValidator && !combined.aborted) {\n try {\n const formErrors = await runFormValidator(combined);\n\n if (!combined.aborted) {\n const allKeys = new Set([FORM_ERROR, ...Object.keys(formErrors)]);\n\n for (const key of allKeys) {\n queue.push({ error: formErrors[key], field: key });\n }\n }\n } catch {\n // aborted\n }\n }\n })\n .catch((err) => {\n if (!isAbortError(err)) {\n ctrl.abort();\n queue.fail(err);\n }\n })\n .finally(() => {\n ctrl.abort();\n queue.finish();\n });\n\n return queue.iterator;\n }\n\n return { runValidationCore, submit, submitOrThrow, validate, validateFields, validateStream };\n}\n\nexport type ValidationOps<TValues extends Record<string, unknown>> = Return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,CAAc,CAAG,EAAG,MAAM,CAGhC,CACF,CAAC,CACH,CAAC,CACE,KAAK,SAAY,CAEhB,GAAI,EAAI,eAAiB,CAAC,EAAS,QACjC,GAAI,CACF,IAAM,EAAa,MAAM,EAAiB,CAAQ,EAElD,GAAI,CAAC,EAAS,QAAS,CACrB,IAAM,EAAU,IAAI,IAAI,CAAC,EAAA,WAAY,GAAG,OAAO,KAAK,CAAU,CAAC,CAAC,EAEhE,IAAK,IAAM,KAAO,EAChB,EAAM,KAAK,CAAE,MAAO,EAAW,GAAM,MAAO,CAAI,CAAC,CAErD,CACF,MAAQ,CAER,CAEJ,CAAC,CAAC,CACD,MAAO,GAAQ,EACV,EAAA,EAAA,aAAA,CAAc,CAAG,IACnB,EAAK,MAAM,EACX,EAAM,KAAK,CAAG,EAElB,CAAC,CAAC,CACD,YAAc,CACb,EAAK,MAAM,EACX,EAAM,OAAO,CACf,CAAC,EAEI,EAAM,QACf,CAEA,MAAO,CAAE,oBAAmB,SAAQ,gBAAe,WAAU,iBAAgB,gBAAe,CAC9F"}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import type { FormContext } from './context';
|
|
2
|
-
import type { ValueOps } from './values';
|
|
3
|
-
import { type FlatKeyOf, type MaybePromise, type SubmitResult, type ValidateResult } from '../types';
|
|
4
|
-
/**
|
|
5
|
-
* Validation + submit operations: field/form validator execution, error application,
|
|
6
|
-
* `validate()`/`validateFields()`/`validateStream()`, and `submit()`/`submitOrThrow()`.
|
|
7
|
-
* Moved verbatim from `createForm()`'s "Validation" and "Submit" sections.
|
|
8
|
-
*/
|
|
9
|
-
export declare function createValidationOps<TValues extends Record<string, unknown>>(ctx: FormContext<TValues>, deps: Pick<ValueOps<TValues>, 'touchAll' | 'values'>): {
|
|
10
|
-
runValidationCore: (fields: string[], scope: "full" | "partial", signal?: AbortSignal) => Promise<ValidateResult & {
|
|
11
|
-
aborted: boolean;
|
|
12
|
-
}>;
|
|
13
|
-
submit: <TResult = void>(handler: (values: TValues) => MaybePromise<TResult>) => Promise<SubmitResult<TResult>>;
|
|
14
|
-
submitOrThrow: <TResult = void>(handler: (values: TValues) => MaybePromise<TResult>) => Promise<TResult>;
|
|
15
|
-
validate: (nameOrFieldsOrSignal?: FlatKeyOf<TValues> | FlatKeyOf<TValues>[] | AbortSignal, signal?: AbortSignal) => Promise<ValidateResult>;
|
|
16
|
-
validateFields: (fields: FlatKeyOf<TValues>[] | string[], signal?: AbortSignal) => Promise<ValidateResult>;
|
|
17
|
-
validateStream: (signal?: AbortSignal) => AsyncIterableIterator<{
|
|
18
|
-
error: string | undefined;
|
|
19
|
-
field: string;
|
|
20
|
-
}>;
|
|
21
|
-
};
|
|
22
|
-
export type ValidationOps<TValues extends Record<string, unknown>> = ReturnType<typeof createValidationOps<TValues>>;
|
|
23
|
-
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/core/validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAIzC,OAAO,EAAE,KAAK,SAAS,EAAc,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAGjH;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACzE,GAAG,EAAE,WAAW,CAAC,OAAO,CAAC,EACzB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,UAAU,GAAG,QAAQ,CAAC;gCAyE1C,MAAM,EAAE,SACT,MAAM,GAAG,SAAS,WAChB,WAAW,KACnB,OAAO,CAAC,cAAc,GAAG;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;aAuI3B,OAAO,kBAClB,CAAC,MAAM,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,KAClD,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;oBAVJ,OAAO,kBAAkB,CAAC,MAAM,EAAE,OAAO,KAAK,YAAY,CAAC,OAAO,CAAC,KAAG,OAAO,CAAC,OAAO,CAAC;sCA7B1F,SAAS,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,WAAW,WACrE,WAAW,KACnB,OAAO,CAAC,cAAc,CAAC;6BAbhB,SAAS,CAAC,OAAO,CAAC,EAAE,GAAG,MAAM,EAAE,WAC9B,WAAW,KACnB,OAAO,CAAC,cAAc,CAAC;8BA8EO,WAAW,KAAG,qBAAqB,CAAC;QAAE,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;EA+DnH;AAED,MAAM,MAAM,aAAa,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,UAAU,CAAC,OAAO,mBAAmB,CAAC,OAAO,CAAC,CAAC,CAAC"}
|
package/dist/core/validation.js
DELETED
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
import { ForgeSubmitError as e, ForgeValidationError as t } from "../errors.js";
|
|
2
|
-
import { anySignal as n, isSafeKey as r } from "../_utils.js";
|
|
3
|
-
import { FORM_ERROR as i } from "../types.js";
|
|
4
|
-
import { createAsyncQueue as a } from "./asyncQueue.js";
|
|
5
|
-
import { isAbortError as o } from "@vielzeug/arsenal";
|
|
6
|
-
//#region src/core/validation.ts
|
|
7
|
-
function s(s, c) {
|
|
8
|
-
async function l(e, t) {
|
|
9
|
-
let n = s.validators.get(e);
|
|
10
|
-
if (!n) return;
|
|
11
|
-
if (t.aborted) throw t.reason;
|
|
12
|
-
let r = await n(s.store.get(e), t);
|
|
13
|
-
return typeof r == "string" ? r : void 0;
|
|
14
|
-
}
|
|
15
|
-
async function u(e) {
|
|
16
|
-
if (!s.formValidator) return {};
|
|
17
|
-
if (e.aborted) throw e.reason;
|
|
18
|
-
let t = await s.formValidator(c.values(), e), n = {};
|
|
19
|
-
if (t) for (let [e, i] of Object.entries(t)) r(e) && typeof i == "string" && (n[e] = i);
|
|
20
|
-
return n;
|
|
21
|
-
}
|
|
22
|
-
function d(e, t, n, r) {
|
|
23
|
-
if (r === "full") {
|
|
24
|
-
s.fieldErrors.clear();
|
|
25
|
-
for (let [e, r] of Object.entries(n)) t[e] === void 0 && (t[e] = r);
|
|
26
|
-
for (let [e, n] of Object.entries(t)) s.fieldErrors.set(e, n);
|
|
27
|
-
s.invalidateErrors(), s.requestNotify();
|
|
28
|
-
} else {
|
|
29
|
-
let n = /* @__PURE__ */ new Set();
|
|
30
|
-
for (let r of e) {
|
|
31
|
-
let e = t[r], i = s.fieldErrors.get(r);
|
|
32
|
-
e === void 0 ? s.fieldErrors.delete(r) && n.add(r) : (s.fieldErrors.set(r, e), i !== e && n.add(r));
|
|
33
|
-
}
|
|
34
|
-
n.size > 0 && s.invalidateErrors(), s.requestNotify(n);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
async function f(e, t, r) {
|
|
38
|
-
let i = new Set(e), a = /* @__PURE__ */ new Map();
|
|
39
|
-
for (let e of i) {
|
|
40
|
-
s.fieldCtrls.get(e)?.abort();
|
|
41
|
-
let t = new AbortController();
|
|
42
|
-
s.fieldCtrls.set(e, t), a.set(e, t);
|
|
43
|
-
}
|
|
44
|
-
let c = new AbortController(), f = n(c.signal, r, s.disposeController.signal);
|
|
45
|
-
s.runCtrls.add(c);
|
|
46
|
-
let p = Symbol();
|
|
47
|
-
for (let e of i) {
|
|
48
|
-
let t = s.validatingRuns.get(e);
|
|
49
|
-
t || (t = /* @__PURE__ */ new Set(), s.validatingRuns.set(e, t)), t.add(p);
|
|
50
|
-
}
|
|
51
|
-
s.requestNotify();
|
|
52
|
-
try {
|
|
53
|
-
let e = await Promise.all([...i].map(async (e) => [e, await l(e, t === "partial" ? n(a.get(e).signal, f) : f)]));
|
|
54
|
-
if (f.aborted) return {
|
|
55
|
-
aborted: !0,
|
|
56
|
-
errors: Object.fromEntries(s.fieldErrors),
|
|
57
|
-
valid: s.fieldErrors.size === 0
|
|
58
|
-
};
|
|
59
|
-
let r = {};
|
|
60
|
-
for (let [t, n] of e) n !== void 0 && (r[t] = n);
|
|
61
|
-
return d(i, r, t === "full" ? await u(f) : {}, t), {
|
|
62
|
-
aborted: !1,
|
|
63
|
-
errors: Object.fromEntries(s.fieldErrors),
|
|
64
|
-
valid: s.fieldErrors.size === 0
|
|
65
|
-
};
|
|
66
|
-
} catch (e) {
|
|
67
|
-
if (o(e)) return {
|
|
68
|
-
aborted: !0,
|
|
69
|
-
errors: Object.fromEntries(s.fieldErrors),
|
|
70
|
-
valid: s.fieldErrors.size === 0
|
|
71
|
-
};
|
|
72
|
-
throw e;
|
|
73
|
-
} finally {
|
|
74
|
-
s.runCtrls.delete(c);
|
|
75
|
-
for (let e of i) {
|
|
76
|
-
let t = s.validatingRuns.get(e);
|
|
77
|
-
t && (t.delete(p), t.size === 0 && s.validatingRuns.delete(e));
|
|
78
|
-
}
|
|
79
|
-
s.requestNotify();
|
|
80
|
-
for (let [e, t] of a) s.fieldCtrls.get(e) === t && s.fieldCtrls.delete(e);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
async function p(e, t) {
|
|
84
|
-
s.ensureNotDisposed();
|
|
85
|
-
let n = await f(e, "partial", t);
|
|
86
|
-
return {
|
|
87
|
-
errors: n.errors,
|
|
88
|
-
valid: n.valid
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
async function m(e, t) {
|
|
92
|
-
if (s.ensureNotDisposed(), e === void 0 || e instanceof AbortSignal) {
|
|
93
|
-
let t = await f([...s.validators.keys()], "full", e);
|
|
94
|
-
return {
|
|
95
|
-
errors: t.errors,
|
|
96
|
-
valid: t.valid
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
if (Array.isArray(e)) return p(e, t);
|
|
100
|
-
await p([e], t);
|
|
101
|
-
let n = e, r = s.fieldErrors.get(n);
|
|
102
|
-
return {
|
|
103
|
-
errors: r === void 0 ? {} : { [n]: r },
|
|
104
|
-
valid: r === void 0
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
async function h(e) {
|
|
108
|
-
let n = await g(e);
|
|
109
|
-
if (!n.ok) throw new t(n.errors);
|
|
110
|
-
return n.value;
|
|
111
|
-
}
|
|
112
|
-
async function g(t) {
|
|
113
|
-
if (s.ensureNotDisposed(), s.isSubmittingState) throw new e("submit() called while a submission is already in progress");
|
|
114
|
-
s.batch(() => {
|
|
115
|
-
s.submitCount++, s.isSubmittingState = !0, c.touchAll();
|
|
116
|
-
});
|
|
117
|
-
try {
|
|
118
|
-
let e = await f([...s.validators.keys()], "full");
|
|
119
|
-
return s.ensureNotDisposed(), e.valid ? {
|
|
120
|
-
ok: !0,
|
|
121
|
-
value: await t(c.values())
|
|
122
|
-
} : {
|
|
123
|
-
errors: e.errors,
|
|
124
|
-
ok: !1,
|
|
125
|
-
type: "validation"
|
|
126
|
-
};
|
|
127
|
-
} finally {
|
|
128
|
-
s.isSubmittingState = !1, s.disposed || s.requestNotify();
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
function _(e) {
|
|
132
|
-
s.ensureNotDisposed();
|
|
133
|
-
let t = [...s.validators.keys()], r = new AbortController(), c = e ? n(r.signal, e, s.disposeController.signal) : n(r.signal, s.disposeController.signal), d = a(() => r.abort());
|
|
134
|
-
return Promise.all(t.map(async (e) => {
|
|
135
|
-
if (!c.aborted) try {
|
|
136
|
-
let t = await l(e, c);
|
|
137
|
-
c.aborted || d.push({
|
|
138
|
-
error: t,
|
|
139
|
-
field: e
|
|
140
|
-
});
|
|
141
|
-
} catch (e) {
|
|
142
|
-
if (!o(e)) throw e;
|
|
143
|
-
}
|
|
144
|
-
})).then(async () => {
|
|
145
|
-
if (s.formValidator && !c.aborted) try {
|
|
146
|
-
let e = await u(c);
|
|
147
|
-
if (!c.aborted) {
|
|
148
|
-
let t = /* @__PURE__ */ new Set([i, ...Object.keys(e)]);
|
|
149
|
-
for (let n of t) d.push({
|
|
150
|
-
error: e[n],
|
|
151
|
-
field: n
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
} catch {}
|
|
155
|
-
}).catch((e) => {
|
|
156
|
-
o(e) || (r.abort(), d.fail(e));
|
|
157
|
-
}).finally(() => {
|
|
158
|
-
r.abort(), d.finish();
|
|
159
|
-
}), d.iterator;
|
|
160
|
-
}
|
|
161
|
-
return {
|
|
162
|
-
runValidationCore: f,
|
|
163
|
-
submit: g,
|
|
164
|
-
submitOrThrow: h,
|
|
165
|
-
validate: m,
|
|
166
|
-
validateFields: p,
|
|
167
|
-
validateStream: _
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
//#endregion
|
|
171
|
-
export { s as createValidationOps };
|
|
172
|
-
|
|
173
|
-
//# sourceMappingURL=validation.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../src/core/validation.ts"],"sourcesContent":["import { isAbortError } from '@vielzeug/arsenal';\n\nimport type { FormContext } from './context';\nimport type { ValueOps } from './values';\n\nimport { anySignal, isSafeKey } from '../_utils';\nimport { ForgeSubmitError, ForgeValidationError } from '../errors';\nimport { type FlatKeyOf, FORM_ERROR, type MaybePromise, type SubmitResult, type ValidateResult } from '../types';\nimport { createAsyncQueue } from './asyncQueue';\n\n/**\n * Validation + submit operations: field/form validator execution, error application,\n * `validate()`/`validateFields()`/`validateStream()`, and `submit()`/`submitOrThrow()`.\n * Moved verbatim from `createForm()`'s \"Validation\" and \"Submit\" sections.\n */\nexport function createValidationOps<TValues extends Record<string, unknown>>(\n ctx: FormContext<TValues>,\n deps: Pick<ValueOps<TValues>, 'touchAll' | 'values'>,\n) {\n async function runFieldValidator(name: string, signal: AbortSignal): Promise<string | undefined> {\n const validator = ctx.validators.get(name);\n\n if (!validator) return undefined;\n\n if (signal.aborted) throw signal.reason;\n\n const result = await validator(ctx.store.get(name), signal);\n\n return typeof result === 'string' ? result : undefined;\n }\n\n async function runFormValidator(signal: AbortSignal): Promise<Record<string, string>> {\n if (!ctx.formValidator) return {};\n\n if (signal.aborted) throw signal.reason;\n\n const result = await ctx.formValidator(deps.values(), signal);\n const errors: Record<string, string> = {};\n\n if (result) {\n for (const [key, message] of Object.entries(result)) {\n // Security: a custom FormValidator function is caller-authored code — its returned\n // keys are just as untrusted as a schema's `issue.path`. Reject reserved segments.\n if (isSafeKey(key) && typeof message === 'string') errors[key] = message;\n }\n }\n\n return errors;\n }\n\n function applyFieldErrors(\n fieldSet: Set<string>,\n nextErrors: Record<string, string>,\n formErrors: Record<string, string>,\n scope: 'full' | 'partial',\n ): void {\n if (scope === 'full') {\n ctx.fieldErrors.clear();\n\n for (const [key, message] of Object.entries(formErrors)) {\n if (nextErrors[key] === undefined) nextErrors[key] = message;\n }\n\n for (const [key, message] of Object.entries(nextErrors)) ctx.fieldErrors.set(key, message);\n\n ctx.invalidateErrors();\n ctx.requestNotify();\n } else {\n const changedFields = new Set<string>();\n\n for (const name of fieldSet) {\n const next = nextErrors[name];\n const previous = ctx.fieldErrors.get(name);\n\n if (next !== undefined) {\n ctx.fieldErrors.set(name, next);\n\n if (previous !== next) changedFields.add(name);\n } else if (ctx.fieldErrors.delete(name)) {\n changedFields.add(name);\n }\n }\n\n if (changedFields.size > 0) ctx.invalidateErrors();\n\n ctx.requestNotify(changedFields);\n }\n }\n\n async function runValidationCore(\n fields: string[],\n scope: 'full' | 'partial',\n signal?: AbortSignal,\n ): Promise<ValidateResult & { aborted: boolean }> {\n const fieldSet = new Set(fields);\n const fieldRunCtrls = new Map<string, AbortController>();\n\n for (const name of fieldSet) {\n ctx.fieldCtrls.get(name)?.abort();\n\n const ctrl = new AbortController();\n\n ctx.fieldCtrls.set(name, ctrl);\n fieldRunCtrls.set(name, ctrl);\n }\n\n const runCtrl = new AbortController();\n const runSignal = anySignal(runCtrl.signal, signal, ctx.disposeController.signal)!;\n\n ctx.runCtrls.add(runCtrl);\n\n // Symbol-based ref-counting: each run gets a unique token per field.\n // The field leaves validatingFields only when its Set empties — impossible to miscount.\n const runId = Symbol();\n\n for (const name of fieldSet) {\n let runs = ctx.validatingRuns.get(name);\n\n if (!runs) {\n runs = new Set<symbol>();\n ctx.validatingRuns.set(name, runs);\n }\n\n runs.add(runId);\n }\n\n ctx.requestNotify();\n\n try {\n const results = await Promise.all(\n [...fieldSet].map(async (name) => {\n const fieldSignal = scope === 'partial' ? anySignal(fieldRunCtrls.get(name)!.signal, runSignal)! : runSignal;\n\n return [name, await runFieldValidator(name, fieldSignal)] as const;\n }),\n );\n\n if (runSignal.aborted) {\n return { aborted: true, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n }\n\n const nextErrors: Record<string, string> = {};\n\n for (const [name, message] of results) {\n if (message !== undefined) nextErrors[name] = message;\n }\n\n const formErrors = scope === 'full' ? await runFormValidator(runSignal) : {};\n\n applyFieldErrors(fieldSet, nextErrors, formErrors, scope);\n\n return { aborted: false, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n } catch (error) {\n if (isAbortError(error)) {\n return { aborted: true, errors: Object.fromEntries(ctx.fieldErrors), valid: ctx.fieldErrors.size === 0 };\n }\n\n throw error;\n } finally {\n ctx.runCtrls.delete(runCtrl);\n\n for (const name of fieldSet) {\n const runs = ctx.validatingRuns.get(name);\n\n if (runs) {\n runs.delete(runId);\n\n if (runs.size === 0) ctx.validatingRuns.delete(name);\n }\n }\n\n ctx.requestNotify();\n\n for (const [name, ctrl] of fieldRunCtrls) {\n if (ctx.fieldCtrls.get(name) === ctrl) ctx.fieldCtrls.delete(name);\n }\n }\n }\n\n async function validateFields(\n fields: FlatKeyOf<TValues>[] | string[],\n signal?: AbortSignal,\n ): Promise<ValidateResult> {\n ctx.ensureNotDisposed();\n\n const result = await runValidationCore(fields as string[], 'partial', signal);\n\n return { errors: result.errors, valid: result.valid };\n }\n\n async function validate(\n nameOrFieldsOrSignal?: FlatKeyOf<TValues> | FlatKeyOf<TValues>[] | AbortSignal,\n signal?: AbortSignal,\n ): Promise<ValidateResult> {\n ctx.ensureNotDisposed();\n\n if (nameOrFieldsOrSignal === undefined || nameOrFieldsOrSignal instanceof AbortSignal) {\n const result = await runValidationCore(\n [...ctx.validators.keys()],\n 'full',\n nameOrFieldsOrSignal as AbortSignal | undefined,\n );\n\n return { errors: result.errors, valid: result.valid };\n }\n\n if (Array.isArray(nameOrFieldsOrSignal)) {\n return validateFields(nameOrFieldsOrSignal, signal);\n }\n\n await validateFields([nameOrFieldsOrSignal], signal);\n\n const name = nameOrFieldsOrSignal as string;\n const error = ctx.fieldErrors.get(name);\n\n return { errors: error !== undefined ? { [name]: error } : {}, valid: error === undefined };\n }\n\n /* ======== Submit ======== */\n\n async function submitOrThrow<TResult = void>(handler: (values: TValues) => MaybePromise<TResult>): Promise<TResult> {\n const result = await submit(handler);\n\n if (!result.ok) throw new ForgeValidationError(result.errors as Record<string, string>);\n\n return result.value;\n }\n\n async function submit<TResult = void>(\n handler: (values: TValues) => MaybePromise<TResult>,\n ): Promise<SubmitResult<TResult>> {\n ctx.ensureNotDisposed();\n\n if (ctx.isSubmittingState) throw new ForgeSubmitError('submit() called while a submission is already in progress');\n\n ctx.batch(() => {\n ctx.submitCount++;\n ctx.isSubmittingState = true;\n deps.touchAll();\n });\n\n try {\n const validation = await runValidationCore([...ctx.validators.keys()], 'full');\n\n ctx.ensureNotDisposed();\n\n if (!validation.valid) {\n return { errors: validation.errors, ok: false, type: 'validation' };\n }\n\n return { ok: true, value: await handler(deps.values()) };\n } finally {\n ctx.isSubmittingState = false;\n\n if (!ctx.disposed) ctx.requestNotify();\n }\n }\n\n /* ======== validateStream ======== */\n\n function validateStream(signal?: AbortSignal): AsyncIterableIterator<{ error: string | undefined; field: string }> {\n ctx.ensureNotDisposed();\n\n const fields = [...ctx.validators.keys()];\n const ctrl = new AbortController();\n const combined = signal\n ? anySignal(ctrl.signal, signal, ctx.disposeController.signal)!\n : anySignal(ctrl.signal, ctx.disposeController.signal)!;\n\n type Item = { error: string | undefined; field: string };\n\n const queue = createAsyncQueue<Item>(() => ctrl.abort());\n\n // Run validators read-only — does NOT write to fieldErrors or fire requestNotify.\n // Each result is yielded as it settles; the form-level validator is yielded last.\n Promise.all(\n fields.map(async (f) => {\n if (combined.aborted) return;\n\n try {\n const error = await runFieldValidator(f, combined);\n\n if (!combined.aborted) queue.push({ error, field: f });\n } catch (err) {\n if (!isAbortError(err)) throw err;\n\n // aborted or disposed — skip this field\n }\n }),\n )\n .then(async () => {\n // Yield the form-level validator result last (F4: streams _form key too)\n if (ctx.formValidator && !combined.aborted) {\n try {\n const formErrors = await runFormValidator(combined);\n\n if (!combined.aborted) {\n const allKeys = new Set([FORM_ERROR, ...Object.keys(formErrors)]);\n\n for (const key of allKeys) {\n queue.push({ error: formErrors[key], field: key });\n }\n }\n } catch {\n // aborted\n }\n }\n })\n .catch((err) => {\n if (!isAbortError(err)) {\n ctrl.abort();\n queue.fail(err);\n }\n })\n .finally(() => {\n ctrl.abort();\n queue.finish();\n });\n\n return queue.iterator;\n }\n\n return { runValidationCore, submit, submitOrThrow, validate, validateFields, validateStream };\n}\n\nexport type ValidationOps<TValues extends Record<string, unknown>> = ReturnType<typeof createValidationOps<TValues>>;\n"],"mappings":";;;;;;AAeA,SAAgB,EACd,GACA,GACA;CACA,eAAe,EAAkB,GAAc,GAAkD;EAC/F,IAAM,IAAY,EAAI,WAAW,IAAI,CAAI;EAEzC,IAAI,CAAC,GAAW;EAEhB,IAAI,EAAO,SAAS,MAAM,EAAO;EAEjC,IAAM,IAAS,MAAM,EAAU,EAAI,MAAM,IAAI,CAAI,GAAG,CAAM;EAE1D,OAAO,OAAO,KAAW,WAAW,IAAS,KAAA;CAC/C;CAEA,eAAe,EAAiB,GAAsD;EACpF,IAAI,CAAC,EAAI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AW;MAAM,OAAO;KAAI,CAAC;IAErD;GACF,QAAQ,CAER;EAEJ,CAAC,CAAC,CACD,OAAO,MAAQ;GACd,AAAK,EAAa,CAAG,MACnB,EAAK,MAAM,GACX,EAAM,KAAK,CAAG;EAElB,CAAC,CAAC,CACD,cAAc;GAEb,AADA,EAAK,MAAM,GACX,EAAM,OAAO;EACf,CAAC,GAEI,EAAM;CACf;CAEA,OAAO;EAAE;EAAmB;EAAQ;EAAe;EAAU;EAAgB;CAAe;AAC9F"}
|
package/dist/core/values.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../_dev.cjs"),t=require("../_utils.cjs"),n=require("./array.cjs");let r=require("@vielzeug/arsenal");function i(i){function a(e){let n=e;return t.assertSafeKey(n),i.store.get(n)}function o(){return i.cachedValues??=(0,r.unflattenPaths)(Object.fromEntries(i.store))}function s(e,t){i.baseline.get(e)===t?i.dirty.delete(e):i.dirty.add(e)}function c(e,n,r={}){i.ensureNotDisposed();let a=e;t.assertSafeKey(a),i.store.set(a,n),s(a,n),r.touched&&i.touched.add(a),i.requestNotify(a)}function l(e){let n=e;return t.assertSafeKey(n),i.getFieldSnapshot(n)}function u(e,n){i.ensureNotDisposed();let r=e;t.assertSafeKey(r),i.fieldErrors.set(r,n),i.invalidateErrors(),i.requestNotify(r)}function d(e){i.ensureNotDisposed();let n=e;t.assertSafeKey(n),i.fieldErrors.delete(n)&&(i.invalidateErrors(),i.requestNotify(n))}function f(e={}){i.ensureNotDisposed(),i.fieldErrors.clear();for(let[n,r]of Object.entries(e))t.assertSafeKey(n),typeof r==`string`&&i.fieldErrors.set(n,r);i.invalidateErrors(),i.requestNotify()}function p(n,r){/\.\d+(\.|$)/.test(n)&&!i.store.has(n)&&e.warn(`${r}('${t.sanitizeForLog(n,80)}'): path looks like an array item key. Array items are stored as whole arrays — register on the parent key instead.`)}function m(e,n){i.ensureNotDisposed();let r=e;t.assertSafeKey(r),p(r,`setValidator`),i.fieldCtrls.get(r)?.abort(),i.fieldCtrls.delete(r),n?i.validators.set(r,n):(i.validators.delete(r),i.fieldErrors.delete(r)&&(i.invalidateErrors(),i.requestNotify(r)))}function h(e,n={}){i.ensureNotDisposed();let r=e;return t.assertSafeKey(r),p(r,`fields.register`),n.validator!==void 0&&m(e,n.validator),n.defaultValue!==void 0&&!i.store.has(r)&&(i.store.set(r,n.defaultValue),i.baseline.set(r,n.defaultValue),i.requestNotify(r)),()=>{i.disposed||S(e)}}function g(){let e=new Set;for(let t of i.store.keys())e.add(t);for(let t of i.validators.keys())e.add(t);return Object.freeze([...e])}function _(e){i.ensureNotDisposed();let n=e;t.assertSafeKey(n),i.touched.add(n),i.requestNotify(n)}function v(e){i.ensureNotDisposed();let n=e;t.assertSafeKey(n),i.touched.delete(n)&&i.requestNotify(n)}function y(){i.ensureNotDisposed();for(let e of i.store.keys())i.touched.add(e);for(let e of i.validators.keys())i.touched.add(e);i.requestNotify()}function b(){i.ensureNotDisposed(),i.touched.clear(),i.requestNotify()}function x(e){i.ensureNotDisposed();let n=e;t.assertSafeKey(n),i.fieldCtrls.get(n)?.abort(),i.fieldCtrls.delete(n),i.store.set(n,i.baseline.get(n)),i.dirty.delete(n),i.touched.delete(n),i.fieldErrors.delete(n)&&i.invalidateErrors(),i.requestNotify(n)}function S(e){i.ensureNotDisposed();let n=e;t.assertSafeKey(n),i.store.delete(n),i.baseline.delete(n),i.dirty.delete(n),i.touched.delete(n),i.validators.delete(n),i.arrayCache.delete(n),i.fieldCtrls.get(n)?.abort(),i.fieldCtrls.delete(n),i.fieldErrors.delete(n)&&i.invalidateErrors(),i.requestNotify(n)}function C(){i.ensureNotDisposed();for(let e of i.runCtrls)e.abort();for(let e of i.fieldCtrls.values())e.abort();i.runCtrls.clear(),i.fieldCtrls.clear(),i.validatingRuns.clear(),i.store.clear(),i.fieldErrors.clear(),i.touched.clear(),i.dirty.clear(),i.submitCount=0,i.invalidateErrors();for(let[e,t]of i.baseline)i.store.set(e,t);i.requestNotify()}function w(e){i.ensureNotDisposed();for(let e of i.runCtrls)e.abort();for(let e of i.fieldCtrls.values())e.abort();i.runCtrls.clear(),i.fieldCtrls.clear(),i.validatingRuns.clear();let t=(0,r.flattenPaths)(e);i.store.clear(),i.baseline.clear(),i.fieldErrors.clear(),i.touched.clear(),i.dirty.clear(),i.submitCount=0,i.invalidateErrors();for(let[e,n]of Object.entries(t))i.store.set(e,n),i.baseline.set(e,n);i.requestNotify()}function T(e){i.ensureNotDisposed();let t=(0,r.flattenPaths)(e);for(let[e,n]of Object.entries(t))i.baseline.set(e,n),i.store.set(e,n),i.dirty.delete(e);i.requestNotify(Object.keys(t))}function E(e){i.ensureNotDisposed();let r=e;t.assertSafeKey(r);let a=i.arrayCache.get(r);if(a)return a;let o=n.createArrayField(e,i.store,c);return i.arrayCache.set(r,o),o}return{array:E,clearError:d,field:l,get:a,listFields:g,patch:T,registerField:h,removeField:S,replace:w,reset:C,resetErrors:f,resetField:x,set:c,setError:u,setValidator:m,touch:_,touchAll:y,untouch:v,untouchAll:b,values:o}}exports.createValueOps=i;
|
|
2
|
-
//# sourceMappingURL=values.cjs.map
|
package/dist/core/values.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"values.cjs","names":[],"sources":["../../src/core/values.ts"],"sourcesContent":["import type { FormContext } from './context';\n\nimport { warn } from '../_dev';\nimport { assertSafeKey, flattenValues, sanitizeForLog, unflattenValues } from '../_utils';\nimport {\n type ArrayField,\n type ErrorKeyOf,\n type FieldState,\n type FieldValidator,\n type FlatKeyOf,\n type RegisterFieldOptions,\n type SetOptions,\n type TypeAtPath,\n type Unsubscribe,\n} from '../types';\nimport { createArrayField } from './array';\n\n/**\n * Value/field-mutation operations: get/set/values, dirty tracking, errors, dynamic field\n * registration, touch, and reset/replace/patch/array. Moved verbatim from `createForm()`'s\n * \"Value access\" through \"Lifecycle: field operations\" sections.\n */\nexport function createValueOps<TValues extends Record<string, unknown>>(ctx: FormContext<TValues>) {\n function get<K extends FlatKeyOf<TValues>>(name: K): TypeAtPath<TValues, K> {\n const key = name as string;\n\n assertSafeKey(key);\n\n return ctx.store.get(key) as TypeAtPath<TValues, K>;\n }\n\n function values(): TValues {\n return (ctx.cachedValues ??= unflattenValues(Object.fromEntries(ctx.store)) as TValues);\n }\n\n /* ======== Dirty tracking ======== */\n\n function trackDirty(name: string, value: unknown): void {\n if (ctx.baseline.get(name) === value) ctx.dirty.delete(name);\n else ctx.dirty.add(name);\n }\n\n /* ======== Field mutation ======== */\n\n function set<K extends FlatKeyOf<TValues>>(name: K, value: TypeAtPath<TValues, K>, options: SetOptions = {}): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n ctx.store.set(key, value);\n trackDirty(key, value);\n\n if (options.touched) ctx.touched.add(key);\n\n ctx.requestNotify(key);\n }\n\n function field<K extends FlatKeyOf<TValues>>(name: K): FieldState<TypeAtPath<TValues, K>> {\n const key = name as string;\n\n assertSafeKey(key);\n\n return ctx.getFieldSnapshot(key) as FieldState<TypeAtPath<TValues, K>>;\n }\n\n function setError(name: ErrorKeyOf<TValues>, message: string): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n ctx.fieldErrors.set(key, message);\n ctx.invalidateErrors();\n ctx.requestNotify(key);\n }\n\n function clearError(name: ErrorKeyOf<TValues>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n\n if (ctx.fieldErrors.delete(key)) {\n ctx.invalidateErrors();\n ctx.requestNotify(key);\n }\n }\n\n function resetErrors(nextErrors: Partial<Record<ErrorKeyOf<TValues>, string | undefined>> = {}): void {\n ctx.ensureNotDisposed();\n\n ctx.fieldErrors.clear();\n\n for (const [key, message] of Object.entries(nextErrors)) {\n assertSafeKey(key);\n\n if (typeof message === 'string') ctx.fieldErrors.set(key, message);\n }\n\n ctx.invalidateErrors();\n ctx.requestNotify();\n }\n\n /**\n * Warns when `key` looks like a dot-notation array item path (e.g. \"tags.0\") that isn't\n * already a real store entry — array items are stored as whole arrays, not individual keys.\n * Shared by `setValidator()` and `registerField()`.\n */\n function warnIfArrayItemKey(key: string, apiLabel: string): void {\n if (/\\.\\d+(\\.|$)/.test(key) && !ctx.store.has(key)) {\n const displayKey = sanitizeForLog(key, 80);\n\n warn(\n `${apiLabel}('${displayKey}'): path looks like an array item key. ` +\n `Array items are stored as whole arrays — register on the parent key instead.`,\n );\n }\n }\n\n function setValidator(name: FlatKeyOf<TValues>, validator?: FieldValidator<unknown>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n warnIfArrayItemKey(key, 'setValidator');\n\n ctx.fieldCtrls.get(key)?.abort();\n ctx.fieldCtrls.delete(key);\n\n if (validator) {\n ctx.validators.set(key, validator);\n } else {\n ctx.validators.delete(key);\n\n if (ctx.fieldErrors.delete(key)) {\n ctx.invalidateErrors();\n ctx.requestNotify(key);\n }\n }\n }\n\n /* ======== Dynamic field registration ======== */\n\n function registerField<K extends FlatKeyOf<TValues>>(\n name: K,\n options: RegisterFieldOptions<TypeAtPath<TValues, K>> = {},\n ): Unsubscribe {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n warnIfArrayItemKey(key, 'fields.register');\n\n if (options.validator !== undefined) setValidator(name, options.validator as FieldValidator<unknown>);\n\n if (options.defaultValue !== undefined && !ctx.store.has(key)) {\n ctx.store.set(key, options.defaultValue);\n ctx.baseline.set(key, options.defaultValue);\n ctx.requestNotify(key);\n }\n\n return () => {\n if (!ctx.disposed) removeField(name);\n };\n }\n\n /* ======== Field enumeration ======== */\n\n function listFields(): readonly string[] {\n const known = new Set<string>();\n\n for (const name of ctx.store.keys()) known.add(name);\n for (const name of ctx.validators.keys()) known.add(name);\n\n return Object.freeze([...known]);\n }\n\n /* ======== Touch ======== */\n\n function touch(name: FlatKeyOf<TValues>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n ctx.touched.add(key);\n ctx.requestNotify(key);\n }\n\n function untouch(name: FlatKeyOf<TValues>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n\n if (ctx.touched.delete(key)) ctx.requestNotify(key);\n }\n\n function touchAll(): void {\n ctx.ensureNotDisposed();\n\n for (const name of ctx.store.keys()) ctx.touched.add(name);\n for (const name of ctx.validators.keys()) ctx.touched.add(name);\n\n ctx.requestNotify();\n }\n\n function untouchAll(): void {\n ctx.ensureNotDisposed();\n ctx.touched.clear();\n ctx.requestNotify();\n }\n\n /* ======== Lifecycle: field operations ======== */\n\n function resetField(name: FlatKeyOf<TValues>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n ctx.fieldCtrls.get(key)?.abort();\n ctx.fieldCtrls.delete(key);\n ctx.store.set(key, ctx.baseline.get(key));\n ctx.dirty.delete(key);\n ctx.touched.delete(key);\n\n if (ctx.fieldErrors.delete(key)) ctx.invalidateErrors();\n\n ctx.requestNotify(key);\n }\n\n function removeField(name: FlatKeyOf<TValues>): void {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n ctx.store.delete(key);\n ctx.baseline.delete(key);\n ctx.dirty.delete(key);\n ctx.touched.delete(key);\n ctx.validators.delete(key);\n ctx.arrayCache.delete(key);\n ctx.fieldCtrls.get(key)?.abort();\n ctx.fieldCtrls.delete(key);\n\n if (ctx.fieldErrors.delete(key)) ctx.invalidateErrors();\n\n ctx.requestNotify(key);\n }\n\n function reset(): void {\n ctx.ensureNotDisposed();\n\n for (const ctrl of ctx.runCtrls) ctrl.abort();\n for (const ctrl of ctx.fieldCtrls.values()) ctrl.abort();\n\n ctx.runCtrls.clear();\n ctx.fieldCtrls.clear();\n ctx.validatingRuns.clear();\n ctx.store.clear();\n ctx.fieldErrors.clear();\n ctx.touched.clear();\n ctx.dirty.clear();\n ctx.submitCount = 0;\n ctx.invalidateErrors();\n\n for (const [name, value] of ctx.baseline) ctx.store.set(name, value);\n\n ctx.requestNotify();\n }\n\n function replace(newValues: TValues): void {\n ctx.ensureNotDisposed();\n\n for (const ctrl of ctx.runCtrls) ctrl.abort();\n for (const ctrl of ctx.fieldCtrls.values()) ctrl.abort();\n\n ctx.runCtrls.clear();\n ctx.fieldCtrls.clear();\n ctx.validatingRuns.clear();\n\n const flat = flattenValues(newValues as Record<string, unknown>);\n\n ctx.store.clear();\n ctx.baseline.clear();\n ctx.fieldErrors.clear();\n ctx.touched.clear();\n ctx.dirty.clear();\n ctx.submitCount = 0;\n ctx.invalidateErrors();\n\n for (const [name, value] of Object.entries(flat)) {\n ctx.store.set(name, value);\n ctx.baseline.set(name, value);\n }\n\n ctx.requestNotify();\n }\n\n function patch(partial: Record<string, unknown>): void {\n ctx.ensureNotDisposed();\n\n const flat = flattenValues(partial);\n\n for (const [key, value] of Object.entries(flat)) {\n ctx.baseline.set(key, value);\n ctx.store.set(key, value);\n ctx.dirty.delete(key);\n }\n\n ctx.requestNotify(Object.keys(flat));\n }\n\n /* ======== Array helpers ======== */\n\n function array(name: FlatKeyOf<TValues>): ArrayField {\n ctx.ensureNotDisposed();\n\n const key = name as string;\n\n assertSafeKey(key);\n\n const cached = ctx.arrayCache.get(key);\n\n if (cached) return cached;\n\n const helpers = createArrayField(name, ctx.store, set as (name: string, value: unknown) => void);\n\n ctx.arrayCache.set(key, helpers);\n\n return helpers;\n }\n\n return {\n array,\n clearError,\n field,\n get,\n listFields,\n patch,\n registerField,\n removeField,\n replace,\n reset,\n resetErrors,\n resetField,\n set,\n setError,\n setValidator,\n touch,\n touchAll,\n untouch,\n untouchAll,\n values,\n };\n}\n\nexport type ValueOps<TValues extends Record<string, unknown>> = ReturnType<typeof createValueOps<TValues>>;\n"],"mappings":"sHAsBA,SAAgB,EAAwD,EAA2B,CACjG,SAAS,EAAkC,EAAiC,CAC1E,IAAM,EAAM,EAIZ,OAFA,EAAA,cAAc,CAAG,EAEV,EAAI,MAAM,IAAI,CAAG,CAC1B,CAEA,S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AAkB,EAEtB,IAAM,GAAA,EAAA,EAAA,aAAA,CAAqB,CAAO,EAElC,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC5C,EAAI,SAAS,IAAI,EAAK,CAAK,EAC3B,EAAI,MAAM,IAAI,EAAK,CAAK,EACxB,EAAI,MAAM,OAAO,CAAG,EAGtB,EAAI,cAAc,OAAO,KAAK,CAAI,CAAC,CACrC,CAIA,SAAS,EAAM,EAAsC,CACnD,EAAI,kBAAkB,EAEtB,IAAM,EAAM,EAEZ,EAAA,cAAc,CAAG,EAEjB,IAAM,EAAS,EAAI,WAAW,IAAI,CAAG,EAErC,GAAI,EAAQ,OAAO,EAEnB,IAAM,EAAU,EAAA,iBAAiB,EAAM,EAAI,MAAO,CAA6C,EAI/F,OAFA,EAAI,WAAW,IAAI,EAAK,CAAO,EAExB,CACT,CAEA,MAAO,CACL,QACA,aACA,QACA,MACA,aACA,QACA,gBACA,cACA,UACA,QACA,cACA,aACA,MACA,WACA,eACA,QACA,WACA,UACA,aACA,QACF,CACF"}
|
package/dist/core/values.d.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import type { FormContext } from './context';
|
|
2
|
-
import { type ArrayField, type ErrorKeyOf, type FieldState, type FieldValidator, type FlatKeyOf, type RegisterFieldOptions, type SetOptions, type TypeAtPath, type Unsubscribe } from '../types';
|
|
3
|
-
/**
|
|
4
|
-
* Value/field-mutation operations: get/set/values, dirty tracking, errors, dynamic field
|
|
5
|
-
* registration, touch, and reset/replace/patch/array. Moved verbatim from `createForm()`'s
|
|
6
|
-
* "Value access" through "Lifecycle: field operations" sections.
|
|
7
|
-
*/
|
|
8
|
-
export declare function createValueOps<TValues extends Record<string, unknown>>(ctx: FormContext<TValues>): {
|
|
9
|
-
array: (name: FlatKeyOf<TValues>) => ArrayField;
|
|
10
|
-
clearError: (name: ErrorKeyOf<TValues>) => void;
|
|
11
|
-
field: <K extends FlatKeyOf<TValues>>(name: K) => FieldState<TypeAtPath<TValues, K>>;
|
|
12
|
-
get: <K extends FlatKeyOf<TValues>>(name: K) => TypeAtPath<TValues, K>;
|
|
13
|
-
listFields: () => readonly string[];
|
|
14
|
-
patch: (partial: Record<string, unknown>) => void;
|
|
15
|
-
registerField: <K extends FlatKeyOf<TValues>>(name: K, options?: RegisterFieldOptions<TypeAtPath<TValues, K>>) => Unsubscribe;
|
|
16
|
-
removeField: (name: FlatKeyOf<TValues>) => void;
|
|
17
|
-
replace: (newValues: TValues) => void;
|
|
18
|
-
reset: () => void;
|
|
19
|
-
resetErrors: (nextErrors?: Partial<Record<ErrorKeyOf<TValues>, string | undefined>>) => void;
|
|
20
|
-
resetField: (name: FlatKeyOf<TValues>) => void;
|
|
21
|
-
set: <K extends FlatKeyOf<TValues>>(name: K, value: TypeAtPath<TValues, K>, options?: SetOptions) => void;
|
|
22
|
-
setError: (name: ErrorKeyOf<TValues>, message: string) => void;
|
|
23
|
-
setValidator: (name: FlatKeyOf<TValues>, validator?: FieldValidator<unknown>) => void;
|
|
24
|
-
touch: (name: FlatKeyOf<TValues>) => void;
|
|
25
|
-
touchAll: () => void;
|
|
26
|
-
untouch: (name: FlatKeyOf<TValues>) => void;
|
|
27
|
-
untouchAll: () => void;
|
|
28
|
-
values: () => TValues;
|
|
29
|
-
};
|
|
30
|
-
export type ValueOps<TValues extends Record<string, unknown>> = ReturnType<typeof createValueOps<TValues>>;
|
|
31
|
-
//# sourceMappingURL=values.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"values.d.ts","sourceRoot":"","sources":["../../src/core/values.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAI7C,OAAO,EACL,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,oBAAoB,EACzB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,WAAW,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