@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
@@ -1,767 +0,0 @@
1
- import { getDefaultAdapter } from '../conf';
2
- import { formatErrorFromParseMethod } from '../utils';
3
- export class Schema {
4
- $$type = '$PSchema';
5
- fieldType = 'schema';
6
- // Those functions will assume control of the validation process on adapters, instead of the schema.
7
- // Why this is used? The idea is that the Schema has NO idea
8
- // that one of it's children might be an UnionSchema for example. The adapter might not support unions,
9
- // so then we give control to the union. The parent schema will already have an array of translated
10
- // adapter schemas. This means for a union with Number and String it'll generate two schemas, one for number
11
- // and one for the value as String. Of course this gets multiplied. So if we have a union with Number and String.
12
- // We should take those two schemas from the array and validate them individually. This logic is
13
- // handled by the union schema. If we have an intersection type for example, instead of validating
14
- // One schema OR the other, we validate one schema AND the other. This will be handled
15
- // by the schema that contains that intersection logic.
16
- __beforeValidationCallbacks = new Map();
17
- __cachedGetParent;
18
- set __getParent(value) {
19
- this.__cachedGetParent = value;
20
- }
21
- get __getParent() {
22
- return this.__cachedGetParent;
23
- }
24
- __alreadyAppliedModel;
25
- __runBeforeParseAndData;
26
- __rootFallbacksValidator;
27
- __saveCallback;
28
- __modelOmitCallback;
29
- __parsers = {
30
- high: new Map(),
31
- medium: new Map(),
32
- low: new Map(),
33
- _fallbacks: new Set()
34
- };
35
- __refinements = [];
36
- __nullable = {
37
- message: 'Cannot be null',
38
- allow: false
39
- };
40
- __optional = {
41
- message: 'Required',
42
- allow: false
43
- };
44
- __extends = undefined;
45
- __transformedSchemas = {};
46
- __defaultFunction = undefined;
47
- __toRepresentation = undefined;
48
- __toValidate = undefined;
49
- __toInternal = undefined;
50
- __type = {
51
- message: 'Invalid type',
52
- check: ()=>true
53
- };
54
- __getDefaultTransformedSchemas() {
55
- const adapterInstance = getDefaultAdapter();
56
- // eslint-disable-next-line ts/no-unnecessary-condition
57
- if (this.__transformedSchemas[adapterInstance.constructor.name] === undefined) this.__transformedSchemas[adapterInstance.constructor.name] = {
58
- transformed: false,
59
- adapter: adapterInstance,
60
- schemas: []
61
- };
62
- }
63
- /**
64
- * This will validate the data with the fallbacks, so internally, without relaying on the schema adapter.
65
- * This is nice because we can support things that the schema adapter is not able to support by default.
66
- *
67
- * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors.
68
- * @param path - The path of the error.
69
- * @param parseResult - The result of the parse method.
70
- */ async __validateByFallbacks(path, parseResult, options) {
71
- // eslint-disable-next-line ts/no-unnecessary-condition
72
- if (this.__rootFallbacksValidator) return this.__rootFallbacksValidator.validate(options.errorsAsHashedSet, path, parseResult, options);
73
- return parseResult;
74
- }
75
- /**
76
- * This will validate by the adapter. In other words, we send the data to the schema adapter and then we validate
77
- * that data.
78
- * So understand that, first we send the data to the adapter, the adapter validates it, then, after we validate
79
- * from the adapter we validate with the fallbacks so we can do all of the extra validations not handled by
80
- * the adapter.
81
- *
82
- * @param value - The value to be validated.
83
- * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors on the validator.
84
- * @param path - The path of the error so we can construct an object with the nested paths of the error.
85
- * @param parseResult - The result of the parse method.
86
- *
87
- * @returns The result and the errors of the parse method.
88
- */ async __validateByAdapter(adapter, fieldAdapter, schema, value, path, options) {
89
- const parseResult = {
90
- errors: [],
91
- parsed: value
92
- };
93
- // On the next iteration we will reset the errors and the parsed value
94
- parseResult.errors = [];
95
- parseResult.parsed = value;
96
- // eslint-disable-next-line ts/no-unnecessary-condition
97
- if (fieldAdapter === undefined || typeof fieldAdapter.parse !== 'function') return parseResult;
98
- const adapterParseResult = await fieldAdapter.parse(adapter, adapter.field, schema.transformed, value, options.args);
99
- parseResult.parsed = adapterParseResult.parsed;
100
- if (adapterParseResult.errors) {
101
- if (Array.isArray(adapterParseResult.errors)) parseResult.errors = await Promise.all(adapterParseResult.errors.map(async (error)=>formatErrorFromParseMethod(adapter, fieldAdapter, error, value, schema.transformed, path, options.errorsAsHashedSet || new Set())));
102
- else parseResult.errors = [
103
- await formatErrorFromParseMethod(adapter, fieldAdapter, parseResult.errors, value, schema.transformed, path, options.errorsAsHashedSet || new Set())
104
- ];
105
- }
106
- parseResult.errors = parseResult.errors.filter((error)=>typeof error !== 'undefined');
107
- return parseResult;
108
- }
109
- // eslint-disable-next-line ts/require-await
110
- async __transformToAdapter(_options) {
111
- throw new Error('Not implemented');
112
- }
113
- /** */ async __parsersToTransformValue(value, parsersToUse) {
114
- let shouldStop = false;
115
- for (const [parserName, parser] of this.__parsers.high.entries()){
116
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
117
- const result = await Promise.resolve(parser(value));
118
- if (result.preventNextParsers) shouldStop = true;
119
- value = result.value;
120
- } else continue;
121
- }
122
- if (shouldStop === false) {
123
- for (const [parserName, parser] of this.__parsers.medium.entries()){
124
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
125
- const result = await Promise.resolve(parser(value));
126
- if (result.preventNextParsers) shouldStop = true;
127
- value = result.value;
128
- } else continue;
129
- }
130
- }
131
- if (shouldStop === false) {
132
- for (const [parserName, parser] of this.__parsers.low.entries()){
133
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
134
- const result = await Promise.resolve(parser(value));
135
- if (result.preventNextParsers) shouldStop = true;
136
- value = result.value;
137
- } else continue;
138
- }
139
- }
140
- return value;
141
- }
142
- async __parse(value, path = [], options) {
143
- this.__getDefaultTransformedSchemas();
144
- if (typeof this.__runBeforeParseAndData === 'function') await this.__runBeforeParseAndData(this);
145
- // This is used to run the toInternal command. If we didn't do this, we would need to parse through all of
146
- // the schemas to run the toInternal command, from the leafs (ObjectSchemas) to the root schema. This is not
147
- // a good idea, so what we do is that during validation the leafs attach a function to the
148
- // options.toInternalToBubbleUp like
149
- // `options.toInternalToBubbleUp.push(async () => (value[key] = await (schema as any).__toInternal(parsed)));``
150
- // This way, when the root schema finishes the validation, it will run all of the functions in the
151
- // toInternalToBubbleUp array, modifying the parsed value.
152
- const shouldRunToInternalToBubbleUp = options.toInternalToBubbleUp === undefined;
153
- if (shouldRunToInternalToBubbleUp) options.toInternalToBubbleUp = [];
154
- if (options.errorsAsHashedSet instanceof Set === false) options.errorsAsHashedSet = new Set();
155
- const shouldCallDefaultFunction = value === undefined && typeof this.__defaultFunction === 'function';
156
- const shouldCallToValidateCallback = typeof this.__toValidate === 'function';
157
- const schemaAdapterFieldType = this.fieldType;
158
- if (shouldCallDefaultFunction) value = await this.__defaultFunction();
159
- if (shouldCallToValidateCallback) value = await Promise.resolve(this.__toValidate(value));
160
- const parseResult = {
161
- errors: [],
162
- parsed: value
163
- };
164
- value = await this.__parsersToTransformValue(value, this.__parsers._fallbacks);
165
- if (options.appendFallbacksBeforeAdapterValidation === undefined) options.appendFallbacksBeforeAdapterValidation = (schema, name, callback)=>{
166
- // We just need this if the union adapter is net defined but the parent is not of the same type.
167
- // For example, it's a union child of o object schema
168
- if (this !== schema) this.__beforeValidationCallbacks.set(name, callback);
169
- };
170
- if (this.__transformedSchemas[options.schemaAdapter?.constructor.name || getDefaultAdapter().constructor.name].transformed === false) await this.__transformToAdapter(options);
171
- const adapterToUse = options.schemaAdapter ? options.schemaAdapter : Object.values(this.__transformedSchemas)[0].adapter;
172
- const parsedResultsAfterFallbacks = await this.__validateByFallbacks(path, {
173
- errors: parseResult.errors,
174
- parsed: value
175
- }, options);
176
- parseResult.parsed = parsedResultsAfterFallbacks.parsed;
177
- // eslint-disable-next-line ts/no-unnecessary-condition
178
- parseResult.errors = (parseResult.errors || []).concat(parsedResultsAfterFallbacks.errors || []);
179
- // With this, the children takes control of validating by the adapter. For example on a union schema we
180
- // want to validate all of the schemas and choose the one that has no errors.
181
- if (this.__beforeValidationCallbacks.size > 0) {
182
- for (const callback of this.__beforeValidationCallbacks.values()){
183
- const parsedValuesAfterValidationCallbacks = await callback(adapterToUse, adapterToUse[schemaAdapterFieldType], this, this.__transformedSchemas[adapterToUse.constructor.name].schemas, value, path, options);
184
- parseResult.parsed = parsedValuesAfterValidationCallbacks.parsed;
185
- parseResult.errors = Array.isArray(parseResult.errors) && Array.isArray(parsedValuesAfterValidationCallbacks.errors) ? [
186
- ...parseResult.errors,
187
- ...parsedValuesAfterValidationCallbacks.errors
188
- ] : Array.isArray(parseResult.errors) ? parseResult.errors : parsedValuesAfterValidationCallbacks.errors;
189
- }
190
- } else {
191
- const parsedValuesAfterValidatingByAdapter = await this.__validateByAdapter(adapterToUse, adapterToUse[schemaAdapterFieldType], this.__transformedSchemas[adapterToUse.constructor.name].schemas[0], value, path, options);
192
- parseResult.parsed = parsedValuesAfterValidatingByAdapter.parsed;
193
- // eslint-disable-next-line ts/no-unnecessary-condition
194
- parseResult.errors = (parseResult.errors || []).concat(parsedValuesAfterValidatingByAdapter.errors);
195
- }
196
- const hasToInternalCallback = typeof this.__toInternal === 'function';
197
- const shouldCallToInternalDuringParse = hasToInternalCallback && (options.toInternalToBubbleUp?.length === 0 || Array.isArray(options.toInternalToBubbleUp) === false);
198
- // eslint-disable-next-line ts/no-unnecessary-condition
199
- const hasNoErrors = parseResult.errors === undefined || (parseResult.errors || []).length === 0;
200
- await Promise.all(this.__refinements.map(async (refinement)=>{
201
- const errorOrNothing = await Promise.resolve(refinement(parseResult.parsed));
202
- if (typeof errorOrNothing === 'undefined') return;
203
- parseResult.errors.push({
204
- isValid: false,
205
- code: errorOrNothing.code,
206
- message: errorOrNothing.message,
207
- received: parseResult.parsed,
208
- path
209
- });
210
- }));
211
- if (shouldCallToInternalDuringParse && hasNoErrors) parseResult.parsed = await this.__toInternal(value);
212
- if (shouldRunToInternalToBubbleUp && hasNoErrors) for (const functionToModifyResult of options.toInternalToBubbleUp || [])await functionToModifyResult();
213
- return parseResult;
214
- }
215
- /**
216
- * This let's you refine the schema with custom validations. This is useful when you want to validate something
217
- * that is not supported by default by the schema adapter.
218
- *
219
- * @example
220
- * ```typescript
221
- * import * as p from '@palmares/schemas';
222
- *
223
- * const numberSchema = p.number().refine((value) => {
224
- * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
225
- * });
226
- *
227
- * const { errors, parsed } = await numberSchema.parse(-1);
228
- *
229
- * console.log(errors);
230
- * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
231
- * ```
232
- *
233
- * @param refinementCallback - The callback that will be called to validate the value.
234
- * @param options - Options for the refinement.
235
- * @param options.isAsync - Whether the callback is async or not. Defaults to true.
236
- */ refine(refinementCallback) {
237
- this.__refinements.push(refinementCallback);
238
- return this;
239
- }
240
- /**
241
- * Allows the value to be either undefined or null.
242
- *
243
- * @example
244
- * ```typescript
245
- * import * as p from '@palmares/schemas';
246
- *
247
- * const numberSchema = p.number().optional();
248
- *
249
- * const { errors, parsed } = await numberSchema.parse(undefined);
250
- *
251
- * console.log(parsed); // undefined
252
- *
253
- * const { errors, parsed } = await numberSchema.parse(null);
254
- *
255
- * console.log(parsed); // null
256
- *
257
- * const { errors, parsed } = await numberSchema.parse(1);
258
- *
259
- * console.log(parsed); // 1
260
- * ```
261
- *
262
- * @returns - The schema we are working with.
263
- */ optional(options) {
264
- this.__optional = {
265
- message: typeof options?.message === 'string' ? options.message : 'Required',
266
- allow: typeof options?.allow === 'boolean' ? options.allow : true
267
- };
268
- return this;
269
- }
270
- /**
271
- * Allows the value to be null and ONLY null. You can also use this function to set a custom message when
272
- * the value is NULL by setting the { message: 'Your custom message', allow: false } on the options.
273
- *
274
- * @example
275
- * ```typescript
276
- * import * as p from '@palmares/schemas';
277
- *
278
- * const numberSchema = p.number().nullable();
279
- *
280
- * const { errors, parsed } = await numberSchema.parse(null);
281
- *
282
- * console.log(parsed); // null
283
- *
284
- * const { errors, parsed } = await numberSchema.parse(undefined);
285
- *
286
- * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
287
- * ```
288
- *
289
- * @param options - The options for the nullable function.
290
- * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
291
- * @param options.allow - Whether the value can be null or not. Defaults to true.
292
- *
293
- * @returns The schema.
294
- */ nullable(options) {
295
- this.__nullable = {
296
- message: typeof options?.message === 'string' ? options.message : 'Cannot be null',
297
- allow: typeof options?.allow === 'boolean' ? options.allow : true
298
- };
299
- return this;
300
- }
301
- /**
302
- * Appends a custom schema to the schema, this way it will bypass the creation of the schema in runtime.
303
- *
304
- * By default when validating, on the first validation we create the schema. Just during the first validation.
305
- * With this function, you bypass that, so you can speed up the validation process.
306
- *
307
- * @example
308
- * ```typescript
309
- * import * as p from '@palmares/schemas';
310
- * import * as z from 'zod';
311
- *
312
- * const numberSchema = p.number().appendSchema(z.number());
313
- *
314
- * const { errors, parsed } = await numberSchema.parse(1);
315
- * ```
316
- *
317
- * @param schema - The schema to be appended.
318
- * @param args - The arguments for the schema.
319
- * @param args.adapter - The adapter to be used. If not provided, the default adapter will be used.
320
- *
321
- * @returns The same schema again.
322
- */ appendSchema(schema, args) {
323
- const adapter = args?.adapter || getDefaultAdapter();
324
- this.__transformedSchemas[adapter.constructor.name] = {
325
- transformed: true,
326
- adapter: adapter,
327
- schemas: [
328
- schema
329
- ]
330
- };
331
- return this;
332
- }
333
- /**
334
- * This method will remove the value from the representation of the schema. If the value is undefined it will keep
335
- * that way otherwise it will set the value to undefined after it's validated.
336
- * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
337
- * function. This will remove the value from the representation of the schema.
338
- *
339
- * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
340
- * function. But if you want to remove the value from the internal representation, you can pass the argument
341
- * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
342
- * the argument `toRepresentation` as true as well.
343
- *
344
- * @example
345
- * ```typescript
346
- * import * as p from '@palmares/schemas';
347
- *
348
- * const userSchema = p.object({
349
- * id: p.number().optional(),
350
- * name: p.string(),
351
- * password: p.string().omit()
352
- * });
353
- *
354
- * const user = await userSchema.data({
355
- * id: 1,
356
- * name: 'John Doe',
357
- * password: '123456'
358
- * });
359
- *
360
- * console.log(user); // { id: 1, name: 'John Doe' }
361
- * ```
362
- *
363
- *
364
- * @param args - By default, the value will be removed just from the representation, in other words, when you call
365
- * the {@link data} function.
366
- * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
367
- * as true. Then if you still want to remove the value from the representation, you will need to pass the
368
- * argument `toRepresentation` as true as well.
369
- *
370
- * @returns The schema.
371
- */ omit(args) {
372
- // To representation is true by default, unless to internal is true.
373
- const toRepresentation = typeof args?.toRepresentation === 'boolean' ? args.toRepresentation : typeof args?.toInternal !== 'boolean';
374
- const toInternal = typeof args?.toInternal === 'boolean' ? args.toInternal : false;
375
- if (toInternal) {
376
- if (this.__toInternal) {
377
- const toInternal = this.__toInternal;
378
- this.__toInternal = async (value)=>{
379
- await toInternal(value);
380
- return undefined;
381
- };
382
- // eslint-disable-next-line ts/require-await
383
- } else this.__toInternal = async ()=>undefined;
384
- } else if (toRepresentation) {
385
- if (this.__toRepresentation) {
386
- const toRepresentation = this.__toRepresentation;
387
- this.__toRepresentation = async (value)=>{
388
- await toRepresentation(value);
389
- return undefined;
390
- };
391
- // eslint-disable-next-line ts/require-await
392
- } else this.__toRepresentation = async ()=>undefined;
393
- }
394
- return this;
395
- }
396
- /**
397
- * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
398
- * source like a database. You should always return the schema after you save the value, that way we will always have
399
- * the correct type of the schema after the save operation.
400
- *
401
- * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
402
- *
403
- * @example
404
- * ```typescript
405
- * import * as p from '@palmares/schemas';
406
- *
407
- * import { User } from './models';
408
- *
409
- * const userSchema = p.object({
410
- * id: p.number().optional(),
411
- * name: p.string(),
412
- * email: p.string().email(),
413
- * }).onSave(async (value) => {
414
- * // Create or update the user on the database using palmares models or any other library of your choice.
415
- * if (value.id)
416
- * await User.default.set(value, { search: { id: value.id } });
417
- * else
418
- * await User.default.set(value);
419
- *
420
- * return value;
421
- * });
422
- *
423
- *
424
- * // Then, on your controller, do something like this:
425
- * const { isValid, save, errors } = await userSchema.validate(req.body);
426
- * if (isValid) {
427
- * const savedValue = await save();
428
- * return Response.json(savedValue, { status: 201 });
429
- * }
430
- *
431
- * return Response.json({ errors }, { status: 400 });
432
- * ```
433
- *
434
- * @param callback - The callback that will be called to save the value on an external source.
435
- *
436
- * @returns The schema.
437
- */ onSave(callback) {
438
- this.__saveCallback = callback;
439
- return this;
440
- }
441
- /**
442
- * This function is used to validate the schema and save the value to the database. It is used in
443
- * conjunction with the {@link onSave} function.
444
- *
445
- * Different from other validation libraries, palmares schemas is aware that you want to save. On your
446
- * routes/functions we recommend to ALWAYS use this function instead of {@link parse} directly. This is because
447
- * this function by default will return an object with the property `save` or the `errors`. If the errors are present,
448
- * you can return the errors to the user. If the save property is present, you can use to save the value to an
449
- * external source. e.g. a database.
450
- *
451
- * @example
452
- * ```typescript
453
- * import * as p from '@palmares/schemas';
454
- *
455
- * import { User } from './models';
456
- *
457
- * const userSchema = p.object({
458
- * id: p.number().optional(),
459
- * name: p.string(),
460
- * email: p.string().email(),
461
- * }).onSave(async (value) => {
462
- * // Create or update the user on the database using palmares models or any other library of your choice.
463
- * if (value.id)
464
- * await User.default.set(value, { search: { id: value.id } });
465
- * else
466
- * await User.default.set(value);
467
- *
468
- * return value;
469
- * });
470
- *
471
- *
472
- * // Then, on your controller, do something like this:
473
- * const { isValid, save, errors } = await userSchema.validate(req.body);
474
- * if (isValid) {
475
- * const savedValue = await save();
476
- * return Response.json(savedValue, { status: 201 });
477
- * }
478
- *
479
- * return Response.json({ errors }, { status: 400 });
480
- * ```
481
- *
482
- * @param value - The value to be validated.
483
- *
484
- * @returns An object with the property isValid, if the value is valid, the function `save` will be present.
485
- * If the value is invalid, the property errors will be present.
486
- */ async validate(value, context) {
487
- const { errors, parsed } = await this.__parse(value, [], {
488
- context
489
- });
490
- // eslint-disable-next-line ts/no-unnecessary-condition
491
- if ((errors || []).length > 0) return {
492
- isValid: false,
493
- errors: errors
494
- };
495
- return {
496
- isValid: true,
497
- save: async ()=>this._save.bind(this)(parsed, context)
498
- };
499
- }
500
- /**
501
- * Internal function, when we call the {@link validate} function it's this function that gets called
502
- * when the user uses the `save` function returned by the {@link validate} function if the value is valid.
503
- *
504
- * @param value - The value to be saved.
505
- *
506
- * @returns The value to representation.
507
- */ async _save(value, context) {
508
- if (this.__saveCallback) {
509
- const result = await this.__saveCallback(value, context);
510
- return this.data(result);
511
- }
512
- return this.data(value);
513
- }
514
- /**
515
- * This function is used to validate and parse the value to the internal representation of the schema.
516
- *
517
- * @example
518
- * ```typescript
519
- * import * as p from '@palmares/schemas';
520
- *
521
- * const numberSchema = p.number().allowString();
522
- *
523
- * const { errors, parsed } = await numberSchema.parse('123');
524
- *
525
- * console.log(parsed); // 123
526
- * ```
527
- *
528
- * @param value - The value to be parsed.
529
- *
530
- * @returns The parsed value.
531
- */ async parse(value) {
532
- return this.__parse(value, [], {});
533
- }
534
- /**
535
- * This function is used to transform the value to the representation without validating it.
536
- * This is useful when you want to return a data from a query directly to the user. But for example
537
- * you are returning the data of a user, you can clean the password or any other sensitive data.
538
- *
539
- * @example
540
- * ```typescript
541
- * import * as p from '@palmares/schemas';
542
- *
543
- * const userSchema = p.object({
544
- * id: p.number().optional(),
545
- * name: p.string(),
546
- * email: p.string().email(),
547
- * password: p.string().optional()
548
- * }).toRepresentation(async (value) => {
549
- * return {
550
- * id: value.id,
551
- * name: value.name,
552
- * email: value.email
553
- * }
554
- * });
555
- *
556
- * const user = await userSchema.data({
557
- * id: 1,
558
- * name: 'John Doe',
559
- * email: 'john@gmail.com',
560
- * password: '123456'
561
- * });
562
- * ```
563
- */ async data(value) {
564
- this.__getDefaultTransformedSchemas();
565
- if (typeof this.__runBeforeParseAndData === 'function') await this.__runBeforeParseAndData(this);
566
- value = await this.__parsersToTransformValue(value);
567
- if (this.__toRepresentation) value = await Promise.resolve(this.__toRepresentation(value));
568
- if (this.__defaultFunction && value === undefined) value = await Promise.resolve(this.__defaultFunction());
569
- return value;
570
- }
571
- instanceOf(args) {
572
- this.__type.check = typeof args.check === 'function' ? args.check : this.__type.check;
573
- this.__type.message = typeof args.message === 'string' ? args.message : this.__type.message;
574
- return this;
575
- }
576
- /**
577
- * This function is used to add a default value to the schema. If the value is either undefined or null,
578
- * the default value will be used.
579
- *
580
- * @example
581
- * ```typescript
582
- * import * as p from '@palmares/schemas';
583
- *
584
- * const numberSchema = p.number().default(0);
585
- *
586
- * const { errors, parsed } = await numberSchema.parse(undefined);
587
- *
588
- * console.log(parsed); // 0
589
- * ```
590
- */ default(defaultValueOrFunction) {
591
- const isFunction = typeof defaultValueOrFunction === 'function';
592
- if (isFunction) this.__defaultFunction = defaultValueOrFunction;
593
- else this.__defaultFunction = async ()=>defaultValueOrFunction;
594
- return this;
595
- }
596
- /**
597
- * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
598
- * this function to let you customize the custom schema your own way. Our API does not support passthrough?
599
- * No problem, you can use this function to customize the zod schema.
600
- *
601
- * @example
602
- * ```typescript
603
- * import * as p from '@palmares/schemas';
604
- *
605
- * const numberSchema = p.number().extends((schema) => {
606
- * return schema.nonnegative();
607
- * });
608
- *
609
- * const { errors, parsed } = await numberSchema.parse(-1);
610
- *
611
- * console.log(errors);
612
- * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
613
- * ```
614
- *
615
- * @param callback - The callback that will be called to customize the schema.
616
- * @param toStringCallback - The callback that will be called to transform the schema to a string when you want
617
- * to compile the underlying schema to a string so you can save it for future runs.
618
- *
619
- * @returns The schema.
620
- */ extends(callback, toStringCallback) {
621
- this.__extends = {
622
- callback,
623
- toStringCallback
624
- };
625
- return this;
626
- }
627
- /**
628
- * This function is used to transform the value to the representation of the schema. When using the {@link data}
629
- * function. With this function you have full control to add data cleaning for example, transforming the data
630
- * and whatever. Another use case is when you want to return deeply nested recursive data.
631
- * The schema maps to itself.
632
- *
633
- * @example
634
- * ```typescript
635
- * import * as p from '@palmares/schemas';
636
- *
637
- * const recursiveSchema = p.object({
638
- * id: p.number().optional(),
639
- * name: p.string(),
640
- * }).toRepresentation(async (value) => {
641
- * return {
642
- * id: value.id,
643
- * name: value.name,
644
- * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
645
- * }
646
- * });
647
- *
648
- * const data = await recursiveSchema.data({
649
- * id: 1,
650
- * name: 'John Doe',
651
- * });
652
- * ```
653
- *
654
- * @example
655
- * ```
656
- * import * as p from '@palmares/schemas';
657
- *
658
- * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
659
- * switch (value) {
660
- * case 'red': return { r: 255, g: 0, b: 0 };
661
- * case 'green': return { r: 0, g: 255, b: 0 };
662
- * case 'blue': return { r: 0, g: 0, b: 255 };
663
- * default: return { r: 0, g: 0, b: 0 };
664
- * }
665
- * });
666
- * ```
667
- * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
668
- * @param options - Options for the toRepresentation function.
669
- * @param options.after - Whether the toRepresentationCallback should be called after the existing
670
- * toRepresentationCallback. Defaults to true.
671
- * @param options.before - Whether the toRepresentationCallback should be called before the existing
672
- * toRepresentationCallback. Defaults to true.
673
- *
674
- * @returns The schema with a new return type
675
- */ toRepresentation(toRepresentationCallback, options) {
676
- if (this.__toRepresentation) {
677
- const before = typeof options?.before === 'boolean' ? options.before : typeof options?.after === 'boolean' ? !options.after : true;
678
- const existingToRepresentation = this.__toRepresentation;
679
- this.__toRepresentation = async (value)=>{
680
- if (before) return toRepresentationCallback(await existingToRepresentation(value));
681
- else return existingToRepresentation(await toRepresentationCallback(value));
682
- };
683
- } else this.__toRepresentation = toRepresentationCallback;
684
- return this;
685
- }
686
- /**
687
- * This function is used to transform the value to the internal representation of the schema. This is useful
688
- * when you want to transform the value to a type that the schema adapter can understand. For example, you
689
- * might want to transform a string to a date. This is the function you use.
690
- *
691
- * @example
692
- * ```typescript
693
- * import * as p from '@palmares/schemas';
694
- *
695
- * const dateSchema = p.string().toInternal((value) => {
696
- * return new Date(value);
697
- * });
698
- *
699
- * const date = await dateSchema.parse('2021-01-01');
700
- *
701
- * console.log(date); // Date object
702
- *
703
- * const rgbToColorSchema = p.object({
704
- * r: p.number().min(0).max(255),
705
- * g: p.number().min(0).max(255),
706
- * b: p.number().min(0).max(255),
707
- * }).toInternal(async (value) => {
708
- * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
709
- * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
710
- * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
711
- * return `rgb(${value.r}, ${value.g}, ${value.b})`;
712
- * });
713
- * ```
714
- *
715
- * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
716
- *
717
- * @returns The schema with a new return type.
718
- */ toInternal(toInternalCallback) {
719
- if (this.__toInternal) {
720
- const toInternal = this.__toInternal;
721
- this.__toInternal = async (value)=>{
722
- const newValue = await toInternal(value);
723
- return toInternalCallback(newValue);
724
- };
725
- } else this.__toInternal = toInternalCallback;
726
- return this;
727
- }
728
- /**
729
- * Called before the validation of the schema. Let's say that you want to validate a date that might receive a
730
- * string, you can convert that string to a date here BEFORE the validation. This pretty much transforms the value
731
- * to a type that the schema adapter can understand.
732
- *
733
- * @example
734
- * ```
735
- * import * as p from '@palmares/schemas';
736
- * import * as z from 'zod';
737
- *
738
- * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
739
- * return new Map(value); // Before validating we transform the value to a map.
740
- * });
741
- *
742
- * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
743
- * ```
744
- *
745
- * @param toValidateCallback - The callback that will be called to validate the value.
746
- *
747
- * @returns The schema with a new return type.
748
- */ toValidate(toValidateCallback) {
749
- this.__toValidate = toValidateCallback;
750
- return this;
751
- }
752
- /**
753
- * Used to transform the given schema on a stringfied version of the adapter.
754
- */ async compile(adapter) {
755
- const data = await this.__transformToAdapter({
756
- shouldAddStringVersion: true,
757
- force: true
758
- });
759
- const stringVersions = data.map((value)=>value.asString);
760
- return stringVersions;
761
- }
762
- static new(..._args) {
763
- const result = new Schema();
764
- return result;
765
- }
766
- }
767
- export const schema = Schema.new;