@palmares/schemas 0.1.25 → 0.1.26

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.
Files changed (305) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/src/adapter/fields/array.cjs +96 -0
  3. package/dist/src/adapter/fields/array.d.ts.map +1 -0
  4. package/dist/src/adapter/fields/array.js +70 -0
  5. package/dist/src/adapter/fields/boolean.cjs +102 -0
  6. package/dist/src/adapter/fields/boolean.d.ts.map +1 -0
  7. package/dist/src/adapter/fields/boolean.js +76 -0
  8. package/dist/src/adapter/fields/datetime.cjs +102 -0
  9. package/dist/src/adapter/fields/datetime.d.ts.map +1 -0
  10. package/dist/src/adapter/fields/datetime.js +76 -0
  11. package/dist/src/adapter/fields/index.cjs +87 -0
  12. package/dist/src/adapter/fields/index.d.ts.map +1 -0
  13. package/dist/src/adapter/fields/index.js +61 -0
  14. package/dist/src/adapter/fields/number.cjs +102 -0
  15. package/dist/src/adapter/fields/number.d.ts.map +1 -0
  16. package/dist/src/adapter/fields/number.js +76 -0
  17. package/dist/src/adapter/fields/object.cjs +108 -0
  18. package/dist/src/adapter/fields/object.d.ts.map +1 -0
  19. package/dist/src/adapter/fields/object.js +82 -0
  20. package/dist/src/adapter/fields/string.cjs +102 -0
  21. package/dist/src/adapter/fields/string.d.ts.map +1 -0
  22. package/dist/src/adapter/fields/string.js +76 -0
  23. package/dist/src/adapter/fields/union.cjs +102 -0
  24. package/dist/src/adapter/fields/union.d.ts.map +1 -0
  25. package/dist/src/adapter/fields/union.js +76 -0
  26. package/dist/src/adapter/index.cjs +65 -0
  27. package/dist/src/adapter/index.d.ts.map +1 -0
  28. package/dist/src/adapter/index.js +40 -0
  29. package/dist/src/adapter/types.cjs +18 -0
  30. package/dist/src/adapter/types.d.ts.map +1 -0
  31. package/dist/src/adapter/types.js +0 -0
  32. package/dist/src/compile.cjs +59 -0
  33. package/dist/src/compile.d.ts.map +1 -0
  34. package/dist/src/compile.js +36 -0
  35. package/dist/src/conf.cjs +53 -0
  36. package/dist/src/conf.d.ts.map +1 -0
  37. package/dist/src/conf.js +27 -0
  38. package/dist/src/constants.cjs +40 -0
  39. package/dist/src/constants.d.ts.map +1 -0
  40. package/dist/src/constants.js +14 -0
  41. package/dist/src/domain.cjs +63 -0
  42. package/dist/src/domain.d.ts.map +1 -0
  43. package/dist/src/domain.js +40 -0
  44. package/dist/src/exceptions.cjs +58 -0
  45. package/dist/src/exceptions.d.ts.map +1 -0
  46. package/dist/src/exceptions.js +33 -0
  47. package/dist/src/index.cjs +6520 -0
  48. package/dist/src/index.d.ts.map +1 -0
  49. package/dist/src/index.js +6456 -0
  50. package/dist/src/middleware.cjs +58 -0
  51. package/dist/src/middleware.d.ts.map +1 -0
  52. package/dist/src/middleware.js +35 -0
  53. package/dist/src/model.cjs +6003 -0
  54. package/dist/src/model.d.ts.map +1 -0
  55. package/dist/src/model.js +5978 -0
  56. package/dist/src/parsers/convert-from-number.cjs +34 -0
  57. package/dist/src/parsers/convert-from-number.d.ts.map +1 -0
  58. package/dist/src/parsers/convert-from-number.js +11 -0
  59. package/dist/src/parsers/convert-from-string.cjs +40 -0
  60. package/dist/src/parsers/convert-from-string.d.ts.map +1 -0
  61. package/dist/src/parsers/convert-from-string.js +17 -0
  62. package/dist/src/parsers/index.cjs +50 -0
  63. package/dist/src/parsers/index.d.ts.map +1 -0
  64. package/dist/src/parsers/index.js +24 -0
  65. package/dist/src/schema/array.cjs +1863 -0
  66. package/dist/src/schema/array.d.ts.map +1 -0
  67. package/dist/src/schema/array.js +1837 -0
  68. package/dist/src/schema/boolean.cjs +1800 -0
  69. package/dist/src/schema/boolean.d.ts.map +1 -0
  70. package/dist/src/schema/boolean.js +1774 -0
  71. package/dist/src/schema/datetime.cjs +1789 -0
  72. package/dist/src/schema/datetime.d.ts.map +1 -0
  73. package/dist/src/schema/datetime.js +1763 -0
  74. package/dist/src/schema/index.cjs +2026 -0
  75. package/dist/src/schema/index.d.ts.map +1 -0
  76. package/dist/src/schema/index.js +2001 -0
  77. package/dist/src/schema/number.cjs +2026 -0
  78. package/dist/src/schema/number.d.ts.map +1 -0
  79. package/dist/src/schema/number.js +2000 -0
  80. package/dist/src/schema/object.cjs +1795 -0
  81. package/dist/src/schema/object.d.ts.map +1 -0
  82. package/dist/src/schema/object.js +1769 -0
  83. package/dist/src/schema/schema.cjs +844 -0
  84. package/dist/src/schema/schema.d.ts.map +1 -0
  85. package/dist/src/schema/schema.js +818 -0
  86. package/dist/src/schema/string.cjs +2126 -0
  87. package/dist/src/schema/string.d.ts.map +1 -0
  88. package/dist/src/schema/string.js +2100 -0
  89. package/dist/src/schema/types.cjs +18 -0
  90. package/dist/src/schema/types.d.ts.map +1 -0
  91. package/dist/src/schema/types.js +0 -0
  92. package/dist/src/schema/union.cjs +1737 -0
  93. package/dist/src/schema/union.d.ts.map +1 -0
  94. package/dist/src/schema/union.js +1711 -0
  95. package/dist/src/types.cjs +18 -0
  96. package/dist/src/types.d.ts.map +1 -0
  97. package/dist/src/types.js +0 -0
  98. package/dist/src/utils.cjs +477 -0
  99. package/dist/src/utils.d.ts.map +1 -0
  100. package/dist/src/utils.js +445 -0
  101. package/dist/src/validators/array.cjs +176 -0
  102. package/dist/src/validators/array.d.ts.map +1 -0
  103. package/dist/src/validators/array.js +150 -0
  104. package/dist/src/validators/boolean.cjs +71 -0
  105. package/dist/src/validators/boolean.d.ts.map +1 -0
  106. package/dist/src/validators/boolean.js +47 -0
  107. package/dist/src/validators/datetime.cjs +129 -0
  108. package/dist/src/validators/datetime.d.ts.map +1 -0
  109. package/dist/src/validators/datetime.js +103 -0
  110. package/dist/src/validators/number.cjs +194 -0
  111. package/dist/src/validators/number.d.ts.map +1 -0
  112. package/dist/src/validators/number.js +166 -0
  113. package/dist/src/validators/object.cjs +69 -0
  114. package/dist/src/validators/object.d.ts.map +1 -0
  115. package/dist/src/validators/object.js +46 -0
  116. package/dist/src/validators/schema.cjs +158 -0
  117. package/dist/src/validators/schema.d.ts.map +1 -0
  118. package/dist/src/validators/schema.js +132 -0
  119. package/dist/src/validators/string.cjs +255 -0
  120. package/dist/src/validators/string.d.ts.map +1 -0
  121. package/dist/src/validators/string.js +224 -0
  122. package/dist/src/validators/types.cjs +18 -0
  123. package/dist/src/validators/types.d.ts.map +1 -0
  124. package/dist/src/validators/types.js +0 -0
  125. package/dist/src/validators/union.cjs +69 -0
  126. package/dist/src/validators/union.d.ts.map +1 -0
  127. package/dist/src/validators/union.js +46 -0
  128. package/dist/src/validators/utils.cjs +165 -0
  129. package/dist/src/validators/utils.d.ts.map +1 -0
  130. package/dist/src/validators/utils.js +142 -0
  131. package/dist/tsconfig.types.tsbuildinfo +1 -0
  132. package/package.json +15 -23
  133. package/dist/cjs/src/adapter/fields/array.js +0 -152
  134. package/dist/cjs/src/adapter/fields/boolean.js +0 -162
  135. package/dist/cjs/src/adapter/fields/datetime.js +0 -162
  136. package/dist/cjs/src/adapter/fields/index.js +0 -311
  137. package/dist/cjs/src/adapter/fields/number.js +0 -162
  138. package/dist/cjs/src/adapter/fields/object.js +0 -171
  139. package/dist/cjs/src/adapter/fields/string.js +0 -162
  140. package/dist/cjs/src/adapter/fields/union.js +0 -162
  141. package/dist/cjs/src/adapter/index.js +0 -201
  142. package/dist/cjs/src/adapter/types.js +0 -4
  143. package/dist/cjs/src/compile.js +0 -262
  144. package/dist/cjs/src/conf.js +0 -26
  145. package/dist/cjs/src/constants.js +0 -36
  146. package/dist/cjs/src/domain.js +0 -156
  147. package/dist/cjs/src/exceptions.js +0 -168
  148. package/dist/cjs/src/index.js +0 -317
  149. package/dist/cjs/src/middleware.js +0 -213
  150. package/dist/cjs/src/model.js +0 -628
  151. package/dist/cjs/src/parsers/convert-from-number.js +0 -15
  152. package/dist/cjs/src/parsers/convert-from-string.js +0 -19
  153. package/dist/cjs/src/parsers/index.js +0 -20
  154. package/dist/cjs/src/schema/array.js +0 -1014
  155. package/dist/cjs/src/schema/boolean.js +0 -883
  156. package/dist/cjs/src/schema/datetime.js +0 -840
  157. package/dist/cjs/src/schema/index.js +0 -12
  158. package/dist/cjs/src/schema/number.js +0 -976
  159. package/dist/cjs/src/schema/object.js +0 -1052
  160. package/dist/cjs/src/schema/schema.js +0 -1840
  161. package/dist/cjs/src/schema/string.js +0 -1038
  162. package/dist/cjs/src/schema/types.js +0 -4
  163. package/dist/cjs/src/schema/union.js +0 -1070
  164. package/dist/cjs/src/types.js +0 -4
  165. package/dist/cjs/src/utils.js +0 -647
  166. package/dist/cjs/src/validators/array.js +0 -462
  167. package/dist/cjs/src/validators/boolean.js +0 -201
  168. package/dist/cjs/src/validators/datetime.js +0 -291
  169. package/dist/cjs/src/validators/number.js +0 -375
  170. package/dist/cjs/src/validators/object.js +0 -291
  171. package/dist/cjs/src/validators/schema.js +0 -322
  172. package/dist/cjs/src/validators/string.js +0 -467
  173. package/dist/cjs/src/validators/types.js +0 -4
  174. package/dist/cjs/src/validators/union.js +0 -233
  175. package/dist/cjs/src/validators/utils.js +0 -499
  176. package/dist/cjs/tsconfig.types.tsbuildinfo +0 -1
  177. package/dist/cjs/types/adapter/fields/array.d.ts.map +0 -1
  178. package/dist/cjs/types/adapter/fields/boolean.d.ts.map +0 -1
  179. package/dist/cjs/types/adapter/fields/datetime.d.ts.map +0 -1
  180. package/dist/cjs/types/adapter/fields/index.d.ts.map +0 -1
  181. package/dist/cjs/types/adapter/fields/number.d.ts.map +0 -1
  182. package/dist/cjs/types/adapter/fields/object.d.ts.map +0 -1
  183. package/dist/cjs/types/adapter/fields/string.d.ts.map +0 -1
  184. package/dist/cjs/types/adapter/fields/union.d.ts.map +0 -1
  185. package/dist/cjs/types/adapter/index.d.ts.map +0 -1
  186. package/dist/cjs/types/adapter/types.d.ts.map +0 -1
  187. package/dist/cjs/types/compile.d.ts.map +0 -1
  188. package/dist/cjs/types/conf.d.ts.map +0 -1
  189. package/dist/cjs/types/constants.d.ts.map +0 -1
  190. package/dist/cjs/types/domain.d.ts.map +0 -1
  191. package/dist/cjs/types/exceptions.d.ts.map +0 -1
  192. package/dist/cjs/types/index.d.ts.map +0 -1
  193. package/dist/cjs/types/middleware.d.ts.map +0 -1
  194. package/dist/cjs/types/model.d.ts.map +0 -1
  195. package/dist/cjs/types/parsers/convert-from-number.d.ts.map +0 -1
  196. package/dist/cjs/types/parsers/convert-from-string.d.ts.map +0 -1
  197. package/dist/cjs/types/parsers/index.d.ts.map +0 -1
  198. package/dist/cjs/types/schema/array.d.ts.map +0 -1
  199. package/dist/cjs/types/schema/boolean.d.ts.map +0 -1
  200. package/dist/cjs/types/schema/datetime.d.ts.map +0 -1
  201. package/dist/cjs/types/schema/index.d.ts.map +0 -1
  202. package/dist/cjs/types/schema/number.d.ts.map +0 -1
  203. package/dist/cjs/types/schema/object.d.ts.map +0 -1
  204. package/dist/cjs/types/schema/schema.d.ts.map +0 -1
  205. package/dist/cjs/types/schema/string.d.ts.map +0 -1
  206. package/dist/cjs/types/schema/types.d.ts.map +0 -1
  207. package/dist/cjs/types/schema/union.d.ts.map +0 -1
  208. package/dist/cjs/types/types.d.ts.map +0 -1
  209. package/dist/cjs/types/utils.d.ts.map +0 -1
  210. package/dist/cjs/types/validators/array.d.ts.map +0 -1
  211. package/dist/cjs/types/validators/boolean.d.ts.map +0 -1
  212. package/dist/cjs/types/validators/datetime.d.ts.map +0 -1
  213. package/dist/cjs/types/validators/number.d.ts.map +0 -1
  214. package/dist/cjs/types/validators/object.d.ts.map +0 -1
  215. package/dist/cjs/types/validators/schema.d.ts.map +0 -1
  216. package/dist/cjs/types/validators/string.d.ts.map +0 -1
  217. package/dist/cjs/types/validators/types.d.ts.map +0 -1
  218. package/dist/cjs/types/validators/union.d.ts.map +0 -1
  219. package/dist/cjs/types/validators/utils.d.ts.map +0 -1
  220. package/dist/esm/src/adapter/fields/array.js +0 -13
  221. package/dist/esm/src/adapter/fields/boolean.js +0 -20
  222. package/dist/esm/src/adapter/fields/datetime.js +0 -20
  223. package/dist/esm/src/adapter/fields/index.js +0 -37
  224. package/dist/esm/src/adapter/fields/number.js +0 -20
  225. package/dist/esm/src/adapter/fields/object.js +0 -26
  226. package/dist/esm/src/adapter/fields/string.js +0 -20
  227. package/dist/esm/src/adapter/fields/union.js +0 -20
  228. package/dist/esm/src/adapter/index.js +0 -21
  229. package/dist/esm/src/adapter/types.js +0 -1
  230. package/dist/esm/src/compile.js +0 -10
  231. package/dist/esm/src/conf.js +0 -18
  232. package/dist/esm/src/constants.js +0 -4
  233. package/dist/esm/src/domain.js +0 -11
  234. package/dist/esm/src/exceptions.js +0 -15
  235. package/dist/esm/src/index.js +0 -126
  236. package/dist/esm/src/middleware.js +0 -29
  237. package/dist/esm/src/model.js +0 -264
  238. package/dist/esm/src/parsers/convert-from-number.js +0 -8
  239. package/dist/esm/src/parsers/convert-from-string.js +0 -14
  240. package/dist/esm/src/parsers/index.js +0 -2
  241. package/dist/esm/src/schema/array.js +0 -487
  242. package/dist/esm/src/schema/boolean.js +0 -520
  243. package/dist/esm/src/schema/datetime.js +0 -477
  244. package/dist/esm/src/schema/index.js +0 -3
  245. package/dist/esm/src/schema/number.js +0 -610
  246. package/dist/esm/src/schema/object.js +0 -521
  247. package/dist/esm/src/schema/schema.js +0 -767
  248. package/dist/esm/src/schema/string.js +0 -668
  249. package/dist/esm/src/schema/types.js +0 -1
  250. package/dist/esm/src/schema/union.js +0 -468
  251. package/dist/esm/src/types.js +0 -14
  252. package/dist/esm/src/utils.js +0 -207
  253. package/dist/esm/src/validators/array.js +0 -140
  254. package/dist/esm/src/validators/boolean.js +0 -37
  255. package/dist/esm/src/validators/datetime.js +0 -89
  256. package/dist/esm/src/validators/number.js +0 -148
  257. package/dist/esm/src/validators/object.js +0 -39
  258. package/dist/esm/src/validators/schema.js +0 -118
  259. package/dist/esm/src/validators/string.js +0 -202
  260. package/dist/esm/src/validators/types.js +0 -1
  261. package/dist/esm/src/validators/union.js +0 -39
  262. package/dist/esm/src/validators/utils.js +0 -147
  263. /package/dist/{cjs/types → src}/adapter/fields/array.d.ts +0 -0
  264. /package/dist/{cjs/types → src}/adapter/fields/boolean.d.ts +0 -0
  265. /package/dist/{cjs/types → src}/adapter/fields/datetime.d.ts +0 -0
  266. /package/dist/{cjs/types → src}/adapter/fields/index.d.ts +0 -0
  267. /package/dist/{cjs/types → src}/adapter/fields/number.d.ts +0 -0
  268. /package/dist/{cjs/types → src}/adapter/fields/object.d.ts +0 -0
  269. /package/dist/{cjs/types → src}/adapter/fields/string.d.ts +0 -0
  270. /package/dist/{cjs/types → src}/adapter/fields/union.d.ts +0 -0
  271. /package/dist/{cjs/types → src}/adapter/index.d.ts +0 -0
  272. /package/dist/{cjs/types → src}/adapter/types.d.ts +0 -0
  273. /package/dist/{cjs/types → src}/compile.d.ts +0 -0
  274. /package/dist/{cjs/types → src}/conf.d.ts +0 -0
  275. /package/dist/{cjs/types → src}/constants.d.ts +0 -0
  276. /package/dist/{cjs/types → src}/domain.d.ts +0 -0
  277. /package/dist/{cjs/types → src}/exceptions.d.ts +0 -0
  278. /package/dist/{cjs/types → src}/index.d.ts +0 -0
  279. /package/dist/{cjs/types → src}/middleware.d.ts +0 -0
  280. /package/dist/{cjs/types → src}/model.d.ts +0 -0
  281. /package/dist/{cjs/types → src}/parsers/convert-from-number.d.ts +0 -0
  282. /package/dist/{cjs/types → src}/parsers/convert-from-string.d.ts +0 -0
  283. /package/dist/{cjs/types → src}/parsers/index.d.ts +0 -0
  284. /package/dist/{cjs/types → src}/schema/array.d.ts +0 -0
  285. /package/dist/{cjs/types → src}/schema/boolean.d.ts +0 -0
  286. /package/dist/{cjs/types → src}/schema/datetime.d.ts +0 -0
  287. /package/dist/{cjs/types → src}/schema/index.d.ts +0 -0
  288. /package/dist/{cjs/types → src}/schema/number.d.ts +0 -0
  289. /package/dist/{cjs/types → src}/schema/object.d.ts +0 -0
  290. /package/dist/{cjs/types → src}/schema/schema.d.ts +0 -0
  291. /package/dist/{cjs/types → src}/schema/string.d.ts +0 -0
  292. /package/dist/{cjs/types → src}/schema/types.d.ts +0 -0
  293. /package/dist/{cjs/types → src}/schema/union.d.ts +0 -0
  294. /package/dist/{cjs/types → src}/types.d.ts +0 -0
  295. /package/dist/{cjs/types → src}/utils.d.ts +0 -0
  296. /package/dist/{cjs/types → src}/validators/array.d.ts +0 -0
  297. /package/dist/{cjs/types → src}/validators/boolean.d.ts +0 -0
  298. /package/dist/{cjs/types → src}/validators/datetime.d.ts +0 -0
  299. /package/dist/{cjs/types → src}/validators/number.d.ts +0 -0
  300. /package/dist/{cjs/types → src}/validators/object.d.ts +0 -0
  301. /package/dist/{cjs/types → src}/validators/schema.d.ts +0 -0
  302. /package/dist/{cjs/types → src}/validators/string.d.ts +0 -0
  303. /package/dist/{cjs/types → src}/validators/types.d.ts +0 -0
  304. /package/dist/{cjs/types → src}/validators/union.d.ts +0 -0
  305. /package/dist/{cjs/types → src}/validators/utils.d.ts +0 -0
@@ -0,0 +1,1863 @@
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/schema/array.ts
22
+ var array_exports = {};
23
+ __export(array_exports, {
24
+ ArraySchema: () => ArraySchema,
25
+ array: () => array
26
+ });
27
+ module.exports = __toCommonJS(array_exports);
28
+
29
+ // src/exceptions.ts
30
+ var NoAdapterFoundError = class extends Error {
31
+ static {
32
+ __name(this, "NoAdapterFoundError");
33
+ }
34
+ constructor() {
35
+ super("No adapter found, please define an adapter using setDefaultAdapter() before using any schema.");
36
+ }
37
+ };
38
+
39
+ // src/conf.ts
40
+ function getDefaultAdapter() {
41
+ if (!globalThis.$PSchemasAdapter) throw new NoAdapterFoundError();
42
+ return globalThis.$PSchemasAdapter;
43
+ }
44
+ __name(getDefaultAdapter, "getDefaultAdapter");
45
+
46
+ // src/validators/schema.ts
47
+ function optional(args) {
48
+ return {
49
+ name: "optional",
50
+ type: "high",
51
+ // eslint-disable-next-line ts/require-await
52
+ callback: /* @__PURE__ */ __name(async (value, path) => {
53
+ if (value === void 0) {
54
+ if (args.allow === true) return {
55
+ parsed: value,
56
+ errors: [],
57
+ preventChildValidation: true
58
+ };
59
+ return {
60
+ parsed: value,
61
+ errors: [
62
+ {
63
+ isValid: false,
64
+ message: args.message,
65
+ code: "required",
66
+ // eslint-disable-next-line ts/no-unnecessary-condition
67
+ path: path || []
68
+ }
69
+ ],
70
+ preventChildValidation: true
71
+ };
72
+ }
73
+ return {
74
+ parsed: value,
75
+ errors: [],
76
+ preventChildValidation: false
77
+ };
78
+ }, "callback")
79
+ };
80
+ }
81
+ __name(optional, "optional");
82
+ function nullable(args) {
83
+ return {
84
+ name: "nullable",
85
+ type: "high",
86
+ // eslint-disable-next-line ts/require-await
87
+ callback: /* @__PURE__ */ __name(async (value, path) => {
88
+ if (value === null) {
89
+ if (args.allow === true) return {
90
+ parsed: value,
91
+ errors: [],
92
+ preventChildValidation: true
93
+ };
94
+ return {
95
+ parsed: value,
96
+ errors: [
97
+ {
98
+ isValid: false,
99
+ message: args.message,
100
+ code: "null",
101
+ // eslint-disable-next-line ts/no-unnecessary-condition
102
+ path: path || []
103
+ }
104
+ ],
105
+ preventChildValidation: true
106
+ };
107
+ }
108
+ return {
109
+ parsed: value,
110
+ errors: [],
111
+ preventChildValidation: false
112
+ };
113
+ }, "callback")
114
+ };
115
+ }
116
+ __name(nullable, "nullable");
117
+ function checkType(args) {
118
+ return {
119
+ name: "checkType",
120
+ type: "medium",
121
+ // eslint-disable-next-line ts/require-await
122
+ callback: /* @__PURE__ */ __name(async (value, path) => {
123
+ if (args.check(value)) return {
124
+ parsed: value,
125
+ errors: [],
126
+ preventChildValidation: false
127
+ };
128
+ return {
129
+ parsed: value,
130
+ errors: [
131
+ {
132
+ isValid: false,
133
+ message: args.message,
134
+ code: "invalid_type",
135
+ // eslint-disable-next-line ts/no-unnecessary-condition
136
+ path: path || []
137
+ }
138
+ ],
139
+ preventChildValidation: true
140
+ };
141
+ }, "callback")
142
+ };
143
+ }
144
+ __name(checkType, "checkType");
145
+
146
+ // src/validators/utils.ts
147
+ var priorityByType = {
148
+ low: 0,
149
+ medium: 1,
150
+ high: 2
151
+ };
152
+ var typeByPriority = Object.entries(priorityByType).reduce((acc, [key, value]) => {
153
+ acc[value] = key;
154
+ return acc;
155
+ }, {});
156
+ var Validator = class _Validator {
157
+ static {
158
+ __name(this, "Validator");
159
+ }
160
+ $$type = "$PValidator";
161
+ child;
162
+ parent;
163
+ fallbackNamesAdded = /* @__PURE__ */ new Set();
164
+ priority;
165
+ fallbacks = [];
166
+ constructor(type) {
167
+ this.fallbackNamesAdded = /* @__PURE__ */ new Set();
168
+ this.fallbacks = [];
169
+ this.priority = priorityByType[type];
170
+ }
171
+ /**
172
+ * We create all of the validators on the schema in order, i actually didn't want to go on that route but i
173
+ * found it easier to do so.
174
+ *
175
+ * The logic here is simple, if it's not the same priority we will walk on the linked list until we find
176
+ * a validator that matches the priority we are expecting. If we can't walk anymore, we create the next
177
+ * priority validator and append it to the linked list. Be aware that it's a double linked list, so we
178
+ * can walk both ways, from the end to the start and from the start to the end.
179
+ * So you don't really need to start from the root, the linked list can start from anywhere and it will
180
+ * find it's way through.
181
+ *
182
+ * I know there are better ways to do this instead of walking through the linked list, but like i explained
183
+ * before, this is enough for now.
184
+ *
185
+ * If the priority is higher than the current priority saved on the schema, we should substitute the
186
+ * rootValidator on the schema with the new one.
187
+ *
188
+ * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific schema.
189
+ * @param type - The type of the fallback that we are adding.
190
+ * @param fallback - The fallback function that we are adding.
191
+ * @param childOrParent - If we are adding a fallback to the child or to the parent.
192
+ * @param options - The options that we are passing to the fallback.
193
+ */
194
+ checkAppendOrCreate(schema2, type, fallbackName, fallback, childOrParent, options) {
195
+ const schemaWithProtected = schema2;
196
+ if (this[childOrParent]) this[childOrParent].addFallback(schemaWithProtected, type, fallbackName, fallback, options);
197
+ else {
198
+ const nextPriority = childOrParent === "child" ? this.priority - 1 : this.priority + 1;
199
+ if (Object.keys(typeByPriority).includes(String(nextPriority))) {
200
+ const nextType = typeByPriority[nextPriority];
201
+ const validatorInstance = new _Validator(nextType);
202
+ this[childOrParent] = validatorInstance;
203
+ this[childOrParent][childOrParent === "parent" ? "child" : "parent"] = this;
204
+ this[childOrParent].addFallback(schemaWithProtected, type, fallbackName, fallback, options);
205
+ if (nextPriority > schemaWithProtected.__rootFallbacksValidator.priority) schemaWithProtected.__rootFallbacksValidator = validatorInstance;
206
+ }
207
+ }
208
+ }
209
+ addFallback(schema2, type, fallbackName, fallback, options) {
210
+ if (this.fallbackNamesAdded.has(fallbackName) && options?.removeCurrent !== true) return;
211
+ this.fallbackNamesAdded.add(fallbackName);
212
+ const priority = priorityByType[type];
213
+ if (this.priority === priority) {
214
+ if (typeof options?.at === "number") this.fallbacks.splice(options.at, options.removeCurrent === true ? 1 : 0, fallback);
215
+ else this.fallbacks.push(fallback);
216
+ } else if (priority > this.priority) this.checkAppendOrCreate(schema2, type, fallbackName, fallback, "parent", options);
217
+ else if (priority < this.priority) this.checkAppendOrCreate(schema2, type, fallbackName, fallback, "child", options);
218
+ }
219
+ /**
220
+ * Validates the value against all of the fallbacks, the fallbacks are executed in order, from the highest
221
+ * priority to the lowest priority. A validator can stop the execution of the other validators if it feels
222
+ * like so. Like on the example of a value being null or undefined.
223
+ *
224
+ * @param errorsAsHashedSet - This is a set that contains all of the errors that we already found, this is
225
+ * used to avoid duplicated errors.
226
+ * @param path - The path that we are validating right now.
227
+ * @param parseResult - The result of the parsing, it contains the parsed value and the errors that we found.
228
+ * @param options - The options that we are passing to the fallback.
229
+ */
230
+ async validate(errorsAsHashedSet, path, parseResult, options) {
231
+ let doesItShouldPreventChildValidation = false;
232
+ for (const fallback of this.fallbacks) {
233
+ const { parsed, errors, preventChildValidation } = await fallback(parseResult.parsed, path, options);
234
+ parseResult.parsed = parsed;
235
+ for (const error of errors) {
236
+ if (error.isValid === false) {
237
+ const sortedError = Object.fromEntries(Object.entries(error).sort(([a], [b]) => a.localeCompare(b)));
238
+ const hashedError = JSON.stringify(sortedError);
239
+ if (errorsAsHashedSet.has(hashedError)) continue;
240
+ errorsAsHashedSet.add(hashedError);
241
+ if (!Array.isArray(parseResult.errors)) parseResult.errors = [];
242
+ parseResult.errors.push({
243
+ ...error,
244
+ received: parseResult.parsed
245
+ });
246
+ }
247
+ }
248
+ doesItShouldPreventChildValidation = doesItShouldPreventChildValidation || preventChildValidation || false;
249
+ }
250
+ if (this.child && doesItShouldPreventChildValidation === false) return await this.child.validate(errorsAsHashedSet, path, parseResult, options);
251
+ return parseResult;
252
+ }
253
+ /**
254
+ * This static method takes care of everything for you. This means that you should only call this method
255
+ * for appending new fallbacks, it takes care of creating the root validator and making sure that the
256
+ * rootValidator on the schema is the highest priority one.
257
+ *
258
+ * @param schema - The schema that we are working on right now, all fallbacks are tied to that specific
259
+ * schema. We automatically define the rootValidator on the schema so you don't need to worry about that.
260
+ * @param fallback - The fallback that we are adding. This is an object that contains the type of the
261
+ * fallback and the callback that we are adding.
262
+ * @param options - The options that we are passing to the fallback. Options like `at` and `removeCurrent`
263
+ * are passed to the `addFallback` method.
264
+ */
265
+ static createAndAppendFallback(schema2, fallback, options) {
266
+ const schemaWithProtected = schema2;
267
+ let validatorInstance = schemaWithProtected.__rootFallbacksValidator;
268
+ if (schemaWithProtected.__rootFallbacksValidator === void 0) {
269
+ validatorInstance = new _Validator(fallback.type);
270
+ schemaWithProtected.__rootFallbacksValidator = validatorInstance;
271
+ }
272
+ validatorInstance.addFallback(schema2, fallback.type, fallback.name, fallback.callback, options);
273
+ return validatorInstance;
274
+ }
275
+ toString(ident = 0) {
276
+ return `Priority: ${this.priority}
277
+ Fallbacks: ${this.fallbacks.length}
278
+ ${this.child ? `Children:
279
+ ${this.child.toString(ident + 2)}` : ""}`;
280
+ }
281
+ };
282
+
283
+ // src/utils.ts
284
+ var WithFallback = class {
285
+ static {
286
+ __name(this, "WithFallback");
287
+ }
288
+ $$type = "$PWithFallback";
289
+ fallbackFor;
290
+ transformedSchema;
291
+ adapterType;
292
+ constructor(adapterType, fallbackFor, transformedSchema) {
293
+ this.adapterType = adapterType;
294
+ this.fallbackFor = new Set(fallbackFor);
295
+ this.transformedSchema = transformedSchema;
296
+ }
297
+ };
298
+ function withFallbackFactory(adapterType) {
299
+ return (fallbackFor, transformedSchema) => new WithFallback(adapterType, fallbackFor, transformedSchema);
300
+ }
301
+ __name(withFallbackFactory, "withFallbackFactory");
302
+ async function defaultTransform(type, schema2, adapter, fieldAdapter, getValidationData, fallbackFunctions, options) {
303
+ const validationData = await Promise.resolve(getValidationData(false));
304
+ const validationDataForStringVersion = options.shouldAddStringVersion ? await Promise.resolve(getValidationData(true)) : void 0;
305
+ const schemaWithPrivateFields = schema2;
306
+ const checkIfShouldUseParserAndAppend = /* @__PURE__ */ __name((parser) => {
307
+ const isValidationDataAParser = validationData.parsers?.[parser] !== void 0;
308
+ if (isValidationDataAParser) schema2.__parsers._fallbacks.add(parser);
309
+ }, "checkIfShouldUseParserAndAppend");
310
+ const getExtendedOrNotSchemaAndString = /* @__PURE__ */ __name((schema3, toStringVersion) => {
311
+ const extendedOrNotSchema2 = typeof schemaWithPrivateFields.__extends?.callback === "function" ? schemaWithPrivateFields.__extends.callback(schema3) : schema3;
312
+ const extendedOrNotSchemaString2 = typeof schemaWithPrivateFields.__extends?.toStringCallback === "function" ? schemaWithPrivateFields.__extends.toStringCallback(toStringVersion) : toStringVersion;
313
+ return [
314
+ extendedOrNotSchema2,
315
+ extendedOrNotSchemaString2
316
+ ];
317
+ }, "getExtendedOrNotSchemaAndString");
318
+ const checkIfShouldAppendFallbackAndAppend = /* @__PURE__ */ __name((fallback) => {
319
+ const wereArgumentsForThatFallbackDefinedAndFallbackFunctionDefined = validationData[fallback] !== void 0 && fallbackFunctions[fallback] !== void 0;
320
+ if (wereArgumentsForThatFallbackDefinedAndFallbackFunctionDefined) {
321
+ const fallbackReturnType = fallbackFunctions[fallback](validationData[fallback]);
322
+ Validator.createAndAppendFallback(schema2, fallbackReturnType);
323
+ }
324
+ }, "checkIfShouldAppendFallbackAndAppend");
325
+ const appendRootFallback = /* @__PURE__ */ __name(() => {
326
+ if (options.validatorsIfFallbackOrNotSupported) {
327
+ const validatorsIfFallbackOrNotSupported = Array.isArray(options.validatorsIfFallbackOrNotSupported) ? options.validatorsIfFallbackOrNotSupported : [
328
+ options.validatorsIfFallbackOrNotSupported
329
+ ];
330
+ for (const fallback of validatorsIfFallbackOrNotSupported) Validator.createAndAppendFallback(schema2, fallback);
331
+ }
332
+ }, "appendRootFallback");
333
+ const appendRequiredFallbacks = /* @__PURE__ */ __name(() => {
334
+ const hasFallbacks = schemaWithPrivateFields.__rootFallbacksValidator?.["$$type"] === "$PValidator";
335
+ if (hasFallbacks) {
336
+ Validator.createAndAppendFallback(schema2, optional(schemaWithPrivateFields.__optional));
337
+ Validator.createAndAppendFallback(schema2, nullable(schemaWithPrivateFields.__nullable));
338
+ Validator.createAndAppendFallback(schema2, checkType(schemaWithPrivateFields.__type));
339
+ }
340
+ }, "appendRequiredFallbacks");
341
+ const isFieldAdapterNotSupportedForThatFieldType = fieldAdapter === void 0;
342
+ if (options.fallbackIfNotSupported !== void 0 && isFieldAdapterNotSupportedForThatFieldType) {
343
+ const existingFallbacks = Object.keys(fallbackFunctions);
344
+ const allParsers = Object.keys(validationData["parsers"]);
345
+ appendRootFallback();
346
+ for (const fallback of existingFallbacks) checkIfShouldAppendFallbackAndAppend(fallback);
347
+ for (const parser of allParsers) checkIfShouldUseParserAndAppend(parser);
348
+ appendRequiredFallbacks();
349
+ return options.fallbackIfNotSupported();
350
+ }
351
+ if (!fieldAdapter) throw new Error("The field adapter is not supported and no fallback was provided.");
352
+ const translatedSchemaOrWithFallback = await Promise.resolve(fieldAdapter.translate(adapter.field, {
353
+ withFallback: withFallbackFactory(type),
354
+ ...validationData
355
+ }));
356
+ let stringVersion = "";
357
+ if (options.shouldAddStringVersion) stringVersion = await fieldAdapter.toString(adapter, adapter.field, validationDataForStringVersion);
358
+ if (translatedSchemaOrWithFallback?.["$$type"] === "$PWithFallback") {
359
+ appendRootFallback();
360
+ for (const fallback of translatedSchemaOrWithFallback.fallbackFor) {
361
+ checkIfShouldAppendFallbackAndAppend(fallback);
362
+ checkIfShouldUseParserAndAppend(fallback);
363
+ }
364
+ const [extendedOrNotSchema2, extendedOrNotSchemaString2] = getExtendedOrNotSchemaAndString(translatedSchemaOrWithFallback.transformedSchema, stringVersion);
365
+ appendRequiredFallbacks();
366
+ return [
367
+ {
368
+ transformed: extendedOrNotSchema2,
369
+ asString: extendedOrNotSchemaString2
370
+ }
371
+ ];
372
+ }
373
+ const [extendedOrNotSchema, extendedOrNotSchemaString] = getExtendedOrNotSchemaAndString(translatedSchemaOrWithFallback, stringVersion);
374
+ return [
375
+ {
376
+ transformed: extendedOrNotSchema,
377
+ asString: extendedOrNotSchemaString
378
+ }
379
+ ];
380
+ }
381
+ __name(defaultTransform, "defaultTransform");
382
+ async function defaultTransformToAdapter(callback, schema2, transformedSchemas, options, type) {
383
+ const isTransformedSchemasEmpty = Object.keys(transformedSchemas).length <= 0;
384
+ if (isTransformedSchemasEmpty) {
385
+ const adapterInstanceToUse = (
386
+ // eslint-disable-next-line ts/no-unnecessary-condition
387
+ options.schemaAdapter?.["$$type"] === "$PSchemaAdapter" ? options.schemaAdapter : getDefaultAdapter()
388
+ );
389
+ schema2["__transformedSchemas"][adapterInstanceToUse.name] = {
390
+ transformed: false,
391
+ adapter: adapterInstanceToUse,
392
+ schemas: []
393
+ };
394
+ }
395
+ const schemaAdapterNameToUse = options.schemaAdapter?.name || Object.keys(transformedSchemas)[0];
396
+ const isACustomSchemaAdapterAndNotYetDefined = (
397
+ // eslint-disable-next-line ts/no-unnecessary-condition
398
+ transformedSchemas[schemaAdapterNameToUse] === void 0 && options.schemaAdapter !== void 0
399
+ );
400
+ if (isACustomSchemaAdapterAndNotYetDefined) transformedSchemas[schemaAdapterNameToUse] = {
401
+ transformed: false,
402
+ adapter: options.schemaAdapter,
403
+ schemas: []
404
+ };
405
+ const shouldTranslate = transformedSchemas[schemaAdapterNameToUse].transformed === false || options.force === true;
406
+ if (shouldTranslate) {
407
+ const translatedSchemas = await callback(transformedSchemas[schemaAdapterNameToUse].adapter);
408
+ transformedSchemas[schemaAdapterNameToUse].schemas = translatedSchemas;
409
+ transformedSchemas[schemaAdapterNameToUse].transformed = true;
410
+ }
411
+ transformedSchemas[schemaAdapterNameToUse].transformed = true;
412
+ return transformedSchemas[schemaAdapterNameToUse].schemas;
413
+ }
414
+ __name(defaultTransformToAdapter, "defaultTransformToAdapter");
415
+ async function formatErrorFromParseMethod(adapter, fieldAdapter, error, received, schema2, path, errorsAsHashedSet) {
416
+ const formattedError = await fieldAdapter.formatError(adapter, adapter.field, schema2, error);
417
+ formattedError.path = Array.isArray(formattedError.path) ? [
418
+ ...path,
419
+ ...formattedError.path
420
+ ] : path;
421
+ const formattedErrorAsParseResultError = formattedError;
422
+ formattedErrorAsParseResultError.isValid = false;
423
+ const sortedError = Object.fromEntries(Object.entries(formattedErrorAsParseResultError).sort(([a], [b]) => a.localeCompare(b)));
424
+ const hashedError = JSON.stringify(sortedError);
425
+ errorsAsHashedSet.add(JSON.stringify(sortedError));
426
+ formattedErrorAsParseResultError.received = received;
427
+ return formattedErrorAsParseResultError;
428
+ }
429
+ __name(formatErrorFromParseMethod, "formatErrorFromParseMethod");
430
+ async function transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schema2, options) {
431
+ const schemaWithProtected = schema2;
432
+ const transformedData = await schemaWithProtected.__transformToAdapter(options);
433
+ const doesKeyHaveFallback = schemaWithProtected.__rootFallbacksValidator !== void 0;
434
+ const doesKeyHaveToInternal = typeof schemaWithProtected.__toInternal === "function";
435
+ const doesKeyHaveToValidate = typeof schemaWithProtected.__toValidate === "function";
436
+ const doesKeyHaveToDefault = typeof schemaWithProtected.__defaultFunction === "function";
437
+ const doesKeyHaveRunBeforeParseAndData = typeof schemaWithProtected.__runBeforeParseAndData === "function";
438
+ const doesKeyHaveParserFallback = schemaWithProtected.__parsers._fallbacks.size > 0;
439
+ const shouldAddFallbackValidation = doesKeyHaveFallback || doesKeyHaveToInternal || doesKeyHaveToValidate || doesKeyHaveToDefault || doesKeyHaveParserFallback || doesKeyHaveRunBeforeParseAndData || // eslint-disable-next-line ts/no-unnecessary-condition
440
+ transformedData === void 0;
441
+ return [
442
+ transformedData,
443
+ shouldAddFallbackValidation
444
+ ];
445
+ }
446
+ __name(transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas, "transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas");
447
+ function shouldRunDataOnComplexSchemas(schema2) {
448
+ return schema2["__parsers"].high.size > 0 || schema2["__parsers"].medium.size > 0 || schema2["__parsers"].low.size > 0 || schema2["__parsers"]._fallbacks.size > 0 || typeof schema2["__runBeforeParseAndData"] === "function" || typeof schema2["__toRepresentation"] === "function" || typeof schema2["__defaultFunction"] === "function";
449
+ }
450
+ __name(shouldRunDataOnComplexSchemas, "shouldRunDataOnComplexSchemas");
451
+
452
+ // src/schema/schema.ts
453
+ var Schema = class _Schema {
454
+ static {
455
+ __name(this, "Schema");
456
+ }
457
+ $$type = "$PSchema";
458
+ fieldType = "schema";
459
+ // Those functions will assume control of the validation process on adapters, instead of the schema.
460
+ // Why this is used? The idea is that the Schema has NO idea
461
+ // that one of it's children might be an UnionSchema for example. The adapter might not support unions,
462
+ // so then we give control to the union. The parent schema will already have an array of translated
463
+ // adapter schemas. This means for a union with Number and String it'll generate two schemas, one for number
464
+ // and one for the value as String. Of course this gets multiplied. So if we have a union with Number and String.
465
+ // We should take those two schemas from the array and validate them individually. This logic is
466
+ // handled by the union schema. If we have an intersection type for example, instead of validating
467
+ // One schema OR the other, we validate one schema AND the other. This will be handled
468
+ // by the schema that contains that intersection logic.
469
+ __beforeValidationCallbacks = /* @__PURE__ */ new Map();
470
+ __cachedGetParent;
471
+ set __getParent(value) {
472
+ this.__cachedGetParent = value;
473
+ }
474
+ get __getParent() {
475
+ return this.__cachedGetParent;
476
+ }
477
+ __alreadyAppliedModel;
478
+ __runBeforeParseAndData;
479
+ __rootFallbacksValidator;
480
+ __saveCallback;
481
+ __modelOmitCallback;
482
+ __parsers = {
483
+ high: /* @__PURE__ */ new Map(),
484
+ medium: /* @__PURE__ */ new Map(),
485
+ low: /* @__PURE__ */ new Map(),
486
+ _fallbacks: /* @__PURE__ */ new Set()
487
+ };
488
+ __refinements = [];
489
+ __nullable = {
490
+ message: "Cannot be null",
491
+ allow: false
492
+ };
493
+ __optional = {
494
+ message: "Required",
495
+ allow: false
496
+ };
497
+ __extends = void 0;
498
+ __transformedSchemas = {};
499
+ __defaultFunction = void 0;
500
+ __toRepresentation = void 0;
501
+ __toValidate = void 0;
502
+ __toInternal = void 0;
503
+ __type = {
504
+ message: "Invalid type",
505
+ check: /* @__PURE__ */ __name(() => true, "check")
506
+ };
507
+ __getDefaultTransformedSchemas() {
508
+ const adapterInstance = getDefaultAdapter();
509
+ if (this.__transformedSchemas[adapterInstance.constructor.name] === void 0) this.__transformedSchemas[adapterInstance.constructor.name] = {
510
+ transformed: false,
511
+ adapter: adapterInstance,
512
+ schemas: []
513
+ };
514
+ }
515
+ /**
516
+ * This will validate the data with the fallbacks, so internally, without relaying on the schema adapter.
517
+ * This is nice because we can support things that the schema adapter is not able to support by default.
518
+ *
519
+ * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors.
520
+ * @param path - The path of the error.
521
+ * @param parseResult - The result of the parse method.
522
+ */
523
+ async __validateByFallbacks(path, parseResult, options) {
524
+ if (this.__rootFallbacksValidator) return this.__rootFallbacksValidator.validate(options.errorsAsHashedSet, path, parseResult, options);
525
+ return parseResult;
526
+ }
527
+ /**
528
+ * This will validate by the adapter. In other words, we send the data to the schema adapter and then we validate
529
+ * that data.
530
+ * So understand that, first we send the data to the adapter, the adapter validates it, then, after we validate
531
+ * from the adapter we validate with the fallbacks so we can do all of the extra validations not handled by
532
+ * the adapter.
533
+ *
534
+ * @param value - The value to be validated.
535
+ * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors on the validator.
536
+ * @param path - The path of the error so we can construct an object with the nested paths of the error.
537
+ * @param parseResult - The result of the parse method.
538
+ *
539
+ * @returns The result and the errors of the parse method.
540
+ */
541
+ async __validateByAdapter(adapter, fieldAdapter, schema2, value, path, options) {
542
+ const parseResult = {
543
+ errors: [],
544
+ parsed: value
545
+ };
546
+ parseResult.errors = [];
547
+ parseResult.parsed = value;
548
+ if (fieldAdapter === void 0 || typeof fieldAdapter.parse !== "function") return parseResult;
549
+ const adapterParseResult = await fieldAdapter.parse(adapter, adapter.field, schema2.transformed, value, options.args);
550
+ parseResult.parsed = adapterParseResult.parsed;
551
+ if (adapterParseResult.errors) {
552
+ if (Array.isArray(adapterParseResult.errors)) parseResult.errors = await Promise.all(adapterParseResult.errors.map(async (error) => formatErrorFromParseMethod(adapter, fieldAdapter, error, value, schema2.transformed, path, options.errorsAsHashedSet || /* @__PURE__ */ new Set())));
553
+ else parseResult.errors = [
554
+ await formatErrorFromParseMethod(adapter, fieldAdapter, parseResult.errors, value, schema2.transformed, path, options.errorsAsHashedSet || /* @__PURE__ */ new Set())
555
+ ];
556
+ }
557
+ parseResult.errors = parseResult.errors.filter((error) => typeof error !== "undefined");
558
+ return parseResult;
559
+ }
560
+ // eslint-disable-next-line ts/require-await
561
+ async __transformToAdapter(_options) {
562
+ throw new Error("Not implemented");
563
+ }
564
+ /** */
565
+ async __parsersToTransformValue(value, parsersToUse) {
566
+ let shouldStop = false;
567
+ for (const [parserName, parser] of this.__parsers.high.entries()) {
568
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
569
+ const result = await Promise.resolve(parser(value));
570
+ if (result.preventNextParsers) shouldStop = true;
571
+ value = result.value;
572
+ } else continue;
573
+ }
574
+ if (shouldStop === false) {
575
+ for (const [parserName, parser] of this.__parsers.medium.entries()) {
576
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
577
+ const result = await Promise.resolve(parser(value));
578
+ if (result.preventNextParsers) shouldStop = true;
579
+ value = result.value;
580
+ } else continue;
581
+ }
582
+ }
583
+ if (shouldStop === false) {
584
+ for (const [parserName, parser] of this.__parsers.low.entries()) {
585
+ if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
586
+ const result = await Promise.resolve(parser(value));
587
+ if (result.preventNextParsers) shouldStop = true;
588
+ value = result.value;
589
+ } else continue;
590
+ }
591
+ }
592
+ return value;
593
+ }
594
+ async __parse(value, path = [], options) {
595
+ this.__getDefaultTransformedSchemas();
596
+ if (typeof this.__runBeforeParseAndData === "function") await this.__runBeforeParseAndData(this);
597
+ const shouldRunToInternalToBubbleUp = options.toInternalToBubbleUp === void 0;
598
+ if (shouldRunToInternalToBubbleUp) options.toInternalToBubbleUp = [];
599
+ if (options.errorsAsHashedSet instanceof Set === false) options.errorsAsHashedSet = /* @__PURE__ */ new Set();
600
+ const shouldCallDefaultFunction = value === void 0 && typeof this.__defaultFunction === "function";
601
+ const shouldCallToValidateCallback = typeof this.__toValidate === "function";
602
+ const schemaAdapterFieldType = this.fieldType;
603
+ if (shouldCallDefaultFunction) value = await this.__defaultFunction();
604
+ if (shouldCallToValidateCallback) value = await Promise.resolve(this.__toValidate(value));
605
+ const parseResult = {
606
+ errors: [],
607
+ parsed: value
608
+ };
609
+ value = await this.__parsersToTransformValue(value, this.__parsers._fallbacks);
610
+ if (options.appendFallbacksBeforeAdapterValidation === void 0) options.appendFallbacksBeforeAdapterValidation = (schema2, name, callback) => {
611
+ if (this !== schema2) this.__beforeValidationCallbacks.set(name, callback);
612
+ };
613
+ if (this.__transformedSchemas[options.schemaAdapter?.constructor.name || getDefaultAdapter().constructor.name].transformed === false) await this.__transformToAdapter(options);
614
+ const adapterToUse = options.schemaAdapter ? options.schemaAdapter : Object.values(this.__transformedSchemas)[0].adapter;
615
+ const parsedResultsAfterFallbacks = await this.__validateByFallbacks(path, {
616
+ errors: parseResult.errors,
617
+ parsed: value
618
+ }, options);
619
+ parseResult.parsed = parsedResultsAfterFallbacks.parsed;
620
+ parseResult.errors = (parseResult.errors || []).concat(parsedResultsAfterFallbacks.errors || []);
621
+ if (this.__beforeValidationCallbacks.size > 0) {
622
+ for (const callback of this.__beforeValidationCallbacks.values()) {
623
+ const parsedValuesAfterValidationCallbacks = await callback(adapterToUse, adapterToUse[schemaAdapterFieldType], this, this.__transformedSchemas[adapterToUse.constructor.name].schemas, value, path, options);
624
+ parseResult.parsed = parsedValuesAfterValidationCallbacks.parsed;
625
+ parseResult.errors = Array.isArray(parseResult.errors) && Array.isArray(parsedValuesAfterValidationCallbacks.errors) ? [
626
+ ...parseResult.errors,
627
+ ...parsedValuesAfterValidationCallbacks.errors
628
+ ] : Array.isArray(parseResult.errors) ? parseResult.errors : parsedValuesAfterValidationCallbacks.errors;
629
+ }
630
+ } else {
631
+ const parsedValuesAfterValidatingByAdapter = await this.__validateByAdapter(adapterToUse, adapterToUse[schemaAdapterFieldType], this.__transformedSchemas[adapterToUse.constructor.name].schemas[0], value, path, options);
632
+ parseResult.parsed = parsedValuesAfterValidatingByAdapter.parsed;
633
+ parseResult.errors = (parseResult.errors || []).concat(parsedValuesAfterValidatingByAdapter.errors);
634
+ }
635
+ const hasToInternalCallback = typeof this.__toInternal === "function";
636
+ const shouldCallToInternalDuringParse = hasToInternalCallback && (options.toInternalToBubbleUp?.length === 0 || Array.isArray(options.toInternalToBubbleUp) === false);
637
+ const hasNoErrors = parseResult.errors === void 0 || (parseResult.errors || []).length === 0;
638
+ await Promise.all(this.__refinements.map(async (refinement) => {
639
+ const errorOrNothing = await Promise.resolve(refinement(parseResult.parsed));
640
+ if (typeof errorOrNothing === "undefined") return;
641
+ parseResult.errors.push({
642
+ isValid: false,
643
+ code: errorOrNothing.code,
644
+ message: errorOrNothing.message,
645
+ received: parseResult.parsed,
646
+ path
647
+ });
648
+ }));
649
+ if (shouldCallToInternalDuringParse && hasNoErrors) parseResult.parsed = await this.__toInternal(value);
650
+ if (shouldRunToInternalToBubbleUp && hasNoErrors) for (const functionToModifyResult of options.toInternalToBubbleUp || []) await functionToModifyResult();
651
+ return parseResult;
652
+ }
653
+ /**
654
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something
655
+ * that is not supported by default by the schema adapter.
656
+ *
657
+ * @example
658
+ * ```typescript
659
+ * import * as p from '@palmares/schemas';
660
+ *
661
+ * const numberSchema = p.number().refine((value) => {
662
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
663
+ * });
664
+ *
665
+ * const { errors, parsed } = await numberSchema.parse(-1);
666
+ *
667
+ * console.log(errors);
668
+ * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
669
+ * ```
670
+ *
671
+ * @param refinementCallback - The callback that will be called to validate the value.
672
+ * @param options - Options for the refinement.
673
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
674
+ */
675
+ refine(refinementCallback) {
676
+ this.__refinements.push(refinementCallback);
677
+ return this;
678
+ }
679
+ /**
680
+ * Allows the value to be either undefined or null.
681
+ *
682
+ * @example
683
+ * ```typescript
684
+ * import * as p from '@palmares/schemas';
685
+ *
686
+ * const numberSchema = p.number().optional();
687
+ *
688
+ * const { errors, parsed } = await numberSchema.parse(undefined);
689
+ *
690
+ * console.log(parsed); // undefined
691
+ *
692
+ * const { errors, parsed } = await numberSchema.parse(null);
693
+ *
694
+ * console.log(parsed); // null
695
+ *
696
+ * const { errors, parsed } = await numberSchema.parse(1);
697
+ *
698
+ * console.log(parsed); // 1
699
+ * ```
700
+ *
701
+ * @returns - The schema we are working with.
702
+ */
703
+ optional(options) {
704
+ this.__optional = {
705
+ message: typeof options?.message === "string" ? options.message : "Required",
706
+ allow: typeof options?.allow === "boolean" ? options.allow : true
707
+ };
708
+ return this;
709
+ }
710
+ /**
711
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when
712
+ * the value is NULL by setting the { message: 'Your custom message', allow: false } on the options.
713
+ *
714
+ * @example
715
+ * ```typescript
716
+ * import * as p from '@palmares/schemas';
717
+ *
718
+ * const numberSchema = p.number().nullable();
719
+ *
720
+ * const { errors, parsed } = await numberSchema.parse(null);
721
+ *
722
+ * console.log(parsed); // null
723
+ *
724
+ * const { errors, parsed } = await numberSchema.parse(undefined);
725
+ *
726
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
727
+ * ```
728
+ *
729
+ * @param options - The options for the nullable function.
730
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
731
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
732
+ *
733
+ * @returns The schema.
734
+ */
735
+ nullable(options) {
736
+ this.__nullable = {
737
+ message: typeof options?.message === "string" ? options.message : "Cannot be null",
738
+ allow: typeof options?.allow === "boolean" ? options.allow : true
739
+ };
740
+ return this;
741
+ }
742
+ /**
743
+ * Appends a custom schema to the schema, this way it will bypass the creation of the schema in runtime.
744
+ *
745
+ * By default when validating, on the first validation we create the schema. Just during the first validation.
746
+ * With this function, you bypass that, so you can speed up the validation process.
747
+ *
748
+ * @example
749
+ * ```typescript
750
+ * import * as p from '@palmares/schemas';
751
+ * import * as z from 'zod';
752
+ *
753
+ * const numberSchema = p.number().appendSchema(z.number());
754
+ *
755
+ * const { errors, parsed } = await numberSchema.parse(1);
756
+ * ```
757
+ *
758
+ * @param schema - The schema to be appended.
759
+ * @param args - The arguments for the schema.
760
+ * @param args.adapter - The adapter to be used. If not provided, the default adapter will be used.
761
+ *
762
+ * @returns The same schema again.
763
+ */
764
+ appendSchema(schema2, args) {
765
+ const adapter = args?.adapter || getDefaultAdapter();
766
+ this.__transformedSchemas[adapter.constructor.name] = {
767
+ transformed: true,
768
+ adapter,
769
+ schemas: [
770
+ schema2
771
+ ]
772
+ };
773
+ return this;
774
+ }
775
+ /**
776
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep
777
+ * that way otherwise it will set the value to undefined after it's validated.
778
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
779
+ * function. This will remove the value from the representation of the schema.
780
+ *
781
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
782
+ * function. But if you want to remove the value from the internal representation, you can pass the argument
783
+ * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
784
+ * the argument `toRepresentation` as true as well.
785
+ *
786
+ * @example
787
+ * ```typescript
788
+ * import * as p from '@palmares/schemas';
789
+ *
790
+ * const userSchema = p.object({
791
+ * id: p.number().optional(),
792
+ * name: p.string(),
793
+ * password: p.string().omit()
794
+ * });
795
+ *
796
+ * const user = await userSchema.data({
797
+ * id: 1,
798
+ * name: 'John Doe',
799
+ * password: '123456'
800
+ * });
801
+ *
802
+ * console.log(user); // { id: 1, name: 'John Doe' }
803
+ * ```
804
+ *
805
+ *
806
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call
807
+ * the {@link data} function.
808
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
809
+ * as true. Then if you still want to remove the value from the representation, you will need to pass the
810
+ * argument `toRepresentation` as true as well.
811
+ *
812
+ * @returns The schema.
813
+ */
814
+ omit(args) {
815
+ const toRepresentation = typeof args?.toRepresentation === "boolean" ? args.toRepresentation : typeof args?.toInternal !== "boolean";
816
+ const toInternal = typeof args?.toInternal === "boolean" ? args.toInternal : false;
817
+ if (toInternal) {
818
+ if (this.__toInternal) {
819
+ const toInternal2 = this.__toInternal;
820
+ this.__toInternal = async (value) => {
821
+ await toInternal2(value);
822
+ return void 0;
823
+ };
824
+ } else this.__toInternal = async () => void 0;
825
+ } else if (toRepresentation) {
826
+ if (this.__toRepresentation) {
827
+ const toRepresentation2 = this.__toRepresentation;
828
+ this.__toRepresentation = async (value) => {
829
+ await toRepresentation2(value);
830
+ return void 0;
831
+ };
832
+ } else this.__toRepresentation = async () => void 0;
833
+ }
834
+ return this;
835
+ }
836
+ /**
837
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
838
+ * source like a database. You should always return the schema after you save the value, that way we will always have
839
+ * the correct type of the schema after the save operation.
840
+ *
841
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
842
+ *
843
+ * @example
844
+ * ```typescript
845
+ * import * as p from '@palmares/schemas';
846
+ *
847
+ * import { User } from './models';
848
+ *
849
+ * const userSchema = p.object({
850
+ * id: p.number().optional(),
851
+ * name: p.string(),
852
+ * email: p.string().email(),
853
+ * }).onSave(async (value) => {
854
+ * // Create or update the user on the database using palmares models or any other library of your choice.
855
+ * if (value.id)
856
+ * await User.default.set(value, { search: { id: value.id } });
857
+ * else
858
+ * await User.default.set(value);
859
+ *
860
+ * return value;
861
+ * });
862
+ *
863
+ *
864
+ * // Then, on your controller, do something like this:
865
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
866
+ * if (isValid) {
867
+ * const savedValue = await save();
868
+ * return Response.json(savedValue, { status: 201 });
869
+ * }
870
+ *
871
+ * return Response.json({ errors }, { status: 400 });
872
+ * ```
873
+ *
874
+ * @param callback - The callback that will be called to save the value on an external source.
875
+ *
876
+ * @returns The schema.
877
+ */
878
+ onSave(callback) {
879
+ this.__saveCallback = callback;
880
+ return this;
881
+ }
882
+ /**
883
+ * This function is used to validate the schema and save the value to the database. It is used in
884
+ * conjunction with the {@link onSave} function.
885
+ *
886
+ * Different from other validation libraries, palmares schemas is aware that you want to save. On your
887
+ * routes/functions we recommend to ALWAYS use this function instead of {@link parse} directly. This is because
888
+ * this function by default will return an object with the property `save` or the `errors`. If the errors are present,
889
+ * you can return the errors to the user. If the save property is present, you can use to save the value to an
890
+ * external source. e.g. a database.
891
+ *
892
+ * @example
893
+ * ```typescript
894
+ * import * as p from '@palmares/schemas';
895
+ *
896
+ * import { User } from './models';
897
+ *
898
+ * const userSchema = p.object({
899
+ * id: p.number().optional(),
900
+ * name: p.string(),
901
+ * email: p.string().email(),
902
+ * }).onSave(async (value) => {
903
+ * // Create or update the user on the database using palmares models or any other library of your choice.
904
+ * if (value.id)
905
+ * await User.default.set(value, { search: { id: value.id } });
906
+ * else
907
+ * await User.default.set(value);
908
+ *
909
+ * return value;
910
+ * });
911
+ *
912
+ *
913
+ * // Then, on your controller, do something like this:
914
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
915
+ * if (isValid) {
916
+ * const savedValue = await save();
917
+ * return Response.json(savedValue, { status: 201 });
918
+ * }
919
+ *
920
+ * return Response.json({ errors }, { status: 400 });
921
+ * ```
922
+ *
923
+ * @param value - The value to be validated.
924
+ *
925
+ * @returns An object with the property isValid, if the value is valid, the function `save` will be present.
926
+ * If the value is invalid, the property errors will be present.
927
+ */
928
+ async validate(value, context) {
929
+ const { errors, parsed } = await this.__parse(value, [], {
930
+ context
931
+ });
932
+ if ((errors || []).length > 0) return {
933
+ isValid: false,
934
+ errors
935
+ };
936
+ return {
937
+ isValid: true,
938
+ save: /* @__PURE__ */ __name(async () => this._save.bind(this)(parsed, context), "save")
939
+ };
940
+ }
941
+ /**
942
+ * Internal function, when we call the {@link validate} function it's this function that gets called
943
+ * when the user uses the `save` function returned by the {@link validate} function if the value is valid.
944
+ *
945
+ * @param value - The value to be saved.
946
+ *
947
+ * @returns The value to representation.
948
+ */
949
+ async _save(value, context) {
950
+ if (this.__saveCallback) {
951
+ const result = await this.__saveCallback(value, context);
952
+ return this.data(result);
953
+ }
954
+ return this.data(value);
955
+ }
956
+ /**
957
+ * This function is used to validate and parse the value to the internal representation of the schema.
958
+ *
959
+ * @example
960
+ * ```typescript
961
+ * import * as p from '@palmares/schemas';
962
+ *
963
+ * const numberSchema = p.number().allowString();
964
+ *
965
+ * const { errors, parsed } = await numberSchema.parse('123');
966
+ *
967
+ * console.log(parsed); // 123
968
+ * ```
969
+ *
970
+ * @param value - The value to be parsed.
971
+ *
972
+ * @returns The parsed value.
973
+ */
974
+ async parse(value) {
975
+ return this.__parse(value, [], {});
976
+ }
977
+ /**
978
+ * This function is used to transform the value to the representation without validating it.
979
+ * This is useful when you want to return a data from a query directly to the user. But for example
980
+ * you are returning the data of a user, you can clean the password or any other sensitive data.
981
+ *
982
+ * @example
983
+ * ```typescript
984
+ * import * as p from '@palmares/schemas';
985
+ *
986
+ * const userSchema = p.object({
987
+ * id: p.number().optional(),
988
+ * name: p.string(),
989
+ * email: p.string().email(),
990
+ * password: p.string().optional()
991
+ * }).toRepresentation(async (value) => {
992
+ * return {
993
+ * id: value.id,
994
+ * name: value.name,
995
+ * email: value.email
996
+ * }
997
+ * });
998
+ *
999
+ * const user = await userSchema.data({
1000
+ * id: 1,
1001
+ * name: 'John Doe',
1002
+ * email: 'john@gmail.com',
1003
+ * password: '123456'
1004
+ * });
1005
+ * ```
1006
+ */
1007
+ async data(value) {
1008
+ this.__getDefaultTransformedSchemas();
1009
+ if (typeof this.__runBeforeParseAndData === "function") await this.__runBeforeParseAndData(this);
1010
+ value = await this.__parsersToTransformValue(value);
1011
+ if (this.__toRepresentation) value = await Promise.resolve(this.__toRepresentation(value));
1012
+ if (this.__defaultFunction && value === void 0) value = await Promise.resolve(this.__defaultFunction());
1013
+ return value;
1014
+ }
1015
+ instanceOf(args) {
1016
+ this.__type.check = typeof args.check === "function" ? args.check : this.__type.check;
1017
+ this.__type.message = typeof args.message === "string" ? args.message : this.__type.message;
1018
+ return this;
1019
+ }
1020
+ /**
1021
+ * This function is used to add a default value to the schema. If the value is either undefined or null,
1022
+ * the default value will be used.
1023
+ *
1024
+ * @example
1025
+ * ```typescript
1026
+ * import * as p from '@palmares/schemas';
1027
+ *
1028
+ * const numberSchema = p.number().default(0);
1029
+ *
1030
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1031
+ *
1032
+ * console.log(parsed); // 0
1033
+ * ```
1034
+ */
1035
+ default(defaultValueOrFunction) {
1036
+ const isFunction = typeof defaultValueOrFunction === "function";
1037
+ if (isFunction) this.__defaultFunction = defaultValueOrFunction;
1038
+ else this.__defaultFunction = async () => defaultValueOrFunction;
1039
+ return this;
1040
+ }
1041
+ /**
1042
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
1043
+ * this function to let you customize the custom schema your own way. Our API does not support passthrough?
1044
+ * No problem, you can use this function to customize the zod schema.
1045
+ *
1046
+ * @example
1047
+ * ```typescript
1048
+ * import * as p from '@palmares/schemas';
1049
+ *
1050
+ * const numberSchema = p.number().extends((schema) => {
1051
+ * return schema.nonnegative();
1052
+ * });
1053
+ *
1054
+ * const { errors, parsed } = await numberSchema.parse(-1);
1055
+ *
1056
+ * console.log(errors);
1057
+ * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
1058
+ * ```
1059
+ *
1060
+ * @param callback - The callback that will be called to customize the schema.
1061
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you want
1062
+ * to compile the underlying schema to a string so you can save it for future runs.
1063
+ *
1064
+ * @returns The schema.
1065
+ */
1066
+ extends(callback, toStringCallback) {
1067
+ this.__extends = {
1068
+ callback,
1069
+ toStringCallback
1070
+ };
1071
+ return this;
1072
+ }
1073
+ /**
1074
+ * This function is used to transform the value to the representation of the schema. When using the {@link data}
1075
+ * function. With this function you have full control to add data cleaning for example, transforming the data
1076
+ * and whatever. Another use case is when you want to return deeply nested recursive data.
1077
+ * The schema maps to itself.
1078
+ *
1079
+ * @example
1080
+ * ```typescript
1081
+ * import * as p from '@palmares/schemas';
1082
+ *
1083
+ * const recursiveSchema = p.object({
1084
+ * id: p.number().optional(),
1085
+ * name: p.string(),
1086
+ * }).toRepresentation(async (value) => {
1087
+ * return {
1088
+ * id: value.id,
1089
+ * name: value.name,
1090
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
1091
+ * }
1092
+ * });
1093
+ *
1094
+ * const data = await recursiveSchema.data({
1095
+ * id: 1,
1096
+ * name: 'John Doe',
1097
+ * });
1098
+ * ```
1099
+ *
1100
+ * @example
1101
+ * ```
1102
+ * import * as p from '@palmares/schemas';
1103
+ *
1104
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
1105
+ * switch (value) {
1106
+ * case 'red': return { r: 255, g: 0, b: 0 };
1107
+ * case 'green': return { r: 0, g: 255, b: 0 };
1108
+ * case 'blue': return { r: 0, g: 0, b: 255 };
1109
+ * default: return { r: 0, g: 0, b: 0 };
1110
+ * }
1111
+ * });
1112
+ * ```
1113
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
1114
+ * @param options - Options for the toRepresentation function.
1115
+ * @param options.after - Whether the toRepresentationCallback should be called after the existing
1116
+ * toRepresentationCallback. Defaults to true.
1117
+ * @param options.before - Whether the toRepresentationCallback should be called before the existing
1118
+ * toRepresentationCallback. Defaults to true.
1119
+ *
1120
+ * @returns The schema with a new return type
1121
+ */
1122
+ toRepresentation(toRepresentationCallback, options) {
1123
+ if (this.__toRepresentation) {
1124
+ const before = typeof options?.before === "boolean" ? options.before : typeof options?.after === "boolean" ? !options.after : true;
1125
+ const existingToRepresentation = this.__toRepresentation;
1126
+ this.__toRepresentation = async (value) => {
1127
+ if (before) return toRepresentationCallback(await existingToRepresentation(value));
1128
+ else return existingToRepresentation(await toRepresentationCallback(value));
1129
+ };
1130
+ } else this.__toRepresentation = toRepresentationCallback;
1131
+ return this;
1132
+ }
1133
+ /**
1134
+ * This function is used to transform the value to the internal representation of the schema. This is useful
1135
+ * when you want to transform the value to a type that the schema adapter can understand. For example, you
1136
+ * might want to transform a string to a date. This is the function you use.
1137
+ *
1138
+ * @example
1139
+ * ```typescript
1140
+ * import * as p from '@palmares/schemas';
1141
+ *
1142
+ * const dateSchema = p.string().toInternal((value) => {
1143
+ * return new Date(value);
1144
+ * });
1145
+ *
1146
+ * const date = await dateSchema.parse('2021-01-01');
1147
+ *
1148
+ * console.log(date); // Date object
1149
+ *
1150
+ * const rgbToColorSchema = p.object({
1151
+ * r: p.number().min(0).max(255),
1152
+ * g: p.number().min(0).max(255),
1153
+ * b: p.number().min(0).max(255),
1154
+ * }).toInternal(async (value) => {
1155
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
1156
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
1157
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
1158
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
1159
+ * });
1160
+ * ```
1161
+ *
1162
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
1163
+ *
1164
+ * @returns The schema with a new return type.
1165
+ */
1166
+ toInternal(toInternalCallback) {
1167
+ if (this.__toInternal) {
1168
+ const toInternal = this.__toInternal;
1169
+ this.__toInternal = async (value) => {
1170
+ const newValue = await toInternal(value);
1171
+ return toInternalCallback(newValue);
1172
+ };
1173
+ } else this.__toInternal = toInternalCallback;
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a
1178
+ * string, you can convert that string to a date here BEFORE the validation. This pretty much transforms the value
1179
+ * to a type that the schema adapter can understand.
1180
+ *
1181
+ * @example
1182
+ * ```
1183
+ * import * as p from '@palmares/schemas';
1184
+ * import * as z from 'zod';
1185
+ *
1186
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
1187
+ * return new Map(value); // Before validating we transform the value to a map.
1188
+ * });
1189
+ *
1190
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
1191
+ * ```
1192
+ *
1193
+ * @param toValidateCallback - The callback that will be called to validate the value.
1194
+ *
1195
+ * @returns The schema with a new return type.
1196
+ */
1197
+ toValidate(toValidateCallback) {
1198
+ this.__toValidate = toValidateCallback;
1199
+ return this;
1200
+ }
1201
+ /**
1202
+ * Used to transform the given schema on a stringfied version of the adapter.
1203
+ */
1204
+ async compile(adapter) {
1205
+ const data = await this.__transformToAdapter({
1206
+ shouldAddStringVersion: true,
1207
+ force: true
1208
+ });
1209
+ const stringVersions = data.map((value) => value.asString);
1210
+ return stringVersions;
1211
+ }
1212
+ static new(..._args) {
1213
+ const result = new _Schema();
1214
+ return result;
1215
+ }
1216
+ };
1217
+ var schema = Schema.new;
1218
+
1219
+ // src/validators/array.ts
1220
+ function arrayValidation(isTuple, schemas) {
1221
+ return {
1222
+ name: "array",
1223
+ type: "medium",
1224
+ callback: /* @__PURE__ */ __name(async (value, path, options) => {
1225
+ const isNotAnArray = Array.isArray(value) === false;
1226
+ if (isNotAnArray) return {
1227
+ parsed: value,
1228
+ preventChildValidation: true,
1229
+ errors: [
1230
+ {
1231
+ isValid: false,
1232
+ code: "array",
1233
+ // eslint-disable-next-line ts/no-unnecessary-condition
1234
+ path: path || [],
1235
+ message: "The value must be an array. Received: " + typeof value
1236
+ }
1237
+ ]
1238
+ };
1239
+ if (isTuple && value.length !== schemas.length) return {
1240
+ parsed: value,
1241
+ preventChildValidation: true,
1242
+ errors: [
1243
+ {
1244
+ isValid: false,
1245
+ code: "tuple",
1246
+ // eslint-disable-next-line ts/no-unnecessary-condition
1247
+ path: path || [],
1248
+ message: "The tuple must have exactly " + schemas.length + " elements. Received: " + value.length
1249
+ }
1250
+ ]
1251
+ };
1252
+ const errorsOfArray = [];
1253
+ const schemaIndexByTypeof = /* @__PURE__ */ new Map();
1254
+ let parsedValues = [];
1255
+ parsedValues = await Promise.all(value.map(async (element, index) => {
1256
+ let errorsToAppendAfterLoopIfNoSchemaMatched = [];
1257
+ const typeofElement = typeof element;
1258
+ const schemaIndex = schemaIndexByTypeof.get(typeofElement);
1259
+ const existsASchemaIndex = typeof schemaIndex === "number";
1260
+ const schemasToValidateAgainst = isTuple ? [
1261
+ schemas[index]
1262
+ ] : existsASchemaIndex ? [
1263
+ schemas[schemaIndex]
1264
+ ] : schemas;
1265
+ for (let indexOfSchema = 0; indexOfSchema < schemasToValidateAgainst.length; indexOfSchema++) {
1266
+ const schemaToValidate = schemasToValidateAgainst[indexOfSchema];
1267
+ const schemaWithProtected = schemaToValidate;
1268
+ const { parsed, errors } = await schemaWithProtected.__parse(element, [
1269
+ ...path,
1270
+ index
1271
+ ], options);
1272
+ if (schemaWithProtected.__toInternal && options.toInternalToBubbleUp) options.toInternalToBubbleUp.push(async () => parsedValues[indexOfSchema] = await schemaWithProtected.__toInternal?.(parsed));
1273
+ if ((errors || []).length <= 0) {
1274
+ errorsToAppendAfterLoopIfNoSchemaMatched = [];
1275
+ schemaIndexByTypeof.set(typeofElement, indexOfSchema);
1276
+ return parsed;
1277
+ }
1278
+ errorsToAppendAfterLoopIfNoSchemaMatched.push(...errors);
1279
+ }
1280
+ errorsOfArray.push(...errorsToAppendAfterLoopIfNoSchemaMatched);
1281
+ return element;
1282
+ }));
1283
+ return {
1284
+ parsed: parsedValues,
1285
+ errors: errorsOfArray
1286
+ };
1287
+ }, "callback")
1288
+ };
1289
+ }
1290
+ __name(arrayValidation, "arrayValidation");
1291
+ function minLength(args) {
1292
+ return {
1293
+ name: "minLength",
1294
+ type: "low",
1295
+ // eslint-disable-next-line ts/require-await
1296
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
1297
+ const isValid = args.inclusive ? value.length >= args.value : value.length > args.value;
1298
+ return {
1299
+ parsed: value,
1300
+ errors: isValid ? [] : [
1301
+ {
1302
+ isValid: false,
1303
+ code: "minLength",
1304
+ // eslint-disable-next-line ts/no-unnecessary-condition
1305
+ path: path || [],
1306
+ message: args.message
1307
+ }
1308
+ ]
1309
+ };
1310
+ }, "callback")
1311
+ };
1312
+ }
1313
+ __name(minLength, "minLength");
1314
+ function maxLength(args) {
1315
+ return {
1316
+ name: "maxLength",
1317
+ type: "low",
1318
+ // eslint-disable-next-line ts/require-await
1319
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
1320
+ const isValid = args.inclusive ? value.length <= args.value : value.length < args.value;
1321
+ return {
1322
+ parsed: value,
1323
+ errors: isValid ? [] : [
1324
+ {
1325
+ isValid: false,
1326
+ code: "maxLength",
1327
+ // eslint-disable-next-line ts/no-unnecessary-condition
1328
+ path: path || [],
1329
+ message: args.message
1330
+ }
1331
+ ]
1332
+ };
1333
+ }, "callback")
1334
+ };
1335
+ }
1336
+ __name(maxLength, "maxLength");
1337
+ function nonEmpty(args) {
1338
+ return {
1339
+ name: "nonEmpty",
1340
+ type: "low",
1341
+ // eslint-disable-next-line ts/require-await
1342
+ callback: /* @__PURE__ */ __name(async (value, path, _options) => {
1343
+ const isValid = value.length > 0;
1344
+ return {
1345
+ parsed: value,
1346
+ errors: isValid ? [] : [
1347
+ {
1348
+ isValid: false,
1349
+ code: "nonEmpty",
1350
+ // eslint-disable-next-line ts/no-unnecessary-condition
1351
+ path: path || [],
1352
+ message: args.message
1353
+ }
1354
+ ]
1355
+ };
1356
+ }, "callback")
1357
+ };
1358
+ }
1359
+ __name(nonEmpty, "nonEmpty");
1360
+
1361
+ // src/schema/array.ts
1362
+ var ArraySchema = class _ArraySchema extends Schema {
1363
+ static {
1364
+ __name(this, "ArraySchema");
1365
+ }
1366
+ $$type = "$PArraySchema";
1367
+ fieldType = "array";
1368
+ __schemas;
1369
+ __type = {
1370
+ message: "Invalid type",
1371
+ check: /* @__PURE__ */ __name((value) => Array.isArray(value), "check")
1372
+ };
1373
+ __minLength;
1374
+ __maxLength;
1375
+ __nonEmpty;
1376
+ constructor(...schemas) {
1377
+ super();
1378
+ this.__schemas = schemas;
1379
+ }
1380
+ async __transformToAdapter(options) {
1381
+ return defaultTransformToAdapter(async (adapter) => {
1382
+ const schemas = Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas;
1383
+ const transformedSchemasAsString = [];
1384
+ const transformedSchemas = [];
1385
+ let shouldBeHandledByFallback = false;
1386
+ await Promise.all(schemas.map(async (schema2) => {
1387
+ const [transformedData, shouldAddFallbackValidationForThisSchema] = await transformSchemaAndCheckIfShouldBeHandledByFallbackOnComplexSchemas(schema2, options);
1388
+ if (shouldAddFallbackValidationForThisSchema) shouldBeHandledByFallback = true;
1389
+ for (const transformedSchema of transformedData) {
1390
+ transformedSchemasAsString.push(transformedSchema.asString);
1391
+ transformedSchemas.push(transformedSchema.transformed);
1392
+ }
1393
+ }));
1394
+ if (shouldBeHandledByFallback) Validator.createAndAppendFallback(this, arrayValidation(Array.isArray(this.__schemas[0]) === false, Array.isArray(this.__schemas[0]) ? this.__schemas[0] : this.__schemas));
1395
+ return defaultTransform("array", this, adapter, adapter.array, () => ({
1396
+ isTuple: Array.isArray(this.__schemas[0]) === false,
1397
+ nullable: this.__nullable,
1398
+ optional: this.__optional,
1399
+ maxLength: this.__maxLength,
1400
+ minLength: this.__minLength,
1401
+ nonEmpty: this.__nonEmpty,
1402
+ schemas: transformedSchemas,
1403
+ type: this.__type,
1404
+ parsers: {
1405
+ nullable: this.__nullable.allow,
1406
+ optional: this.__optional.allow
1407
+ }
1408
+ }), {
1409
+ optional,
1410
+ nullable,
1411
+ minLength,
1412
+ maxLength,
1413
+ nonEmpty
1414
+ }, {
1415
+ shouldAddStringVersion: options.shouldAddStringVersion,
1416
+ // eslint-disable-next-line ts/require-await
1417
+ fallbackIfNotSupported: /* @__PURE__ */ __name(async () => [], "fallbackIfNotSupported")
1418
+ });
1419
+ }, this, this.__transformedSchemas, options, "array");
1420
+ }
1421
+ /**
1422
+ * This let's you refine the schema with custom validations. This is useful when you want to validate something that
1423
+ * is not supported by default by the schema adapter.
1424
+ *
1425
+ * @example
1426
+ * ```typescript
1427
+ * import * as p from '@palmares/schemas';
1428
+ *
1429
+ * const numberSchema = p.number().refine((value) => {
1430
+ * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
1431
+ * });
1432
+ *
1433
+ * const { errors, parsed } = await numberSchema.parse(-1);
1434
+ *
1435
+ * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
1436
+ * console.log(errors);
1437
+ * ```
1438
+ *
1439
+ * @param refinementCallback - The callback that will be called to validate the value.
1440
+ * @param options - Options for the refinement.
1441
+ * @param options.isAsync - Whether the callback is async or not. Defaults to true.
1442
+ */
1443
+ refine(refinementCallback) {
1444
+ return super.refine(refinementCallback);
1445
+ }
1446
+ /**
1447
+ * Allows the value to be either undefined or null. Different from the `optional` method on other schemas, You can
1448
+ * pass `outputOnly` as `true` to this method.
1449
+ * This will allow you to pass `null` or `undefined` as a value on the {@link Schema.data} method, but it will not
1450
+ * allow the value to be `null` or `undefined`. This is useful for typing purposes.
1451
+ *
1452
+ * @example
1453
+ * ```typescript
1454
+ * import * as p from '@palmares/schemas';
1455
+ *
1456
+ * const numberSchema = p.number().optional();
1457
+ *
1458
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1459
+ *
1460
+ * console.log(parsed); // undefined
1461
+ *
1462
+ * const { errors, parsed } = await numberSchema.parse(null);
1463
+ *
1464
+ * console.log(parsed); // null
1465
+ *
1466
+ * const { errors, parsed } = await numberSchema.parse(1);
1467
+ *
1468
+ * console.log(parsed); // 1
1469
+ *
1470
+ * const companySchema = p.object({ id: p.number(), name: p.string() });
1471
+ * const userSchema = p.object({
1472
+ * id: p.number(),
1473
+ * name: p.string(),
1474
+ * company: companySchema.optional({ outputOnly: true })
1475
+ * });
1476
+ *
1477
+ * // Will not allow the company to be null or undefined on a typing level.
1478
+ * const { errors, parsed } = await userSchema.data({ id: 1, name: 'John Doe' });
1479
+ * // Will allow the company to be null or undefined on a typing level
1480
+ * const value = await userSchema.data({ id: 1, name: 'John Doe' });
1481
+ * ```
1482
+ *
1483
+ * @returns - The schema we are working with.
1484
+ */
1485
+ optional(options) {
1486
+ return options?.outputOnly ? this : super.optional(options);
1487
+ }
1488
+ /**
1489
+ * Just adds a message when the value is undefined. It's just a syntax sugar for
1490
+ *
1491
+ * ```typescript
1492
+ * p.datetime().optional({ message: 'This value should be defined', allow: false })
1493
+ * ```
1494
+ *
1495
+ * @param options - The options of nonOptional function
1496
+ * @param options.message - A custom message if the value is undefined.
1497
+ *
1498
+ * @returns - The schema.
1499
+ */
1500
+ nonOptional(options) {
1501
+ return super.optional({
1502
+ message: options?.message,
1503
+ allow: false
1504
+ });
1505
+ }
1506
+ /**
1507
+ * Allows the value to be null and ONLY null. You can also use this function to set a custom message when the value
1508
+ * is NULL by setting the { message: 'Your custom message', allow: false } on the options.
1509
+ *
1510
+ * @example
1511
+ * ```typescript
1512
+ * import * as p from '@palmares/schemas';
1513
+ *
1514
+ * const numberSchema = p.number().nullable();
1515
+ *
1516
+ * const { errors, parsed } = await numberSchema.parse(null);
1517
+ *
1518
+ * console.log(parsed); // null
1519
+ *
1520
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1521
+ *
1522
+ * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
1523
+ * ```
1524
+ *
1525
+ * @param options - The options for the nullable function.
1526
+ * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
1527
+ * @param options.allow - Whether the value can be null or not. Defaults to true.
1528
+ *
1529
+ * @returns The schema.
1530
+ */
1531
+ nullable(options) {
1532
+ return super.nullable(options);
1533
+ }
1534
+ /**
1535
+ * Just adds a message when the value is null. It's just a syntax sugar for
1536
+ *
1537
+ * ```typescript
1538
+ * p.datetime().nullable({ message: 'This value cannot be null', allow: false })
1539
+ * ```
1540
+ *
1541
+ * @param options - The options of nonNullable function
1542
+ * @param options.message - A custom message if the value is null.
1543
+ *
1544
+ * @returns - The schema.
1545
+ */
1546
+ nonNullable(options) {
1547
+ return super.nullable({
1548
+ message: options?.message || "",
1549
+ allow: false
1550
+ });
1551
+ }
1552
+ /**
1553
+ * This method will remove the value from the representation of the schema. If the value is undefined it will keep
1554
+ * that way otherwise it will set the value to undefined after it's validated.
1555
+ * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
1556
+ * function. This will remove the value from the representation of the schema.
1557
+ *
1558
+ * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
1559
+ * function. But if you want to remove the value from the internal representation, you can pass the argument
1560
+ * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
1561
+ * the argument `toRepresentation` as true as well.
1562
+ *
1563
+ * @example
1564
+ * ```typescript
1565
+ * import * as p from '@palmares/schemas';
1566
+ *
1567
+ * const userSchema = p.object({
1568
+ * id: p.number().optional(),
1569
+ * name: p.string(),
1570
+ * password: p.string().omit()
1571
+ * });
1572
+ *
1573
+ * const user = await userSchema.data({
1574
+ * id: 1,
1575
+ * name: 'John Doe',
1576
+ * password: '123456'
1577
+ * });
1578
+ *
1579
+ * console.log(user); // { id: 1, name: 'John Doe' }
1580
+ * ```
1581
+ *
1582
+ *
1583
+ * @param args - By default, the value will be removed just from the representation, in other words, when you call
1584
+ * the {@link data} function.
1585
+ * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
1586
+ * as true.
1587
+ * Then if you still want to remove the value from the representation, you will need to pass the argument
1588
+ * `toRepresentation` as true as well.
1589
+ *
1590
+ * @returns The schema.
1591
+ */
1592
+ omit(args) {
1593
+ return super.omit(args);
1594
+ }
1595
+ /**
1596
+ * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
1597
+ * source like a database. You should always return the schema after you save the value, that way we will always have
1598
+ * the correct type of the schema after the save operation.
1599
+ *
1600
+ * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
1601
+ *
1602
+ * @example
1603
+ * ```typescript
1604
+ * import * as p from '@palmares/schemas';
1605
+ *
1606
+ * import { User } from './models';
1607
+ *
1608
+ * const userSchema = p.object({
1609
+ * id: p.number().optional(),
1610
+ * name: p.string(),
1611
+ * email: p.string().email(),
1612
+ * }).onSave(async (value) => {
1613
+ * // Create or update the user on the database using palmares models or any other library of your choice.
1614
+ * if (value.id)
1615
+ * await User.default.set(value, { search: { id: value.id } });
1616
+ * else
1617
+ * await User.default.set(value);
1618
+ *
1619
+ * return value;
1620
+ * });
1621
+ *
1622
+ *
1623
+ * // Then, on your controller, do something like this:
1624
+ * const { isValid, save, errors } = await userSchema.validate(req.body);
1625
+ * if (isValid) {
1626
+ * const savedValue = await save();
1627
+ * return Response.json(savedValue, { status: 201 });
1628
+ * }
1629
+ *
1630
+ * return Response.json({ errors }, { status: 400 });
1631
+ * ```
1632
+ *
1633
+ * @param callback - The callback that will be called to save the value on an external source.
1634
+ *
1635
+ * @returns The schema.
1636
+ */
1637
+ onSave(callback) {
1638
+ return super.onSave(callback);
1639
+ }
1640
+ /**
1641
+ * This function is used to add a default value to the schema. If the value is either undefined or null, the default
1642
+ * value will be used.
1643
+ *
1644
+ * @example
1645
+ * ```typescript
1646
+ * import * as p from '@palmares/schemas';
1647
+ *
1648
+ * const numberSchema = p.number().default(0);
1649
+ *
1650
+ * const { errors, parsed } = await numberSchema.parse(undefined);
1651
+ *
1652
+ * console.log(parsed); // 0
1653
+ * ```
1654
+ */
1655
+ default(defaultValueOrFunction) {
1656
+ return super.default(defaultValueOrFunction);
1657
+ }
1658
+ /**
1659
+ * This function is used to transform the value to the representation without validating it.
1660
+ * This is useful when you want to return a data from a query directly to the user. But for example
1661
+ * you are returning the data of a user, you can clean the password or any other sensitive data.
1662
+ *
1663
+ * @example
1664
+ * ```typescript
1665
+ * import * as p from '@palmares/schemas';
1666
+ *
1667
+ * const userSchema = p.object({
1668
+ * id: p.number().optional(),
1669
+ * name: p.string(),
1670
+ * email: p.string().email(),
1671
+ * password: p.string().optional()
1672
+ * }).toRepresentation(async (value) => {
1673
+ * return {
1674
+ * id: value.id,
1675
+ * name: value.name,
1676
+ * email: value.email
1677
+ * }
1678
+ * });
1679
+ *
1680
+ * const user = await userSchema.data({
1681
+ * id: 1,
1682
+ * name: 'John Doe',
1683
+ * email: 'john@gmail.com',
1684
+ * password: '123456'
1685
+ * });
1686
+ * ```
1687
+ */
1688
+ async data(value) {
1689
+ let parsedValue = await super.data(value);
1690
+ if (Array.isArray(parsedValue)) {
1691
+ parsedValue = await Promise.all(Array.isArray(this.__schemas[0]) ? parsedValue.map((value2) => {
1692
+ const schema2 = this.__schemas[0][0];
1693
+ return shouldRunDataOnComplexSchemas(schema2) ? schema2.data(value2) : value2;
1694
+ }) : this.__schemas.map(async (schema2) => {
1695
+ return shouldRunDataOnComplexSchemas(schema2) ? schema2.data(value) : value;
1696
+ }));
1697
+ }
1698
+ return parsedValue;
1699
+ }
1700
+ /**
1701
+ * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
1702
+ * this function to let you customize the custom schema your own way. Our API does not support passthrough?
1703
+ * No problem, you can use this function to customize the zod schema.
1704
+ *
1705
+ * @example
1706
+ * ```typescript
1707
+ * import * as p from '@palmares/schemas';
1708
+ *
1709
+ * const numberSchema = p.number().extends((schema) => {
1710
+ * return schema.nonnegative();
1711
+ * });
1712
+ *
1713
+ * const { errors, parsed } = await numberSchema.parse(-1);
1714
+ *
1715
+ * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
1716
+ * console.log(errors);
1717
+ * ```
1718
+ *
1719
+ * @param callback - The callback that will be called to customize the schema.
1720
+ * @param toStringCallback - The callback that will be called to transform the schema to a string when you want to
1721
+ * compile the underlying schema to a string so you can save it for future runs.
1722
+ *
1723
+ * @returns The schema.
1724
+ */
1725
+ extends(callback, toStringCallback) {
1726
+ return super.extends(callback, toStringCallback);
1727
+ }
1728
+ /**
1729
+ * This function is used to transform the value to the representation of the schema. When using the {@link data}
1730
+ * function. With this function you have full control to add data cleaning for example, transforming the data and
1731
+ * whatever. Another use case is when you want to return deeply nested recursive data.
1732
+ * The schema maps to itself.
1733
+ *
1734
+ * @example
1735
+ * ```typescript
1736
+ * import * as p from '@palmares/schemas';
1737
+ *
1738
+ * const recursiveSchema = p.object({
1739
+ * id: p.number().optional(),
1740
+ * name: p.string(),
1741
+ * }).toRepresentation(async (value) => {
1742
+ * return {
1743
+ * id: value.id,
1744
+ * name: value.name,
1745
+ * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
1746
+ * }
1747
+ * });
1748
+ *
1749
+ * const data = await recursiveSchema.data({
1750
+ * id: 1,
1751
+ * name: 'John Doe',
1752
+ * });
1753
+ * ```
1754
+ *
1755
+ * @example
1756
+ * ```
1757
+ * import * as p from '@palmares/schemas';
1758
+ *
1759
+ * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
1760
+ * switch (value) {
1761
+ * case 'red': return { r: 255, g: 0, b: 0 };
1762
+ * case 'green': return { r: 0, g: 255, b: 0 };
1763
+ * case 'blue': return { r: 0, g: 0, b: 255 };
1764
+ * default: return { r: 0, g: 0, b: 0 };
1765
+ * }
1766
+ * });
1767
+ * ```
1768
+ * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
1769
+ *
1770
+ * @returns The schema with a new return type
1771
+ */
1772
+ toRepresentation(toRepresentationCallback) {
1773
+ return super.toRepresentation(toRepresentationCallback);
1774
+ }
1775
+ /**
1776
+ * This function is used to transform the value to the internal representation of the schema. This is useful when you
1777
+ * want to transform the value to a type that the schema adapter can understand. For example, you might want to
1778
+ * transform a string to a date. This is the function you use.
1779
+ *
1780
+ * @example
1781
+ * ```typescript
1782
+ * import * as p from '@palmares/schemas';
1783
+ *
1784
+ * const dateSchema = p.string().toInternal((value) => {
1785
+ * return new Date(value);
1786
+ * });
1787
+ *
1788
+ * const date = await dateSchema.parse('2021-01-01');
1789
+ *
1790
+ * console.log(date); // Date object
1791
+ *
1792
+ * const rgbToColorSchema = p.object({
1793
+ * r: p.number().min(0).max(255),
1794
+ * g: p.number().min(0).max(255),
1795
+ * b: p.number().min(0).max(255),
1796
+ * }).toInternal(async (value) => {
1797
+ * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
1798
+ * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
1799
+ * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
1800
+ * return `rgb(${value.r}, ${value.g}, ${value.b})`;
1801
+ * });
1802
+ * ```
1803
+ *
1804
+ * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
1805
+ *
1806
+ * @returns The schema with a new return type.
1807
+ */
1808
+ toInternal(toInternalCallback) {
1809
+ return super.toInternal(toInternalCallback);
1810
+ }
1811
+ /**
1812
+ * Called before the validation of the schema. Let's say that you want to validate a date that might receive a string,
1813
+ * you can convert that string to a date here BEFORE the validation. This pretty much transforms the value to a type
1814
+ * that the schema adapter can understand.
1815
+ *
1816
+ * @example
1817
+ * ```
1818
+ * import * as p from '@palmares/schemas';
1819
+ * import * as z from 'zod';
1820
+ *
1821
+ * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
1822
+ * return new Map(value); // Before validating we transform the value to a map.
1823
+ * });
1824
+ *
1825
+ * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
1826
+ * ```
1827
+ *
1828
+ * @param toValidateCallback - The callback that will be called to validate the value.
1829
+ *
1830
+ * @returns The schema with a new return type.
1831
+ */
1832
+ toValidate(toValidateCallback) {
1833
+ return super.toValidate(toValidateCallback);
1834
+ }
1835
+ minLength(value, options) {
1836
+ const message = options?.message || `The array must have a minimum length of ${value}`;
1837
+ this.__minLength = {
1838
+ value,
1839
+ inclusive: typeof options?.inclusive === "boolean" ? options.inclusive : true,
1840
+ message
1841
+ };
1842
+ return this;
1843
+ }
1844
+ maxLength(value, options) {
1845
+ const message = options?.message || `The array must have a maximum length of ${value}`;
1846
+ this.__maxLength = {
1847
+ value,
1848
+ inclusive: typeof options?.inclusive === "boolean" ? options.inclusive : true,
1849
+ message
1850
+ };
1851
+ return this;
1852
+ }
1853
+ static new(...schemas) {
1854
+ const returnValue = new _ArraySchema(...schemas);
1855
+ return returnValue;
1856
+ }
1857
+ };
1858
+ var array = /* @__PURE__ */ __name((...schemas) => ArraySchema.new(...schemas), "array");
1859
+ // Annotate the CommonJS export names for ESM import in node:
1860
+ 0 && (module.exports = {
1861
+ ArraySchema,
1862
+ array
1863
+ });