react-form-action 0.3.0 → 0.4.1

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 CHANGED
@@ -22,7 +22,7 @@ End-to-end typesafe success, error & validation state control for Next.js 14 for
22
22
  ## Install
23
23
 
24
24
  ```
25
- npm i react-form-action
25
+ npm i react-form-action zod-form-data
26
26
  ```
27
27
 
28
28
  ## Usage
@@ -37,8 +37,6 @@ import { formAction } from "react-form-action";
37
37
  import { z } from "zod";
38
38
  import { cookies } from "next/headers";
39
39
 
40
- const emailSchema = z.object({ email: z.string().email() });
41
-
42
40
  const i18nMiddleware = async () => {
43
41
  const { t } = await useTranslation("auth", cookies().get("i18n")?.value);
44
42
  // will be added to context
@@ -46,7 +44,6 @@ const i18nMiddleware = async () => {
46
44
  };
47
45
 
48
46
  const authAction = formAction
49
- .input(emailschema)
50
47
  .use(i18nMiddleware)
51
48
  .use(async ({ ctx: { t } }) =>
52
49
  console.log("🎉 context enhanced by previous middlewares 🎉", t)
@@ -61,25 +58,39 @@ const authAction = formAction
61
58
  }
62
59
  });
63
60
 
64
- export const resendVerifyEmailAction = authAction.run(
65
- async ({ ctx: { t }, input: { email } }) => {
66
- // do custom work
67
- await db.resendVerificationEmail({ email });
61
+ export const signIn = authAction
62
+ .input(z.object({ email: z.string().email() }))
63
+ // 🎉 extend the previous input (only without refinements and transforms)
64
+ .input(z.object({ password: z.string() }))
65
+ .run(async ({ ctx: { t }, input: { email, password } }) => {
66
+ // Type inferred: {email: string, password: string}
67
+
68
+ await db.signIn({ email, password });
68
69
 
69
- // return translated success message
70
70
  return t("verificationEmail.success");
71
- }
72
- );
71
+ });
73
72
 
74
- export const signUp = authAction
75
- // extend the input
76
- .input(z.object({ password: z.string() }))
73
+ import { formAction } from "react-fomr-action";
74
+
75
+ export const signUp = formAction
76
+ .input(
77
+ z
78
+ .object({
79
+ email: z.string().email(),
80
+ password: z.string(),
81
+ confirm: z.string(),
82
+ })
83
+ .refine((data) => data.password === data.confirm, {
84
+ message: "Passwords don't match",
85
+ path: ["confirm"],
86
+ })
87
+ ) // if using refinement, only one input call is permited, as schema with ZodEffects is not extendable.
77
88
  .run(async ({ ctx: { t }, input: { email, password } }) => {
78
- // do custom work
79
- await db.signupWithEmailAndPassword({ email, password });
89
+ // 🎉 passwords match!
90
+
91
+ await db.signUp({ email, password });
80
92
 
81
- // return translated success message
82
- return t("signUp.success");
93
+ return "We've sent you an email!";
83
94
  });
84
95
  ```
85
96
 
package/dist/index.d.mts CHANGED
@@ -1,7 +1,9 @@
1
- import { F as FormState, a as FailureState, S as SuccessState, I as InvalidState } from './createFormAction-3a51310f.js';
1
+ import { F as FormState, I as InvalidState, a as FailureState, S as SuccessState } from './createFormAction-3a51310f.js';
2
2
  export { b as InitialState, c as createFormAction } from './createFormAction-3a51310f.js';
3
- import { z, ZodRawShape, ZodObject, objectUtil, ZodSchema } from 'zod';
3
+ import { ZodTypeAny, ZodType, ZodObject, ZodRawShape, objectUtil, z, ZodSchema, ZodEffects } from 'zod';
4
4
 
5
+ declare const emptyInput: unique symbol;
6
+ type EmptyInput = typeof emptyInput;
5
7
  type Flatten<T> = Identity<{
6
8
  [K in keyof T]: T[K];
7
9
  }>;
@@ -20,15 +22,15 @@ type SchemaAction<Data, Context, Schema extends ZodSchema> = (params: {
20
22
  ctx: Context;
21
23
  input: z.infer<Schema>;
22
24
  }) => Promise<Data>;
23
- type EmptyZodObject = ZodObject<ZodRawShape>;
24
- type FormActionBuilder<Schema extends EmptyZodObject, Err = Error, Context = InitialContext> = {
25
- input: <T extends ZodRawShape>(schema: ZodObject<T>) => FormActionBuilder<ZodObject<objectUtil.extendShape<T, Schema["shape"]>>, Err, Context>;
25
+ type AnyZodEffects = ZodEffects<any, any, any>;
26
+ type FormActionBuilder<Schema extends ZodTypeAny | EmptyInput, Err = Error, Context = InitialContext> = {
27
+ input: <T extends ZodTypeAny>(newInput: T extends ZodType<infer Out extends Record<string, unknown>> ? Schema extends AnyZodEffects ? "Extending schema with effect is not possible." : Schema extends EmptyInput ? T : Schema extends ZodTypeAny ? T extends AnyZodEffects ? "Your input contains effect which prevents merging it with the previous inputs." : T : T : "The schema output must be an object.") => FormActionBuilder<Schema extends ZodObject<infer O1 extends ZodRawShape> ? T extends ZodObject<infer O2 extends ZodRawShape> ? ZodObject<objectUtil.extendShape<O1, O2>> : never : T, Err, Context>;
26
28
  /**
27
29
  * A finishing call on the builder completing your action.
28
30
  * @param action async function to execute. It will receive parsed formData as input, when the builder was initialized with a schema.
29
31
  * @returns runnable server action exportable from a module.
30
32
  */
31
- run: Schema extends undefined ? <Data>(action: Action<Data, Context>) => (state: FormState<Data, Err>, payload: FormData) => Promise<Flatten<FailureState<Err> | SuccessState<Data>>> : <Data>(action: SchemaAction<Data, Context, Schema>) => (state: FormState<Data, Err, z.inferFlattenedErrors<Schema>>, payload: FormData) => Promise<Flatten<InvalidState<z.inferFlattenedErrors<Schema>> | FailureState<Err> | SuccessState<Data>>>;
33
+ run: Schema extends ZodTypeAny ? <Data>(action: SchemaAction<Data, Context, Schema>) => (state: FormState<Data, Err, z.inferFlattenedErrors<Schema>>, payload: FormData) => Promise<Flatten<InvalidState<z.inferFlattenedErrors<Schema>> | FailureState<Err> | SuccessState<Data>>> : <Data>(action: Action<Data, Context>) => (state: FormState<Data, Err>, payload: FormData) => Promise<Flatten<FailureState<Err> | SuccessState<Data>>>;
32
34
  /**
33
35
  * A chainable context enhancing helper.
34
36
  * @param middleware A function which receives the current context, and returns an object which will be added to the context.
@@ -48,6 +50,6 @@ type FormActionBuilder<Schema extends EmptyZodObject, Err = Error, Context = Ini
48
50
  ctx: Context;
49
51
  }) => Err) => FormActionBuilder<Schema, Err, Context>;
50
52
  };
51
- declare const formAction: FormActionBuilder<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, Error, InitialContext>;
53
+ declare const formAction: FormActionBuilder<typeof emptyInput, Error, InitialContext>;
52
54
 
53
55
  export { FailureState, FormState, InvalidState, SuccessState, formAction };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- function p(a){function o(e){return{type:"success",data:e,error:null,validationError:null}}function n(e){return{type:"failure",data:null,error:e,validationError:null}}function l(e){return{type:"invalid",data:null,error:null,validationError:e}}return(e,s)=>a({success:o,failure:n,invalid:l})(e,s)}import{z as D}from"zod";import{zfd as h}from"zod-form-data";function u(a,o=[],n){async function l(t){let r={formData:t};for(let i of o){let d=await i({ctx:r});r={...r,...d}}return r}let e=t=>p(({success:r,failure:i})=>async(d,x)=>{let m=await l(x);try{return r(await t({ctx:m}))}catch(c){if(n)return i(n({error:c,ctx:m}));throw c}}),s=t=>p(({success:r,failure:i,invalid:d})=>{let x=h.formData(a);return async(m,c)=>{let E=await l(c),S=x.safeParse(c);if(!S.success)return d(S.error.flatten());let y=S.data;try{return r(await t({input:y,ctx:E}))}catch(C){if(n)return i(n({error:C,ctx:E}));throw C}}});return{input(t){let r=a.merge(t);return u(r,o)},use(t){return u(a,[...o,t])},error(t){return u(a,o,t)},run:Object.keys(a.shape).length===0?e:s}}var j=u(D.object({}));export{p as createFormAction,j as formAction};
1
+ function y(e){function o(a){return{type:"success",data:a,error:null,validationError:null}}function n(a){return{type:"failure",data:null,error:a,validationError:null}}function s(a){return{type:"invalid",data:null,error:null,validationError:a}}return(a,S)=>e({success:o,failure:n,invalid:s})(a,S)}import{ZodFirstPartyTypeKind as C}from"zod";import{zfd as w}from"zod-form-data";var l=Symbol();function d(e,o=[],n){async function s(t){let r={formData:t};for(let i of o){let u=await i({ctx:r});r={...r,...u}}return r}return{input(t){if(e===l)return d(t,o,n);if(e._def.effect)throw new Error("Previous input is not augmentable because it contains an effect.");if(t._def.effect)throw new Error("Your input contains effect which prevents merging it with the previous inputs.");if(e._def.typeName===C.ZodObject){let r=e.merge(t);return d(r,o)}else throw Error("Merging inputs works only for object schemas without effects.")},use(t){return d(e,[...o,t],n)},error(t){return d(e,o,t)},run:e===l?t=>y(({success:r,failure:i})=>async(u,x)=>{let p=await s(x);try{return r(await t({ctx:p}))}catch(c){if(n)return i(n({error:c,ctx:p}));throw c}}):e===l?void 0:t=>y(({success:r,failure:i,invalid:u})=>{let x=w.formData(e);return async(p,c)=>{let f=await s(c),m=x.safeParse(c);if(!m.success)return u(m.error.flatten());let h=m.data;try{return r(await t({input:h,ctx:f}))}catch(E){if(n)return i(n({error:E,ctx:f}));throw E}}})}}var b=d(l);export{y as createFormAction,b as formAction};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-form-action",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "State management helpers for the react form actions.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,7 +13,8 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "build": "tsup",
16
- "test": "vitest"
16
+ "test": "vitest",
17
+ "typecheck": "vitest --typecheck"
17
18
  },
18
19
  "exports": {
19
20
  ".": {