@palmares/schemas 0.1.20 → 0.1.22

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 (111) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/src/adapter/index.js +2 -0
  3. package/dist/cjs/src/conf.js +3 -4
  4. package/dist/cjs/src/model.js +34 -38
  5. package/dist/cjs/src/schema/array.js +1 -0
  6. package/dist/cjs/src/schema/object.js +2 -8
  7. package/dist/cjs/src/schema/schema.js +1 -0
  8. package/dist/cjs/src/utils.js +12 -14
  9. package/dist/cjs/src/validators/utils.js +1 -0
  10. package/dist/cjs/tsconfig.types.tsbuildinfo +1 -1
  11. package/dist/cjs/types/adapter/index.d.ts +2 -0
  12. package/dist/cjs/types/adapter/index.d.ts.map +1 -1
  13. package/dist/cjs/types/conf.d.ts +3 -0
  14. package/dist/cjs/types/conf.d.ts.map +1 -1
  15. package/dist/cjs/types/domain.d.ts +3 -0
  16. package/dist/cjs/types/domain.d.ts.map +1 -1
  17. package/dist/cjs/types/model.d.ts +2 -2
  18. package/dist/cjs/types/model.d.ts.map +1 -1
  19. package/dist/cjs/types/schema/array.d.ts +1 -0
  20. package/dist/cjs/types/schema/array.d.ts.map +1 -1
  21. package/dist/cjs/types/schema/object.d.ts.map +1 -1
  22. package/dist/cjs/types/schema/schema.d.ts +1 -0
  23. package/dist/cjs/types/schema/schema.d.ts.map +1 -1
  24. package/dist/cjs/types/utils.d.ts +2 -1
  25. package/dist/cjs/types/utils.d.ts.map +1 -1
  26. package/dist/cjs/types/validators/utils.d.ts +1 -0
  27. package/dist/cjs/types/validators/utils.d.ts.map +1 -1
  28. package/dist/esm/src/adapter/index.js +2 -0
  29. package/dist/esm/src/conf.js +3 -4
  30. package/dist/esm/src/model.js +32 -30
  31. package/dist/esm/src/schema/array.js +1 -0
  32. package/dist/esm/src/schema/object.js +2 -1
  33. package/dist/esm/src/schema/schema.js +1 -0
  34. package/dist/esm/src/utils.js +9 -6
  35. package/dist/esm/src/validators/utils.js +1 -0
  36. package/package.json +11 -5
  37. package/.turbo/turbo-build$colon$watch.log +0 -24
  38. package/.turbo/turbo-build.log +0 -4
  39. package/.turbo/turbo-build:watch.log +0 -26
  40. package/__tests__/.drizzle/migrations/0000_skinny_harrier.sql +0 -22
  41. package/__tests__/.drizzle/migrations/meta/0000_snapshot.json +0 -156
  42. package/__tests__/.drizzle/migrations/meta/_journal.json +0 -13
  43. package/__tests__/.drizzle/schema.ts +0 -35
  44. package/__tests__/drizzle.config.ts +0 -11
  45. package/__tests__/eslint.config.js +0 -10
  46. package/__tests__/manage.ts +0 -5
  47. package/__tests__/node_modules/.bin/drizzle-kit +0 -17
  48. package/__tests__/node_modules/.bin/tsc +0 -17
  49. package/__tests__/node_modules/.bin/tsserver +0 -17
  50. package/__tests__/node_modules/.bin/tsx +0 -17
  51. package/__tests__/package.json +0 -34
  52. package/__tests__/sqlite.db +0 -0
  53. package/__tests__/src/core/array.test.ts +0 -131
  54. package/__tests__/src/core/boolean.test.ts +0 -66
  55. package/__tests__/src/core/datetime.test.ts +0 -102
  56. package/__tests__/src/core/index.ts +0 -35
  57. package/__tests__/src/core/model.test.ts +0 -260
  58. package/__tests__/src/core/models.ts +0 -50
  59. package/__tests__/src/core/numbers.test.ts +0 -177
  60. package/__tests__/src/core/object.test.ts +0 -218
  61. package/__tests__/src/core/string.test.ts +0 -222
  62. package/__tests__/src/core/test.test.ts +0 -59
  63. package/__tests__/src/core/types.test.ts +0 -97
  64. package/__tests__/src/core/union.test.ts +0 -99
  65. package/__tests__/src/settings.ts +0 -69
  66. package/__tests__/tsconfig.json +0 -11
  67. package/src/adapter/fields/array.ts +0 -31
  68. package/src/adapter/fields/boolean.ts +0 -43
  69. package/src/adapter/fields/datetime.ts +0 -43
  70. package/src/adapter/fields/index.ts +0 -72
  71. package/src/adapter/fields/number.ts +0 -43
  72. package/src/adapter/fields/object.ts +0 -52
  73. package/src/adapter/fields/string.ts +0 -43
  74. package/src/adapter/fields/union.ts +0 -43
  75. package/src/adapter/index.ts +0 -35
  76. package/src/adapter/types.ts +0 -276
  77. package/src/compile.ts +0 -14
  78. package/src/conf.ts +0 -27
  79. package/src/constants.ts +0 -7
  80. package/src/domain.ts +0 -15
  81. package/src/exceptions.ts +0 -17
  82. package/src/index.ts +0 -318
  83. package/src/middleware.ts +0 -52
  84. package/src/model.ts +0 -507
  85. package/src/parsers/convert-from-number.ts +0 -13
  86. package/src/parsers/convert-from-string.ts +0 -19
  87. package/src/parsers/index.ts +0 -2
  88. package/src/schema/array.ts +0 -824
  89. package/src/schema/boolean.ts +0 -792
  90. package/src/schema/datetime.ts +0 -704
  91. package/src/schema/index.ts +0 -5
  92. package/src/schema/number.ts +0 -929
  93. package/src/schema/object.ts +0 -798
  94. package/src/schema/schema.ts +0 -1178
  95. package/src/schema/string.ts +0 -941
  96. package/src/schema/types.ts +0 -154
  97. package/src/schema/union.ts +0 -724
  98. package/src/types.ts +0 -66
  99. package/src/utils.ts +0 -383
  100. package/src/validators/array.ts +0 -183
  101. package/src/validators/boolean.ts +0 -52
  102. package/src/validators/datetime.ts +0 -121
  103. package/src/validators/number.ts +0 -178
  104. package/src/validators/object.ts +0 -56
  105. package/src/validators/schema.ts +0 -142
  106. package/src/validators/string.ts +0 -278
  107. package/src/validators/types.ts +0 -1
  108. package/src/validators/union.ts +0 -52
  109. package/src/validators/utils.ts +0 -225
  110. package/tsconfig.json +0 -9
  111. package/tsconfig.types.json +0 -10
@@ -1,1178 +0,0 @@
1
- import { getDefaultAdapter } from '../conf';
2
- import { formatErrorFromParseMethod } from '../utils';
3
-
4
- import type {
5
- DefinitionsOfSchemaType,
6
- OnlyFieldAdaptersFromSchemaAdapter,
7
- ValidationFallbackCallbackReturnType
8
- } from './types';
9
- import type { SchemaAdapter } from '../adapter';
10
- import type { FieldAdapter } from '../adapter/fields';
11
- import type { ValidationDataBasedOnType } from '../adapter/types';
12
- import type { Validator } from '../validators/utils';
13
-
14
- export class Schema<
15
- TType extends {
16
- input: any;
17
- validate: any;
18
- internal: any;
19
- output: any;
20
- representation: any;
21
- } = {
22
- input: any;
23
- validate: any;
24
- internal: any;
25
- output: any;
26
- representation: any;
27
- },
28
- TDefinitions extends DefinitionsOfSchemaType = DefinitionsOfSchemaType
29
- > {
30
- protected fieldType = 'schema';
31
- // Those functions will assume control of the validation process on adapters, instead of the schema.
32
- // Why this is used? The idea is that the Schema has NO idea
33
- // that one of it's children might be an UnionSchema for example. The adapter might not support unions,
34
- // so then we give control to the union. The parent schema will already have an array of translated
35
- // adapter schemas. This means for a union with Number and String it'll generate two schemas, one for number
36
- // and one for the value as String. Of course this gets multiplied. So if we have a union with Number and String.
37
- // We should take those two schemas from the array and validate them individually. This logic is
38
- // handled by the union schema. If we have an intersection type for example, instead of validating
39
- // One schema OR the other, we validate one schema AND the other. This will be handled
40
- // by the schema that contains that intersection logic.
41
- protected __beforeValidationCallbacks: Map<
42
- string,
43
- (
44
- adapterToUse: SchemaAdapter,
45
- fieldAdapter: FieldAdapter,
46
- schema: Schema<any, any> & {
47
- __validateByAdapter: Schema<any, any>['__validateByAdapter'];
48
- },
49
- translatedSchemas: any[],
50
- value: TType['input'],
51
- path: ValidationFallbackCallbackReturnType['errors'][number]['path'],
52
- options: Parameters<Schema['__transformToAdapter']>[0]
53
- ) => ReturnType<Schema['__validateByAdapter']>
54
- > = new Map();
55
-
56
- protected __cachedGetParent?: () => Schema<any, any>;
57
- protected set __getParent(value: () => Schema<any, any>) {
58
- this.__cachedGetParent = value;
59
- }
60
- protected get __getParent(): (() => Schema<any, any>) | undefined {
61
- return this.__cachedGetParent;
62
- }
63
-
64
- protected __alreadyAppliedModel?: Promise<any>;
65
- protected __runBeforeParseAndData?: (self: any) => Promise<void>;
66
- protected __rootFallbacksValidator!: Validator;
67
- protected __saveCallback?: <TContext = any>(value: any, context: TContext) => Promise<any | void> | any | void;
68
- protected __modelOmitCallback?: () => void;
69
- protected __parsers: Record<
70
- 'high' | 'medium' | 'low',
71
- Map<
72
- string,
73
- (value: any) =>
74
- | {
75
- value: any;
76
- preventNextParsers: boolean;
77
- }
78
- | Promise<{
79
- value: any;
80
- preventNextParsers: boolean;
81
- }>
82
- >
83
- > & { _fallbacks: Set<string> } = {
84
- high: new Map(),
85
- medium: new Map(),
86
- low: new Map(),
87
- _fallbacks: new Set()
88
- };
89
- protected __refinements: ((
90
- value: any
91
- ) =>
92
- | Promise<void | undefined | { code: string; message: string }>
93
- | void
94
- | undefined
95
- | { code: string; message: string })[] = [];
96
- protected __nullable: {
97
- message: string;
98
- allow: boolean;
99
- } = {
100
- message: 'Cannot be null',
101
- allow: false
102
- };
103
- protected __optional: {
104
- message: string;
105
- allow: boolean;
106
- } = {
107
- message: 'Required',
108
- allow: false
109
- };
110
- protected __extends:
111
- | {
112
- callback: (schema: any) => any;
113
- toStringCallback?: (schemaAsString: string) => string;
114
- }
115
- | undefined = undefined;
116
-
117
- protected __transformedSchemas: Record<
118
- string,
119
- {
120
- transformed: boolean;
121
- adapter: TDefinitions['schemaAdapter'];
122
- schemas: any[]; // This is the transformed schemas
123
- }
124
- > = {};
125
- protected __defaultFunction: (() => Promise<TType['input'] | TType['output']>) | undefined = undefined;
126
- protected __toRepresentation: ((value: TType['output']) => TType['output']) | undefined = undefined;
127
- protected __toValidate: ((value: TType['input']) => TType['validate']) | undefined = undefined;
128
- protected __toInternal: ((value: TType['validate']) => TType['internal']) | undefined = undefined;
129
- protected __type: {
130
- message: string;
131
- check: (value: TType['input']) => boolean;
132
- } = {
133
- message: 'Invalid type',
134
- check: () => true
135
- };
136
-
137
- protected __getDefaultTransformedSchemas() {
138
- const adapterInstance = getDefaultAdapter();
139
-
140
- // eslint-disable-next-line ts/no-unnecessary-condition
141
- if (this.__transformedSchemas[adapterInstance.constructor.name] === undefined)
142
- this.__transformedSchemas[adapterInstance.constructor.name] = {
143
- transformed: false,
144
- adapter: adapterInstance,
145
- schemas: []
146
- };
147
- }
148
-
149
- /**
150
- * This will validate the data with the fallbacks, so internally, without relaying on the schema adapter.
151
- * This is nice because we can support things that the schema adapter is not able to support by default.
152
- *
153
- * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors.
154
- * @param path - The path of the error.
155
- * @param parseResult - The result of the parse method.
156
- */
157
- private async __validateByFallbacks(
158
- path: ValidationFallbackCallbackReturnType['errors'][number]['path'],
159
- parseResult: {
160
- errors: undefined | ValidationFallbackCallbackReturnType['errors'];
161
- parsed: TType['input'];
162
- },
163
- options: Parameters<Schema['__transformToAdapter']>[0]
164
- ) {
165
- // eslint-disable-next-line ts/no-unnecessary-condition
166
- if (this.__rootFallbacksValidator)
167
- return this.__rootFallbacksValidator.validate(options.errorsAsHashedSet as Set<any>, path, parseResult, options);
168
-
169
- return parseResult;
170
- }
171
-
172
- /**
173
- * This will validate by the adapter. In other words, we send the data to the schema adapter and then we validate
174
- * that data.
175
- * So understand that, first we send the data to the adapter, the adapter validates it, then, after we validate
176
- * from the adapter we validate with the fallbacks so we can do all of the extra validations not handled by
177
- * the adapter.
178
- *
179
- * @param value - The value to be validated.
180
- * @param errorsAsHashedSet - The errors as a hashed set. This is used to prevent duplicate errors on the validator.
181
- * @param path - The path of the error so we can construct an object with the nested paths of the error.
182
- * @param parseResult - The result of the parse method.
183
- *
184
- * @returns The result and the errors of the parse method.
185
- */
186
- protected async __validateByAdapter(
187
- adapter: SchemaAdapter,
188
- fieldAdapter: FieldAdapter,
189
- schema: any,
190
- value: TType['input'],
191
- path: NonNullable<Parameters<Schema['__parse']>[1]>,
192
- options: Parameters<Schema['__transformToAdapter']>[0]
193
- ) {
194
- const parseResult: Awaited<ReturnType<Schema['__parse']>> = {
195
- errors: [],
196
- parsed: value
197
- };
198
- // On the next iteration we will reset the errors and the parsed value
199
- parseResult.errors = [];
200
- parseResult.parsed = value;
201
-
202
- // eslint-disable-next-line ts/no-unnecessary-condition
203
- if (fieldAdapter === undefined || typeof fieldAdapter.parse !== 'function') return parseResult;
204
-
205
- const adapterParseResult = await fieldAdapter.parse(
206
- adapter,
207
- adapter.field,
208
- schema.transformed,
209
- value,
210
- options.args
211
- );
212
-
213
- parseResult.parsed = adapterParseResult.parsed;
214
-
215
- if (adapterParseResult.errors) {
216
- if (Array.isArray(adapterParseResult.errors))
217
- parseResult.errors = await Promise.all(
218
- adapterParseResult.errors.map(async (error) =>
219
- formatErrorFromParseMethod(
220
- adapter,
221
- fieldAdapter,
222
- error,
223
- value,
224
- schema.transformed,
225
- path,
226
- options.errorsAsHashedSet || new Set()
227
- )
228
- )
229
- );
230
- else
231
- parseResult.errors = [
232
- await formatErrorFromParseMethod(
233
- adapter,
234
- fieldAdapter,
235
- parseResult.errors,
236
- value,
237
- schema.transformed,
238
- path,
239
- options.errorsAsHashedSet || new Set()
240
- )
241
- ];
242
- }
243
- parseResult.errors = parseResult.errors.filter((error) => typeof error !== 'undefined');
244
- return parseResult;
245
- }
246
-
247
- // eslint-disable-next-line ts/require-await
248
- protected async __transformToAdapter(_options: {
249
- // force to transform
250
- args: Omit<ValidationDataBasedOnType<any>, 'withFallback'>;
251
- force?: boolean;
252
- toInternalToBubbleUp?: (() => Promise<void>)[];
253
- schemaAdapter?: SchemaAdapter;
254
- errorsAsHashedSet?: Set<string>;
255
- shouldAddStringVersion?: boolean;
256
- context?: any;
257
- appendFallbacksBeforeAdapterValidation?: (
258
- schema: Schema<any, any>,
259
- uniqueNameOfFallback: string,
260
- fallbackValidationBeforeAdapter: (
261
- adapterToUse: SchemaAdapter,
262
- fieldAdapter: FieldAdapter,
263
- schema: Omit<Schema<any, any>, '__validateByAdapter'> & {
264
- __validateByAdapter: Schema<any, any>['__validateByAdapter'];
265
- },
266
- translatedSchemas: any[],
267
- value: any,
268
- path: ValidationFallbackCallbackReturnType['errors'][number]['path'],
269
- options: Parameters<Schema['__transformToAdapter']>[0]
270
- ) => ReturnType<Schema['__validateByAdapter']>
271
- ) => void;
272
- }): Promise<
273
- {
274
- transformed: ReturnType<FieldAdapter['translate']>;
275
- asString: string;
276
- }[]
277
- > {
278
- throw new Error('Not implemented');
279
- }
280
-
281
- /** */
282
- protected async __parsersToTransformValue(value: any, parsersToUse?: Set<string>) {
283
- let shouldStop = false;
284
-
285
- for (const [parserName, parser] of this.__parsers.high.entries()) {
286
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
287
- const result = await Promise.resolve(parser(value));
288
- if (result.preventNextParsers) shouldStop = true;
289
- value = result.value;
290
- } else continue;
291
- }
292
- if (shouldStop === false) {
293
- for (const [parserName, parser] of this.__parsers.medium.entries()) {
294
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
295
- const result = await Promise.resolve(parser(value));
296
- if (result.preventNextParsers) shouldStop = true;
297
- value = result.value;
298
- } else continue;
299
- }
300
- }
301
- if (shouldStop === false) {
302
- for (const [parserName, parser] of this.__parsers.low.entries()) {
303
- if (parsersToUse instanceof Set === false || parsersToUse.has(parserName)) {
304
- const result = await Promise.resolve(parser(value));
305
- if (result.preventNextParsers) shouldStop = true;
306
- value = result.value;
307
- } else continue;
308
- }
309
- }
310
-
311
- return value;
312
- }
313
-
314
- protected async __parse(
315
- value: TType['input'],
316
- path: ValidationFallbackCallbackReturnType['errors'][number]['path'] = [],
317
- options: Parameters<Schema['__transformToAdapter']>[0]
318
- ): Promise<{ errors: any[]; parsed: TType['internal'] }> {
319
- this.__getDefaultTransformedSchemas();
320
- if (typeof this.__runBeforeParseAndData === 'function') await this.__runBeforeParseAndData(this);
321
-
322
- // This is used to run the toInternal command. If we didn't do this, we would need to parse through all of
323
- // the schemas to run the toInternal command, from the leafs (ObjectSchemas) to the root schema. This is not
324
- // a good idea, so what we do is that during validation the leafs attach a function to the
325
- // options.toInternalToBubbleUp like
326
- // `options.toInternalToBubbleUp.push(async () => (value[key] = await (schema as any).__toInternal(parsed)));``
327
- // This way, when the root schema finishes the validation, it will run all of the functions in the
328
- // toInternalToBubbleUp array, modifying the parsed value.
329
- const shouldRunToInternalToBubbleUp = options.toInternalToBubbleUp === undefined;
330
- if (shouldRunToInternalToBubbleUp) options.toInternalToBubbleUp = [];
331
- if (options.errorsAsHashedSet instanceof Set === false) options.errorsAsHashedSet = new Set();
332
-
333
- const shouldCallDefaultFunction = value === undefined && typeof this.__defaultFunction === 'function';
334
- const shouldCallToValidateCallback = typeof this.__toValidate === 'function';
335
- const schemaAdapterFieldType = this.fieldType;
336
-
337
- if (shouldCallDefaultFunction) value = await (this.__defaultFunction as any)();
338
- if (shouldCallToValidateCallback) value = await Promise.resolve((this.__toValidate as any)(value));
339
-
340
- const parseResult: {
341
- errors: ValidationFallbackCallbackReturnType['errors'];
342
- parsed: TType['input'];
343
- } = { errors: [], parsed: value };
344
- value = await this.__parsersToTransformValue(value, this.__parsers._fallbacks);
345
-
346
- if (options.appendFallbacksBeforeAdapterValidation === undefined)
347
- options.appendFallbacksBeforeAdapterValidation = (schema, name, callback) => {
348
- // We just need this if the union adapter is net defined but the parent is not of the same type.
349
- // For example, it's a union child of o object schema
350
- if (this !== schema) this.__beforeValidationCallbacks.set(name, callback);
351
- };
352
-
353
- if (
354
- this.__transformedSchemas[options.schemaAdapter?.constructor.name || getDefaultAdapter().constructor.name]
355
- .transformed === false
356
- )
357
- await this.__transformToAdapter(options);
358
-
359
- const adapterToUse = options.schemaAdapter
360
- ? options.schemaAdapter
361
- : Object.values(this.__transformedSchemas)[0].adapter;
362
-
363
- const parsedResultsAfterFallbacks = await this.__validateByFallbacks(
364
- path,
365
- {
366
- errors: parseResult.errors,
367
- parsed: value
368
- },
369
- options
370
- );
371
-
372
- parseResult.parsed = parsedResultsAfterFallbacks.parsed;
373
- // eslint-disable-next-line ts/no-unnecessary-condition
374
- parseResult.errors = (parseResult.errors || []).concat(parsedResultsAfterFallbacks.errors || []);
375
- // With this, the children takes control of validating by the adapter. For example on a union schema we
376
- // want to validate all of the schemas and choose the one that has no errors.
377
- if (this.__beforeValidationCallbacks.size > 0) {
378
- for (const callback of this.__beforeValidationCallbacks.values()) {
379
- const parsedValuesAfterValidationCallbacks = await callback(
380
- adapterToUse,
381
- (adapterToUse as any)[schemaAdapterFieldType],
382
- this as any,
383
- this.__transformedSchemas[adapterToUse.constructor.name].schemas,
384
- value,
385
- path,
386
- options
387
- );
388
- parseResult.parsed = parsedValuesAfterValidationCallbacks.parsed;
389
-
390
- parseResult.errors =
391
- Array.isArray(parseResult.errors) && Array.isArray(parsedValuesAfterValidationCallbacks.errors)
392
- ? [...parseResult.errors, ...parsedValuesAfterValidationCallbacks.errors]
393
- : Array.isArray(parseResult.errors)
394
- ? parseResult.errors
395
- : parsedValuesAfterValidationCallbacks.errors;
396
- }
397
- } else {
398
- const parsedValuesAfterValidatingByAdapter = await this.__validateByAdapter(
399
- adapterToUse,
400
- (adapterToUse as any)[schemaAdapterFieldType],
401
- this.__transformedSchemas[adapterToUse.constructor.name].schemas[0],
402
- value,
403
- path,
404
- options
405
- );
406
-
407
- parseResult.parsed = parsedValuesAfterValidatingByAdapter.parsed;
408
- // eslint-disable-next-line ts/no-unnecessary-condition
409
- parseResult.errors = (parseResult.errors || []).concat(parsedValuesAfterValidatingByAdapter.errors);
410
- }
411
-
412
- const hasToInternalCallback = typeof this.__toInternal === 'function';
413
- const shouldCallToInternalDuringParse =
414
- hasToInternalCallback &&
415
- (options.toInternalToBubbleUp?.length === 0 || Array.isArray(options.toInternalToBubbleUp) === false);
416
- // eslint-disable-next-line ts/no-unnecessary-condition
417
- const hasNoErrors = parseResult.errors === undefined || (parseResult.errors || []).length === 0;
418
-
419
- await Promise.all(
420
- this.__refinements.map(async (refinement) => {
421
- const errorOrNothing = await Promise.resolve(refinement(parseResult.parsed));
422
-
423
- if (typeof errorOrNothing === 'undefined') return;
424
- parseResult.errors.push({
425
- isValid: false,
426
- code: errorOrNothing.code as any,
427
- message: errorOrNothing.message,
428
- received: parseResult.parsed,
429
- path
430
- });
431
- })
432
- );
433
-
434
- if (shouldCallToInternalDuringParse && hasNoErrors) parseResult.parsed = await (this.__toInternal as any)(value);
435
- if (shouldRunToInternalToBubbleUp && hasNoErrors)
436
- for (const functionToModifyResult of options.toInternalToBubbleUp || []) await functionToModifyResult();
437
-
438
- return parseResult;
439
- }
440
-
441
- /**
442
- * This let's you refine the schema with custom validations. This is useful when you want to validate something
443
- * that is not supported by default by the schema adapter.
444
- *
445
- * @example
446
- * ```typescript
447
- * import * as p from '@palmares/schemas';
448
- *
449
- * const numberSchema = p.number().refine((value) => {
450
- * if (value < 0) return { code: 'invalid_number', message: 'The number should be greater than 0' };
451
- * });
452
- *
453
- * const { errors, parsed } = await numberSchema.parse(-1);
454
- *
455
- * console.log(errors);
456
- * // [{ isValid: false, code: 'invalid_number', message: 'The number should be greater than 0', path: [] }]
457
- * ```
458
- *
459
- * @param refinementCallback - The callback that will be called to validate the value.
460
- * @param options - Options for the refinement.
461
- * @param options.isAsync - Whether the callback is async or not. Defaults to true.
462
- */
463
- refine(
464
- refinementCallback: (
465
- value: TType['input']
466
- ) =>
467
- | Promise<void | undefined | { code: string; message: string }>
468
- | void
469
- | undefined
470
- | { code: string; message: string }
471
- ) {
472
- this.__refinements.push(refinementCallback);
473
-
474
- return this as unknown as Schema<
475
- {
476
- input: TType['input'];
477
- validate: TType['validate'];
478
- internal: TType['internal'];
479
- output: TType['output'];
480
- representation: TType['representation'];
481
- },
482
- TDefinitions
483
- >;
484
- }
485
-
486
- /**
487
- * Allows the value to be either undefined or null.
488
- *
489
- * @example
490
- * ```typescript
491
- * import * as p from '@palmares/schemas';
492
- *
493
- * const numberSchema = p.number().optional();
494
- *
495
- * const { errors, parsed } = await numberSchema.parse(undefined);
496
- *
497
- * console.log(parsed); // undefined
498
- *
499
- * const { errors, parsed } = await numberSchema.parse(null);
500
- *
501
- * console.log(parsed); // null
502
- *
503
- * const { errors, parsed } = await numberSchema.parse(1);
504
- *
505
- * console.log(parsed); // 1
506
- * ```
507
- *
508
- * @returns - The schema we are working with.
509
- */
510
- optional(options?: { message?: string; allow?: false }) {
511
- this.__optional = {
512
- message: typeof options?.message === 'string' ? options.message : 'Required',
513
- allow: typeof options?.allow === 'boolean' ? options.allow : true
514
- };
515
-
516
- return this as unknown as Schema<
517
- {
518
- input: TType['input'] | undefined | null;
519
- validate: TType['validate'] | undefined | null;
520
- internal: TType['internal'] | undefined | null;
521
- output: TType['output'] | undefined | null;
522
- representation: TType['representation'] | undefined | null;
523
- },
524
- TDefinitions
525
- >;
526
- }
527
-
528
- /**
529
- * Allows the value to be null and ONLY null. You can also use this function to set a custom message when
530
- * the value is NULL by setting the { message: 'Your custom message', allow: false } on the options.
531
- *
532
- * @example
533
- * ```typescript
534
- * import * as p from '@palmares/schemas';
535
- *
536
- * const numberSchema = p.number().nullable();
537
- *
538
- * const { errors, parsed } = await numberSchema.parse(null);
539
- *
540
- * console.log(parsed); // null
541
- *
542
- * const { errors, parsed } = await numberSchema.parse(undefined);
543
- *
544
- * console.log(errors); // [{ isValid: false, code: 'invalid_type', message: 'Invalid type', path: [] }]
545
- * ```
546
- *
547
- * @param options - The options for the nullable function.
548
- * @param options.message - The message to be shown when the value is not null. Defaults to 'Cannot be null'.
549
- * @param options.allow - Whether the value can be null or not. Defaults to true.
550
- *
551
- * @returns The schema.
552
- */
553
- nullable(options?: { message: string; allow: false }) {
554
- this.__nullable = {
555
- message: typeof options?.message === 'string' ? options.message : 'Cannot be null',
556
- allow: typeof options?.allow === 'boolean' ? options.allow : true
557
- };
558
-
559
- return this as unknown as Schema<
560
- {
561
- input: TType['input'] | null;
562
- validate: TType['validate'] | null;
563
- internal: TType['internal'] | null;
564
- output: TType['output'] | null;
565
- representation: TType['representation'] | null;
566
- },
567
- TDefinitions
568
- >;
569
- }
570
-
571
- /**
572
- * Appends a custom schema to the schema, this way it will bypass the creation of the schema in runtime.
573
- *
574
- * By default when validating, on the first validation we create the schema. Just during the first validation.
575
- * With this function, you bypass that, so you can speed up the validation process.
576
- *
577
- * @example
578
- * ```typescript
579
- * import * as p from '@palmares/schemas';
580
- * import * as z from 'zod';
581
- *
582
- * const numberSchema = p.number().appendSchema(z.number());
583
- *
584
- * const { errors, parsed } = await numberSchema.parse(1);
585
- * ```
586
- *
587
- * @param schema - The schema to be appended.
588
- * @param args - The arguments for the schema.
589
- * @param args.adapter - The adapter to be used. If not provided, the default adapter will be used.
590
- *
591
- * @returns The same schema again.
592
- */
593
- appendSchema<TType extends any = any>(schema: TDefinitions['schemaAdapter'], args?: { adapter?: SchemaAdapter }) {
594
- const adapter = args?.adapter || getDefaultAdapter();
595
-
596
- this.__transformedSchemas[adapter.constructor.name] = {
597
- transformed: true,
598
- adapter: adapter,
599
- schemas: [schema]
600
- };
601
-
602
- return this as unknown as Schema<
603
- {
604
- input: TType;
605
- validate: TType;
606
- internal: TType;
607
- output: TType;
608
- representation: TType;
609
- },
610
- TDefinitions
611
- >;
612
- }
613
-
614
- /**
615
- * This method will remove the value from the representation of the schema. If the value is undefined it will keep
616
- * that way otherwise it will set the value to undefined after it's validated.
617
- * This is used in conjunction with the {@link data} function, the {@link parse} function or {@link validate}
618
- * function. This will remove the value from the representation of the schema.
619
- *
620
- * By default, the value will be removed just from the representation, in other words, when you call the {@link data}
621
- * function. But if you want to remove the value from the internal representation, you can pass the argument
622
- * `toInternal` as true. Then if you still want to remove the value from the representation, you will need to pass
623
- * the argument `toRepresentation` as true as well.
624
- *
625
- * @example
626
- * ```typescript
627
- * import * as p from '@palmares/schemas';
628
- *
629
- * const userSchema = p.object({
630
- * id: p.number().optional(),
631
- * name: p.string(),
632
- * password: p.string().omit()
633
- * });
634
- *
635
- * const user = await userSchema.data({
636
- * id: 1,
637
- * name: 'John Doe',
638
- * password: '123456'
639
- * });
640
- *
641
- * console.log(user); // { id: 1, name: 'John Doe' }
642
- * ```
643
- *
644
- *
645
- * @param args - By default, the value will be removed just from the representation, in other words, when you call
646
- * the {@link data} function.
647
- * But if you want to remove the value from the internal representation, you can pass the argument `toInternal`
648
- * as true. Then if you still want to remove the value from the representation, you will need to pass the
649
- * argument `toRepresentation` as true as well.
650
- *
651
- * @returns The schema.
652
- */
653
- omit<
654
- TToInternal extends boolean,
655
- TToRepresentation extends boolean = boolean extends TToInternal ? true : false
656
- >(args?: { toInternal?: TToInternal; toRepresentation?: TToRepresentation }) {
657
- // To representation is true by default, unless to internal is true.
658
- const toRepresentation =
659
- typeof args?.toRepresentation === 'boolean' ? args.toRepresentation : typeof args?.toInternal !== 'boolean';
660
- const toInternal = typeof args?.toInternal === 'boolean' ? args.toInternal : false;
661
-
662
- if (toInternal) {
663
- if (this.__toInternal) {
664
- const toInternal = this.__toInternal;
665
- this.__toInternal = async (value) => {
666
- await toInternal(value);
667
- return undefined;
668
- };
669
- // eslint-disable-next-line ts/require-await
670
- } else this.__toInternal = async () => undefined;
671
- } else if (toRepresentation) {
672
- if (this.__toRepresentation) {
673
- const toRepresentation = this.__toRepresentation;
674
- this.__toRepresentation = async (value) => {
675
- await toRepresentation(value);
676
- return undefined;
677
- };
678
- // eslint-disable-next-line ts/require-await
679
- } else this.__toRepresentation = async () => undefined;
680
- }
681
-
682
- return this as unknown as Schema<
683
- {
684
- input: TToInternal extends true ? TType['input'] | undefined : TType['input'];
685
- validate: TToInternal extends true ? TType['validate'] | undefined : TType['validate'];
686
- internal: TToInternal extends true ? undefined : TType['internal'];
687
- output: TToRepresentation extends true ? TType['output'] | undefined : TType['output'];
688
- representation: TToRepresentation extends true ? undefined : TType['representation'];
689
- },
690
- TDefinitions
691
- >;
692
- }
693
-
694
- /**
695
- * This function is used in conjunction with the {@link validate} function. It's used to save a value to an external
696
- * source like a database. You should always return the schema after you save the value, that way we will always have
697
- * the correct type of the schema after the save operation.
698
- *
699
- * You can use the {@link toRepresentation} function to transform and clean the value it returns after the save.
700
- *
701
- * @example
702
- * ```typescript
703
- * import * as p from '@palmares/schemas';
704
- *
705
- * import { User } from './models';
706
- *
707
- * const userSchema = p.object({
708
- * id: p.number().optional(),
709
- * name: p.string(),
710
- * email: p.string().email(),
711
- * }).onSave(async (value) => {
712
- * // Create or update the user on the database using palmares models or any other library of your choice.
713
- * if (value.id)
714
- * await User.default.set(value, { search: { id: value.id } });
715
- * else
716
- * await User.default.set(value);
717
- *
718
- * return value;
719
- * });
720
- *
721
- *
722
- * // Then, on your controller, do something like this:
723
- * const { isValid, save, errors } = await userSchema.validate(req.body);
724
- * if (isValid) {
725
- * const savedValue = await save();
726
- * return Response.json(savedValue, { status: 201 });
727
- * }
728
- *
729
- * return Response.json({ errors }, { status: 400 });
730
- * ```
731
- *
732
- * @param callback - The callback that will be called to save the value on an external source.
733
- *
734
- * @returns The schema.
735
- */
736
- onSave(
737
- callback: <TContext = any>(
738
- value: TType['internal'],
739
- context: TContext
740
- ) => Promise<TType['output']> | TType['output']
741
- ) {
742
- this.__saveCallback = callback;
743
-
744
- return this as unknown as Schema<
745
- {
746
- input: TType['input'];
747
- validate: TType['validate'];
748
- internal: TType['internal'];
749
- output: TType['output'];
750
- representation: TType['representation'];
751
- },
752
- TDefinitions & {
753
- hasSave: true;
754
- }
755
- >;
756
- }
757
-
758
- /**
759
- * This function is used to validate the schema and save the value to the database. It is used in
760
- * conjunction with the {@link onSave} function.
761
- *
762
- * Different from other validation libraries, palmares schemas is aware that you want to save. On your
763
- * routes/functions we recommend to ALWAYS use this function instead of {@link parse} directly. This is because
764
- * this function by default will return an object with the property `save` or the `errors`. If the errors are present,
765
- * you can return the errors to the user. If the save property is present, you can use to save the value to an
766
- * external source. e.g. a database.
767
- *
768
- * @example
769
- * ```typescript
770
- * import * as p from '@palmares/schemas';
771
- *
772
- * import { User } from './models';
773
- *
774
- * const userSchema = p.object({
775
- * id: p.number().optional(),
776
- * name: p.string(),
777
- * email: p.string().email(),
778
- * }).onSave(async (value) => {
779
- * // Create or update the user on the database using palmares models or any other library of your choice.
780
- * if (value.id)
781
- * await User.default.set(value, { search: { id: value.id } });
782
- * else
783
- * await User.default.set(value);
784
- *
785
- * return value;
786
- * });
787
- *
788
- *
789
- * // Then, on your controller, do something like this:
790
- * const { isValid, save, errors } = await userSchema.validate(req.body);
791
- * if (isValid) {
792
- * const savedValue = await save();
793
- * return Response.json(savedValue, { status: 201 });
794
- * }
795
- *
796
- * return Response.json({ errors }, { status: 400 });
797
- * ```
798
- *
799
- * @param value - The value to be validated.
800
- *
801
- * @returns An object with the property isValid, if the value is valid, the function `save` will be present.
802
- * If the value is invalid, the property errors will be present.
803
- */
804
- async validate(
805
- value: TType['input'],
806
- context: any
807
- ): Promise<{ isValid: false; errors: any[] } | { isValid: true; save: () => Promise<TType['representation']> }> {
808
- const { errors, parsed } = await this.__parse(value, [], { context } as any);
809
- // eslint-disable-next-line ts/no-unnecessary-condition
810
- if ((errors || []).length > 0) return { isValid: false, errors: errors };
811
- return { isValid: true, save: async () => this._save.bind(this)(parsed, context) };
812
- }
813
-
814
- /**
815
- * Internal function, when we call the {@link validate} function it's this function that gets called
816
- * when the user uses the `save` function returned by the {@link validate} function if the value is valid.
817
- *
818
- * @param value - The value to be saved.
819
- *
820
- * @returns The value to representation.
821
- */
822
- protected async _save(value: TType['input'], context: any): Promise<TType['representation']> {
823
- if (this.__saveCallback) {
824
- const result = await this.__saveCallback(value, context);
825
- return this.data(result) as Promise<
826
- true extends TDefinitions['hasSave'] ? TType['representation'] : { errors?: any[]; parsed: TType['internal'] }
827
- >;
828
- }
829
-
830
- return this.data(value);
831
- }
832
-
833
- /**
834
- * This function is used to validate and parse the value to the internal representation of the schema.
835
- *
836
- * @example
837
- * ```typescript
838
- * import * as p from '@palmares/schemas';
839
- *
840
- * const numberSchema = p.number().allowString();
841
- *
842
- * const { errors, parsed } = await numberSchema.parse('123');
843
- *
844
- * console.log(parsed); // 123
845
- * ```
846
- *
847
- * @param value - The value to be parsed.
848
- *
849
- * @returns The parsed value.
850
- */
851
- async parse(value: TType['input']): Promise<{ errors?: any[]; parsed: TType['internal'] }> {
852
- return this.__parse(value, [], {} as any);
853
- }
854
-
855
- /**
856
- * This function is used to transform the value to the representation without validating it.
857
- * This is useful when you want to return a data from a query directly to the user. But for example
858
- * you are returning the data of a user, you can clean the password or any other sensitive data.
859
- *
860
- * @example
861
- * ```typescript
862
- * import * as p from '@palmares/schemas';
863
- *
864
- * const userSchema = p.object({
865
- * id: p.number().optional(),
866
- * name: p.string(),
867
- * email: p.string().email(),
868
- * password: p.string().optional()
869
- * }).toRepresentation(async (value) => {
870
- * return {
871
- * id: value.id,
872
- * name: value.name,
873
- * email: value.email
874
- * }
875
- * });
876
- *
877
- * const user = await userSchema.data({
878
- * id: 1,
879
- * name: 'John Doe',
880
- * email: 'john@gmail.com',
881
- * password: '123456'
882
- * });
883
- * ```
884
- */
885
- async data(value: TType['output']): Promise<TType['representation']> {
886
- this.__getDefaultTransformedSchemas();
887
- if (typeof this.__runBeforeParseAndData === 'function') await this.__runBeforeParseAndData(this);
888
- value = await this.__parsersToTransformValue(value);
889
-
890
- if (this.__toRepresentation) value = await Promise.resolve(this.__toRepresentation(value));
891
- if (this.__defaultFunction && value === undefined) value = await Promise.resolve(this.__defaultFunction());
892
- return value;
893
- }
894
-
895
- instanceOf(args: Schema['__type']) {
896
- this.__type.check = typeof args.check === 'function' ? args.check : this.__type.check;
897
- this.__type.message = typeof args.message === 'string' ? args.message : this.__type.message;
898
-
899
- return this as unknown as Schema<
900
- {
901
- input: TType['input'];
902
- validate: TType['validate'];
903
- internal: TType['internal'];
904
- output: TType['output'];
905
- representation: TType['representation'];
906
- },
907
- TDefinitions
908
- >;
909
- }
910
-
911
- /**
912
- * This function is used to add a default value to the schema. If the value is either undefined or null,
913
- * the default value will be used.
914
- *
915
- * @example
916
- * ```typescript
917
- * import * as p from '@palmares/schemas';
918
- *
919
- * const numberSchema = p.number().default(0);
920
- *
921
- * const { errors, parsed } = await numberSchema.parse(undefined);
922
- *
923
- * console.log(parsed); // 0
924
- * ```
925
- */
926
- default<TDefaultValue extends TType['input'] | (() => Promise<TType['input']>)>(
927
- defaultValueOrFunction: TDefaultValue
928
- ) {
929
- const isFunction = typeof defaultValueOrFunction === 'function';
930
- if (isFunction) this.__defaultFunction = defaultValueOrFunction;
931
- // eslint-disable-next-line ts/require-await
932
- else this.__defaultFunction = async () => defaultValueOrFunction;
933
-
934
- return this as unknown as Schema<
935
- {
936
- input: TType['input'] | undefined | null;
937
- validate: TType['validate'];
938
- internal: TType['internal'];
939
- output: TType['output'] | undefined | null;
940
- representation: TType['representation'];
941
- },
942
- TDefinitions
943
- >;
944
- }
945
-
946
- /**
947
- * This function let's you customize the schema your own way. After we translate the schema on the adapter we call
948
- * this function to let you customize the custom schema your own way. Our API does not support passthrough?
949
- * No problem, you can use this function to customize the zod schema.
950
- *
951
- * @example
952
- * ```typescript
953
- * import * as p from '@palmares/schemas';
954
- *
955
- * const numberSchema = p.number().extends((schema) => {
956
- * return schema.nonnegative();
957
- * });
958
- *
959
- * const { errors, parsed } = await numberSchema.parse(-1);
960
- *
961
- * console.log(errors);
962
- * // [{ isValid: false, code: 'nonnegative', message: 'The number should be nonnegative', path: [] }]
963
- * ```
964
- *
965
- * @param callback - The callback that will be called to customize the schema.
966
- * @param toStringCallback - The callback that will be called to transform the schema to a string when you want
967
- * to compile the underlying schema to a string so you can save it for future runs.
968
- *
969
- * @returns The schema.
970
- */
971
- extends(
972
- callback: (
973
- schema: Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter'][TDefinitions['schemaType']]>['translate']>>
974
- ) => Awaited<ReturnType<NonNullable<TDefinitions['schemaAdapter'][TDefinitions['schemaType']]>['translate']>>,
975
- toStringCallback?: (schemaAsString: string) => string
976
- ) {
977
- this.__extends = {
978
- callback,
979
- toStringCallback
980
- };
981
- return this;
982
- }
983
-
984
- /**
985
- * This function is used to transform the value to the representation of the schema. When using the {@link data}
986
- * function. With this function you have full control to add data cleaning for example, transforming the data
987
- * and whatever. Another use case is when you want to return deeply nested recursive data.
988
- * The schema maps to itself.
989
- *
990
- * @example
991
- * ```typescript
992
- * import * as p from '@palmares/schemas';
993
- *
994
- * const recursiveSchema = p.object({
995
- * id: p.number().optional(),
996
- * name: p.string(),
997
- * }).toRepresentation(async (value) => {
998
- * return {
999
- * id: value.id,
1000
- * name: value.name,
1001
- * children: await Promise.all(value.children.map(async (child) => await recursiveSchema.data(child)))
1002
- * }
1003
- * });
1004
- *
1005
- * const data = await recursiveSchema.data({
1006
- * id: 1,
1007
- * name: 'John Doe',
1008
- * });
1009
- * ```
1010
- *
1011
- * @example
1012
- * ```
1013
- * import * as p from '@palmares/schemas';
1014
- *
1015
- * const colorToRGBSchema = p.string().toRepresentation(async (value) => {
1016
- * switch (value) {
1017
- * case 'red': return { r: 255, g: 0, b: 0 };
1018
- * case 'green': return { r: 0, g: 255, b: 0 };
1019
- * case 'blue': return { r: 0, g: 0, b: 255 };
1020
- * default: return { r: 0, g: 0, b: 0 };
1021
- * }
1022
- * });
1023
- * ```
1024
- * @param toRepresentationCallback - The callback that will be called to transform the value to the representation.
1025
- * @param options - Options for the toRepresentation function.
1026
- * @param options.after - Whether the toRepresentationCallback should be called after the existing
1027
- * toRepresentationCallback. Defaults to true.
1028
- * @param options.before - Whether the toRepresentationCallback should be called before the existing
1029
- * toRepresentationCallback. Defaults to true.
1030
- *
1031
- * @returns The schema with a new return type
1032
- */
1033
- toRepresentation<TRepresentation>(
1034
- toRepresentationCallback: (value: TType['representation']) => Promise<TRepresentation> | TRepresentation,
1035
- options?: {
1036
- after?: boolean;
1037
- before?: boolean;
1038
- }
1039
- ) {
1040
- if (this.__toRepresentation) {
1041
- const before =
1042
- typeof options?.before === 'boolean'
1043
- ? options.before
1044
- : typeof options?.after === 'boolean'
1045
- ? !options.after
1046
- : true;
1047
- const existingToRepresentation = this.__toRepresentation;
1048
-
1049
- this.__toRepresentation = async (value) => {
1050
- if (before) return toRepresentationCallback(await existingToRepresentation(value));
1051
- else return existingToRepresentation(await toRepresentationCallback(value));
1052
- };
1053
- } else this.__toRepresentation = toRepresentationCallback;
1054
-
1055
- return this as unknown as Schema<
1056
- {
1057
- input: TType['input'];
1058
- validate: TType['validate'];
1059
- internal: TType['internal'];
1060
- output: TType['output'];
1061
- representation: TRepresentation;
1062
- },
1063
- TDefinitions
1064
- >;
1065
- }
1066
-
1067
- /**
1068
- * This function is used to transform the value to the internal representation of the schema. This is useful
1069
- * when you want to transform the value to a type that the schema adapter can understand. For example, you
1070
- * might want to transform a string to a date. This is the function you use.
1071
- *
1072
- * @example
1073
- * ```typescript
1074
- * import * as p from '@palmares/schemas';
1075
- *
1076
- * const dateSchema = p.string().toInternal((value) => {
1077
- * return new Date(value);
1078
- * });
1079
- *
1080
- * const date = await dateSchema.parse('2021-01-01');
1081
- *
1082
- * console.log(date); // Date object
1083
- *
1084
- * const rgbToColorSchema = p.object({
1085
- * r: p.number().min(0).max(255),
1086
- * g: p.number().min(0).max(255),
1087
- * b: p.number().min(0).max(255),
1088
- * }).toInternal(async (value) => {
1089
- * if (value.r === 255 && value.g === 0 && value.b === 0) return 'red';
1090
- * if (value.r === 0 && value.g === 255 && value.b === 0) return 'green';
1091
- * if (value.r === 0 && value.g === 0 && value.b === 255) return 'blue';
1092
- * return `rgb(${value.r}, ${value.g}, ${value.b})`;
1093
- * });
1094
- * ```
1095
- *
1096
- * @param toInternalCallback - The callback that will be called to transform the value to the internal representation.
1097
- *
1098
- * @returns The schema with a new return type.
1099
- */
1100
- toInternal<TInternal>(toInternalCallback: (value: TType['validate']) => Promise<TInternal>) {
1101
- if (this.__toInternal) {
1102
- const toInternal = this.__toInternal;
1103
- this.__toInternal = async (value) => {
1104
- const newValue = await toInternal(value);
1105
- return toInternalCallback(newValue);
1106
- };
1107
- } else this.__toInternal = toInternalCallback;
1108
-
1109
- return this as unknown as Schema<
1110
- {
1111
- input: TType['input'];
1112
- validate: TType['validate'];
1113
- internal: TInternal;
1114
- output: TType['output'];
1115
- representation: TType['representation'];
1116
- },
1117
- TDefinitions
1118
- >;
1119
- }
1120
-
1121
- /**
1122
- * Called before the validation of the schema. Let's say that you want to validate a date that might receive a
1123
- * string, you can convert that string to a date here BEFORE the validation. This pretty much transforms the value
1124
- * to a type that the schema adapter can understand.
1125
- *
1126
- * @example
1127
- * ```
1128
- * import * as p from '@palmares/schemas';
1129
- * import * as z from 'zod';
1130
- *
1131
- * const customRecordToMapSchema = p.schema().appendSchema(z.map()).toValidate(async (value) => {
1132
- * return new Map(value); // Before validating we transform the value to a map.
1133
- * });
1134
- *
1135
- * const { errors, parsed } = await customRecordToMapSchema.parse({ key: 'value' });
1136
- * ```
1137
- *
1138
- * @param toValidateCallback - The callback that will be called to validate the value.
1139
- *
1140
- * @returns The schema with a new return type.
1141
- */
1142
- toValidate<TValidate>(toValidateCallback: (value: TType['input']) => Promise<TValidate> | TValidate) {
1143
- this.__toValidate = toValidateCallback;
1144
-
1145
- return this as unknown as Schema<
1146
- {
1147
- input: TType['input'];
1148
- validate: TValidate;
1149
- internal: TType['internal'];
1150
- output: TType['output'];
1151
- representation: TType['representation'];
1152
- },
1153
- TDefinitions
1154
- >;
1155
- }
1156
-
1157
- /**
1158
- * Used to transform the given schema on a stringfied version of the adapter.
1159
- */
1160
- async compile(adapter: SchemaAdapter) {
1161
- const data = await this.__transformToAdapter({
1162
- shouldAddStringVersion: true,
1163
- force: true
1164
- } as any);
1165
-
1166
- const stringVersions = data.map((value) => value.asString);
1167
- return stringVersions;
1168
- }
1169
-
1170
- static new<TType extends { input: any; output: any; internal: any; representation: any; validate: any }>(
1171
- ..._args: any[]
1172
- ): Schema<TType> {
1173
- const result = new Schema<TType>();
1174
- return result;
1175
- }
1176
- }
1177
-
1178
- export const schema = Schema.new;