@omer-x/next-form-actions 1.0.0-alpha.0 → 1.0.0-alpha.3

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.
@@ -1,21 +1,22 @@
1
- import { ZodType, ZodObject } from 'zod';
1
+ import { ZodObject, ZodType } from "zod";
2
2
 
3
+ //#region src/core/defineFormAction.d.ts
3
4
  /**
4
5
  * Describes the definition of a type-safe server action for forms.
5
6
  */
6
7
  type ActionDefinition<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]> = {
7
- /**
8
- * An array of middleware functions to execute before the action. (Optional)
9
- */
10
- middlewares?: (() => void | Promise<void>)[];
11
- /**
12
- * The Zod schema used to validate form data.
13
- */
14
- schema: ZodType<SchemaO, SchemaI> & ZodObject<Shape>;
15
- /**
16
- * The function to execute if validation succeeds. Receives parsed data and returns a function for additional arguments.
17
- */
18
- action: (input: SchemaO) => ((...args: [...Args]) => Promise<Partial<Record<string, string>>>);
8
+ /**
9
+ * An array of middleware functions to execute before the action. (Optional)
10
+ */
11
+ middlewares?: (() => void | Promise<void>)[];
12
+ /**
13
+ * The Zod schema used to validate form data.
14
+ */
15
+ schema: ZodType<SchemaO, SchemaI> & ZodObject<Shape>;
16
+ /**
17
+ * The function to execute if validation succeeds. Receives parsed data and returns a function for additional arguments.
18
+ */
19
+ action: (input: SchemaO) => ((...args: [...Args]) => Promise<Partial<Record<string, string>>>);
19
20
  };
20
21
  type FormAction<Args extends unknown[]> = (...allParams: [...Args, initialState: unknown, formData: FormData]) => Promise<Record<string, string>>;
21
22
  /**
@@ -29,7 +30,8 @@ type FormAction<Args extends unknown[]> = (...allParams: [...Args, initialState:
29
30
  * @returns An object containing the server action handler keyed by the action name.
30
31
  */
31
32
  declare function defineFormAction<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]>(definition: ActionDefinition<Shape, SchemaI, SchemaO, Args>): FormAction<Args>;
32
-
33
- declare function displayMessage(messageType: "error" | "warning" | "success", message: string): never;
34
-
35
- export { defineFormAction, displayMessage };
33
+ //#endregion
34
+ //#region src/core/displayMessage.d.ts
35
+ declare function displayMessage(messageType: "error" | "warning" | "success" | (string & {}), message: string): never;
36
+ //#endregion
37
+ export { defineFormAction, displayMessage };
package/dist/index.mjs ADDED
@@ -0,0 +1,105 @@
1
+ //#region src/core/bundleErrors.ts
2
+ /**
3
+ * Maps a Zod issue to a string error code or message.
4
+ * @param issue - The Zod issue object.
5
+ * @returns The error code or message for the issue.
6
+ */
7
+ function handleZodIssue(issue) {
8
+ switch (issue.code) {
9
+ case "custom": {
10
+ const params = issue.params ?? {};
11
+ if ("customErrorCode" in params && typeof params.customErrorCode === "string") return params.customErrorCode;
12
+ return issue.message;
13
+ }
14
+ case "invalid_format": return `invalid_${issue.format}`;
15
+ case "invalid_type":
16
+ if (/expected .+?, received undefined/.test(issue.message)) return "required";
17
+ return issue.code;
18
+ case "too_small":
19
+ case "too_big": return issue.code;
20
+ default: return "unknown_error";
21
+ }
22
+ }
23
+ /**
24
+ * Bundles an array of Zod issues into a record mapping field locations to error codes/messages.
25
+ * @param issues - Array of Zod issues.
26
+ * @returns An object mapping field names to error codes/messages.
27
+ */
28
+ function bundleErrors(issues) {
29
+ return issues.reduce((bundle, issue) => {
30
+ const [location] = issue.path;
31
+ return {
32
+ ...bundle,
33
+ [location]: handleZodIssue(issue).toUpperCase()
34
+ };
35
+ }, {});
36
+ }
37
+ //#endregion
38
+ //#region src/core/solveKnownIssues.ts
39
+ function solveKnownIssues(schema, input) {
40
+ const validation = schema.safeParse(input);
41
+ if (!validation.success) {
42
+ for (const issue of validation.error.issues) if (issue.code === "invalid_type") {
43
+ if (issue.expected === "number" && issue.message.includes("expected number, received string")) {
44
+ const [location] = issue.path;
45
+ return solveKnownIssues(schema, {
46
+ ...input,
47
+ [location]: parseFloat(input[location])
48
+ });
49
+ }
50
+ if (issue.expected === "boolean" && issue.message.includes("expected boolean, received string")) {
51
+ const [location] = issue.path;
52
+ const value = input[location];
53
+ if (value === "true" || value === "false") return solveKnownIssues(schema, {
54
+ ...input,
55
+ [location]: value === "true"
56
+ });
57
+ }
58
+ }
59
+ }
60
+ return validation;
61
+ }
62
+ //#endregion
63
+ //#region src/core/defineFormAction.ts
64
+ /**
65
+ * Defines a type-safe React server action for forms, validating form data with Zod and handling errors internally.
66
+ *
67
+ * @param definition - The form action definition object.
68
+ * @param definition.name - The unique name of the action.
69
+ * @param definition.middleware - An array of middleware functions to execute before the action. (Optional)
70
+ * @param definition.schema - The Zod schema used to validate form data.
71
+ * @param definition.action - The function to execute if validation succeeds.
72
+ * @returns An object containing the server action handler keyed by the action name.
73
+ */
74
+ function defineFormAction(definition) {
75
+ async function handler(...allParams) {
76
+ if (definition.middlewares) await Promise.all(definition.middlewares.map((middleware) => middleware()));
77
+ const formData = allParams[allParams.length - 1];
78
+ const customArgs = allParams.slice(0, allParams.length - 2);
79
+ const validation = solveKnownIssues(definition.schema.strip(), Object.fromEntries(formData.entries()));
80
+ if (!validation.success) return bundleErrors(validation.error.issues);
81
+ try {
82
+ return await definition.action(validation.data)(...customArgs);
83
+ } catch (error) {
84
+ if (error && typeof error === "object" && "isDisplayMessage" in error && "messageType" in error && "message" in error) return { [error.messageType]: error.message };
85
+ throw error;
86
+ }
87
+ }
88
+ return handler;
89
+ }
90
+ //#endregion
91
+ //#region src/core/displayMessage.ts
92
+ function displayMessage(messageType, message) {
93
+ if (messageType === "error" || messageType === "warning" || messageType === "success") throw {
94
+ isDisplayMessage: true,
95
+ messageType: `[${messageType}]`,
96
+ message
97
+ };
98
+ throw {
99
+ isDisplayMessage: true,
100
+ messageType,
101
+ message
102
+ };
103
+ }
104
+ //#endregion
105
+ export { defineFormAction, displayMessage };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omer-x/next-form-actions",
3
- "version": "1.0.0-alpha.0",
3
+ "version": "1.0.0-alpha.3",
4
4
  "description": "Provides helper functions to define a type-safe React server action for forms, validating form data with Zod and handling errors internally.",
5
5
  "keywords": [
6
6
  "nextjs",
@@ -28,14 +28,15 @@
28
28
  },
29
29
  "license": "MIT",
30
30
  "type": "module",
31
+ "main": "./dist/index.mjs",
32
+ "types": "./dist/index.d.mts",
31
33
  "files": [
32
34
  "dist/"
33
35
  ],
34
36
  "exports": {
35
37
  ".": {
36
- "types": "./dist/index.d.ts",
37
- "import": "./dist/index.js",
38
- "require": "./dist/index.cjs"
38
+ "types": "./dist/index.d.mts",
39
+ "import": "./dist/index.mjs"
39
40
  }
40
41
  },
41
42
  "scripts": {
@@ -43,20 +44,20 @@
43
44
  "lint:fix": "eslint --fix --flag unstable_native_nodejs_ts_config",
44
45
  "test": "vitest run --coverage",
45
46
  "test:watch": "vitest --coverage",
46
- "dev": "tsup --watch",
47
- "build": "tsup"
47
+ "dev": "tsdown --watch",
48
+ "build": "tsdown"
48
49
  },
49
50
  "peerDependencies": {
50
51
  "zod": "^4"
51
52
  },
52
53
  "devDependencies": {
53
- "@omer-x/eslint-config": "^2.2.6",
54
- "@types/node": "^25.0.10",
55
- "@vitest/coverage-v8": "^4.0.17",
54
+ "@omer-x/eslint-config": "^2.3.2",
55
+ "@types/node": "^26.1.0",
56
+ "@vitest/coverage-v8": "^4.1.9",
56
57
  "eslint": "^9.39.2",
57
- "semantic-release": "^25.0.2",
58
- "tsup": "^8.5.1",
59
- "typescript": "^5.9.3",
60
- "vitest": "^4.0.17"
58
+ "semantic-release": "^25.0.5",
59
+ "tsdown": "^0.22.3",
60
+ "typescript": "^6.0.3",
61
+ "vitest": "^4.1.9"
61
62
  }
62
63
  }
package/dist/index.cjs DELETED
@@ -1,109 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- defineFormAction: () => defineFormAction,
24
- displayMessage: () => displayMessage
25
- });
26
- module.exports = __toCommonJS(index_exports);
27
-
28
- // src/core/bundleErrors.ts
29
- function handleZodIssue(issue) {
30
- switch (issue.code) {
31
- case "custom": {
32
- const params = issue.params ?? {};
33
- if ("customErrorCode" in params && typeof params.customErrorCode === "string") {
34
- return params.customErrorCode;
35
- }
36
- return issue.message;
37
- }
38
- case "invalid_format":
39
- return `invalid_${issue.format}`;
40
- // e.g., INVALID_EMAIL, INVALID_URL, INVALID_UUID
41
- case "invalid_type": {
42
- if (/expected .+?, received undefined/.test(issue.message)) {
43
- return "required";
44
- }
45
- return issue.code;
46
- }
47
- case "too_small":
48
- case "too_big":
49
- return issue.code;
50
- // known errors
51
- default:
52
- return "unknown_error";
53
- }
54
- }
55
- function bundleErrors(issues) {
56
- return issues.reduce((bundle, issue) => {
57
- const [location] = issue.path;
58
- return {
59
- ...bundle,
60
- [location]: handleZodIssue(issue).toUpperCase()
61
- };
62
- }, {});
63
- }
64
-
65
- // src/core/solveKnownIssues.ts
66
- function solveKnownIssues(schema, input) {
67
- const validation = schema.safeParse(input);
68
- if (!validation.success) {
69
- for (const issue of validation.error.issues) {
70
- if (issue.code === "invalid_type") {
71
- if (issue.expected === "number" && issue.message.includes("expected number, received string")) {
72
- const [location] = issue.path;
73
- return solveKnownIssues(schema, {
74
- ...input,
75
- [location]: parseFloat(input[location])
76
- });
77
- }
78
- }
79
- }
80
- }
81
- return validation;
82
- }
83
-
84
- // src/core/defineFormAction.ts
85
- function defineFormAction(definition) {
86
- async function handler(...allParams) {
87
- if (definition.middlewares) {
88
- await Promise.all(definition.middlewares.map((middleware) => middleware()));
89
- }
90
- const formData = allParams[allParams.length - 1];
91
- const customArgs = allParams.slice(0, allParams.length - 2);
92
- const validation = solveKnownIssues(definition.schema.strip(), Object.fromEntries(formData.entries()));
93
- if (!validation.success) {
94
- return bundleErrors(validation.error.issues);
95
- }
96
- return await definition.action(validation.data)(...customArgs);
97
- }
98
- return handler;
99
- }
100
-
101
- // src/core/displayMessage.ts
102
- function displayMessage(messageType, message) {
103
- throw { isDisplayMessage: true, messageType, message };
104
- }
105
- // Annotate the CommonJS export names for ESM import in node:
106
- 0 && (module.exports = {
107
- defineFormAction,
108
- displayMessage
109
- });
package/dist/index.d.ts DELETED
@@ -1,35 +0,0 @@
1
- import { ZodType, ZodObject } from 'zod';
2
-
3
- /**
4
- * Describes the definition of a type-safe server action for forms.
5
- */
6
- type ActionDefinition<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]> = {
7
- /**
8
- * An array of middleware functions to execute before the action. (Optional)
9
- */
10
- middlewares?: (() => void | Promise<void>)[];
11
- /**
12
- * The Zod schema used to validate form data.
13
- */
14
- schema: ZodType<SchemaO, SchemaI> & ZodObject<Shape>;
15
- /**
16
- * The function to execute if validation succeeds. Receives parsed data and returns a function for additional arguments.
17
- */
18
- action: (input: SchemaO) => ((...args: [...Args]) => Promise<Partial<Record<string, string>>>);
19
- };
20
- type FormAction<Args extends unknown[]> = (...allParams: [...Args, initialState: unknown, formData: FormData]) => Promise<Record<string, string>>;
21
- /**
22
- * Defines a type-safe React server action for forms, validating form data with Zod and handling errors internally.
23
- *
24
- * @param definition - The form action definition object.
25
- * @param definition.name - The unique name of the action.
26
- * @param definition.middleware - An array of middleware functions to execute before the action. (Optional)
27
- * @param definition.schema - The Zod schema used to validate form data.
28
- * @param definition.action - The function to execute if validation succeeds.
29
- * @returns An object containing the server action handler keyed by the action name.
30
- */
31
- declare function defineFormAction<Shape extends Record<string, ZodType>, SchemaI, SchemaO, Args extends unknown[]>(definition: ActionDefinition<Shape, SchemaI, SchemaO, Args>): FormAction<Args>;
32
-
33
- declare function displayMessage(messageType: "error" | "warning" | "success", message: string): never;
34
-
35
- export { defineFormAction, displayMessage };
package/dist/index.js DELETED
@@ -1,81 +0,0 @@
1
- // src/core/bundleErrors.ts
2
- function handleZodIssue(issue) {
3
- switch (issue.code) {
4
- case "custom": {
5
- const params = issue.params ?? {};
6
- if ("customErrorCode" in params && typeof params.customErrorCode === "string") {
7
- return params.customErrorCode;
8
- }
9
- return issue.message;
10
- }
11
- case "invalid_format":
12
- return `invalid_${issue.format}`;
13
- // e.g., INVALID_EMAIL, INVALID_URL, INVALID_UUID
14
- case "invalid_type": {
15
- if (/expected .+?, received undefined/.test(issue.message)) {
16
- return "required";
17
- }
18
- return issue.code;
19
- }
20
- case "too_small":
21
- case "too_big":
22
- return issue.code;
23
- // known errors
24
- default:
25
- return "unknown_error";
26
- }
27
- }
28
- function bundleErrors(issues) {
29
- return issues.reduce((bundle, issue) => {
30
- const [location] = issue.path;
31
- return {
32
- ...bundle,
33
- [location]: handleZodIssue(issue).toUpperCase()
34
- };
35
- }, {});
36
- }
37
-
38
- // src/core/solveKnownIssues.ts
39
- function solveKnownIssues(schema, input) {
40
- const validation = schema.safeParse(input);
41
- if (!validation.success) {
42
- for (const issue of validation.error.issues) {
43
- if (issue.code === "invalid_type") {
44
- if (issue.expected === "number" && issue.message.includes("expected number, received string")) {
45
- const [location] = issue.path;
46
- return solveKnownIssues(schema, {
47
- ...input,
48
- [location]: parseFloat(input[location])
49
- });
50
- }
51
- }
52
- }
53
- }
54
- return validation;
55
- }
56
-
57
- // src/core/defineFormAction.ts
58
- function defineFormAction(definition) {
59
- async function handler(...allParams) {
60
- if (definition.middlewares) {
61
- await Promise.all(definition.middlewares.map((middleware) => middleware()));
62
- }
63
- const formData = allParams[allParams.length - 1];
64
- const customArgs = allParams.slice(0, allParams.length - 2);
65
- const validation = solveKnownIssues(definition.schema.strip(), Object.fromEntries(formData.entries()));
66
- if (!validation.success) {
67
- return bundleErrors(validation.error.issues);
68
- }
69
- return await definition.action(validation.data)(...customArgs);
70
- }
71
- return handler;
72
- }
73
-
74
- // src/core/displayMessage.ts
75
- function displayMessage(messageType, message) {
76
- throw { isDisplayMessage: true, messageType, message };
77
- }
78
- export {
79
- defineFormAction,
80
- displayMessage
81
- };