@vielzeug/forge 1.4.0 → 2.0.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/README.md +21 -53
- package/dist/_utils.cjs +1 -2
- package/dist/_utils.d.ts +1 -10
- package/dist/_utils.d.ts.map +1 -1
- package/dist/_utils.js +2 -33
- package/dist/adapters/form-data.cjs +1 -1
- package/dist/adapters/form-data.cjs.map +1 -1
- package/dist/adapters/form-data.d.ts.map +1 -1
- package/dist/adapters/form-data.js +5 -5
- package/dist/adapters/form-data.js.map +1 -1
- package/dist/core/path.cjs +2 -0
- package/dist/core/path.cjs.map +1 -0
- package/dist/core/path.d.ts +22 -0
- package/dist/core/path.d.ts.map +1 -0
- package/dist/core/path.js +125 -0
- package/dist/core/path.js.map +1 -0
- package/dist/devtools.cjs +1 -1
- package/dist/devtools.cjs.map +1 -1
- package/dist/devtools.d.ts +3 -36
- package/dist/devtools.d.ts.map +1 -1
- package/dist/devtools.js +6 -24
- package/dist/devtools.js.map +1 -1
- package/dist/dom.cjs +2 -0
- package/dist/dom.cjs.map +1 -0
- package/dist/dom.d.ts +9 -0
- package/dist/dom.d.ts.map +1 -0
- package/dist/dom.js +24 -0
- package/dist/dom.js.map +1 -0
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +1 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -6
- 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 +3 -5
- package/dist/form.d.ts.map +1 -1
- package/dist/form.js +223 -58
- package/dist/form.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +3 -4
- package/dist/spell.cjs +2 -0
- package/dist/spell.cjs.map +1 -0
- package/dist/spell.d.ts +5 -0
- package/dist/spell.d.ts.map +1 -0
- package/dist/spell.js +57 -0
- package/dist/spell.js.map +1 -0
- package/dist/types.d.ts +70 -392
- package/dist/types.d.ts.map +1 -1
- package/dist/vault.cjs +2 -0
- package/dist/vault.cjs.map +1 -0
- package/dist/vault.d.ts +10 -0
- package/dist/vault.d.ts.map +1 -0
- package/dist/vault.js +14 -0
- package/dist/vault.js.map +1 -0
- package/package.json +36 -11
- package/dist/_dev.cjs +0 -2
- package/dist/_dev.cjs.map +0 -1
- package/dist/_dev.js +0 -12
- package/dist/_dev.js.map +0 -1
- package/dist/_utils.cjs.map +0 -1
- package/dist/_utils.js.map +0 -1
- package/dist/adapters/validators.cjs +0 -2
- package/dist/adapters/validators.cjs.map +0 -1
- package/dist/adapters/validators.d.ts +0 -44
- package/dist/adapters/validators.d.ts.map +0 -1
- package/dist/adapters/validators.js +0 -20
- package/dist/adapters/validators.js.map +0 -1
- package/dist/core/array.cjs +0 -2
- package/dist/core/array.cjs.map +0 -1
- package/dist/core/array.d.ts +0 -10
- package/dist/core/array.d.ts.map +0 -1
- package/dist/core/array.js +0 -77
- package/dist/core/array.js.map +0 -1
- package/dist/core/asyncQueue.cjs +0 -2
- package/dist/core/asyncQueue.cjs.map +0 -1
- package/dist/core/asyncQueue.d.ts +0 -22
- package/dist/core/asyncQueue.d.ts.map +0 -1
- package/dist/core/asyncQueue.js +0 -67
- package/dist/core/asyncQueue.js.map +0 -1
- package/dist/core/context.cjs +0 -2
- package/dist/core/context.cjs.map +0 -1
- package/dist/core/context.d.ts +0 -7
- package/dist/core/context.d.ts.map +0 -1
- package/dist/core/context.js +0 -139
- package/dist/core/context.js.map +0 -1
- package/dist/core/fields.cjs +0 -2
- package/dist/core/fields.cjs.map +0 -1
- package/dist/core/fields.d.ts +0 -52
- package/dist/core/fields.d.ts.map +0 -1
- package/dist/core/fields.js +0 -310
- package/dist/core/fields.js.map +0 -1
- package/dist/core/lifecycle.cjs +0 -2
- package/dist/core/lifecycle.cjs.map +0 -1
- package/dist/core/lifecycle.d.ts +0 -15
- package/dist/core/lifecycle.d.ts.map +0 -1
- package/dist/core/lifecycle.js +0 -38
- package/dist/core/lifecycle.js.map +0 -1
- package/dist/core/notifier.cjs +0 -2
- package/dist/core/notifier.cjs.map +0 -1
- package/dist/core/notifier.d.ts +0 -33
- package/dist/core/notifier.d.ts.map +0 -1
- package/dist/core/notifier.js +0 -78
- package/dist/core/notifier.js.map +0 -1
- package/dist/core/observe.cjs +0 -2
- package/dist/core/observe.cjs.map +0 -1
- package/dist/core/observe.d.ts +0 -20
- package/dist/core/observe.d.ts.map +0 -1
- package/dist/core/observe.js +0 -79
- package/dist/core/observe.js.map +0 -1
- package/dist/core/scope.cjs +0 -2
- package/dist/core/scope.cjs.map +0 -1
- package/dist/core/scope.d.ts +0 -11
- package/dist/core/scope.d.ts.map +0 -1
- package/dist/core/scope.js +0 -235
- package/dist/core/scope.js.map +0 -1
- package/dist/types.cjs +0 -2
- package/dist/types.cjs.map +0 -1
- package/dist/types.js +0 -21
- package/dist/types.js.map +0 -1
package/dist/core/scope.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scope.js","names":[],"sources":["../../src/core/scope.ts"],"sourcesContent":["import type {\n ArrayField,\n ConnectOptions,\n ConnectionResult,\n ErrorKeyOf,\n FieldState,\n FieldValidator,\n FlatKeyOf,\n Form,\n FormSnapshot,\n FormState,\n MaybePromise,\n RegisterFieldOptions,\n ScopedValues,\n SetOptions,\n SubmitResult,\n SubscribeOptions,\n TypeAtPath,\n Unsubscribe,\n ValidateResult,\n} from '../types';\nimport type { FormContext } from './context';\nimport type { FieldOps } from './fields';\n\nimport { flattenValues, unflattenValues } from '../_utils';\nimport { ForgeSubmitError, ForgeValidationError } from '../errors';\n\n/**\n * Everything a scoped sub-form needs from its parent. Deliberately just three members —\n * `ctx` (the same `FormContext` the root form's own ops read/write, not a copy of its\n * fields) and a narrow slice of `fieldOps`'s predicate-based bulk primitives\n * (`reset`/`replace`/`patch`/`touchAll`/`untouchAll`/`resetErrors`'s shared implementations,\n * plus `runValidationCore`). Bulk scoped operations call these with an `isScopedKey`\n * predicate instead of maintaining a second copy of each loop.\n * @internal\n */\nexport interface ScopeContext<TValues extends Record<string, unknown> = Record<string, unknown>> {\n ctx: FormContext<TValues>;\n fieldOps: Pick<\n FieldOps<TValues>,\n | 'patchKeys'\n | 'replaceKeys'\n | 'resetErrorsKeys'\n | 'resetKeys'\n | 'runValidationCore'\n | 'touchAllKeys'\n | 'untouchAllKeys'\n >;\n /** The fully-featured root form — used for all simple one-field delegations. */\n root: Form<TValues>;\n}\n\n/**\n * Creates a scoped sub-form whose field paths are relative to `pfx`.\n * All simple single-field operations delegate to `scopeCtx.root`. Bulk operations\n * (reset, replace, patch, touchAll, untouchAll, resetErrors) call `scopeCtx.fieldOps`'s\n * shared predicate-based primitives with an `isScopedKey` filter. Only `validate`/`submit`\n * (which need to compute a scoped field-name subset before calling `runValidationCore`) and\n * the handful of read-only projections (`state`, `values`, `fields.list`) contain custom code.\n */\nexport function createScopedForm<TValues extends Record<string, unknown>, P extends string>(\n scopeCtx: ScopeContext<TValues>,\n pfx: P,\n): Form<ScopedValues<TValues, P>> {\n const { ctx, fieldOps, root } = scopeCtx;\n const pfxDot = `${pfx}.`;\n\n function pre(name: string): string {\n return `${pfx}.${name}`;\n }\n\n function isScopedKey(key: string): boolean {\n return key === pfx || key.startsWith(pfxDot);\n }\n\n function unscope(key: string): string {\n return key.startsWith(pfxDot) ? key.slice(pfxDot.length) : key;\n }\n\n /* ---- Non-trivial scoped implementations ---- */\n\n /**\n * Compute a scoped projection of FormState from current raw Maps.\n * Errors, touchedFields, validatingFields, isValid, isDirty, isTouched reflect only\n * fields within the prefix. isSubmitting, isLoading, isValidating, submitCount are full-form.\n */\n function getScopedState(): FormState {\n const rootState = ctx.getStateSnapshot();\n const errors = Object.fromEntries(\n Object.entries(rootState.errors)\n .filter(([k]) => isScopedKey(k))\n .map(([k, v]) => [unscope(k), v]),\n );\n const touchedFields = rootState.touchedFields.filter(isScopedKey).map(unscope);\n const validatingFields = rootState.validatingFields.filter(isScopedKey).map(unscope);\n const isValid = Object.keys(errors).length === 0;\n const isDirty = [...ctx.dirty].some(isScopedKey);\n const isTouched = [...ctx.touched].some(isScopedKey);\n const isValidating = validatingFields.length > 0;\n\n return Object.freeze({\n errors: Object.freeze(errors) as FormState['errors'],\n isDirty,\n isLoading: rootState.isLoading,\n isSubmitting: rootState.isSubmitting,\n isTouched,\n isValid,\n isValidating,\n submitCount: rootState.submitCount,\n touchedFields: Object.freeze(touchedFields) as readonly string[],\n validatingFields: Object.freeze(validatingFields) as readonly string[],\n });\n }\n\n function scopedValues(): ScopedValues<TValues, P> {\n const sub: Record<string, unknown> = {};\n\n for (const [key, value] of ctx.store) {\n if (key.startsWith(pfxDot)) sub[key.slice(pfxDot.length)] = value;\n }\n\n return unflattenValues(sub) as ScopedValues<TValues, P>;\n }\n\n /**\n * Enumerate field paths within this scope's prefix, stripped to relative paths —\n * matching `scope.state`'s relative-path convention, not `state.touchedFields`'s\n * absolute-path convention. Same \"known field\" definition `scopedTouchAll()` uses.\n */\n function scopedListFields(): readonly string[] {\n const known = new Set<string>();\n\n for (const key of ctx.store.keys()) {\n if (isScopedKey(key)) known.add(unscope(key));\n }\n\n for (const key of ctx.validators.keys()) {\n if (isScopedKey(key)) known.add(unscope(key));\n }\n\n return Object.freeze([...known]);\n }\n\n function scopedTouchAll(): void {\n ctx.ensureNotDisposed('touchAll');\n fieldOps.touchAllKeys(isScopedKey);\n ctx.requestNotify();\n }\n\n function scopedUntouchAll(): void {\n ctx.ensureNotDisposed('untouchAll');\n fieldOps.untouchAllKeys(isScopedKey);\n ctx.requestNotify();\n }\n\n function scopedReset(): void {\n ctx.ensureNotDisposed('reset');\n fieldOps.resetKeys(isScopedKey);\n ctx.requestNotify();\n }\n\n function scopedReplace(newValues: ScopedValues<TValues, P>): void {\n ctx.ensureNotDisposed('replace');\n fieldOps.replaceKeys(isScopedKey, flattenValues(newValues as Record<string, unknown>), pre);\n ctx.requestNotify();\n }\n\n function scopedPatch(partial: Record<string, unknown>): void {\n ctx.ensureNotDisposed('patch');\n ctx.requestNotify(fieldOps.patchKeys(partial, pre));\n }\n\n function scopedResetErrors(\n nextErrors?: Partial<Record<ErrorKeyOf<ScopedValues<TValues, P>>, string | undefined>>,\n ): void {\n ctx.ensureNotDisposed('resetErrors');\n fieldOps.resetErrorsKeys(isScopedKey, nextErrors ?? {}, pre);\n ctx.requestNotify();\n }\n\n async function scopedValidate(\n nameOrFieldsOrSignal?: FlatKeyOf<ScopedValues<TValues, P>> | FlatKeyOf<ScopedValues<TValues, P>>[] | AbortSignal,\n signal?: AbortSignal,\n ): Promise<ValidateResult> {\n ctx.ensureNotDisposed('validate');\n\n if (\n nameOrFieldsOrSignal !== undefined &&\n !Array.isArray(nameOrFieldsOrSignal) &&\n !(nameOrFieldsOrSignal instanceof AbortSignal)\n ) {\n // validate(name) — single field\n const prefixedName = pre(nameOrFieldsOrSignal as string) as FlatKeyOf<TValues>;\n\n await fieldOps.runValidationCore([prefixedName as string], 'partial', signal);\n\n const error = ctx.fieldErrors.get(prefixedName as string);\n\n return {\n errors: error !== undefined ? { [nameOrFieldsOrSignal as string]: error } : {},\n valid: error === undefined,\n };\n }\n\n if (Array.isArray(nameOrFieldsOrSignal)) {\n // validate(fields[]) — specific subset\n const prefixedFields = nameOrFieldsOrSignal.map((f) => pre(f as string)) as string[];\n\n await fieldOps.runValidationCore(prefixedFields, 'partial', signal);\n\n const errors: Record<string, string> = {};\n\n for (const pf of prefixedFields) {\n const msg = ctx.fieldErrors.get(pf);\n\n if (msg !== undefined) errors[unscope(pf)] = msg;\n }\n\n return { errors, valid: Object.keys(errors).length === 0 };\n }\n\n // validate(signal?) — all scoped fields\n const sig = nameOrFieldsOrSignal as AbortSignal | undefined;\n const fields = [...ctx.validators.keys()].filter(isScopedKey);\n\n await fieldOps.runValidationCore(fields, 'partial', sig);\n\n const errors: Record<string, string> = {};\n\n for (const [key, message] of ctx.fieldErrors) {\n if (isScopedKey(key)) errors[unscope(key)] = message;\n }\n\n return { errors, valid: Object.keys(errors).length === 0 };\n }\n\n async function scopedSubmit<TResult>(\n handler: (values: ScopedValues<TValues, P>) => MaybePromise<TResult>,\n ): Promise<SubmitResult<TResult>> {\n ctx.ensureNotDisposed('submit');\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 scopedTouchAll();\n });\n\n try {\n const fields = [...ctx.validators.keys()].filter(isScopedKey);\n\n await fieldOps.runValidationCore(fields, 'partial');\n\n ctx.ensureNotDisposed('submit');\n\n const errors: Record<string, string> = {};\n\n for (const [key, message] of ctx.fieldErrors) {\n if (isScopedKey(key)) errors[unscope(key)] = message;\n }\n\n if (Object.keys(errors).length > 0) {\n return { errors, ok: false, type: 'validation' as const };\n }\n\n return { ok: true as const, value: await handler(scopedValues()) };\n } finally {\n ctx.isSubmittingState = false;\n\n if (!ctx.disposed) ctx.requestNotify();\n }\n }\n\n /**\n * Subscribe filtered to scoped fields only — this scoped form's `subscribe()` implementation.\n * Errors, touchedFields, and validatingFields are remapped to relative paths.\n * `isValid`, `isDirty`, and `isTouched` reflect only fields within this scope's prefix.\n * `isSubmitting`, `isLoading`, `isValidating`, and `submitCount` reflect the full form.\n *\n * The listener fires only when the scoped projection changes — mutations outside this\n * prefix do not fire the listener.\n */\n function scopedSubscribe(listener: (state: FormState) => void, options?: SubscribeOptions): Unsubscribe {\n // Track the previous scoped projection for equality comparison.\n let prevState: FormState | null = null;\n\n return root.subscribe(() => {\n const next = getScopedState();\n\n // Skip if no scoped-relevant state has changed.\n if (prevState) {\n const p = prevState;\n const errKeys = Object.keys(next.errors);\n const prevErrKeys = Object.keys(p.errors);\n const errorsMatch =\n errKeys.length === prevErrKeys.length && errKeys.every((k) => next.errors[k] === p.errors[k]);\n\n const touchedMatch =\n next.touchedFields.length === p.touchedFields.length &&\n next.touchedFields.every((v, i) => v === p.touchedFields[i]);\n\n const validatingMatch =\n next.validatingFields.length === p.validatingFields.length &&\n next.validatingFields.every((v, i) => v === p.validatingFields[i]);\n\n const flagsMatch =\n next.isDirty === p.isDirty &&\n next.isLoading === p.isLoading &&\n next.isSubmitting === p.isSubmitting &&\n next.isTouched === p.isTouched &&\n next.isValid === p.isValid &&\n next.isValidating === p.isValidating &&\n next.submitCount === p.submitCount;\n\n if (flagsMatch && errorsMatch && touchedMatch && validatingMatch) return;\n }\n\n prevState = next;\n listener(next);\n }, options);\n }\n\n function createScopedAdapter() {\n return {\n array(name: string): ArrayField {\n return root.array(pre(name) as FlatKeyOf<TValues>) as ArrayField;\n },\n clearError(name: string): void {\n root.clearError(pre(name) as ErrorKeyOf<TValues>);\n },\n connect(name: string, config?: ConnectOptions): ConnectionResult<unknown> {\n return root.connect(pre(name) as FlatKeyOf<TValues>, config) as ConnectionResult<unknown>;\n },\n field(name: string): FieldState<unknown> {\n return root.field(pre(name) as FlatKeyOf<TValues>) as FieldState<unknown>;\n },\n get(name: string): unknown {\n return root.get(pre(name) as FlatKeyOf<TValues>);\n },\n register(name: string, options?: RegisterFieldOptions<unknown>): Unsubscribe {\n return root.fields.register(\n pre(name) as FlatKeyOf<TValues>,\n options as RegisterFieldOptions<TypeAtPath<TValues, FlatKeyOf<TValues>>>,\n );\n },\n remove(name: string): void {\n root.fields.remove(pre(name) as FlatKeyOf<TValues>);\n },\n resetField(name: string): void {\n root.resetField(pre(name) as FlatKeyOf<TValues>);\n },\n set(name: string, value: unknown, options?: SetOptions): void {\n root.set(pre(name) as FlatKeyOf<TValues>, value as TypeAtPath<TValues, FlatKeyOf<TValues>>, options);\n },\n setError(name: string, message: string): void {\n root.setError(pre(name) as ErrorKeyOf<TValues>, message);\n },\n setValidator(name: string, validator?: FieldValidator): void {\n root.fields.setValidator(pre(name) as FlatKeyOf<TValues>, validator);\n },\n subscribeField(\n name: string,\n listener: (state: FieldState<unknown>) => void,\n options?: SubscribeOptions,\n ): Unsubscribe {\n return root.subscribeField(\n pre(name) as FlatKeyOf<TValues>,\n listener as (state: FieldState<TypeAtPath<TValues, FlatKeyOf<TValues>>>) => void,\n options,\n );\n },\n touch(name: string): void {\n root.touch(pre(name) as FlatKeyOf<TValues>);\n },\n untouch(name: string): void {\n root.untouch(pre(name) as FlatKeyOf<TValues>);\n },\n };\n }\n\n /* ---- Public scoped form object ---- */\n\n type S = ScopedValues<TValues, P>;\n\n const adapter = createScopedAdapter();\n\n return {\n array: (name) =>\n adapter.array(name as string) as ArrayField<\n TypeAtPath<S, typeof name> extends readonly (infer E)[] ? E : unknown\n >,\n batch: (fn) => root.batch(fn),\n clearError: (name) => adapter.clearError(name as string),\n connect: (name, config?) => adapter.connect(name as string, config) as ConnectionResult<TypeAtPath<S, typeof name>>,\n get disposalSignal() {\n return root.disposalSignal;\n },\n dispose: () => {\n /* Scoped forms share lifecycle with parent — call parentForm.dispose() to tear down */\n },\n get disposed() {\n return ctx.disposed;\n },\n field: (name) => adapter.field(name as string) as FieldState<TypeAtPath<S, typeof name>>,\n fields: {\n list: scopedListFields,\n register: (name, options?) => adapter.register(name as string, options as RegisterFieldOptions<unknown>),\n remove: (name) => adapter.remove(name as string),\n setValidator: (name, validator?) => adapter.setValidator(name as string, validator),\n },\n get: (name) => adapter.get(name as string) as TypeAtPath<S, typeof name>,\n history: {\n // Casts are irreducible: FormSnapshot<S> and FormSnapshot<TValues> are structurally\n // unrelated generic instantiations -- TS cannot verify one against the other.\n restore: (snap) => root.history.restore(snap as FormSnapshot<TValues>),\n snapshot: () => root.history.snapshot() as FormSnapshot<S>,\n },\n get isLoading() {\n return root.isLoading;\n },\n get isSubmitting() {\n return root.isSubmitting;\n },\n patch: scopedPatch as Form<S>['patch'],\n replace: scopedReplace as Form<S>['replace'],\n reset: scopedReset,\n resetErrors: scopedResetErrors as Form<S>['resetErrors'],\n resetField: (name) => adapter.resetField(name as string),\n scope: (subPrefix) =>\n createScopedForm(scopeCtx, pre(subPrefix as string)) as Form<ScopedValues<S, typeof subPrefix>>,\n set: (name, value, options?: SetOptions) => adapter.set(name as string, value, options),\n setError: (name, message) => adapter.setError(name as string, message),\n get state() {\n return getScopedState();\n },\n submit: scopedSubmit as Form<S>['submit'],\n submitOrThrow: async (handler) => {\n const result = await scopedSubmit(handler);\n\n if (!result.ok) throw new ForgeValidationError(result.errors as Record<string, string>);\n\n return result.value;\n },\n // Scoped forms filter+remap; on a root form this method is the unfiltered notifier pass-through.\n subscribe: scopedSubscribe,\n subscribeField: (name, listener, options?) =>\n adapter.subscribeField(name as string, listener as (state: FieldState<unknown>) => void, options),\n [Symbol.asyncIterator]: () => root[Symbol.asyncIterator](),\n [Symbol.dispose]() {\n this.dispose();\n },\n touch: (name) => adapter.touch(name as string),\n touchAll: scopedTouchAll,\n untouch: (name) => adapter.untouch(name as string),\n untouchAll: scopedUntouchAll,\n validate: scopedValidate as Form<S>['validate'],\n values: scopedValues,\n };\n}\n"],"mappings":";;;AA4DA,SAAgB,EACd,GACA,GACgC;CAChC,IAAM,EAAE,QAAK,aAAU,YAAS,GAC1B,IAAS,GAAG,EAAI;CAEtB,SAAS,EAAI,GAAsB;EACjC,OAAO,GAAG,EAAI,GAAG;CACnB;CAEA,SAAS,EAAY,GAAsB;EACzC,OAAO,MAAQ,KAAO,EAAI,WAAW,CAAM;CAC7C;CAEA,SAAS,EAAQ,GAAqB;EACpC,OAAO,EAAI,WAAW,CAAM,IAAI,EAAI,MAAM,EAAO,MAAM,IAAI;CAC7D;CASA,SAAS,IAA4B;EACnC,IAAM,IAAY,EAAI,iBAAiB,GACjC,IAAS,OAAO,YACpB,OAAO,QAAQ,EAAU,MAAM,CAAC,CAC7B,QAAQ,CAAC,OAAO,EAAY,CAAC,CAAC,CAAC,CAC/B,KAAK,CAAC,GAAG,OAAO,CAAC,EAAQ,CAAC,GAAG,CA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ACP,SAAS;EACT,OAAO;EACP,aAAa;EACb,aAAa,MAAS,EAAQ,WAAW,CAAc;EACvD,QAAQ,MACN,EAAiB,GAAU,EAAI,CAAmB,CAAC;EACrD,MAAM,GAAM,GAAO,MAAyB,EAAQ,IAAI,GAAgB,GAAO,CAAO;EACtF,WAAW,GAAM,MAAY,EAAQ,SAAS,GAAgB,CAAO;EACrE,IAAI,QAAQ;GACV,OAAO,EAAe;EACxB;EACA,QAAQ;EACR,eAAe,OAAO,MAAY;GAChC,IAAM,IAAS,MAAM,EAAa,CAAO;GAEzC,IAAI,CAAC,EAAO,IAAI,MAAM,IAAI,EAAqB,EAAO,MAAgC;GAEtF,OAAO,EAAO;EAChB;EAEA,WAAW;EACX,iBAAiB,GAAM,GAAU,MAC/B,EAAQ,eAAe,GAAgB,GAAkD,CAAO;GACjG,OAAO,sBAAsB,EAAK,OAAO,cAAc,CAAC;EACzD,CAAC,OAAO,WAAW;GACjB,KAAK,QAAQ;EACf;EACA,QAAQ,MAAS,EAAQ,MAAM,CAAc;EAC7C,UAAU;EACV,UAAU,MAAS,EAAQ,QAAQ,CAAc;EACjD,YAAY;EACZ,UAAU;EACV,QAAQ;CACV;AACF"}
|
package/dist/types.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e=`_form`,t=5,n={onBlur:{touchOnBlur:!0,validateOnBlur:!0},onChange:{touchOnBlur:!0,validateOnChange:!0},onSubmit:{},onTouched:{touchOnBlur:!0,validateOnBlur:!0,validateOnTouch:!0}};exports.FORM_ERROR=e,exports.MAX_TYPED_PATH_DEPTH=t,exports.ValidationModes=n;
|
|
2
|
-
//# sourceMappingURL=types.cjs.map
|
package/dist/types.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","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,EAAa,QA+Bb,EAAuB,EAsMvB,EAAkB,CAC7B,OAAQ,CAAE,YAAa,GAAM,eAAgB,EAAK,EAClD,SAAU,CAAE,YAAa,GAAM,iBAAkB,EAAK,EACtD,SAAU,CAAC,EACX,UAAW,CAAE,YAAa,GAAM,eAAgB,GAAM,gBAAiB,EAAK,CAC9E"}
|
package/dist/types.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
//#region src/types.ts
|
|
2
|
-
var e = "_form", t = 5, n = {
|
|
3
|
-
onBlur: {
|
|
4
|
-
touchOnBlur: !0,
|
|
5
|
-
validateOnBlur: !0
|
|
6
|
-
},
|
|
7
|
-
onChange: {
|
|
8
|
-
touchOnBlur: !0,
|
|
9
|
-
validateOnChange: !0
|
|
10
|
-
},
|
|
11
|
-
onSubmit: {},
|
|
12
|
-
onTouched: {
|
|
13
|
-
touchOnBlur: !0,
|
|
14
|
-
validateOnBlur: !0,
|
|
15
|
-
validateOnTouch: !0
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
//#endregion
|
|
19
|
-
export { e as FORM_ERROR, t as MAX_TYPED_PATH_DEPTH, n as ValidationModes };
|
|
20
|
-
|
|
21
|
-
//# sourceMappingURL=types.js.map
|
package/dist/types.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|