@palmares/schemas 0.1.25 → 0.2.0

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