react-form-action 2.9.1 → 2.9.2

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/client.d.mts CHANGED
@@ -1,31 +1,30 @@
1
- import * as React$1 from 'react';
2
- import React__default, { PropsWithChildren, JSX } from 'react';
3
- import { F as FormAction, A as ActionState, I as InitialState, a as InvalidState, b as FailureState, S as SuccessState } from './createFormAction-DjhozgiG.mjs';
4
- import { $ZodErrorTree } from 'zod/v4/core';
5
-
1
+ import { a as InvalidState, i as InitialState, n as FailureState, o as SuccessState, r as FormAction, t as ActionState } from "./createFormAction-4p5Fvn2A.mjs";
2
+ import React$1, { JSX, PropsWithChildren } from "react";
3
+ import { $ZodErrorTree } from "zod/v4/core";
4
+ //#region src/Action.d.ts
6
5
  type ActionProps<Data, Error, ValidationError, Arguments extends unknown[] = []> = PropsWithChildren<Arguments extends [unknown, ...unknown[]] ? {
7
- action: FormAction<Data, Error, ValidationError, FormData, Arguments>;
8
- args: Arguments;
9
- initialData: Data;
10
- permalink?: string;
6
+ action: FormAction<Data, Error, ValidationError, FormData, Arguments>;
7
+ args: Arguments;
8
+ initialData: Data;
9
+ permalink?: string;
11
10
  } : {
12
- action: FormAction<Data, Error, ValidationError, FormData, Arguments>;
13
- initialData: Data;
14
- args?: undefined;
15
- permalink?: string;
11
+ action: FormAction<Data, Error, ValidationError, FormData, Arguments>;
12
+ initialData: Data;
13
+ args?: undefined;
14
+ permalink?: string;
16
15
  }>;
17
16
  type ActionStatusFlags<T extends ActionState<unknown, unknown, unknown>["type"] | unknown = unknown> = {
18
- isInitial: T extends "initial" ? true : false;
19
- isInvalid: T extends "invalid" ? true : false;
20
- isFailure: T extends "failure" ? true : false;
21
- isSuccess: T extends "success" ? true : false;
17
+ isInitial: T extends "initial" ? true : false;
18
+ isInvalid: T extends "invalid" ? true : false;
19
+ isFailure: T extends "failure" ? true : false;
20
+ isSuccess: T extends "success" ? true : false;
22
21
  };
23
22
  type ActionContextState<T extends ActionState<unknown, unknown, unknown>> = T & ActionStatusFlags<T["type"]> & {
24
- /**
25
- * The dispatch function returned from React.useActionState()
26
- */
27
- action: (payload: FormData) => void;
28
- isPending: boolean;
23
+ /**
24
+ * The dispatch function returned from React.useActionState()
25
+ */
26
+ action: (payload: FormData) => void;
27
+ isPending: boolean;
29
28
  };
30
29
  /**
31
30
  * NOTE: ActionContextState<ActionState<...>> would not allow discriminate the union inside of the ActionState.
@@ -35,74 +34,76 @@ type SpreadActionContext<Data = unknown, Error = unknown, ValidationError = unkn
35
34
  * A hook to consume the form action state from the context.
36
35
  */
37
36
  declare function useActionContext<Data, Error, ValidationError, Args extends unknown[] = []>(action?: FormAction<Data, Error, ValidationError, FormData, Args>): SpreadActionContext<Data, Error, ValidationError>;
38
- declare function Action<Data, Error, ValidationError, Args extends unknown[] = []>({ children, action: formAction, initialData, args, permalink, }: ActionProps<Data, Error, ValidationError, Args>): React__default.JSX.Element;
39
-
37
+ declare function Action<Data, Error, ValidationError, Args extends unknown[] = []>({ children, action: formAction, initialData, args, permalink }: ActionProps<Data, Error, ValidationError, Args>): React$1.JSX.Element;
38
+ //#endregion
39
+ //#region src/Form.d.ts
40
40
  type FormProps = Omit<JSX.IntrinsicElements["form"], "action"> & {
41
- /**
42
- * Opt-in into automatic form reset by using the form "action" prop.
43
- * By default, the onSubmit with a custom transition which opts-out of the implicit form reset.
44
- * See for more. https://github.com/facebook/react/issues/29034
45
- * @default false
46
- */
47
- autoReset?: boolean;
41
+ /**
42
+ * Opt-in into automatic form reset by using the form "action" prop.
43
+ * By default, the onSubmit with a custom transition which opts-out of the implicit form reset.
44
+ * See for more. https://github.com/facebook/react/issues/29034
45
+ * @default false
46
+ */
47
+ autoReset?: boolean;
48
48
  };
49
49
  declare function Form({ autoReset, ...props }: FormProps): JSX.Element;
50
-
50
+ //#endregion
51
+ //#region src/ZodFieldError.d.ts
51
52
  declare const SEPARATOR: ".";
52
- type Paths<Shape extends $ZodErrorTree<object>, Props = Required<NonNullable<Shape["properties"]>>> = {
53
- [k in keyof Props]: k extends string ? NonNullable<Props[k]> extends $ZodErrorTree<object> ? "properties" extends keyof NonNullable<Props[k]> ? `${k}${typeof SEPARATOR}${Paths<NonNullable<Props[k]>>}` : k : k : never;
54
- }[keyof Props];
53
+ type Paths<Shape extends $ZodErrorTree<object>, Props = Required<NonNullable<Shape["properties"]>>> = { [k in keyof Props]: k extends string ? NonNullable<Props[k]> extends $ZodErrorTree<object> ? "properties" extends keyof NonNullable<Props[k]> ? `${k}${typeof SEPARATOR}${Paths<NonNullable<Props[k]>>}` : k : k : never; }[keyof Props];
55
54
  type InferZodErrorPaths<T> = T extends $ZodErrorTree<object> ? Paths<T> : never;
56
55
  type ZodFieldErrorProps<Errors extends $ZodErrorTree<any>, Name extends "" | InferZodErrorPaths<Errors>> = {
57
- errors: Errors;
58
- name: Name;
59
- children?: (props: ZodFieldErrorChildrenProps<Name>) => React__default.ReactNode;
56
+ errors: Errors;
57
+ name: Name;
58
+ children?: (props: ZodFieldErrorChildrenProps<Name>) => React$1.ReactNode;
60
59
  };
61
60
  type ZodFieldErrorChildrenProps<Name> = {
62
- name: Name;
63
- error?: string;
64
- errors: readonly string[];
61
+ name: Name;
62
+ error?: string;
63
+ errors: readonly string[];
65
64
  };
66
65
  declare const noError: Readonly<{
67
- errors: readonly string[];
66
+ errors: readonly string[];
68
67
  }>;
69
- declare function ZodFieldError<Errors extends $ZodErrorTree<object>, Name extends "" | InferZodErrorPaths<Errors> = "">({ errors, name, children, }: ZodFieldErrorProps<Errors, Name>): React__default.ReactNode;
70
-
68
+ declare function ZodFieldError<Errors extends $ZodErrorTree<object>, Name extends "" | InferZodErrorPaths<Errors> = "">({ errors, name, children }: ZodFieldErrorProps<Errors, Name>): React$1.ReactNode;
69
+ //#endregion
70
+ //#region src/createComponents.d.ts
71
71
  /**
72
72
  * Creates a typed components for actions created with the formAction builder.
73
73
  */
74
74
  declare function createComponents<Data, Error, ValidationError extends $ZodErrorTree<any>, Args extends unknown[] = []>(action: FormAction<Data, Error, ValidationError, FormData, Args>): {
75
- FieldError: <Name extends "" | InferZodErrorPaths<ValidationError>>({ name, children, }: {
76
- name: Name;
77
- children?: (props: ZodFieldErrorChildrenProps<Name>) => React__default.ReactNode;
78
- }) => React__default.JSX.Element;
79
- Success: ({ children, }: PropsWithChildren | {
80
- children?: (props: {
81
- isSuccess: false;
82
- data: Data | null;
83
- } | {
84
- isSuccess: true;
85
- data: Data;
86
- }) => React__default.ReactNode;
87
- }) => React__default.ReactNode;
88
- Invalid: ({ children, }: PropsWithChildren | {
89
- children?: (props: {
90
- isInvalid: false;
91
- validationError: null;
92
- } | {
93
- isInvalid: true;
94
- validationError: ValidationError;
95
- }) => React__default.ReactNode;
96
- }) => React__default.ReactNode;
75
+ FieldError: <Name extends "" | InferZodErrorPaths<ValidationError>>({ name, children }: {
76
+ name: Name;
77
+ children?: (props: ZodFieldErrorChildrenProps<Name>) => React$1.ReactNode;
78
+ }) => React$1.JSX.Element;
79
+ Success: ({ children }: PropsWithChildren | {
80
+ children?: (props: {
81
+ isSuccess: false;
82
+ data: Data | null;
83
+ } | {
84
+ isSuccess: true;
85
+ data: Data;
86
+ }) => React$1.ReactNode;
87
+ }) => React$1.ReactNode;
88
+ Invalid: ({ children }: PropsWithChildren | {
89
+ children?: (props: {
90
+ isInvalid: false;
91
+ validationError: null;
92
+ } | {
93
+ isInvalid: true;
94
+ validationError: ValidationError;
95
+ }) => React$1.ReactNode;
96
+ }) => React$1.ReactNode;
97
97
  };
98
-
98
+ //#endregion
99
+ //#region src/Pending.d.ts
99
100
  /**
100
101
  * Conditionally renders the children, when the form action is in the "pending" state.
101
102
  */
102
- declare function Pending({ children, }: PropsWithChildren | {
103
- children?: (props: {
104
- isPending: boolean;
105
- }) => React.ReactNode;
106
- }): React$1.ReactNode;
107
-
108
- export { Action, type ActionContextState, type ActionProps, Form, type FormProps, type InferZodErrorPaths, type Paths, Pending, ZodFieldError, type ZodFieldErrorChildrenProps, type ZodFieldErrorProps, createComponents, noError, useActionContext };
103
+ declare function Pending({ children }: PropsWithChildren | {
104
+ children?: (props: {
105
+ isPending: boolean;
106
+ }) => React.ReactNode;
107
+ }): import("react").ReactNode;
108
+ //#endregion
109
+ export { Action, ActionContextState, ActionProps, Form, FormProps, InferZodErrorPaths, Paths, Pending, ZodFieldError, ZodFieldErrorChildrenProps, ZodFieldErrorProps, createComponents, noError, useActionContext };
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- "use client";import{a as f}from"./chunk-LPB4R2UB.mjs";import S from"react";import{useActionState as F,createContext as P,use as y}from"react";var c={isInitial:!1,isInvalid:!1,isFailure:!1,isSuccess:!1},E=P(null);function s(e){let t=y(E);if(!t)throw new Error("ActionContext must be initialized before use. Is your useActionContext hook wrapped with an <Action> Component?");return t}function v({children:e,action:t,initialData:a,args:i,permalink:r}){let o=i?t.bind(null,...i):t,[n,l,d]=F(o,f(a),r),u=n.type==="initial"?{...n,...c,action:l,isPending:d,isInitial:!0}:n.type==="invalid"?{...n,...c,action:l,isPending:d,isInvalid:!0}:n.type==="failure"?{...n,...c,action:l,isPending:d,isFailure:!0}:{...n,...c,action:l,isPending:d,isSuccess:!0};return S.createElement(E,{value:u},e)}import h,{startTransition as g}from"react";function I({autoReset:e=!1,...t}){let{action:a}=s();return h.createElement("form",{...e?{action:a}:{onSubmit:r=>{r.preventDefault();let o=r.currentTarget;g(()=>{a(new FormData(o))})}},...t})}import m from"react";import x from"react";var k=".",p=Object.freeze({errors:Object.freeze([])});function A({errors:e,name:t,children:a=({error:i})=>x.createElement(x.Fragment,null,i)}){if(t.length===0)return a({name:t,error:e.errors[0],errors:e.errors});let i=t.split(k),r=e;for(;i.length;){let o=i.shift();if(!r.properties){r=p;break}r=r.properties[o]??p}return a({name:t,error:r.errors[0],errors:r.errors})}function J(e){function t({name:r,children:o}){let{isInvalid:n,validationError:l}=s(e);return m.createElement(A,{errors:l??p,name:r},o??(({error:u})=>n&&m.createElement(m.Fragment,null,u)))}function a({children:r}){let{isSuccess:o,data:n}=s(e);return typeof r=="function"?r(o?{isSuccess:o,data:n}:{isSuccess:o,data:n}):o&&r}function i({children:r}){let{isInvalid:o,validationError:n}=s(e);return typeof r=="function"?r(o?{isInvalid:o,validationError:n}:{isInvalid:o,validationError:n}):o&&r}return{FieldError:t,Success:a,Invalid:i}}function q({children:e}){let{isPending:t}=s();return typeof e=="function"?e({isPending:t}):t&&e}export{v as Action,I as Form,q as Pending,A as ZodFieldError,J as createComponents,p as noError,s as useActionContext};
1
+ "use client";import{n as e}from"./createFormAction-BwMYAzm2.mjs";import t,{createContext as n,startTransition as r,use as i,useActionState as a}from"react";const o={isInitial:!1,isInvalid:!1,isFailure:!1,isSuccess:!1},s=n(null);function c(e){let t=i(s);if(!t)throw Error(`ActionContext must be initialized before use. Is your useActionContext hook wrapped with an <Action> Component?`);return t}function l({children:n,action:r,initialData:i,args:c,permalink:l}){let[u,d,f]=a(c?r.bind(null,...c):r,e(i),l),p=u.type===`initial`?{...u,...o,action:d,isPending:f,isInitial:!0}:u.type===`invalid`?{...u,...o,action:d,isPending:f,isInvalid:!0}:u.type===`failure`?{...u,...o,action:d,isPending:f,isFailure:!0}:{...u,...o,action:d,isPending:f,isSuccess:!0};return t.createElement(s,{value:p},n)}function u({autoReset:e=!1,...n}){let{action:i}=c(),a=e?{action:i}:{onSubmit:e=>{e.preventDefault();let t=e.currentTarget;r(()=>{i(new FormData(t))})}};return t.createElement(`form`,{...a,...n})}const d=Object.freeze({errors:Object.freeze([])});function f({errors:e,name:n,children:r=({error:e})=>t.createElement(t.Fragment,null,e)}){if(n.length===0)return r({name:n,error:e.errors[0],errors:e.errors});let i=n.split(`.`),a=e;for(;i.length;){let e=i.shift();if(!a.properties){a=d;break}a=a.properties[e]??d}return r({name:n,error:a.errors[0],errors:a.errors})}function p(e){function n({name:n,children:r}){let{isInvalid:i,validationError:a}=c(e);return t.createElement(f,{errors:a??d,name:n},r??(({error:e})=>i&&t.createElement(t.Fragment,null,e)))}function r({children:t}){let{isSuccess:n,data:r}=c(e);return typeof t==`function`?t({isSuccess:n,data:r}):n&&t}function i({children:t}){let{isInvalid:n,validationError:r}=c(e);return typeof t==`function`?t({isInvalid:n,validationError:r}):n&&t}return{FieldError:n,Success:r,Invalid:i}}function m({children:e}){let{isPending:t}=c();return typeof e==`function`?e({isPending:t}):t&&e}export{l as Action,u as Form,m as Pending,f as ZodFieldError,p as createComponents,d as noError,c as useActionContext};
@@ -1,38 +1,35 @@
1
+ //#region src/createFormAction.d.ts
1
2
  type InitialState<T> = {
2
- type: "initial";
3
- data: T;
4
- error: null;
5
- validationError: null;
3
+ type: "initial";
4
+ data: T;
5
+ error: null;
6
+ validationError: null;
6
7
  };
7
8
  type InvalidState<T> = {
8
- type: "invalid";
9
- data: null;
10
- error: null;
11
- validationError: T;
9
+ type: "invalid";
10
+ data: null;
11
+ error: null;
12
+ validationError: T;
12
13
  };
13
14
  type FailureState<T> = {
14
- type: "failure";
15
- data: null;
16
- error: T;
17
- validationError: null;
15
+ type: "failure";
16
+ data: null;
17
+ error: T;
18
+ validationError: null;
18
19
  };
19
20
  type SuccessState<T> = {
20
- type: "success";
21
- data: T;
22
- error: null;
23
- validationError: null;
21
+ type: "success";
22
+ data: T;
23
+ error: null;
24
+ validationError: null;
24
25
  };
25
26
  type ActionState<Data, Error, ValidationError = Record<string, never>> = InitialState<Data> | InvalidState<ValidationError> | FailureState<Error> | SuccessState<Data>;
26
- type FormAction<Data, Error = Data, ValidationError = Record<string, never>, Payload = FormData, Arguments extends unknown[] = []> = (...args: [
27
- ...Arguments,
28
- state: ActionState<Data, Error, ValidationError>,
29
- payload: Payload
30
- ]) => Promise<ActionState<Data, Error, ValidationError>>;
27
+ type FormAction<Data, Error = Data, ValidationError = Record<string, never>, Payload = FormData, Arguments extends unknown[] = []> = (...args: [...Arguments, state: ActionState<Data, Error, ValidationError>, payload: Payload]) => Promise<ActionState<Data, Error, ValidationError>>;
31
28
  declare function initial<Data>(data: Data): InitialState<Data>;
32
29
  declare function createFormAction<Data, Error = Data, ValidationError = Record<string, never>, Payload = FormData, Arguments extends [...unknown[]] = []>(formAction: (params: {
33
- success: (data: Data) => SuccessState<Data>;
34
- failure: (error: Error) => FailureState<Error>;
35
- invalid: (validationError: ValidationError) => InvalidState<ValidationError>;
30
+ success: (data: Data) => SuccessState<Data>;
31
+ failure: (error: Error) => FailureState<Error>;
32
+ invalid: (validationError: ValidationError) => InvalidState<ValidationError>;
36
33
  }, ...args: Arguments) => FormAction<Data, Error, ValidationError, Payload>): (...args: [...Arguments, state: ActionState<Data, Error, ValidationError>, payload: Payload]) => Promise<ActionState<Data, Error, ValidationError>>;
37
-
38
- export { type ActionState as A, type FormAction as F, type InitialState as I, type SuccessState as S, type InvalidState as a, type FailureState as b, createFormAction as c, initial as i };
34
+ //#endregion
35
+ export { InvalidState as a, initial as c, InitialState as i, FailureState as n, SuccessState as o, FormAction as r, createFormAction as s, ActionState as t };
@@ -0,0 +1 @@
1
+ function e(e){return{type:`initial`,data:e,error:null,validationError:null}}function t(e){function t(e){return{type:`success`,data:e,error:null,validationError:null}}function n(e){return{type:`failure`,data:null,error:e,validationError:null}}function r(e){return{type:`invalid`,data:null,error:null,validationError:e}}return(...i)=>{let a=i.pop(),o=i.pop(),s=[...i];return e({success:t,failure:n,invalid:r},...s)(o,a)}}export{e as n,t};
package/dist/index.d.mts CHANGED
@@ -1,68 +1,57 @@
1
- import { A as ActionState, a as InvalidState, b as FailureState, S as SuccessState } from './createFormAction-DjhozgiG.mjs';
2
- export { F as FormAction, I as InitialState, c as createFormAction, i as initial } from './createFormAction-DjhozgiG.mjs';
3
- import { ZodType, z, ZodTuple, ZodObject } from 'zod/v4';
4
- import { $ZodType, $ZodShape, $ZodErrorTree } from 'zod/v4/core';
5
-
1
+ import { a as InvalidState, c as initial, i as InitialState, n as FailureState, o as SuccessState, r as FormAction, s as createFormAction, t as ActionState } from "./createFormAction-4p5Fvn2A.mjs";
2
+ import { ZodObject, ZodTuple, ZodType, z } from "zod/v4";
3
+ import { $ZodErrorTree, $ZodShape, $ZodType } from "zod/v4/core";
4
+ //#region src/formAction.d.ts
6
5
  declare const emptyInput: unique symbol;
7
6
  type EmptyInput = typeof emptyInput;
8
- type Flatten<T> = Identity<{
9
- [K in keyof T]: T[K];
10
- }>;
7
+ type Flatten<T> = Identity<{ [K in keyof T]: T[K]; }>;
11
8
  type Identity<T> = T;
12
9
  type ErrorHandler<Context, Err, Args> = (params: {
13
- error: unknown;
14
- ctx: Context;
15
- args: Args;
10
+ error: unknown;
11
+ ctx: Context;
12
+ args: Args;
16
13
  }) => Promise<Err>;
17
14
  type InitialContext = Record<"formData", FormData>;
18
15
  /**
19
16
  * Action without schema has no input.
20
17
  */
21
18
  type Action<Data, Context, Args extends unknown[]> = (params: {
22
- args: Args;
23
- ctx: Context;
19
+ args: Args;
20
+ ctx: Context;
24
21
  }) => Promise<Data>;
25
22
  /**
26
23
  * Action with schema will get parsed formData as the input.
27
24
  */
28
25
  type SchemaAction<Data, Context, Args extends unknown[], Schema extends ZodType> = (params: {
29
- args: Args;
30
- ctx: Context;
31
- input: z.output<Schema>;
26
+ args: Args;
27
+ ctx: Context;
28
+ input: z.output<Schema>;
32
29
  }) => Promise<Data>;
33
30
  type FormActionBuilder<Schema extends ZodType | EmptyInput, Args extends $ZodType[] = [], TErr = unknown, Context = InitialContext, PlainArgs extends unknown[] = z.output<ZodTuple<Args, null>>> = {
34
- args: <T extends [$ZodType, ...$ZodType[]]>(args: T) => FormActionBuilder<Schema, [...Args, ...T], TErr, Context>;
35
- input: <T extends ZodObject>(newInput: T extends ZodObject ? T : "The schema output must be an object.") => FormActionBuilder<Schema extends ZodObject<infer O1 extends $ZodShape> ? T extends ZodObject<infer O2 extends $ZodShape> ? ZodObject<O1 & O2> : never : T, Args, TErr, Context>;
36
- /**
37
- * A finishing call on the builder completing your action.
38
- * @param action async function to execute. It will receive parsed formData as input, when the builder was initialized with a schema.
39
- * @returns runnable server action exportable from a module.
40
- */
41
- run: Schema extends ZodType ? <Data>(action: SchemaAction<Data, Flatten<Context>, PlainArgs, Schema>) => (...args: [
42
- ...PlainArgs,
43
- state: ActionState<Data, TErr, $ZodErrorTree<z.output<Schema>> & $ZodErrorTree<PlainArgs>>,
44
- payload: FormData
45
- ]) => Promise<Flatten<InvalidState<$ZodErrorTree<z.output<Schema>> & $ZodErrorTree<PlainArgs>> | FailureState<TErr> | SuccessState<Data>>> : <Data>(action: Action<Data, Flatten<Context>, PlainArgs>) => (...args: [
46
- ...PlainArgs,
47
- state: ActionState<Data, TErr, $ZodErrorTree<PlainArgs>>,
48
- payload: FormData
49
- ]) => Promise<Flatten<InvalidState<$ZodErrorTree<PlainArgs>> | FailureState<TErr> | SuccessState<Data>>>;
50
- /**
51
- * A chainable context enhancing helper.
52
- * @param middleware A function which receives the current context, and returns an object which will be added to the context.
53
- * @returns FormActionBuilder
54
- */
55
- use: <NewContext extends Record<string, unknown>>(middleware: ({ ctx }: {
56
- ctx: Context;
57
- }) => Promise<NewContext>) => FormActionBuilder<Schema, Args, TErr, Context & NewContext>;
58
- /**
59
- * A chainable error handler to handle errors thrown while running the action passed to .run().
60
- * It does not receive errors thrown from the context/middleware.
61
- * @param processError A function which receives action's errors.
62
- * @returns FormActionBuilder
63
- */
64
- error: <TErr>(processError: ErrorHandler<Context, TErr, PlainArgs>) => FormActionBuilder<Schema, Args, TErr, Context>;
31
+ args: <T extends [$ZodType, ...$ZodType[]]>(args: T) => FormActionBuilder<Schema, [...Args, ...T], TErr, Context>;
32
+ input: <T extends ZodObject>(newInput: T extends ZodObject ? T : "The schema output must be an object.") => FormActionBuilder<Schema extends ZodObject<infer O1 extends $ZodShape> ? T extends ZodObject<infer O2 extends $ZodShape> ? ZodObject<O1 & O2> : never : T, Args, TErr, Context>;
33
+ /**
34
+ * A finishing call on the builder completing your action.
35
+ * @param action async function to execute. It will receive parsed formData as input, when the builder was initialized with a schema.
36
+ * @returns runnable server action exportable from a module.
37
+ */
38
+ run: Schema extends ZodType ? <Data>(action: SchemaAction<Data, Flatten<Context>, PlainArgs, Schema>) => (...args: [...PlainArgs, state: ActionState<Data, TErr, $ZodErrorTree<z.output<Schema>> & $ZodErrorTree<PlainArgs>>, payload: FormData]) => Promise<Flatten<InvalidState<$ZodErrorTree<z.output<Schema>> & $ZodErrorTree<PlainArgs>> | FailureState<TErr> | SuccessState<Data>>> : <Data>(action: Action<Data, Flatten<Context>, PlainArgs>) => (...args: [...PlainArgs, state: ActionState<Data, TErr, $ZodErrorTree<PlainArgs>>, payload: FormData]) => Promise<Flatten<InvalidState<$ZodErrorTree<PlainArgs>> | FailureState<TErr> | SuccessState<Data>>>;
39
+ /**
40
+ * A chainable context enhancing helper.
41
+ * @param middleware A function which receives the current context, and returns an object which will be added to the context.
42
+ * @returns FormActionBuilder
43
+ */
44
+ use: <NewContext extends Record<string, unknown>>(middleware: ({ ctx }: {
45
+ ctx: Context;
46
+ }) => Promise<NewContext>) => FormActionBuilder<Schema, Args, TErr, Context & NewContext>;
47
+ /**
48
+ * A chainable error handler to handle errors thrown while running the action passed to .run().
49
+ * It does not receive errors thrown from the context/middleware.
50
+ * @param processError A function which receives action's errors.
51
+ * @returns FormActionBuilder
52
+ */
53
+ error: <TErr>(processError: ErrorHandler<Context, TErr, PlainArgs>) => FormActionBuilder<Schema, Args, TErr, Context>;
65
54
  };
66
55
  declare const formAction: FormActionBuilder<typeof emptyInput, [], unknown, InitialContext, []>;
67
-
68
- export { ActionState, FailureState, InvalidState, SuccessState, formAction };
56
+ //#endregion
57
+ export { ActionState, FailureState, FormAction, InitialState, InvalidState, SuccessState, createFormAction, formAction, initial };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as w,b as A}from"./chunk-LPB4R2UB.mjs";import{z as c}from"zod/v4";import{zfd as C}from"zod-form-data";var T=Symbol();function d(r,i=[],a,n){async function f(t){let e={formData:t};for(let p of i){let u=await p({ctx:e});e={...e,...u}}return e}return{args(t){let e=n?[...n,...t]:t;return d(r,i,a,e)},input(t){if(r===T)return d(t,i,a,n);if(r._zod.def.checks)throw new Error("Previous input is not augmentable because it contains an effect.");if(t._zod.def.checks)throw new Error("Your input contains effect which prevents merging it with the previous inputs.");if(r._zod.def.type==="object"){let e=c.object({...r.shape,...t.shape});return d(e,i)}else throw Error("Merging inputs works only for object schemas without effects.")},use(t){return d(r,[...i,t],a,n)},error(t){return d(r,i,t,n)},run:r===T?t=>A(({success:e,failure:p,invalid:u},...s)=>async(y,g)=>{let x=await f(g);if(n){let o=c.tuple(n).safeParse(s);if(!o.success)return u(c.treeifyError(o.error))}try{return e(await t({args:s,ctx:x}))}catch(o){if(a)return p(await a({args:s,error:o,ctx:x}));throw o}}):r===T?void 0:t=>A(({success:e,failure:p,invalid:u},...s)=>{let y=C.formData(r);return async(g,x)=>{let o=await f(x);if(n){let l=c.tuple(n).safeParse(s);if(!l.success)return u(c.treeifyError(l.error))}let m=y.safeParse(x);if(!m.success)return u(c.treeifyError(m.error));let E=m.data;try{return e(await t({args:s,input:E,ctx:o}))}catch(l){if(a)return p(await a({args:s,error:l,ctx:o}));throw l}}})}}var k=d(T);export{A as createFormAction,k as formAction,w as initial};
1
+ import{n as e,t}from"./createFormAction-BwMYAzm2.mjs";import{z as n}from"zod/v4";import{zfd as r}from"zod-form-data";const i=Symbol();function a(e,o=[],s,c){async function l(e){let t={formData:e};for(let e of o){let n=await e({ctx:t});t={...t,...n}}return t}return{args(t){return a(e,o,s,c?[...c,...t]:t)},input(t){if(e===i)return a(t,o,s,c);if(e._zod.def.checks)throw Error(`Previous input is not augmentable because it contains an effect.`);if(t._zod.def.checks)throw Error(`Your input contains effect which prevents merging it with the previous inputs.`);if(e._zod.def.type===`object`)return a(n.object({...e.shape,...t.shape}),o,s,c);throw Error(`Merging inputs works only for object schemas without effects.`)},use(t){return a(e,[...o,t],s,c)},error(t){return a(e,o,t,c)},run:e===i?e=>t(({success:t,failure:r,invalid:i},...a)=>async(o,u)=>{let d=await l(u);if(c){let e=n.tuple(c).safeParse(a);if(!e.success)return i(n.treeifyError(e.error))}try{return t(await e({args:a,ctx:d}))}catch(e){if(s)return r(await s({args:a,error:e,ctx:d}));throw e}}):e===i?void 0:i=>t(({success:t,failure:a,invalid:o},...u)=>{let d=r.formData(e);return async(e,r)=>{let f=await l(r);if(c){let e=n.tuple(c).safeParse(u);if(!e.success)return o(n.treeifyError(e.error))}let p=d.safeParse(r);if(!p.success)return o(n.treeifyError(p.error));let m=p.data;try{return t(await i({args:u,input:m,ctx:f}))}catch(e){if(s)return a(await s({args:u,error:e,ctx:f}));throw e}}})}}const o=a(i);export{t as createFormAction,o as formAction,e as initial};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-form-action",
3
- "version": "2.9.1",
3
+ "version": "2.9.2",
4
4
  "description": "State management helpers for the react form actions.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,7 @@
12
12
  "/dist"
13
13
  ],
14
14
  "scripts": {
15
- "build": "tsup",
15
+ "build": "tsdown src/index.ts src/client.ts --minify",
16
16
  "test": "vitest",
17
17
  "typecheck": "vitest --typecheck",
18
18
  "format": "prettier . --write",
@@ -56,21 +56,21 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@testing-library/dom": "^10.4.1",
59
- "@testing-library/jest-dom": "^6.9.1",
60
- "@testing-library/react": "^16.3.0",
59
+ "@testing-library/jest-dom": "^7.0.0",
60
+ "@testing-library/react": "^16.3.2",
61
61
  "@testing-library/user-event": "^14.6.1",
62
- "@types/react": "^19.2.2",
63
- "@types/react-dom": "^19.2.2",
64
- "@vitejs/plugin-react": "^5.1.0",
65
- "happy-dom": "^20.0.8",
66
- "npm-check-updates": "^19.1.1",
67
- "prettier": "^3.6.2",
68
- "react": "^19.2.0",
69
- "react-dom": "^19.2.0",
70
- "tsup": "^8.5.0",
71
- "typescript": "^5.9.3",
72
- "vitest": "^4.0.4",
62
+ "@types/react": "^19.2.17",
63
+ "@types/react-dom": "^19.2.3",
64
+ "@vitejs/plugin-react": "^6.0.3",
65
+ "happy-dom": "^20.11.0",
66
+ "npm-check-updates": "^22.2.9",
67
+ "prettier": "^3.9.6",
68
+ "react": "^19.2.7",
69
+ "react-dom": "^19.2.7",
70
+ "tsdown": "^0.22.12",
71
+ "typescript": "^6.0.3",
72
+ "vitest": "^4.1.10",
73
73
  "zod": "^3.25.0",
74
- "zod-form-data": "^3.0.1"
74
+ "zod-form-data": "^3.0.3"
75
75
  }
76
76
  }
@@ -1 +0,0 @@
1
- function u(a){return{type:"initial",data:a,error:null,validationError:null}}function d(a){function t(r){return{type:"success",data:r,error:null,validationError:null}}function o(r){return{type:"failure",data:null,error:r,validationError:null}}function n(r){return{type:"invalid",data:null,error:null,validationError:r}}return(...r)=>{let e=r.pop(),i=r.pop(),l=[...r];return a({success:t,failure:o,invalid:n},...l)(i,e)}}export{u as a,d as b};