@arkyn/server 3.0.1-beta.76 → 3.0.1-beta.77
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/bundle.js +252 -109
- package/dist/bundle.umd.cjs +7 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/services/formAsyncParse.d.ts +59 -0
- package/dist/services/formAsyncParse.d.ts.map +1 -0
- package/dist/services/formAsyncParse.js +58 -0
- package/dist/services/schemaValidator.d.ts +145 -0
- package/dist/services/schemaValidator.d.ts.map +1 -1
- package/dist/services/schemaValidator.js +158 -0
- package/package.json +1 -1
package/dist/bundle.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var o = (e, t, s) =>
|
|
1
|
+
var U = Object.defineProperty;
|
|
2
|
+
var C = (e, t, s) => t in e ? U(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
|
|
3
|
+
var o = (e, t, s) => C(e, typeof t != "symbol" ? t + "" : t, s);
|
|
4
4
|
import "zod";
|
|
5
|
-
import { removeNonNumeric as
|
|
6
|
-
import
|
|
7
|
-
import { countries as
|
|
5
|
+
import { removeNonNumeric as N } from "@arkyn/shared";
|
|
6
|
+
import v from "node:dns";
|
|
7
|
+
import { countries as j } from "@arkyn/templates";
|
|
8
8
|
function g(e) {
|
|
9
9
|
var s;
|
|
10
10
|
if (process.env.NODE_ENV === "development" || ((s = process.env) == null ? void 0 : s.SHOW_ERRORS_IN_CONSOLE) === "true") {
|
|
@@ -22,7 +22,7 @@ function g(e) {
|
|
|
22
22
|
}), console.log(c);
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
const
|
|
25
|
+
const k = {};
|
|
26
26
|
class $ {
|
|
27
27
|
/**
|
|
28
28
|
* Sets the file name to be ignored during stack trace analysis.
|
|
@@ -63,7 +63,7 @@ class $ {
|
|
|
63
63
|
* When set, the `getCaller` function will skip stack frames containing this file name.
|
|
64
64
|
*/
|
|
65
65
|
o($, "ignoreFiles", []);
|
|
66
|
-
function
|
|
66
|
+
function E() {
|
|
67
67
|
const e = process.cwd(), n = (new Error().stack || "").split(`
|
|
68
68
|
`).map((u) => u.trim()), r = $.ignoreFiles;
|
|
69
69
|
let a = 2;
|
|
@@ -92,18 +92,18 @@ function N() {
|
|
|
92
92
|
i.lastIndexOf(")")
|
|
93
93
|
)), i = i.split(":").slice(0, -2).join(":");
|
|
94
94
|
try {
|
|
95
|
-
i =
|
|
95
|
+
i = k.relative(e, i);
|
|
96
96
|
} catch {
|
|
97
97
|
}
|
|
98
98
|
return { functionName: h, callerInfo: i };
|
|
99
99
|
}
|
|
100
100
|
class y {
|
|
101
101
|
onDebug(t) {
|
|
102
|
-
const { name: s, body: n, cause: r, message: a } = t, c = [], { callerInfo: h, functionName: i } =
|
|
102
|
+
const { name: s, body: n, cause: r, message: a } = t, c = [], { callerInfo: h, functionName: i } = E();
|
|
103
103
|
c.push(`${s} initialized`), c.push(`Caller Function: ${i}`), c.push(`Caller Location: ${h}`), a && c.push(`Message: ${a}`), n && c.push(`Body: ${JSON.stringify(n, null, 2)}`), r && c.push(`Cause: ${JSON.stringify(r, null, 2)}`), g({ scheme: "red", name: "ARKYN-BAD-RESPONSE-DEBUG", debugs: c });
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
|
-
class
|
|
106
|
+
class J extends y {
|
|
107
107
|
/**
|
|
108
108
|
* Creates an instance of the `BadGateway` class.
|
|
109
109
|
*
|
|
@@ -151,7 +151,7 @@ class j extends y {
|
|
|
151
151
|
return Response.json(this.body, s);
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
|
-
class
|
|
154
|
+
class b extends y {
|
|
155
155
|
/**
|
|
156
156
|
* Creates an instance of the `BadRequest` class.
|
|
157
157
|
*
|
|
@@ -391,7 +391,7 @@ class q extends y {
|
|
|
391
391
|
return Response.json(this.body, s);
|
|
392
392
|
}
|
|
393
393
|
}
|
|
394
|
-
class
|
|
394
|
+
class x extends y {
|
|
395
395
|
/**
|
|
396
396
|
* Creates an instance of the `ServerError` class.
|
|
397
397
|
*
|
|
@@ -487,7 +487,7 @@ class F extends y {
|
|
|
487
487
|
return Response.json(this.body, s);
|
|
488
488
|
}
|
|
489
489
|
}
|
|
490
|
-
class
|
|
490
|
+
class R extends y {
|
|
491
491
|
/**
|
|
492
492
|
* Creates an instance of the `UnprocessableEntity` class.
|
|
493
493
|
*
|
|
@@ -558,7 +558,7 @@ class m {
|
|
|
558
558
|
* ```
|
|
559
559
|
*/
|
|
560
560
|
onDebug(t, s, n) {
|
|
561
|
-
const r = [], { callerInfo: a, functionName: c } =
|
|
561
|
+
const r = [], { callerInfo: a, functionName: c } = E();
|
|
562
562
|
r.push(`${t} initialized
|
|
563
563
|
`), r.push(`Caller Function: ${c}
|
|
564
564
|
`), r.push(`Caller Location: ${a}
|
|
@@ -571,7 +571,7 @@ class m {
|
|
|
571
571
|
});
|
|
572
572
|
}
|
|
573
573
|
}
|
|
574
|
-
class
|
|
574
|
+
class P extends m {
|
|
575
575
|
/**
|
|
576
576
|
* Creates an instance of the `Created` class.
|
|
577
577
|
*
|
|
@@ -615,7 +615,7 @@ class Y extends m {
|
|
|
615
615
|
return Response.json(this.body, s);
|
|
616
616
|
}
|
|
617
617
|
}
|
|
618
|
-
class
|
|
618
|
+
class Y extends m {
|
|
619
619
|
/**
|
|
620
620
|
* Creates an instance of the `Found` class.
|
|
621
621
|
*
|
|
@@ -662,7 +662,7 @@ class P extends m {
|
|
|
662
662
|
return Response.json(this.body, s);
|
|
663
663
|
}
|
|
664
664
|
}
|
|
665
|
-
class
|
|
665
|
+
class z extends m {
|
|
666
666
|
/**
|
|
667
667
|
* Creates an instance of the `NoContent` class.
|
|
668
668
|
*
|
|
@@ -690,7 +690,7 @@ class M extends m {
|
|
|
690
690
|
return new Response(null, s);
|
|
691
691
|
}
|
|
692
692
|
}
|
|
693
|
-
class
|
|
693
|
+
class M extends m {
|
|
694
694
|
/**
|
|
695
695
|
* Creates an instance of the `Success` class.
|
|
696
696
|
*
|
|
@@ -803,7 +803,7 @@ class V {
|
|
|
803
803
|
};
|
|
804
804
|
}
|
|
805
805
|
}
|
|
806
|
-
class
|
|
806
|
+
class I {
|
|
807
807
|
/**
|
|
808
808
|
* Sets the configuration for the arkyn. This method initializes the arkyn configuration
|
|
809
809
|
* with the provided `arkynConfig` values. If the configuration has already been set,
|
|
@@ -841,9 +841,9 @@ class O {
|
|
|
841
841
|
this.arkynConfig = void 0;
|
|
842
842
|
}
|
|
843
843
|
}
|
|
844
|
-
o(
|
|
844
|
+
o(I, "arkynConfig");
|
|
845
845
|
async function G(e) {
|
|
846
|
-
const t =
|
|
846
|
+
const t = I.getArkynConfig();
|
|
847
847
|
if (!t) return;
|
|
848
848
|
const { arkynUserToken: s, arkynApiUrl: n } = t, {
|
|
849
849
|
elapsedTime: r,
|
|
@@ -854,7 +854,7 @@ async function G(e) {
|
|
|
854
854
|
responseBody: l,
|
|
855
855
|
responseHeaders: u,
|
|
856
856
|
status: d,
|
|
857
|
-
token:
|
|
857
|
+
token: A,
|
|
858
858
|
rawUrl: f
|
|
859
859
|
} = e;
|
|
860
860
|
if (process.env.NODE_ENV !== "development")
|
|
@@ -862,7 +862,7 @@ async function G(e) {
|
|
|
862
862
|
const p = new URL(f);
|
|
863
863
|
let S = "HTTPS";
|
|
864
864
|
p.protocol === "http:" && (S = "HTTP");
|
|
865
|
-
const
|
|
865
|
+
const w = JSON.stringify({
|
|
866
866
|
domainUrl: p.protocol + "//" + p.host,
|
|
867
867
|
pathnameUrl: p.pathname,
|
|
868
868
|
status: d,
|
|
@@ -883,7 +883,7 @@ async function G(e) {
|
|
|
883
883
|
),
|
|
884
884
|
{
|
|
885
885
|
method: "POST",
|
|
886
|
-
body:
|
|
886
|
+
body: w,
|
|
887
887
|
headers: {
|
|
888
888
|
"Content-Type": "application/json",
|
|
889
889
|
Authorization: `Bearer ${s}`
|
|
@@ -1062,11 +1062,11 @@ class Ss {
|
|
|
1062
1062
|
return this.onDebug(t, "delete", [r, a]), await Z(n, r, a);
|
|
1063
1063
|
}
|
|
1064
1064
|
}
|
|
1065
|
-
function
|
|
1065
|
+
function Ds(e, t) {
|
|
1066
1066
|
var s, n, r;
|
|
1067
1067
|
return e != null && e.message && typeof (e == null ? void 0 : e.message) == "string" ? e == null ? void 0 : e.message : e != null && e.error && typeof (e == null ? void 0 : e.error) == "string" ? e == null ? void 0 : e.error : (s = e == null ? void 0 : e.error) != null && s.message && typeof ((n = e == null ? void 0 : e.error) == null ? void 0 : n.message) == "string" ? (r = e == null ? void 0 : e.error) == null ? void 0 : r.message : t != null && t.statusText && typeof (t == null ? void 0 : t.statusText) == "string" ? t == null ? void 0 : t.statusText : "Missing error message";
|
|
1068
1068
|
}
|
|
1069
|
-
const
|
|
1069
|
+
const Os = async (e) => {
|
|
1070
1070
|
let t;
|
|
1071
1071
|
const s = await e.arrayBuffer(), n = new TextDecoder().decode(s);
|
|
1072
1072
|
try {
|
|
@@ -1077,9 +1077,9 @@ const Ds = async (e) => {
|
|
|
1077
1077
|
const a = new URLSearchParams(n);
|
|
1078
1078
|
t = Object.fromEntries(a.entries());
|
|
1079
1079
|
} else
|
|
1080
|
-
throw new
|
|
1080
|
+
throw new b("Invalid URLSearchParams format");
|
|
1081
1081
|
} catch {
|
|
1082
|
-
throw new
|
|
1082
|
+
throw new b("Failed to extract data from request");
|
|
1083
1083
|
}
|
|
1084
1084
|
}
|
|
1085
1085
|
return t;
|
|
@@ -1088,21 +1088,21 @@ function $s(e) {
|
|
|
1088
1088
|
switch (!0) {
|
|
1089
1089
|
case e instanceof Response:
|
|
1090
1090
|
return e;
|
|
1091
|
-
case e instanceof P:
|
|
1092
|
-
return e.toResponse();
|
|
1093
1091
|
case e instanceof Y:
|
|
1094
1092
|
return e.toResponse();
|
|
1095
|
-
case e instanceof
|
|
1093
|
+
case e instanceof P:
|
|
1096
1094
|
return e.toResponse();
|
|
1097
|
-
case e instanceof
|
|
1095
|
+
case e instanceof _:
|
|
1098
1096
|
return e.toResponse();
|
|
1099
1097
|
case e instanceof M:
|
|
1100
1098
|
return e.toResponse();
|
|
1099
|
+
case e instanceof z:
|
|
1100
|
+
return e.toResponse();
|
|
1101
1101
|
}
|
|
1102
1102
|
switch (!0) {
|
|
1103
|
-
case e instanceof
|
|
1103
|
+
case e instanceof J:
|
|
1104
1104
|
return e.toResponse();
|
|
1105
|
-
case e instanceof
|
|
1105
|
+
case e instanceof b:
|
|
1106
1106
|
return e.toResponse();
|
|
1107
1107
|
case e instanceof L:
|
|
1108
1108
|
return e.toResponse();
|
|
@@ -1112,16 +1112,36 @@ function $s(e) {
|
|
|
1112
1112
|
return e.toResponse();
|
|
1113
1113
|
case e instanceof q:
|
|
1114
1114
|
return e.toResponse();
|
|
1115
|
-
case e instanceof
|
|
1115
|
+
case e instanceof x:
|
|
1116
1116
|
return e.toResponse();
|
|
1117
1117
|
case e instanceof F:
|
|
1118
1118
|
return e.toResponse();
|
|
1119
|
-
case e instanceof
|
|
1119
|
+
case e instanceof R:
|
|
1120
1120
|
return e.toResponse();
|
|
1121
1121
|
}
|
|
1122
|
-
return new
|
|
1122
|
+
return new x("Server error", e).toResponse();
|
|
1123
1123
|
}
|
|
1124
|
-
function ss([
|
|
1124
|
+
async function ss([
|
|
1125
|
+
e,
|
|
1126
|
+
t
|
|
1127
|
+
]) {
|
|
1128
|
+
const s = await t.safeParseAsync(e);
|
|
1129
|
+
if (s.success === !1) {
|
|
1130
|
+
const n = Object.fromEntries(
|
|
1131
|
+
s.error.issues.map((r) => [r.path.join("."), r.message])
|
|
1132
|
+
);
|
|
1133
|
+
return {
|
|
1134
|
+
success: s.success,
|
|
1135
|
+
fieldErrors: n,
|
|
1136
|
+
fields: e
|
|
1137
|
+
};
|
|
1138
|
+
} else
|
|
1139
|
+
return {
|
|
1140
|
+
success: s.success,
|
|
1141
|
+
data: s.data
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
function es([
|
|
1125
1145
|
e,
|
|
1126
1146
|
t
|
|
1127
1147
|
]) {
|
|
@@ -1149,39 +1169,161 @@ const Is = (e, t = "") => {
|
|
|
1149
1169
|
).filter(([r]) => r.startsWith(`${t}:`)).map(([r, a]) => [r.replace(`${t}:`, ""), a]);
|
|
1150
1170
|
return new URLSearchParams(n);
|
|
1151
1171
|
};
|
|
1152
|
-
function
|
|
1172
|
+
function ts(e) {
|
|
1153
1173
|
const t = "Error validating:", s = e.issues.map(
|
|
1154
1174
|
({ path: n, message: r }) => `-> ${n.join(".")}: ${r}`
|
|
1155
1175
|
);
|
|
1156
1176
|
return [t, ...s].join(`
|
|
1157
1177
|
`);
|
|
1158
1178
|
}
|
|
1159
|
-
class
|
|
1179
|
+
class As {
|
|
1180
|
+
/**
|
|
1181
|
+
* Creates a new SchemaValidator instance.
|
|
1182
|
+
*
|
|
1183
|
+
* @param {T} schema - The Zod schema to use for validation.
|
|
1184
|
+
*/
|
|
1160
1185
|
constructor(t) {
|
|
1161
1186
|
o(this, "functionName");
|
|
1162
1187
|
o(this, "callerInfo");
|
|
1163
1188
|
this.schema = t;
|
|
1164
|
-
const { callerInfo: s, functionName: n } =
|
|
1189
|
+
const { callerInfo: s, functionName: n } = E();
|
|
1165
1190
|
this.callerInfo = s, this.functionName = n;
|
|
1166
1191
|
}
|
|
1192
|
+
/**
|
|
1193
|
+
* Checks if the provided data is valid according to the schema without throwing errors.
|
|
1194
|
+
*
|
|
1195
|
+
* @param {any} data - The data to validate.
|
|
1196
|
+
*
|
|
1197
|
+
* @returns {boolean} True if the data is valid, false otherwise.
|
|
1198
|
+
*
|
|
1199
|
+
* @example
|
|
1200
|
+
* ```typescript
|
|
1201
|
+
* const validator = new SchemaValidator(userSchema);
|
|
1202
|
+
* const isValid = validator.isValid({ name: "John", email: "invalid-email" });
|
|
1203
|
+
* console.log(isValid); // false
|
|
1204
|
+
* ```
|
|
1205
|
+
*/
|
|
1167
1206
|
isValid(t) {
|
|
1168
1207
|
return this.schema.safeParse(t).success;
|
|
1169
1208
|
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Safely validates data and returns the complete parse result without throwing errors.
|
|
1211
|
+
*
|
|
1212
|
+
* @param {any} data - The data to validate.
|
|
1213
|
+
*
|
|
1214
|
+
* @returns {z.ZodSafeParseResult<z.infer<T>>} The Zod safe parse result containing success status and data or error.
|
|
1215
|
+
*
|
|
1216
|
+
* @example
|
|
1217
|
+
* ```typescript
|
|
1218
|
+
* const validator = new SchemaValidator(userSchema);
|
|
1219
|
+
* const result = validator.safeValidate({ name: "", email: "john@example.com" });
|
|
1220
|
+
*
|
|
1221
|
+
* if (result.success) {
|
|
1222
|
+
* console.log(result.data); // Validated data
|
|
1223
|
+
* } else {
|
|
1224
|
+
* console.log(result.error.issues); // Validation errors
|
|
1225
|
+
* }
|
|
1226
|
+
* ```
|
|
1227
|
+
*/
|
|
1170
1228
|
safeValidate(t) {
|
|
1171
1229
|
return this.schema.safeParse(t);
|
|
1172
1230
|
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Validates data and returns the parsed result, throwing a ServerError on validation failure.
|
|
1233
|
+
*
|
|
1234
|
+
* @param {any} data - The data to validate.
|
|
1235
|
+
*
|
|
1236
|
+
* @returns {z.infer<T>} The validated and parsed data.
|
|
1237
|
+
*
|
|
1238
|
+
* @throws {ServerError} When validation fails, with a formatted error message.
|
|
1239
|
+
*
|
|
1240
|
+
* @example
|
|
1241
|
+
* ```typescript
|
|
1242
|
+
* const validator = new SchemaValidator(userSchema);
|
|
1243
|
+
*
|
|
1244
|
+
* try {
|
|
1245
|
+
* const validUser = validator.validate({ name: "John", email: "john@example.com", age: 25 });
|
|
1246
|
+
* console.log(validUser); // { name: "John", email: "john@example.com", age: 25 }
|
|
1247
|
+
* } catch (error) {
|
|
1248
|
+
* console.error(error.message); // "Error validating:\n-> name: String must contain at least 1 character(s)"
|
|
1249
|
+
* }
|
|
1250
|
+
* ```
|
|
1251
|
+
*/
|
|
1173
1252
|
validate(t) {
|
|
1174
1253
|
try {
|
|
1175
1254
|
return this.schema.parse(t);
|
|
1176
1255
|
} catch (s) {
|
|
1177
|
-
throw new
|
|
1256
|
+
throw new x(ts(s));
|
|
1178
1257
|
}
|
|
1179
1258
|
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
1261
|
+
* This method is specifically designed for form validation in web applications.
|
|
1262
|
+
*
|
|
1263
|
+
* @param {any} data - The form data to validate.
|
|
1264
|
+
* @param {string} [message] - Optional custom error message.
|
|
1265
|
+
*
|
|
1266
|
+
* @returns {z.infer<T>} The validated and parsed form data.
|
|
1267
|
+
*
|
|
1268
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
1269
|
+
*
|
|
1270
|
+
* @example
|
|
1271
|
+
* ```typescript
|
|
1272
|
+
* const validator = new SchemaValidator(userSchema);
|
|
1273
|
+
*
|
|
1274
|
+
* try {
|
|
1275
|
+
* const validFormData = validator.formValidate(requestBody, "User data is invalid");
|
|
1276
|
+
* console.log(validFormData);
|
|
1277
|
+
* } catch (error) {
|
|
1278
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
1279
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
1280
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
1281
|
+
* }
|
|
1282
|
+
* ```
|
|
1283
|
+
*/
|
|
1180
1284
|
formValidate(t, s) {
|
|
1181
|
-
const n =
|
|
1285
|
+
const n = es([t, this.schema]);
|
|
1182
1286
|
if (!n.success) {
|
|
1183
1287
|
const r = Object.keys(n.fieldErrors)[0];
|
|
1184
|
-
throw new
|
|
1288
|
+
throw new R({
|
|
1289
|
+
fields: n.fields,
|
|
1290
|
+
fieldErrors: n.fieldErrors,
|
|
1291
|
+
data: { scrollTo: r },
|
|
1292
|
+
message: s
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
return n.data;
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Asynchronously validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
1299
|
+
* This method is the async version of formValidate, designed for form validation with async schemas.
|
|
1300
|
+
*
|
|
1301
|
+
* @param {any} data - The form data to validate.
|
|
1302
|
+
* @param {string} [message] - Optional custom error message.
|
|
1303
|
+
*
|
|
1304
|
+
* @returns {Promise<z.infer<T>>} A promise that resolves to the validated and parsed form data.
|
|
1305
|
+
*
|
|
1306
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
1307
|
+
*
|
|
1308
|
+
* @example
|
|
1309
|
+
* ```typescript
|
|
1310
|
+
* const validator = new SchemaValidator(userSchemaWithAsyncValidation);
|
|
1311
|
+
*
|
|
1312
|
+
* try {
|
|
1313
|
+
* const validFormData = await validator.formAsyncValidate(requestBody, "User data is invalid");
|
|
1314
|
+
* console.log(validFormData);
|
|
1315
|
+
* } catch (error) {
|
|
1316
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
1317
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
1318
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
1319
|
+
* }
|
|
1320
|
+
* ```
|
|
1321
|
+
*/
|
|
1322
|
+
async formAsyncValidate(t, s) {
|
|
1323
|
+
const n = await ss([t, this.schema]);
|
|
1324
|
+
if (!n.success) {
|
|
1325
|
+
const r = Object.keys(n.fieldErrors)[0];
|
|
1326
|
+
throw new R({
|
|
1185
1327
|
fields: n.fields,
|
|
1186
1328
|
fieldErrors: n.fieldErrors,
|
|
1187
1329
|
data: { scrollTo: r },
|
|
@@ -1191,62 +1333,62 @@ class Os {
|
|
|
1191
1333
|
return n.data;
|
|
1192
1334
|
}
|
|
1193
1335
|
}
|
|
1194
|
-
const
|
|
1336
|
+
const ws = (e) => {
|
|
1195
1337
|
if (!e || !/^[0-9-]+$/.test(e)) return !1;
|
|
1196
|
-
const s =
|
|
1338
|
+
const s = N(e), n = 8, r = /^\d{8}$/.test(s);
|
|
1197
1339
|
return s.length === n && r;
|
|
1198
1340
|
};
|
|
1199
|
-
function
|
|
1341
|
+
function ns(e) {
|
|
1200
1342
|
return e.length !== 14;
|
|
1201
1343
|
}
|
|
1202
|
-
function
|
|
1344
|
+
function rs(e) {
|
|
1203
1345
|
const [t] = e;
|
|
1204
1346
|
return [...e].every((s) => s === t);
|
|
1205
1347
|
}
|
|
1206
|
-
function
|
|
1348
|
+
function D(e, t) {
|
|
1207
1349
|
let s = 0;
|
|
1208
1350
|
for (let r = 0; r < t.length; r++)
|
|
1209
1351
|
s += parseInt(e[r]) * t[r];
|
|
1210
1352
|
const n = s % 11;
|
|
1211
1353
|
return n < 2 ? 0 : 11 - n;
|
|
1212
1354
|
}
|
|
1213
|
-
function
|
|
1355
|
+
function os(e) {
|
|
1214
1356
|
return e.slice(12);
|
|
1215
1357
|
}
|
|
1216
|
-
const
|
|
1358
|
+
const Us = (e) => {
|
|
1217
1359
|
if (!e) return !1;
|
|
1218
|
-
const t =
|
|
1219
|
-
if (
|
|
1220
|
-
const s = t.slice(0, 12), n =
|
|
1360
|
+
const t = N(e);
|
|
1361
|
+
if (ns(t) || rs(t)) return !1;
|
|
1362
|
+
const s = t.slice(0, 12), n = D(s, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]), r = D(
|
|
1221
1363
|
s + n,
|
|
1222
1364
|
[6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
|
|
1223
1365
|
);
|
|
1224
|
-
return
|
|
1366
|
+
return os(t) === `${n}${r}`;
|
|
1225
1367
|
};
|
|
1226
|
-
function
|
|
1368
|
+
function as(e) {
|
|
1227
1369
|
return e.length !== 11;
|
|
1228
1370
|
}
|
|
1229
|
-
function
|
|
1371
|
+
function us(e) {
|
|
1230
1372
|
const [t] = e;
|
|
1231
1373
|
return [...e].every((s) => s === t);
|
|
1232
1374
|
}
|
|
1233
|
-
function
|
|
1375
|
+
function O(e, t) {
|
|
1234
1376
|
let s = 0;
|
|
1235
1377
|
for (const r of e)
|
|
1236
1378
|
t > 1 && (s += parseInt(r) * t--);
|
|
1237
1379
|
const n = s % 11;
|
|
1238
1380
|
return n < 2 ? 0 : 11 - n;
|
|
1239
1381
|
}
|
|
1240
|
-
function
|
|
1382
|
+
function is(e) {
|
|
1241
1383
|
return e.slice(9);
|
|
1242
1384
|
}
|
|
1243
|
-
const
|
|
1385
|
+
const Cs = (e) => {
|
|
1244
1386
|
if (!e) return !1;
|
|
1245
|
-
const t =
|
|
1246
|
-
if (
|
|
1247
|
-
const s =
|
|
1248
|
-
return
|
|
1249
|
-
},
|
|
1387
|
+
const t = N(e);
|
|
1388
|
+
if (as(t) || us(t)) return !1;
|
|
1389
|
+
const s = O(t, 10), n = O(t, 11);
|
|
1390
|
+
return is(t) === `${s}${n}`;
|
|
1391
|
+
}, vs = (e, t) => {
|
|
1250
1392
|
let s, n, r;
|
|
1251
1393
|
const a = (t == null ? void 0 : t.inputFormat) || "DD/MM/YYYY", c = (t == null ? void 0 : t.minYear) || 1900, h = (t == null ? void 0 : t.maxYear) || 3e3;
|
|
1252
1394
|
if (a === "DD/MM/YYYY") {
|
|
@@ -1272,55 +1414,55 @@ const vs = (e) => {
|
|
|
1272
1414
|
} else if (i > d[l - 1])
|
|
1273
1415
|
return !1;
|
|
1274
1416
|
return u < c || u > h ? !1 : new Date(u, l - 1, i).getDate() === i;
|
|
1275
|
-
},
|
|
1276
|
-
function
|
|
1417
|
+
}, cs = v.promises.resolve;
|
|
1418
|
+
function hs(e) {
|
|
1277
1419
|
return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e);
|
|
1278
1420
|
}
|
|
1279
|
-
function
|
|
1421
|
+
function ls(e) {
|
|
1280
1422
|
return !(e.length === 0 || e.length > 64 || e.startsWith(".") || e.endsWith(".") || e.includes("..") || !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(e));
|
|
1281
1423
|
}
|
|
1282
|
-
function
|
|
1424
|
+
function fs(e) {
|
|
1283
1425
|
return !(e.length === 0 || e.length > 63 || e.startsWith("-") || e.endsWith("-") || !/^[a-zA-Z0-9-]+$/.test(e));
|
|
1284
1426
|
}
|
|
1285
|
-
function
|
|
1427
|
+
function ds(e) {
|
|
1286
1428
|
if (e.length === 0 || e.length > 253 || e.startsWith(".") || e.endsWith(".") || e.startsWith("-") || e.endsWith("-"))
|
|
1287
1429
|
return !1;
|
|
1288
1430
|
const t = e.split(".");
|
|
1289
1431
|
if (t.length < 2) return !1;
|
|
1290
|
-
for (const n of t) if (!
|
|
1432
|
+
for (const n of t) if (!fs(n)) return !1;
|
|
1291
1433
|
const s = t[t.length - 1];
|
|
1292
1434
|
return !(s.length < 2 || !/^[a-zA-Z]+$/.test(s));
|
|
1293
1435
|
}
|
|
1294
|
-
function
|
|
1436
|
+
function ys(e) {
|
|
1295
1437
|
const t = e.split("@");
|
|
1296
1438
|
if (t.length !== 2) return !1;
|
|
1297
1439
|
const [s, n] = t;
|
|
1298
|
-
return !(!
|
|
1440
|
+
return !(!ls(s) || !ds(n));
|
|
1299
1441
|
}
|
|
1300
|
-
function
|
|
1442
|
+
function ps(e) {
|
|
1301
1443
|
const t = e.split("@");
|
|
1302
1444
|
return t.length === 2 ? t[1].toLowerCase() : null;
|
|
1303
1445
|
}
|
|
1304
|
-
const
|
|
1305
|
-
async function
|
|
1446
|
+
const gs = ["MX", "A", "AAAA"];
|
|
1447
|
+
async function ms(e, t) {
|
|
1306
1448
|
try {
|
|
1307
|
-
return await
|
|
1449
|
+
return await cs(e, t), !0;
|
|
1308
1450
|
} catch {
|
|
1309
1451
|
return !1;
|
|
1310
1452
|
}
|
|
1311
1453
|
}
|
|
1312
|
-
async function
|
|
1313
|
-
for (const t of
|
|
1314
|
-
if (await
|
|
1454
|
+
async function Ts(e) {
|
|
1455
|
+
for (const t of gs)
|
|
1456
|
+
if (await ms(e, t)) return !0;
|
|
1315
1457
|
return !1;
|
|
1316
1458
|
}
|
|
1317
|
-
const
|
|
1459
|
+
const js = async (e) => {
|
|
1318
1460
|
if (!e || typeof e != "string") return !1;
|
|
1319
1461
|
const t = e.trim();
|
|
1320
|
-
if (!
|
|
1321
|
-
const s =
|
|
1322
|
-
return s ? await
|
|
1323
|
-
},
|
|
1462
|
+
if (!hs(t) || !ys(t)) return !1;
|
|
1463
|
+
const s = ps(t);
|
|
1464
|
+
return s ? await Ts(s) : !1;
|
|
1465
|
+
}, ks = (e) => {
|
|
1324
1466
|
if (!e) return !1;
|
|
1325
1467
|
const t = e.length >= 8, s = /[A-Z]/.test(e), n = /[a-z]/.test(e), r = /\d/.test(e), a = /[!@#$%^&*(),.?":{}|<>_\-+=~`[\]\\\/]/.test(
|
|
1326
1468
|
e
|
|
@@ -1333,7 +1475,7 @@ const ks = async (e) => {
|
|
|
1333
1475
|
a
|
|
1334
1476
|
].every((c) => c);
|
|
1335
1477
|
}, Js = (e) => {
|
|
1336
|
-
for (const t of
|
|
1478
|
+
for (const t of j) {
|
|
1337
1479
|
const s = t.code, n = t.prefix ? `-${t.prefix}` : "", r = t.mask.replace(/[^_]/g, "").length;
|
|
1338
1480
|
if (t.iso === "BR") {
|
|
1339
1481
|
if (new RegExp(`^\\${s} \\d{2}9?\\d{8}$`).test(e)) return !0;
|
|
@@ -1342,43 +1484,44 @@ const ks = async (e) => {
|
|
|
1342
1484
|
if (new RegExp(`^\\${s}${n} \\d{${r}}$`).test(e)) return !0;
|
|
1343
1485
|
}
|
|
1344
1486
|
return !1;
|
|
1345
|
-
},
|
|
1487
|
+
}, Ls = (e) => {
|
|
1346
1488
|
if (!e || !/^[0-9a-zA-Z.-]+$/.test(e)) return !1;
|
|
1347
1489
|
const s = e.replace(/[^a-zA-Z0-9]/g, "");
|
|
1348
1490
|
return s.length < 7 || s.length > 9 ? !1 : /^[0-9]{7,8}[0-9Xx]?$/.test(s);
|
|
1349
1491
|
};
|
|
1350
1492
|
export {
|
|
1351
1493
|
Ss as ApiService,
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1494
|
+
I as ArkynLogService,
|
|
1495
|
+
J as BadGateway,
|
|
1496
|
+
b as BadRequest,
|
|
1355
1497
|
L as Conflict,
|
|
1356
|
-
|
|
1498
|
+
P as Created,
|
|
1357
1499
|
$ as DebugService,
|
|
1358
1500
|
B as Forbidden,
|
|
1359
|
-
|
|
1360
|
-
|
|
1501
|
+
Y as Found,
|
|
1502
|
+
z as NoContent,
|
|
1361
1503
|
H as NotFound,
|
|
1362
1504
|
q as NotImplemented,
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1505
|
+
As as SchemaValidator,
|
|
1506
|
+
x as ServerError,
|
|
1507
|
+
M as Success,
|
|
1366
1508
|
F as Unauthorized,
|
|
1367
|
-
|
|
1509
|
+
R as UnprocessableEntity,
|
|
1368
1510
|
_ as Updated,
|
|
1369
|
-
|
|
1370
|
-
|
|
1511
|
+
Ds as decodeErrorMessageFromRequest,
|
|
1512
|
+
Os as decodeRequestBody,
|
|
1371
1513
|
$s as errorHandler,
|
|
1372
1514
|
g as flushDebugLogs,
|
|
1373
|
-
ss as
|
|
1374
|
-
|
|
1515
|
+
ss as formAsyncParse,
|
|
1516
|
+
es as formParse,
|
|
1517
|
+
E as getCaller,
|
|
1375
1518
|
Is as getScopedParams,
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1519
|
+
ws as validateCep,
|
|
1520
|
+
Us as validateCnpj,
|
|
1521
|
+
Cs as validateCpf,
|
|
1522
|
+
vs as validateDate,
|
|
1523
|
+
js as validateEmail,
|
|
1524
|
+
ks as validatePassword,
|
|
1382
1525
|
Js as validatePhone,
|
|
1383
|
-
|
|
1526
|
+
Ls as validateRg
|
|
1384
1527
|
};
|
package/dist/bundle.umd.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`;e.debugs.forEach(l=>{h+=`${
|
|
3
|
-
`}),console.log(h)}}const
|
|
4
|
-
`).map(i=>i.trim()),r=
|
|
1
|
+
(function(a,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("zod"),require("@arkyn/shared"),require("node:dns"),require("@arkyn/templates")):typeof define=="function"&&define.amd?define(["exports","zod","@arkyn/shared","node:dns","@arkyn/templates"],d):(a=typeof globalThis<"u"?globalThis:a||self,d(a["@arkyn/server"]={},null,a.shared,a.dns,a.templates))})(this,function(a,d,m,M,Y){"use strict";var Us=Object.defineProperty;var ws=(a,d,m)=>d in a?Us(a,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):a[d]=m;var o=(a,d,m)=>ws(a,typeof d!="symbol"?d+"":d,m);function T(e){var s;if(process.env.NODE_ENV==="development"||((s=process.env)==null?void 0:s.SHOW_ERRORS_IN_CONSOLE)==="true"){const u=`${{yellow:"\x1B[33m",cyan:"\x1B[36m",red:"\x1B[31m",green:"\x1B[32m"}[e.scheme]}[${e.name}]\x1B[0m`;let h=`
|
|
2
|
+
`;e.debugs.forEach(l=>{h+=`${u} ${l.trim()}
|
|
3
|
+
`}),console.log(h)}}const _={};class v{static setIgnoreFile(t){this.ignoreFiles.push(t)}static clearIgnoreFiles(){this.ignoreFiles=[]}}o(v,"ignoreFiles",[]);function N(){const e=process.cwd(),n=(new Error().stack||"").split(`
|
|
4
|
+
`).map(i=>i.trim()),r=v.ignoreFiles;let u=2;for(;u<n.length&&(n[u].includes("node:internal")||n[u].includes("/node_modules/"));)u++;if(r.length>0)for(;u<n.length&&r.some(i=>n[u].includes(i));)u++;const h=n[u]||"";let l="Unknown function",c="Unknown caller";const f=h.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);if(f)l=f[1],c=f[2];else{const i=h.match(/at\s+(.+)/);if(i){c=i[1];const g=c.match(/at\s+([^(\s]+)\s+/);g&&g[1]!=="new"&&(l=g[1])}}c.includes("(")&&(c=c.substring(c.indexOf("(")+1,c.lastIndexOf(")"))),c=c.split(":").slice(0,-2).join(":");try{c=_.relative(e,c)}catch{}return{functionName:l,callerInfo:c}}class p{onDebug(t){const{name:s,body:n,cause:r,message:u}=t,h=[],{callerInfo:l,functionName:c}=N();h.push(`${s} initialized`),h.push(`Caller Function: ${c}`),h.push(`Caller Location: ${l}`),u&&h.push(`Message: ${u}`),n&&h.push(`Body: ${JSON.stringify(n,null,2)}`),r&&h.push(`Cause: ${JSON.stringify(r,null,2)}`),T({scheme:"red",name:"ARKYN-BAD-RESPONSE-DEBUG",debugs:h})}}class I extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",502);o(this,"statusText");this.body={name:"BadGateway",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"BadGateway",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class S extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",400);o(this,"statusText");this.body={name:"BadRequest",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"BadRequest",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class $ extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",409);o(this,"statusText");this.body={name:"Conflict",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Conflict",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class C extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",403);o(this,"statusText");this.body={name:"Forbidden",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Forbidden",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class A extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",404);o(this,"statusText");this.body={name:"NotFound",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"NotFound",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class k extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",501);o(this,"statusText");this.body={name:"NotImplemented",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"NotImplemented",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class E extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",500);o(this,"statusText");this.body={name:"ServerError",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"ServerError",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class U extends p{constructor(s,n){super();o(this,"body");o(this,"cause");o(this,"status",401);o(this,"statusText");this.body={name:"Unauthorized",message:s},this.statusText=s,this.cause=n?JSON.stringify(n):void 0,this.onDebug({name:"Unauthorized",body:this.body,cause:this.cause,message:this.statusText})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class D extends p{constructor(s){super();o(this,"body");o(this,"status",422);o(this,"statusText");this.statusText=s.message||"Unprocessable Entity",this.body={name:"UnprocessableEntity",message:s.message||null,data:s.data,fieldErrors:s.fieldErrors,fields:s.fields},this.onDebug({name:"UnprocessableEntity",cause:s.fieldErrors,message:s.message})}toResponse(){const s={headers:{"Content-Type":"application/json"},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class R{onDebug(t,s,n){const r=[],{callerInfo:u,functionName:h}=N();r.push(`${t} initialized
|
|
5
5
|
`),r.push(`Caller Function: ${h}
|
|
6
|
-
`),r.push(`Caller Location: ${
|
|
6
|
+
`),r.push(`Caller Location: ${u}
|
|
7
7
|
`),r.push(`Body: ${JSON.stringify(s,null,2)}
|
|
8
8
|
`),n&&r.push(`Cause: ${JSON.stringify(n,null,2)}
|
|
9
|
-
`),T({scheme:"green",name:"ARKYN-SUCCESS-RESPONSE-DEBUG",debugs:r})}}class w extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||201,this.statusText=(n==null?void 0:n.statusText)||"Resource created successfully",this.onDebug("Created",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class j extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||302,this.statusText=(n==null?void 0:n.statusText)||"Found",this.onDebug("Found",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class J extends R{constructor(s){super();o(this,"headers");o(this,"status");o(this,"statusText");this.headers=(s==null?void 0:s.headers)||{},this.status=(s==null?void 0:s.status)||204,this.statusText=(s==null?void 0:s.statusText)??"No content",this.onDebug("No content",null)}toResponse(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return new Response(null,s)}}class L extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)??"OK",this.onDebug("Success",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class B extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)||"Resource updated successfully",this.onDebug("Updated",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class _{static mapHeaders(t){return t instanceof Headers?Object.fromEntries(t.entries()):typeof t=="object"?Object.entries(t).reduce((s,[n,r])=>(typeof r=="string"?s[n]=r:Array.isArray(r)?s[n]=r.join(", "):s[n]=JSON.stringify(r),s),{}):{}}static mapQueryParams(t){const s={};return t.forEach((n,r)=>{s[r]=n}),s}static handle(t){return{rawUrl:t.url,status:t.status,method:t.method,token:null,elapsedTime:t.elapsedTime,requestHeaders:this.mapHeaders(t.requestHeaders),requestBody:t.requestBody||null,queryParams:this.mapQueryParams(t.queryParams),responseHeaders:this.mapHeaders(t.responseHeaders),responseBody:t.responseBody||null}}}class I{static setArkynConfig(t){if(this.arkynConfig)return;let n=t.arkynLogBaseApiUrl||"https://logs-arkyn-flow-logs.vw6wo7.easypanel.host";n=n+"/http-traffic-records/:trafficSourceId",this.arkynConfig={arkynTrafficSourceId:t.arkynTrafficSourceId,arkynUserToken:t.arkynUserToken,arkynApiUrl:n}}static getArkynConfig(){return this.arkynConfig}static resetArkynConfig(){this.arkynConfig=void 0}}o(I,"arkynConfig");async function V(e){const t=I.getArkynConfig();if(!t)return;const{arkynUserToken:s,arkynApiUrl:n}=t,{elapsedTime:r,method:a,queryParams:h,requestBody:l,requestHeaders:c,responseBody:f,responseHeaders:i,status:g,token:Os,rawUrl:y}=e;if(process.env.NODE_ENV!=="development")try{const b=new URL(y);let P="HTTPS";b.protocol==="http:"&&(P="HTTP");const Us=JSON.stringify({domainUrl:b.protocol+"//"+b.host,pathnameUrl:b.pathname,status:g,protocol:P,method:a,trafficUserId:null,elapsedTime:r,requestHeaders:c,requestBody:l,queryParams:h,responseHeaders:i,responseBody:f});await fetch(n.replace(":trafficSourceId",t.arkynTrafficSourceId),{method:"POST",body:Us,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(b){T({debugs:[`Error sending request: ${b}`],name:"ARKYN_LOG_ERROR",scheme:"red"})}}async function x(e,t,s={},n){const r={POST:"Resource created successfully",PUT:"Resource updated successfully",DELETE:"Resource deleted successfully",PATCH:"Resource patched successfully",GET:"Request successful"};try{const a=performance.now(),h={...s,"Content-Type":"application/json"},l=await fetch(t,{method:e,headers:h,body:n?JSON.stringify(n):void 0}),c=performance.now()-a,f=l.status;let i=null;try{i=await l.json()}catch{i=null}const g=_.handle({elapsedTime:c,method:e,queryParams:new URL(t).searchParams,requestHeaders:h,requestBody:n,responseBody:i,responseHeaders:l.headers,status:f,url:t});return V(g),l.ok?{success:!0,status:f,message:(i==null?void 0:i.message)||r[e],response:i,cause:null}:{success:!1,status:f,message:(i==null?void 0:i.message)||l.statusText||"Request failed",response:i,cause:null}}catch(a){return T({debugs:[`Network error or request failed: ${a}`],name:"ARKYN_MAKE_REQUEST_ERROR",scheme:"red"}),{success:!1,status:0,message:"Network error or request failed",response:null,cause:a instanceof Error?a.message:String(a)}}}async function G(e,t={},s){return x("DELETE",e,t,s)}async function Z(e,t={}){return x("GET",e,t)}async function W(e,t={},s){return x("PATCH",e,t,s)}async function K(e,t={},s){return x("POST",e,t,s)}async function Q(e,t={},s){return x("PUT",e,t,s)}class X{constructor(t){o(this,"baseUrl");o(this,"baseHeaders");o(this,"baseToken");o(this,"enableDebug");this.baseUrl=t.baseUrl,this.baseHeaders=t.baseHeaders||void 0,this.baseToken=t.baseToken||void 0,this.enableDebug=t.enableDebug||!1}onDebug(t,s,n){if(this.enableDebug){const r=[];r.push(`Base URL: ${this.baseUrl}`),r.push(`Endpoint: ${t}`),r.push(`Method: ${s}`),n[0]&&r.push(`Headers: ${JSON.stringify(n[0])}`),n[1]&&r.push(`Body: ${JSON.stringify(n[1])}`),T({debugs:r,name:"ARKYN-API-DEBUG",scheme:"yellow"})}}generateURL(t){return this.baseUrl+t}generateHeaders(t,s){let n={};return this.baseToken&&(n={Authorization:`Bearer ${this.baseToken}`}),this.baseHeaders&&(n={...n,...this.baseHeaders}),t&&(n={...n,...t}),s&&(n={...n,Authorization:`Bearer ${s}`}),n}async get(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token);return this.onDebug(t,"get",[r]),await Z(n,r)}async post(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"post",[r,a]),await K(n,r,a)}async put(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"put",[r,a]),await Q(n,r,a)}async patch(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"patch",[r,a]),await W(n,r,a)}async delete(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),a=s==null?void 0:s.body;return this.onDebug(t,"delete",[r,a]),await G(n,r,a)}}function ss(e,t){var s,n,r;return e!=null&&e.message&&typeof(e==null?void 0:e.message)=="string"?e==null?void 0:e.message:e!=null&&e.error&&typeof(e==null?void 0:e.error)=="string"?e==null?void 0:e.error:(s=e==null?void 0:e.error)!=null&&s.message&&typeof((n=e==null?void 0:e.error)==null?void 0:n.message)=="string"?(r=e==null?void 0:e.error)==null?void 0:r.message:t!=null&&t.statusText&&typeof(t==null?void 0:t.statusText)=="string"?t==null?void 0:t.statusText:"Missing error message"}const es=async e=>{let t;const s=await e.arrayBuffer(),n=new TextDecoder().decode(s);try{t=JSON.parse(n)}catch{try{if(n.includes("=")){const a=new URLSearchParams(n);t=Object.fromEntries(a.entries())}else throw new S("Invalid URLSearchParams format")}catch{throw new S("Failed to extract data from request")}}return t};function ts(e){switch(!0){case e instanceof Response:return e;case e instanceof j:return e.toResponse();case e instanceof w:return e.toResponse();case e instanceof B:return e.toResponse();case e instanceof L:return e.toResponse();case e instanceof J:return e.toResponse()}switch(!0){case e instanceof $:return e.toResponse();case e instanceof S:return e.toResponse();case e instanceof C:return e.toResponse();case e instanceof O:return e.toResponse();case e instanceof U:return e.toResponse();case e instanceof k:return e.toResponse();case e instanceof E:return e.toResponse();case e instanceof A:return e.toResponse();case e instanceof v:return e.toResponse()}return new E("Server error",e).toResponse()}function q([e,t]){const s=t.safeParse(e);if(s.success===!1){const n=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:n,fields:e}}else return{success:s.success,data:s.data}}const ns=(e,t="")=>{const s=new URL(e.url);if(t==="")return s.searchParams;const n=Array.from(s.searchParams.entries()).filter(([r])=>r.startsWith(`${t}:`)).map(([r,a])=>[r.replace(`${t}:`,""),a]);return new URLSearchParams(n)};function rs(e){const t="Error validating:",s=e.issues.map(({path:n,message:r})=>`-> ${n.join(".")}: ${r}`);return[t,...s].join(`
|
|
10
|
-
`)}class
|
|
9
|
+
`),T({scheme:"green",name:"ARKYN-SUCCESS-RESPONSE-DEBUG",debugs:r})}}class w extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||201,this.statusText=(n==null?void 0:n.statusText)||"Resource created successfully",this.onDebug("Created",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class j extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||302,this.statusText=(n==null?void 0:n.statusText)||"Found",this.onDebug("Found",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class J extends R{constructor(s){super();o(this,"headers");o(this,"status");o(this,"statusText");this.headers=(s==null?void 0:s.headers)||{},this.status=(s==null?void 0:s.status)||204,this.statusText=(s==null?void 0:s.statusText)??"No content",this.onDebug("No content",null)}toResponse(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return new Response(null,s)}}class L extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)??"OK",this.onDebug("Success",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class B extends R{constructor(s,n){super();o(this,"body");o(this,"headers");o(this,"status");o(this,"statusText");this.body=s,this.headers=(n==null?void 0:n.headers)||{},this.status=(n==null?void 0:n.status)||200,this.statusText=(n==null?void 0:n.statusText)||"Resource updated successfully",this.onDebug("Updated",s)}toResponse(){const s={headers:{"Content-Type":"application/json",...this.headers},status:this.status,statusText:this.statusText};return new Response(JSON.stringify(this.body),s)}toJson(){const s={headers:this.headers,status:this.status,statusText:this.statusText};return Response.json(this.body,s)}}class V{static mapHeaders(t){return t instanceof Headers?Object.fromEntries(t.entries()):typeof t=="object"?Object.entries(t).reduce((s,[n,r])=>(typeof r=="string"?s[n]=r:Array.isArray(r)?s[n]=r.join(", "):s[n]=JSON.stringify(r),s),{}):{}}static mapQueryParams(t){const s={};return t.forEach((n,r)=>{s[r]=n}),s}static handle(t){return{rawUrl:t.url,status:t.status,method:t.method,token:null,elapsedTime:t.elapsedTime,requestHeaders:this.mapHeaders(t.requestHeaders),requestBody:t.requestBody||null,queryParams:this.mapQueryParams(t.queryParams),responseHeaders:this.mapHeaders(t.responseHeaders),responseBody:t.responseBody||null}}}class O{static setArkynConfig(t){if(this.arkynConfig)return;let n=t.arkynLogBaseApiUrl||"https://logs-arkyn-flow-logs.vw6wo7.easypanel.host";n=n+"/http-traffic-records/:trafficSourceId",this.arkynConfig={arkynTrafficSourceId:t.arkynTrafficSourceId,arkynUserToken:t.arkynUserToken,arkynApiUrl:n}}static getArkynConfig(){return this.arkynConfig}static resetArkynConfig(){this.arkynConfig=void 0}}o(O,"arkynConfig");async function G(e){const t=O.getArkynConfig();if(!t)return;const{arkynUserToken:s,arkynApiUrl:n}=t,{elapsedTime:r,method:u,queryParams:h,requestBody:l,requestHeaders:c,responseBody:f,responseHeaders:i,status:g,token:As,rawUrl:y}=e;if(process.env.NODE_ENV!=="development")try{const b=new URL(y);let z="HTTPS";b.protocol==="http:"&&(z="HTTP");const ks=JSON.stringify({domainUrl:b.protocol+"//"+b.host,pathnameUrl:b.pathname,status:g,protocol:z,method:u,trafficUserId:null,elapsedTime:r,requestHeaders:c,requestBody:l,queryParams:h,responseHeaders:i,responseBody:f});await fetch(n.replace(":trafficSourceId",t.arkynTrafficSourceId),{method:"POST",body:ks,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(b){T({debugs:[`Error sending request: ${b}`],name:"ARKYN_LOG_ERROR",scheme:"red"})}}async function x(e,t,s={},n){const r={POST:"Resource created successfully",PUT:"Resource updated successfully",DELETE:"Resource deleted successfully",PATCH:"Resource patched successfully",GET:"Request successful"};try{const u=performance.now(),h={...s,"Content-Type":"application/json"},l=await fetch(t,{method:e,headers:h,body:n?JSON.stringify(n):void 0}),c=performance.now()-u,f=l.status;let i=null;try{i=await l.json()}catch{i=null}const g=V.handle({elapsedTime:c,method:e,queryParams:new URL(t).searchParams,requestHeaders:h,requestBody:n,responseBody:i,responseHeaders:l.headers,status:f,url:t});return G(g),l.ok?{success:!0,status:f,message:(i==null?void 0:i.message)||r[e],response:i,cause:null}:{success:!1,status:f,message:(i==null?void 0:i.message)||l.statusText||"Request failed",response:i,cause:null}}catch(u){return T({debugs:[`Network error or request failed: ${u}`],name:"ARKYN_MAKE_REQUEST_ERROR",scheme:"red"}),{success:!1,status:0,message:"Network error or request failed",response:null,cause:u instanceof Error?u.message:String(u)}}}async function Z(e,t={},s){return x("DELETE",e,t,s)}async function W(e,t={}){return x("GET",e,t)}async function K(e,t={},s){return x("PATCH",e,t,s)}async function Q(e,t={},s){return x("POST",e,t,s)}async function X(e,t={},s){return x("PUT",e,t,s)}class ss{constructor(t){o(this,"baseUrl");o(this,"baseHeaders");o(this,"baseToken");o(this,"enableDebug");this.baseUrl=t.baseUrl,this.baseHeaders=t.baseHeaders||void 0,this.baseToken=t.baseToken||void 0,this.enableDebug=t.enableDebug||!1}onDebug(t,s,n){if(this.enableDebug){const r=[];r.push(`Base URL: ${this.baseUrl}`),r.push(`Endpoint: ${t}`),r.push(`Method: ${s}`),n[0]&&r.push(`Headers: ${JSON.stringify(n[0])}`),n[1]&&r.push(`Body: ${JSON.stringify(n[1])}`),T({debugs:r,name:"ARKYN-API-DEBUG",scheme:"yellow"})}}generateURL(t){return this.baseUrl+t}generateHeaders(t,s){let n={};return this.baseToken&&(n={Authorization:`Bearer ${this.baseToken}`}),this.baseHeaders&&(n={...n,...this.baseHeaders}),t&&(n={...n,...t}),s&&(n={...n,Authorization:`Bearer ${s}`}),n}async get(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token);return this.onDebug(t,"get",[r]),await W(n,r)}async post(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),u=s==null?void 0:s.body;return this.onDebug(t,"post",[r,u]),await Q(n,r,u)}async put(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),u=s==null?void 0:s.body;return this.onDebug(t,"put",[r,u]),await X(n,r,u)}async patch(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),u=s==null?void 0:s.body;return this.onDebug(t,"patch",[r,u]),await K(n,r,u)}async delete(t,s){const n=this.generateURL(t),r=this.generateHeaders((s==null?void 0:s.headers)||{},s==null?void 0:s.token),u=s==null?void 0:s.body;return this.onDebug(t,"delete",[r,u]),await Z(n,r,u)}}function es(e,t){var s,n,r;return e!=null&&e.message&&typeof(e==null?void 0:e.message)=="string"?e==null?void 0:e.message:e!=null&&e.error&&typeof(e==null?void 0:e.error)=="string"?e==null?void 0:e.error:(s=e==null?void 0:e.error)!=null&&s.message&&typeof((n=e==null?void 0:e.error)==null?void 0:n.message)=="string"?(r=e==null?void 0:e.error)==null?void 0:r.message:t!=null&&t.statusText&&typeof(t==null?void 0:t.statusText)=="string"?t==null?void 0:t.statusText:"Missing error message"}const ts=async e=>{let t;const s=await e.arrayBuffer(),n=new TextDecoder().decode(s);try{t=JSON.parse(n)}catch{try{if(n.includes("=")){const u=new URLSearchParams(n);t=Object.fromEntries(u.entries())}else throw new S("Invalid URLSearchParams format")}catch{throw new S("Failed to extract data from request")}}return t};function ns(e){switch(!0){case e instanceof Response:return e;case e instanceof j:return e.toResponse();case e instanceof w:return e.toResponse();case e instanceof B:return e.toResponse();case e instanceof L:return e.toResponse();case e instanceof J:return e.toResponse()}switch(!0){case e instanceof I:return e.toResponse();case e instanceof S:return e.toResponse();case e instanceof $:return e.toResponse();case e instanceof C:return e.toResponse();case e instanceof A:return e.toResponse();case e instanceof k:return e.toResponse();case e instanceof E:return e.toResponse();case e instanceof U:return e.toResponse();case e instanceof D:return e.toResponse()}return new E("Server error",e).toResponse()}async function q([e,t]){const s=await t.safeParseAsync(e);if(s.success===!1){const n=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:n,fields:e}}else return{success:s.success,data:s.data}}function F([e,t]){const s=t.safeParse(e);if(s.success===!1){const n=Object.fromEntries(s.error.issues.map(r=>[r.path.join("."),r.message]));return{success:s.success,fieldErrors:n,fields:e}}else return{success:s.success,data:s.data}}const rs=(e,t="")=>{const s=new URL(e.url);if(t==="")return s.searchParams;const n=Array.from(s.searchParams.entries()).filter(([r])=>r.startsWith(`${t}:`)).map(([r,u])=>[r.replace(`${t}:`,""),u]);return new URLSearchParams(n)};function os(e){const t="Error validating:",s=e.issues.map(({path:n,message:r})=>`-> ${n.join(".")}: ${r}`);return[t,...s].join(`
|
|
10
|
+
`)}class as{constructor(t){o(this,"functionName");o(this,"callerInfo");this.schema=t;const{callerInfo:s,functionName:n}=N();this.callerInfo=s,this.functionName=n}isValid(t){return this.schema.safeParse(t).success}safeValidate(t){return this.schema.safeParse(t)}validate(t){try{return this.schema.parse(t)}catch(s){throw new E(os(s))}}formValidate(t,s){const n=F([t,this.schema]);if(!n.success){const r=Object.keys(n.fieldErrors)[0];throw new D({fields:n.fields,fieldErrors:n.fieldErrors,data:{scrollTo:r},message:s})}return n.data}async formAsyncValidate(t,s){const n=await q([t,this.schema]);if(!n.success){const r=Object.keys(n.fieldErrors)[0];throw new D({fields:n.fields,fieldErrors:n.fieldErrors,data:{scrollTo:r},message:s})}return n.data}}const us=e=>{if(!e||!/^[0-9-]+$/.test(e))return!1;const s=m.removeNonNumeric(e),n=8,r=/^\d{8}$/.test(s);return s.length===n&&r};function is(e){return e.length!==14}function cs(e){const[t]=e;return[...e].every(s=>s===t)}function H(e,t){let s=0;for(let r=0;r<t.length;r++)s+=parseInt(e[r])*t[r];const n=s%11;return n<2?0:11-n}function hs(e){return e.slice(12)}const ls=e=>{if(!e)return!1;const t=m.removeNonNumeric(e);if(is(t)||cs(t))return!1;const s=t.slice(0,12),n=H(s,[5,4,3,2,9,8,7,6,5,4,3,2]),r=H(s+n,[6,5,4,3,2,9,8,7,6,5,4,3,2]);return hs(t)===`${n}${r}`};function fs(e){return e.length!==11}function ds(e){const[t]=e;return[...e].every(s=>s===t)}function P(e,t){let s=0;for(const r of e)t>1&&(s+=parseInt(r)*t--);const n=s%11;return n<2?0:11-n}function ys(e){return e.slice(9)}const ps=e=>{if(!e)return!1;const t=m.removeNonNumeric(e);if(fs(t)||ds(t))return!1;const s=P(t,10),n=P(t,11);return ys(t)===`${s}${n}`},gs=(e,t)=>{let s,n,r;const u=(t==null?void 0:t.inputFormat)||"DD/MM/YYYY",h=(t==null?void 0:t.minYear)||1900,l=(t==null?void 0:t.maxYear)||3e3;if(u==="DD/MM/YYYY"){const y=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!y.test(e))return!1;[,s,n,r]=e.match(y)||[]}else if(u==="MM-DD-YYYY"){const y=/^(\d{2})-(\d{2})-(\d{4})$/;if(!y.test(e))return!1;[,n,s,r]=e.match(y)||[]}else if(u==="YYYY-MM-DD"){const y=/^(\d{4})-(\d{2})-(\d{2})$/;if(!y.test(e))return!1;[,r,n,s]=e.match(y)||[]}else throw new Error("Invalid date format");const c=parseInt(s,10),f=parseInt(n,10),i=parseInt(r,10);if(c<1||c>31||f<1||f>12)return!1;const g=[31,28,31,30,31,30,31,31,30,31,30,31];if(f===2){const y=i%4===0&&i%100!==0||i%400===0;if(c>(y?29:28))return!1}else if(c>g[f-1])return!1;return i<h||i>l?!1:new Date(i,f-1,c).getDate()===c},ms=M.promises.resolve;function Ts(e){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e)}function bs(e){return!(e.length===0||e.length>64||e.startsWith(".")||e.endsWith(".")||e.includes("..")||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(e))}function Rs(e){return!(e.length===0||e.length>63||e.startsWith("-")||e.endsWith("-")||!/^[a-zA-Z0-9-]+$/.test(e))}function xs(e){if(e.length===0||e.length>253||e.startsWith(".")||e.endsWith(".")||e.startsWith("-")||e.endsWith("-"))return!1;const t=e.split(".");if(t.length<2)return!1;for(const n of t)if(!Rs(n))return!1;const s=t[t.length-1];return!(s.length<2||!/^[a-zA-Z]+$/.test(s))}function Ns(e){const t=e.split("@");if(t.length!==2)return!1;const[s,n]=t;return!(!bs(s)||!xs(n))}function Ss(e){const t=e.split("@");return t.length===2?t[1].toLowerCase():null}const Es=["MX","A","AAAA"];async function Ds(e,t){try{return await ms(e,t),!0}catch{return!1}}async function vs(e){for(const t of Es)if(await Ds(e,t))return!0;return!1}const Os=async e=>{if(!e||typeof e!="string")return!1;const t=e.trim();if(!Ts(t)||!Ns(t))return!1;const s=Ss(t);return s?await vs(s):!1},Is=e=>{if(!e)return!1;const t=e.length>=8,s=/[A-Z]/.test(e),n=/[a-z]/.test(e),r=/\d/.test(e),u=/[!@#$%^&*(),.?":{}|<>_\-+=~`[\]\\\/]/.test(e);return[t,s,n,r,u].every(h=>h)},$s=e=>{for(const t of Y.countries){const s=t.code,n=t.prefix?`-${t.prefix}`:"",r=t.mask.replace(/[^_]/g,"").length;if(t.iso==="BR"){if(new RegExp(`^\\${s} \\d{2}9?\\d{8}$`).test(e))return!0;continue}if(new RegExp(`^\\${s}${n} \\d{${r}}$`).test(e))return!0}return!1},Cs=e=>{if(!e||!/^[0-9a-zA-Z.-]+$/.test(e))return!1;const s=e.replace(/[^a-zA-Z0-9]/g,"");return s.length<7||s.length>9?!1:/^[0-9]{7,8}[0-9Xx]?$/.test(s)};a.ApiService=ss,a.ArkynLogService=O,a.BadGateway=I,a.BadRequest=S,a.Conflict=$,a.Created=w,a.DebugService=v,a.Forbidden=C,a.Found=j,a.NoContent=J,a.NotFound=A,a.NotImplemented=k,a.SchemaValidator=as,a.ServerError=E,a.Success=L,a.Unauthorized=U,a.UnprocessableEntity=D,a.Updated=B,a.decodeErrorMessageFromRequest=es,a.decodeRequestBody=ts,a.errorHandler=ns,a.flushDebugLogs=T,a.formAsyncParse=q,a.formParse=F,a.getCaller=N,a.getScopedParams=rs,a.validateCep=us,a.validateCnpj=ls,a.validateCpf=ps,a.validateDate=gs,a.validateEmail=Os,a.validatePassword=Is,a.validatePhone=$s,a.validateRg=Cs,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
|
package/dist/index.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export { decodeErrorMessageFromRequest } from "./services/decodeErrorMessageFrom
|
|
|
19
19
|
export { decodeRequestBody } from "./services/decodeRequestBody";
|
|
20
20
|
export { errorHandler } from "./services/errorHandler";
|
|
21
21
|
export { flushDebugLogs } from "./services/flushDebugLogs";
|
|
22
|
+
export { formAsyncParse } from "./services/formAsyncParse";
|
|
22
23
|
export { formParse } from "./services/formParse";
|
|
23
24
|
export { getCaller } from "./services/getCaller";
|
|
24
25
|
export { getScopedParams } from "./services/getScopedParams";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG7D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAG9E,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG7D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@ export { decodeErrorMessageFromRequest } from "./services/decodeErrorMessageFrom
|
|
|
22
22
|
export { decodeRequestBody } from "./services/decodeRequestBody";
|
|
23
23
|
export { errorHandler } from "./services/errorHandler";
|
|
24
24
|
export { flushDebugLogs } from "./services/flushDebugLogs";
|
|
25
|
+
export { formAsyncParse } from "./services/formAsyncParse";
|
|
25
26
|
export { formParse } from "./services/formParse";
|
|
26
27
|
export { getCaller } from "./services/getCaller";
|
|
27
28
|
export { getScopedParams } from "./services/getScopedParams";
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { ZodType } from "zod";
|
|
2
|
+
type SuccessResponse<T extends FormParseProps> = {
|
|
3
|
+
success: true;
|
|
4
|
+
data: T[1] extends ZodType<infer U> ? U : never;
|
|
5
|
+
};
|
|
6
|
+
type ErrorResponse = {
|
|
7
|
+
success: false;
|
|
8
|
+
fields: {
|
|
9
|
+
[x: string]: string;
|
|
10
|
+
};
|
|
11
|
+
fieldErrors: {
|
|
12
|
+
[x: string]: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
type FormParseProps = [formData: {
|
|
16
|
+
[k: string]: any;
|
|
17
|
+
}, schema: ZodType];
|
|
18
|
+
type FormParseReturnType<T extends FormParseProps> = SuccessResponse<T> | ErrorResponse;
|
|
19
|
+
/**
|
|
20
|
+
* Asynchronously parses form data using a Zod schema and returns the result.
|
|
21
|
+
*
|
|
22
|
+
* @template T - A type that extends `FormParseProps`.
|
|
23
|
+
*
|
|
24
|
+
* @param {T} param0 - An array containing the form data and the Zod schema.
|
|
25
|
+
* @param {T[0]} param0[0] - The form data to be validated.
|
|
26
|
+
* @param {T[1]} param0[1] - The Zod schema used for validation.
|
|
27
|
+
*
|
|
28
|
+
* @returns {Promise<FormParseReturnType<T>>} A promise that resolves to an object containing the validation result.
|
|
29
|
+
* - If validation fails, it includes:
|
|
30
|
+
* - `success`: A boolean indicating the validation status (false).
|
|
31
|
+
* - `fieldErrors`: An object mapping field names to their respective error messages.
|
|
32
|
+
* - `fields`: The original form data.
|
|
33
|
+
* - If validation succeeds, it includes:
|
|
34
|
+
* - `success`: A boolean indicating the validation status (true).
|
|
35
|
+
* - `data`: The parsed and validated data.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* import { z } from "zod";
|
|
40
|
+
*
|
|
41
|
+
* const schema = z.object({
|
|
42
|
+
* name: z.string().min(1, "Name is required"),
|
|
43
|
+
* age: z.number().min(18, "Must be at least 18"),
|
|
44
|
+
* });
|
|
45
|
+
*
|
|
46
|
+
* const formData = { name: "", age: 17 };
|
|
47
|
+
*
|
|
48
|
+
* const result = await formAsyncParse([formData, schema]);
|
|
49
|
+
*
|
|
50
|
+
* if (!result.success) {
|
|
51
|
+
* console.log(result.fieldErrors); // { name: "Name is required", age: "Must be at least 18" }
|
|
52
|
+
* } else {
|
|
53
|
+
* console.log(result.data); // Parsed data
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
declare function formAsyncParse<T extends FormParseProps>([formData, schema,]: T): Promise<FormParseReturnType<T>>;
|
|
58
|
+
export { formAsyncParse };
|
|
59
|
+
//# sourceMappingURL=formAsyncParse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formAsyncParse.d.ts","sourceRoot":"","sources":["../../src/services/formAsyncParse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEnC,KAAK,eAAe,CAAC,CAAC,SAAS,cAAc,IAAI;IAC/C,OAAO,EAAE,IAAI,CAAC;IACd,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,KAAK,aAAa,GAAG;IACnB,OAAO,EAAE,KAAK,CAAC;IACf,MAAM,EAAE;QAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IAChC,WAAW,EAAE;QAAE,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;CACtC,CAAC;AAEF,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAExE,KAAK,mBAAmB,CAAC,CAAC,SAAS,cAAc,IAC7C,eAAe,CAAC,CAAC,CAAC,GAClB,aAAa,CAAC;AAElB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,iBAAe,cAAc,CAAC,CAAC,SAAS,cAAc,EAAE,CACtD,QAAQ,EACR,MAAM,EACP,EAAE,CAAC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAqBrC;AAED,OAAO,EAAE,cAAc,EAAE,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Asynchronously parses form data using a Zod schema and returns the result.
|
|
3
|
+
*
|
|
4
|
+
* @template T - A type that extends `FormParseProps`.
|
|
5
|
+
*
|
|
6
|
+
* @param {T} param0 - An array containing the form data and the Zod schema.
|
|
7
|
+
* @param {T[0]} param0[0] - The form data to be validated.
|
|
8
|
+
* @param {T[1]} param0[1] - The Zod schema used for validation.
|
|
9
|
+
*
|
|
10
|
+
* @returns {Promise<FormParseReturnType<T>>} A promise that resolves to an object containing the validation result.
|
|
11
|
+
* - If validation fails, it includes:
|
|
12
|
+
* - `success`: A boolean indicating the validation status (false).
|
|
13
|
+
* - `fieldErrors`: An object mapping field names to their respective error messages.
|
|
14
|
+
* - `fields`: The original form data.
|
|
15
|
+
* - If validation succeeds, it includes:
|
|
16
|
+
* - `success`: A boolean indicating the validation status (true).
|
|
17
|
+
* - `data`: The parsed and validated data.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* import { z } from "zod";
|
|
22
|
+
*
|
|
23
|
+
* const schema = z.object({
|
|
24
|
+
* name: z.string().min(1, "Name is required"),
|
|
25
|
+
* age: z.number().min(18, "Must be at least 18"),
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* const formData = { name: "", age: 17 };
|
|
29
|
+
*
|
|
30
|
+
* const result = await formAsyncParse([formData, schema]);
|
|
31
|
+
*
|
|
32
|
+
* if (!result.success) {
|
|
33
|
+
* console.log(result.fieldErrors); // { name: "Name is required", age: "Must be at least 18" }
|
|
34
|
+
* } else {
|
|
35
|
+
* console.log(result.data); // Parsed data
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
async function formAsyncParse([formData, schema,]) {
|
|
40
|
+
const zodResponse = await schema.safeParseAsync(formData);
|
|
41
|
+
if (zodResponse.success === false) {
|
|
42
|
+
const errorsObject = Object.fromEntries(zodResponse.error.issues.map((item) => {
|
|
43
|
+
return [item.path.join("."), item.message];
|
|
44
|
+
}));
|
|
45
|
+
return {
|
|
46
|
+
success: zodResponse.success,
|
|
47
|
+
fieldErrors: errorsObject,
|
|
48
|
+
fields: formData,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
return {
|
|
53
|
+
success: zodResponse.success,
|
|
54
|
+
data: zodResponse.data,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export { formAsyncParse };
|
|
@@ -1,13 +1,158 @@
|
|
|
1
1
|
import { ZodType, z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* A schema validator class that provides multiple validation methods for Zod schemas.
|
|
4
|
+
*
|
|
5
|
+
* @template T - A type that extends ZodType.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { z } from "zod";
|
|
10
|
+
*
|
|
11
|
+
* const userSchema = z.object({
|
|
12
|
+
* name: z.string().min(1, "Name is required"),
|
|
13
|
+
* email: z.string().email("Invalid email"),
|
|
14
|
+
* age: z.number().min(18, "Must be at least 18")
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* const validator = new SchemaValidator(userSchema);
|
|
18
|
+
*
|
|
19
|
+
* // Check if data is valid without throwing
|
|
20
|
+
* const isValid = validator.isValid({ name: "John", email: "john@example.com", age: 25 });
|
|
21
|
+
*
|
|
22
|
+
* // Validate and throw ServerError on failure
|
|
23
|
+
* try {
|
|
24
|
+
* const validData = validator.validate({ name: "John", email: "john@example.com", age: 25 });
|
|
25
|
+
* } catch (error) {
|
|
26
|
+
* console.error(error.message);
|
|
27
|
+
* }
|
|
28
|
+
*
|
|
29
|
+
* // Form validation with UnprocessableEntity error
|
|
30
|
+
* try {
|
|
31
|
+
* const formData = validator.formValidate(requestBody);
|
|
32
|
+
* } catch (error) {
|
|
33
|
+
* // Returns structured error with fieldErrors for forms
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
2
37
|
declare class SchemaValidator<T extends ZodType> {
|
|
3
38
|
readonly schema: T;
|
|
4
39
|
functionName: string;
|
|
5
40
|
callerInfo: string;
|
|
41
|
+
/**
|
|
42
|
+
* Creates a new SchemaValidator instance.
|
|
43
|
+
*
|
|
44
|
+
* @param {T} schema - The Zod schema to use for validation.
|
|
45
|
+
*/
|
|
6
46
|
constructor(schema: T);
|
|
47
|
+
/**
|
|
48
|
+
* Checks if the provided data is valid according to the schema without throwing errors.
|
|
49
|
+
*
|
|
50
|
+
* @param {any} data - The data to validate.
|
|
51
|
+
*
|
|
52
|
+
* @returns {boolean} True if the data is valid, false otherwise.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* const validator = new SchemaValidator(userSchema);
|
|
57
|
+
* const isValid = validator.isValid({ name: "John", email: "invalid-email" });
|
|
58
|
+
* console.log(isValid); // false
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
7
61
|
isValid(data: any): boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Safely validates data and returns the complete parse result without throwing errors.
|
|
64
|
+
*
|
|
65
|
+
* @param {any} data - The data to validate.
|
|
66
|
+
*
|
|
67
|
+
* @returns {z.ZodSafeParseResult<z.infer<T>>} The Zod safe parse result containing success status and data or error.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```typescript
|
|
71
|
+
* const validator = new SchemaValidator(userSchema);
|
|
72
|
+
* const result = validator.safeValidate({ name: "", email: "john@example.com" });
|
|
73
|
+
*
|
|
74
|
+
* if (result.success) {
|
|
75
|
+
* console.log(result.data); // Validated data
|
|
76
|
+
* } else {
|
|
77
|
+
* console.log(result.error.issues); // Validation errors
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
8
81
|
safeValidate(data: any): z.ZodSafeParseResult<z.infer<T>>;
|
|
82
|
+
/**
|
|
83
|
+
* Validates data and returns the parsed result, throwing a ServerError on validation failure.
|
|
84
|
+
*
|
|
85
|
+
* @param {any} data - The data to validate.
|
|
86
|
+
*
|
|
87
|
+
* @returns {z.infer<T>} The validated and parsed data.
|
|
88
|
+
*
|
|
89
|
+
* @throws {ServerError} When validation fails, with a formatted error message.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```typescript
|
|
93
|
+
* const validator = new SchemaValidator(userSchema);
|
|
94
|
+
*
|
|
95
|
+
* try {
|
|
96
|
+
* const validUser = validator.validate({ name: "John", email: "john@example.com", age: 25 });
|
|
97
|
+
* console.log(validUser); // { name: "John", email: "john@example.com", age: 25 }
|
|
98
|
+
* } catch (error) {
|
|
99
|
+
* console.error(error.message); // "Error validating:\n-> name: String must contain at least 1 character(s)"
|
|
100
|
+
* }
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
9
103
|
validate(data: any): z.infer<T>;
|
|
104
|
+
/**
|
|
105
|
+
* Validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
106
|
+
* This method is specifically designed for form validation in web applications.
|
|
107
|
+
*
|
|
108
|
+
* @param {any} data - The form data to validate.
|
|
109
|
+
* @param {string} [message] - Optional custom error message.
|
|
110
|
+
*
|
|
111
|
+
* @returns {z.infer<T>} The validated and parsed form data.
|
|
112
|
+
*
|
|
113
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* const validator = new SchemaValidator(userSchema);
|
|
118
|
+
*
|
|
119
|
+
* try {
|
|
120
|
+
* const validFormData = validator.formValidate(requestBody, "User data is invalid");
|
|
121
|
+
* console.log(validFormData);
|
|
122
|
+
* } catch (error) {
|
|
123
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
124
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
125
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
126
|
+
* }
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
10
129
|
formValidate(data: any, message?: string): z.infer<T>;
|
|
130
|
+
/**
|
|
131
|
+
* Asynchronously validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
132
|
+
* This method is the async version of formValidate, designed for form validation with async schemas.
|
|
133
|
+
*
|
|
134
|
+
* @param {any} data - The form data to validate.
|
|
135
|
+
* @param {string} [message] - Optional custom error message.
|
|
136
|
+
*
|
|
137
|
+
* @returns {Promise<z.infer<T>>} A promise that resolves to the validated and parsed form data.
|
|
138
|
+
*
|
|
139
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```typescript
|
|
143
|
+
* const validator = new SchemaValidator(userSchemaWithAsyncValidation);
|
|
144
|
+
*
|
|
145
|
+
* try {
|
|
146
|
+
* const validFormData = await validator.formAsyncValidate(requestBody, "User data is invalid");
|
|
147
|
+
* console.log(validFormData);
|
|
148
|
+
* } catch (error) {
|
|
149
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
150
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
151
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
152
|
+
* }
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
formAsyncValidate(data: any, message?: string): Promise<z.infer<T>>;
|
|
11
156
|
}
|
|
12
157
|
export { SchemaValidator };
|
|
13
158
|
//# sourceMappingURL=schemaValidator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiBjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,cAAM,eAAe,CAAC,CAAC,SAAS,OAAO;IASzB,QAAQ,CAAC,MAAM,EAAE,CAAC;IAR9B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IAEnB;;;;OAIG;gBACkB,MAAM,EAAE,CAAC;IAM9B;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO;IAI3B;;;;;;;;;;;;;;;;;;OAkBG;IACH,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAIzD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAQ/B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,YAAY,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAiBrD;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CAgB1E;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ZodType, z } from "zod";
|
|
2
2
|
import { ServerError } from "../http/badResponses/serverError";
|
|
3
3
|
import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
|
|
4
|
+
import { formAsyncParse } from "./formAsyncParse";
|
|
4
5
|
import { formParse } from "./formParse";
|
|
5
6
|
import { getCaller } from "./getCaller";
|
|
6
7
|
function formatErrorMessage(error) {
|
|
@@ -8,22 +9,116 @@ function formatErrorMessage(error) {
|
|
|
8
9
|
const lines = error.issues.map(({ path, message }) => `-> ${path.join(".")}: ${message}`);
|
|
9
10
|
return [title, ...lines].join("\n");
|
|
10
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* A schema validator class that provides multiple validation methods for Zod schemas.
|
|
14
|
+
*
|
|
15
|
+
* @template T - A type that extends ZodType.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* import { z } from "zod";
|
|
20
|
+
*
|
|
21
|
+
* const userSchema = z.object({
|
|
22
|
+
* name: z.string().min(1, "Name is required"),
|
|
23
|
+
* email: z.string().email("Invalid email"),
|
|
24
|
+
* age: z.number().min(18, "Must be at least 18")
|
|
25
|
+
* });
|
|
26
|
+
*
|
|
27
|
+
* const validator = new SchemaValidator(userSchema);
|
|
28
|
+
*
|
|
29
|
+
* // Check if data is valid without throwing
|
|
30
|
+
* const isValid = validator.isValid({ name: "John", email: "john@example.com", age: 25 });
|
|
31
|
+
*
|
|
32
|
+
* // Validate and throw ServerError on failure
|
|
33
|
+
* try {
|
|
34
|
+
* const validData = validator.validate({ name: "John", email: "john@example.com", age: 25 });
|
|
35
|
+
* } catch (error) {
|
|
36
|
+
* console.error(error.message);
|
|
37
|
+
* }
|
|
38
|
+
*
|
|
39
|
+
* // Form validation with UnprocessableEntity error
|
|
40
|
+
* try {
|
|
41
|
+
* const formData = validator.formValidate(requestBody);
|
|
42
|
+
* } catch (error) {
|
|
43
|
+
* // Returns structured error with fieldErrors for forms
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
11
47
|
class SchemaValidator {
|
|
12
48
|
schema;
|
|
13
49
|
functionName;
|
|
14
50
|
callerInfo;
|
|
51
|
+
/**
|
|
52
|
+
* Creates a new SchemaValidator instance.
|
|
53
|
+
*
|
|
54
|
+
* @param {T} schema - The Zod schema to use for validation.
|
|
55
|
+
*/
|
|
15
56
|
constructor(schema) {
|
|
16
57
|
this.schema = schema;
|
|
17
58
|
const { callerInfo, functionName } = getCaller();
|
|
18
59
|
this.callerInfo = callerInfo;
|
|
19
60
|
this.functionName = functionName;
|
|
20
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Checks if the provided data is valid according to the schema without throwing errors.
|
|
64
|
+
*
|
|
65
|
+
* @param {any} data - The data to validate.
|
|
66
|
+
*
|
|
67
|
+
* @returns {boolean} True if the data is valid, false otherwise.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```typescript
|
|
71
|
+
* const validator = new SchemaValidator(userSchema);
|
|
72
|
+
* const isValid = validator.isValid({ name: "John", email: "invalid-email" });
|
|
73
|
+
* console.log(isValid); // false
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
21
76
|
isValid(data) {
|
|
22
77
|
return this.schema.safeParse(data).success;
|
|
23
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Safely validates data and returns the complete parse result without throwing errors.
|
|
81
|
+
*
|
|
82
|
+
* @param {any} data - The data to validate.
|
|
83
|
+
*
|
|
84
|
+
* @returns {z.ZodSafeParseResult<z.infer<T>>} The Zod safe parse result containing success status and data or error.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```typescript
|
|
88
|
+
* const validator = new SchemaValidator(userSchema);
|
|
89
|
+
* const result = validator.safeValidate({ name: "", email: "john@example.com" });
|
|
90
|
+
*
|
|
91
|
+
* if (result.success) {
|
|
92
|
+
* console.log(result.data); // Validated data
|
|
93
|
+
* } else {
|
|
94
|
+
* console.log(result.error.issues); // Validation errors
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
24
98
|
safeValidate(data) {
|
|
25
99
|
return this.schema.safeParse(data);
|
|
26
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Validates data and returns the parsed result, throwing a ServerError on validation failure.
|
|
103
|
+
*
|
|
104
|
+
* @param {any} data - The data to validate.
|
|
105
|
+
*
|
|
106
|
+
* @returns {z.infer<T>} The validated and parsed data.
|
|
107
|
+
*
|
|
108
|
+
* @throws {ServerError} When validation fails, with a formatted error message.
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* const validator = new SchemaValidator(userSchema);
|
|
113
|
+
*
|
|
114
|
+
* try {
|
|
115
|
+
* const validUser = validator.validate({ name: "John", email: "john@example.com", age: 25 });
|
|
116
|
+
* console.log(validUser); // { name: "John", email: "john@example.com", age: 25 }
|
|
117
|
+
* } catch (error) {
|
|
118
|
+
* console.error(error.message); // "Error validating:\n-> name: String must contain at least 1 character(s)"
|
|
119
|
+
* }
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
27
122
|
validate(data) {
|
|
28
123
|
try {
|
|
29
124
|
return this.schema.parse(data);
|
|
@@ -32,6 +127,31 @@ class SchemaValidator {
|
|
|
32
127
|
throw new ServerError(formatErrorMessage(error));
|
|
33
128
|
}
|
|
34
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
132
|
+
* This method is specifically designed for form validation in web applications.
|
|
133
|
+
*
|
|
134
|
+
* @param {any} data - The form data to validate.
|
|
135
|
+
* @param {string} [message] - Optional custom error message.
|
|
136
|
+
*
|
|
137
|
+
* @returns {z.infer<T>} The validated and parsed form data.
|
|
138
|
+
*
|
|
139
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```typescript
|
|
143
|
+
* const validator = new SchemaValidator(userSchema);
|
|
144
|
+
*
|
|
145
|
+
* try {
|
|
146
|
+
* const validFormData = validator.formValidate(requestBody, "User data is invalid");
|
|
147
|
+
* console.log(validFormData);
|
|
148
|
+
* } catch (error) {
|
|
149
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
150
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
151
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
152
|
+
* }
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
35
155
|
formValidate(data, message) {
|
|
36
156
|
const formParsed = formParse([data, this.schema]);
|
|
37
157
|
if (!formParsed.success) {
|
|
@@ -45,5 +165,43 @@ class SchemaValidator {
|
|
|
45
165
|
}
|
|
46
166
|
return formParsed.data;
|
|
47
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* Asynchronously validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
|
|
170
|
+
* This method is the async version of formValidate, designed for form validation with async schemas.
|
|
171
|
+
*
|
|
172
|
+
* @param {any} data - The form data to validate.
|
|
173
|
+
* @param {string} [message] - Optional custom error message.
|
|
174
|
+
*
|
|
175
|
+
* @returns {Promise<z.infer<T>>} A promise that resolves to the validated and parsed form data.
|
|
176
|
+
*
|
|
177
|
+
* @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```typescript
|
|
181
|
+
* const validator = new SchemaValidator(userSchemaWithAsyncValidation);
|
|
182
|
+
*
|
|
183
|
+
* try {
|
|
184
|
+
* const validFormData = await validator.formAsyncValidate(requestBody, "User data is invalid");
|
|
185
|
+
* console.log(validFormData);
|
|
186
|
+
* } catch (error) {
|
|
187
|
+
* // UnprocessableEntity with fieldErrors, fields, and scrollTo data
|
|
188
|
+
* console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
|
|
189
|
+
* console.log(error.data.scrollTo); // "name" (first error field)
|
|
190
|
+
* }
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
async formAsyncValidate(data, message) {
|
|
194
|
+
const formParsed = await formAsyncParse([data, this.schema]);
|
|
195
|
+
if (!formParsed.success) {
|
|
196
|
+
const firstErrorKey = Object.keys(formParsed.fieldErrors)[0];
|
|
197
|
+
throw new UnprocessableEntity({
|
|
198
|
+
fields: formParsed.fields,
|
|
199
|
+
fieldErrors: formParsed.fieldErrors,
|
|
200
|
+
data: { scrollTo: firstErrorKey },
|
|
201
|
+
message,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return formParsed.data;
|
|
205
|
+
}
|
|
48
206
|
}
|
|
49
207
|
export { SchemaValidator };
|