@oscarpalmer/jhunal 0.17.0 → 0.18.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 (40) hide show
  1. package/dist/constants.d.mts +28 -15
  2. package/dist/constants.mjs +31 -14
  3. package/dist/helpers.d.mts +8 -1
  4. package/dist/helpers.mjs +68 -3
  5. package/dist/index.d.mts +284 -240
  6. package/dist/index.mjs +188 -50
  7. package/dist/models/infer.model.d.mts +66 -0
  8. package/dist/models/infer.model.mjs +1 -0
  9. package/dist/models/misc.model.d.mts +153 -0
  10. package/dist/models/misc.model.mjs +1 -0
  11. package/dist/models/schema.plain.model.d.mts +92 -0
  12. package/dist/models/schema.plain.model.mjs +1 -0
  13. package/dist/models/schema.typed.model.d.mts +96 -0
  14. package/dist/models/schema.typed.model.mjs +1 -0
  15. package/dist/models/transform.model.d.mts +59 -0
  16. package/dist/models/transform.model.mjs +1 -0
  17. package/dist/models/validation.model.d.mts +81 -0
  18. package/dist/models/validation.model.mjs +21 -0
  19. package/dist/schematic.d.mts +15 -1
  20. package/dist/schematic.mjs +7 -12
  21. package/dist/validation/property.validation.d.mts +1 -1
  22. package/dist/validation/property.validation.mjs +21 -17
  23. package/dist/validation/value.validation.d.mts +2 -2
  24. package/dist/validation/value.validation.mjs +63 -11
  25. package/package.json +2 -2
  26. package/src/constants.ts +84 -19
  27. package/src/helpers.ts +162 -4
  28. package/src/index.ts +3 -1
  29. package/src/models/infer.model.ts +105 -0
  30. package/src/models/misc.model.ts +212 -0
  31. package/src/models/schema.plain.model.ts +110 -0
  32. package/src/models/schema.typed.model.ts +109 -0
  33. package/src/models/transform.model.ts +85 -0
  34. package/src/models/validation.model.ts +123 -0
  35. package/src/schematic.ts +24 -13
  36. package/src/validation/property.validation.ts +41 -36
  37. package/src/validation/value.validation.ts +115 -15
  38. package/dist/models.d.mts +0 -484
  39. package/dist/models.mjs +0 -13
  40. package/src/models.ts +0 -665
@@ -1,9 +1,72 @@
1
1
  import {isPlainObject} from '@oscarpalmer/atoms/is';
2
- import {isSchematic} from '../helpers';
3
- import type {ValidatedProperty, ValidatedPropertyType, ValueName} from '../models';
2
+ import type {GenericCallback} from '@oscarpalmer/atoms/models';
3
+ import {
4
+ getInvalidInputMessage,
5
+ getInvalidMissingMessage,
6
+ getInvalidTypeMessage,
7
+ getInvalidValidatorMessage,
8
+ isSchematic,
9
+ } from '../helpers';
10
+ import type {ValueName} from '../models/misc.model';
11
+ import {
12
+ ValidationError,
13
+ type ReportingInformation,
14
+ type ValidatedProperty,
15
+ type ValidatedPropertyType,
16
+ type ValidationInformation,
17
+ } from '../models/validation.model';
18
+
19
+ function validateNamed(
20
+ property: ValidatedProperty,
21
+ name: ValueName,
22
+ value: unknown,
23
+ validation: ValidationInformation[],
24
+ ): boolean {
25
+ if (!validators[name](value)) {
26
+ return false;
27
+ }
28
+
29
+ const propertyValidators = property.validators[name];
30
+
31
+ if (propertyValidators == null || propertyValidators.length === 0) {
32
+ return true;
33
+ }
34
+
35
+ const {length} = propertyValidators;
36
+
37
+ for (let index = 0; index < length; index += 1) {
38
+ const validator = propertyValidators[index];
4
39
 
5
- export function validateObject(obj: unknown, properties: ValidatedProperty[]): boolean {
40
+ if (!validator(value)) {
41
+ validation.push({
42
+ key: {...property.key},
43
+ message: getInvalidValidatorMessage(property, name, index, length),
44
+ validator: validator as GenericCallback,
45
+ });
46
+
47
+ return false;
48
+ }
49
+ }
50
+
51
+ return true;
52
+ }
53
+
54
+ export function validateObject(
55
+ obj: unknown,
56
+ properties: ValidatedProperty[],
57
+ reporting: ReportingInformation,
58
+ validation?: ValidationInformation[],
59
+ ): boolean {
6
60
  if (!isPlainObject(obj)) {
61
+ if (reporting.throw && validation == null) {
62
+ throw new ValidationError([
63
+ {
64
+ key: {full: '', short: ''},
65
+ message: getInvalidInputMessage(obj),
66
+ },
67
+ ]);
68
+ }
69
+
7
70
  return false;
8
71
  }
9
72
 
@@ -14,22 +77,52 @@ export function validateObject(obj: unknown, properties: ValidatedProperty[]): b
14
77
 
15
78
  const {key, required, types} = property;
16
79
 
17
- const value = obj[key];
80
+ const value = obj[key.short];
18
81
 
19
82
  if (value === undefined && required) {
83
+ const information: ValidationInformation = {
84
+ key: {...key},
85
+ message: getInvalidMissingMessage(property),
86
+ };
87
+
88
+ if (reporting.throw && validation == null) {
89
+ throw new ValidationError([information]);
90
+ }
91
+
92
+ if (validation != null) {
93
+ validation.push(information);
94
+ }
95
+
20
96
  return false;
21
97
  }
22
98
 
23
99
  const typesLength = types.length;
24
100
 
101
+ const information: ValidationInformation[] = [];
102
+
25
103
  for (let typeIndex = 0; typeIndex < typesLength; typeIndex += 1) {
26
104
  const type = types[typeIndex];
27
105
 
28
- if (validateValue(type, property, value)) {
106
+ if (validateValue(type, property, value, reporting, information)) {
29
107
  continue outer;
30
108
  }
31
109
  }
32
110
 
111
+ if (reporting.throw && validation == null) {
112
+ throw new ValidationError(
113
+ information.length === 0
114
+ ? [
115
+ {
116
+ key: {...key},
117
+ message: getInvalidTypeMessage(property, value),
118
+ },
119
+ ]
120
+ : information,
121
+ );
122
+ }
123
+
124
+ validation?.push(...information);
125
+
33
126
  return false;
34
127
  }
35
128
 
@@ -40,23 +133,30 @@ function validateValue(
40
133
  type: ValidatedPropertyType,
41
134
  property: ValidatedProperty,
42
135
  value: unknown,
136
+ reporting: ReportingInformation,
137
+ validation: ValidationInformation[],
43
138
  ): boolean {
44
- switch (true) {
45
- case isSchematic(type):
46
- return type.is(value);
139
+ let result: boolean;
47
140
 
141
+ switch (true) {
48
142
  case typeof type === 'function':
49
- return (type as (value: unknown) => boolean)(value);
143
+ result = (type as GenericCallback)(value);
144
+ break;
50
145
 
51
- case typeof type === 'object':
52
- return validateObject(value, [type] as ValidatedProperty[]);
146
+ case Array.isArray(type):
147
+ result = validateObject(value, type, reporting, validation);
148
+ break;
149
+
150
+ case isSchematic(type):
151
+ result = type.is(value, reporting as never) as unknown as boolean;
152
+ break;
53
153
 
54
154
  default:
55
- return (
56
- validators[type as ValueName](value) &&
57
- (property.validators[type as ValueName]?.every(validator => validator(value)) ?? true)
58
- );
155
+ result = validateNamed(property, type as ValueName, value, validation);
156
+ break;
59
157
  }
158
+
159
+ return result;
60
160
  }
61
161
 
62
162
  //
package/dist/models.d.mts DELETED
@@ -1,484 +0,0 @@
1
- import { Schematic } from "./schematic.mjs";
2
- import { Constructor, GenericCallback, PlainObject, Simplify } from "@oscarpalmer/atoms/models";
3
-
4
- //#region src/models.d.ts
5
- /**
6
- * Removes duplicate types from a tuple, preserving first occurrence order
7
- *
8
- * @template Value - Tuple to deduplicate
9
- * @template Seen - Accumulator for already-seen types _(internal)_
10
- *
11
- * @example
12
- * ```ts
13
- * // DeduplicateTuple<['string', 'number', 'string']>
14
- * // => ['string', 'number']
15
- * ```
16
- */
17
- type DeduplicateTuple<Value extends unknown[], Seen extends unknown[] = []> = Value extends [infer Head, ...infer Tail] ? Head extends Seen[number] ? DeduplicateTuple<Tail, Seen> : DeduplicateTuple<Tail, [...Seen, Head]> : Seen;
18
- /**
19
- * Recursively extracts {@link ValueName} strings from a type, unwrapping arrays and readonly arrays
20
- *
21
- * @template Value - Type to extract value names from
22
- *
23
- * @example
24
- * ```ts
25
- * // ExtractValueNames<'string'> => 'string'
26
- * // ExtractValueNames<['string', 'number']> => 'string' | 'number'
27
- * ```
28
- */
29
- type ExtractValueNames<Value> = Value extends ValueName ? Value : Value extends (infer Item)[] ? ExtractValueNames<Item> : Value extends readonly (infer Item)[] ? ExtractValueNames<Item> : never;
30
- /**
31
- * Infers the TypeScript type from a {@link Schema} definition
32
- *
33
- * @template Model - Schema to infer types from
34
- *
35
- * @example
36
- * ```ts
37
- * const userSchema = {
38
- * name: 'string',
39
- * age: 'number',
40
- * address: { $required: false, $type: 'string' },
41
- * } satisfies Schema;
42
- *
43
- * type User = Infer<typeof userSchema>;
44
- * // { name: string; age: number; address?: string }
45
- * ```
46
- */
47
- type Infer<Model extends Schema> = Simplify<{ [Key in InferRequiredKeys<Model>]: InferSchemaEntry<Model[Key]> } & { [Key in InferOptionalKeys<Model>]?: InferSchemaEntry<Model[Key]> }>;
48
- /**
49
- * Extracts keys from a {@link Schema} whose entries are optional _(i.e., `$required` is `false`)_
50
- *
51
- * @template Model - {@link Schema} to extract optional keys from
52
- */
53
- type InferOptionalKeys<Model extends Schema> = keyof { [Key in keyof Model as IsOptionalProperty<Model[Key]> extends true ? Key : never]: never };
54
- /**
55
- * Infers the TypeScript type of a {@link SchemaProperty}'s `$type` field, unwrapping arrays to infer their item type
56
- *
57
- * @template Value - `$type` value _(single or array)_
58
- */
59
- type InferPropertyType<Value> = Value extends (infer Item)[] ? InferPropertyValue<Item> : InferPropertyValue<Value>;
60
- /**
61
- * Maps a single type definition to its TypeScript equivalent
62
- *
63
- * Resolves, in order: {@link Constructor} instances, {@link Schematic} models, {@link ValueName} strings, and nested {@link Schema} objects
64
- *
65
- * @template Value - single type definition
66
- */
67
- type InferPropertyValue<Value> = Value extends Constructor<infer Instance> ? Instance : Value extends Schematic<infer Model> ? Model : Value extends ValueName ? Values[Value & ValueName] : Value extends Schema ? Infer<Value> : never;
68
- /**
69
- * Extracts keys from a {@link Schema} whose entries are required _(i.e., `$required` is not `false`)_
70
- *
71
- * @template Model - Schema to extract required keys from
72
- */
73
- type InferRequiredKeys<Model extends Schema> = keyof { [Key in keyof Model as IsOptionalProperty<Model[Key]> extends true ? never : Key]: never };
74
- /**
75
- * Infers the type for a top-level {@link Schema} entry, unwrapping arrays to infer their item type
76
- *
77
- * @template Value - Schema entry value _(single or array)_
78
- */
79
- type InferSchemaEntry<Value> = Value extends (infer Item)[] ? InferSchemaEntryValue<Item> : InferSchemaEntryValue<Value>;
80
- /**
81
- * Resolves a single schema entry to its TypeScript type
82
- *
83
- * Handles, in order: {@link Constructor} instances, {@link Schematic} models, {@link SchemaProperty} objects, {@link NestedSchema} objects, {@link ValueName} strings, and plain {@link Schema} objects
84
- *
85
- * @template Value - single schema entry
86
- */
87
- type InferSchemaEntryValue<Value> = Value extends Constructor<infer Instance> ? Instance : Value extends Schematic<infer Model> ? Model : Value extends SchemaProperty ? InferPropertyType<Value['$type']> : Value extends PlainSchema ? Infer<Value & Schema> : Value extends ValueName ? Values[Value & ValueName] : Value extends Schema ? Infer<Value> : never;
88
- /**
89
- * Determines whether a schema entry is optional
90
- *
91
- * Returns `true` if the entry is a {@link SchemaProperty} or {@link NestedSchema} with `$required` set to `false`; otherwise returns `false`
92
- *
93
- * @template Value - Schema entry to check
94
- */
95
- type IsOptionalProperty<Value> = Value extends SchemaProperty ? Value['$required'] extends false ? true : false : false;
96
- /**
97
- * Extracts the last member from a union type by leveraging intersection of function return types
98
- *
99
- * @template Value - Union type
100
- */
101
- type LastOfUnion<Value> = UnionToIntersection<Value extends unknown ? () => Value : never> extends (() => infer Item) ? Item : never;
102
- /**
103
- * Maps each element of a tuple through {@link ToValueType}
104
- *
105
- * @template Value - Tuple of types to map
106
- */
107
- type MapToValueTypes<Value extends unknown[]> = Value extends [infer Head, ...infer Tail] ? [ToValueType<Head>, ...MapToValueTypes<Tail>] : [];
108
- /**
109
- * Maps each element of a tuple through {@link ToSchemaPropertyTypeEach}
110
- *
111
- * @template Value - Tuple of types to map
112
- */
113
- type MapToSchemaPropertyTypes<Value extends unknown[]> = Value extends [infer Head, ...infer Tail] ? [ToSchemaPropertyTypeEach<Head>, ...MapToSchemaPropertyTypes<Tail>] : [];
114
- /**
115
- * Extracts keys from an object type that are optional
116
- *
117
- * @template Value - Object type to inspect
118
- */
119
- type OptionalKeys<Value> = { [Key in keyof Value]-?: {} extends Pick<Value, Key> ? Key : never }[keyof Value];
120
- /**
121
- * A generic schema allowing {@link NestedSchema}, {@link SchemaEntry}, or arrays of {@link SchemaEntry} as values
122
- */
123
- type PlainSchema = {
124
- [key: string]: PlainSchema | SchemaEntry | SchemaEntry[] | undefined;
125
- } & {
126
- $required?: never;
127
- $type?: never;
128
- $validators?: never;
129
- };
130
- /**
131
- * A map of optional validator functions keyed by {@link ValueName}, used to add custom validation to {@link SchemaProperty} definitions
132
- *
133
- * Each key may hold a single validator or an array of validators that receive the typed value
134
- *
135
- * @template Value - `$type` value(s) to derive validator keys from
136
- *
137
- * @example
138
- * ```ts
139
- * const validators: PropertyValidators<'string'> = {
140
- * string: (value) => value.length > 0,
141
- * };
142
- * ```
143
- */
144
- type PropertyValidators<Value> = { [Key in ExtractValueNames<Value>]?: ((value: Values[Key]) => boolean) | Array<(value: Values[Key]) => boolean> };
145
- /**
146
- * Extracts keys from an object type that are required _(i.e., not optional)_
147
- *
148
- * @template Value - Object type to inspect
149
- */
150
- type RequiredKeys<Value> = Exclude<keyof Value, OptionalKeys<Value>>;
151
- /**
152
- * A schema for validating objects
153
- *
154
- * @example
155
- * ```ts
156
- * const schema: Schema = {
157
- * name: 'string',
158
- * age: 'number',
159
- * tags: ['string', 'number'],
160
- * };
161
- * ```
162
- */
163
- type Schema = SchemaIndex;
164
- /**
165
- * A union of all valid types for a single schema entry
166
- *
167
- * Can be a {@link Constructor}, nested {@link Schema}, {@link SchemaProperty}, {@link Schematic}, {@link ValueName} string, or a custom validator function
168
- */
169
- type SchemaEntry = Constructor | PlainSchema | SchemaProperty | Schematic<unknown> | ValueName | ((value: unknown) => boolean);
170
- /**
171
- * Index signature interface backing {@link Schema}, allowing string-keyed entries of {@link NestedSchema}, {@link SchemaEntry}, or arrays of {@link SchemaEntry}
172
- */
173
- interface SchemaIndex {
174
- [key: string]: PlainSchema | SchemaEntry | SchemaEntry[];
175
- }
176
- /**
177
- * A property definition with explicit type(s), an optional requirement flag, and optional validators
178
- *
179
- * @example
180
- * ```ts
181
- * const prop: SchemaProperty = {
182
- * $required: false,
183
- * $type: ['string', 'number'],
184
- * $validators: {
185
- * string: (v) => v.length > 0,
186
- * number: (v) => v > 0,
187
- * },
188
- * };
189
- * ```
190
- */
191
- type SchemaProperty = {
192
- /**
193
- * Whether the property is required _(defaults to `true`)_
194
- */
195
- $required?: boolean;
196
- /**
197
- * The type(s) the property value must match; a single {@link SchemaPropertyType} or an array
198
- */
199
- $type: SchemaPropertyType | SchemaPropertyType[];
200
- /**
201
- * Optional validators keyed by {@link ValueName}, applied during validation
202
- */
203
- $validators?: PropertyValidators<SchemaPropertyType | SchemaPropertyType[]>;
204
- };
205
- /**
206
- * A union of valid types for a {@link SchemaProperty}'s `$type` field
207
- *
208
- * Can be a {@link Constructor}, {@link PlainSchema}, {@link Schematic}, {@link ValueName} string, or a custom validator function
209
- */
210
- type SchemaPropertyType = Constructor | PlainSchema | Schematic<unknown> | ValueName | ((value: unknown) => boolean);
211
- /**
212
- * A custom error class for schematic validation failures
213
- */
214
- declare class SchematicError extends Error {
215
- constructor(message: string);
216
- }
217
- /**
218
- * Converts a type into its corresponding {@link SchemaPropertyType}-representation
219
- *
220
- * Deduplicates and unwraps single-element tuples via {@link UnwrapSingle}
221
- *
222
- * @template Value - type to convert
223
- */
224
- type ToSchemaPropertyType<Value> = UnwrapSingle<DeduplicateTuple<MapToSchemaPropertyTypes<UnionToTuple<Value>>>>;
225
- /**
226
- * Converts a single type to its schema property equivalent
227
- *
228
- * {@link NestedSchema} values have `$required` stripped, plain objects become {@link TypedSchema}, and primitives go through {@link ToValueType}
229
- *
230
- * @template Value - type to convert
231
- */
232
- type ToSchemaPropertyTypeEach<Value> = Value extends PlainObject ? TypedSchema<Value> : ToValueType<Value>;
233
- /**
234
- * Converts a type into its corresponding {@link ValueName}-representation
235
- *
236
- * Deduplicates and unwraps single-element tuples via {@link UnwrapSingle}
237
- *
238
- * @template Value - type to convert
239
- */
240
- type ToSchemaType<Value> = UnwrapSingle<DeduplicateTuple<MapToValueTypes<UnionToTuple<Value>>>>;
241
- /**
242
- * Maps a type to its {@link ValueName} string equivalent
243
- *
244
- * Resolves {@link Schematic} types as-is, then performs a reverse-lookup against {@link Values} _(excluding `'object'`)_ to find a matching key. If no match is found, `object` types resolve to `'object'` or a type-guard function, and all other unrecognised types resolve to a type-guard function
245
- *
246
- * @template Value - type to map
247
- *
248
- * @example
249
- * ```ts
250
- * // ToValueType<string> => 'string'
251
- * // ToValueType<number[]> => 'array'
252
- * // ToValueType<Date> => 'date'
253
- * ```
254
- */
255
- type ToValueType<Value> = Value extends Schematic<any> ? Value : { [Key in keyof Omit<Values, 'object'>]: Value extends Values[Key] ? Key : never }[keyof Omit<Values, 'object'>] extends infer Match ? [Match] extends [never] ? Value extends object ? 'object' | ((value: unknown) => value is Value) : (value: unknown) => value is Value : Match : never;
256
- /**
257
- * Generates all permutations of a tuple type
258
- *
259
- * Used by {@link UnwrapSingle} to allow schema types in any order for small tuples _(length ≤ 5)_
260
- *
261
- * @template Tuple - Tuple to permute
262
- * @template Elput - Accumulator for the current permutation _(internal; name is Tuple backwards)_
263
- *
264
- * @example
265
- * ```ts
266
- * // TuplePermutations<['string', 'number']>
267
- * // => ['string', 'number'] | ['number', 'string']
268
- * ```
269
- */
270
- type TuplePermutations<Tuple extends unknown[], Elput extends unknown[] = []> = Tuple['length'] extends 0 ? Elput : { [Key in keyof Tuple]: TuplePermutations<TupleRemoveAt<Tuple, Key & `${number}`>, [...Elput, Tuple[Key]]> }[keyof Tuple & `${number}`];
271
- /**
272
- * Removes the element at a given index from a tuple
273
- *
274
- * Used internally by {@link TuplePermutations}
275
- *
276
- * @template Items - Tuple to remove from
277
- * @template Item - Stringified index to remove
278
- * @template Prefix - Accumulator for elements before the target _(internal)_
279
- */
280
- type TupleRemoveAt<Items extends unknown[], Item extends string, Prefix extends unknown[] = []> = Items extends [infer Head, ...infer Tail] ? `${Prefix['length']}` extends Item ? [...Prefix, ...Tail] : TupleRemoveAt<Tail, Item, [...Prefix, Head]> : Prefix;
281
- /**
282
- * A typed optional property definition generated by {@link TypedSchema} for optional keys, with `$required` set to `false` and excludes `undefined` from the type
283
- *
284
- * @template Value - Property's type _(including `undefined`)_
285
- *
286
- * @example
287
- * ```ts
288
- * // For `{ name?: string }`, the `name` key produces:
289
- * // TypedPropertyOptional<string | undefined>
290
- * // => { $required: false; $type: 'string'; ... }
291
- * ```
292
- */
293
- type TypedPropertyOptional<Value> = {
294
- /**
295
- * The property is not required
296
- */
297
- $required: false;
298
- /**
299
- * The type(s) of the property
300
- */
301
- $type: ToSchemaPropertyType<Exclude<Value, undefined>>;
302
- /**
303
- * Custom validators for the property and its types
304
- */
305
- $validators?: PropertyValidators<ToSchemaPropertyType<Exclude<Value, undefined>>>;
306
- };
307
- /**
308
- * A typed required property definition generated by {@link TypedSchema} for required keys, with `$required` defaulting to `true`
309
- *
310
- * @template Value - Property's type
311
- *
312
- * @example
313
- * ```ts
314
- * // For `{ name: string }`, the `name` key produces:
315
- * // TypedPropertyRequired<string>
316
- * // => { $required?: true; $type: 'string'; ... }
317
- * ```
318
- */
319
- type TypedPropertyRequired<Value> = {
320
- /**
321
- * The property is required _(defaults to `true`)_
322
- */
323
- $required?: true;
324
- /**
325
- * The type(s) of the property
326
- */
327
- $type: ToSchemaPropertyType<Value>;
328
- /**
329
- * Custom validators for the property and its types
330
- */
331
- $validators?: PropertyValidators<ToSchemaPropertyType<Value>>;
332
- };
333
- /**
334
- * Creates a schema type constrained to match a TypeScript type
335
- *
336
- * Required keys map to {@link ToSchemaType} or {@link TypedPropertyRequired}; plain object values may also use {@link Schematic}. Optional keys map to {@link TypedPropertyOptional} or, for plain objects, {@link TypedSchemaOptional}
337
- *
338
- * @template Model - Object type to generate a schema for
339
- *
340
- * @example
341
- * ```ts
342
- * type User = { name: string; age: number; bio?: string };
343
- *
344
- * const schema: TypedSchema<User> = {
345
- * name: 'string',
346
- * age: 'number',
347
- * bio: { $required: false, $type: 'string' },
348
- * };
349
- * ```
350
- */
351
- type TypedSchema<Model extends PlainObject> = Simplify<{ [Key in RequiredKeys<Model>]: Model[Key] extends PlainObject ? TypedSchemaRequired<Model[Key]> | Schematic<Model[Key]> : ToSchemaType<Model[Key]> | TypedPropertyRequired<Model[Key]> } & { [Key in OptionalKeys<Model>]: Exclude<Model[Key], undefined> extends PlainObject ? TypedSchemaOptional<Exclude<Model[Key], undefined>> | Schematic<Exclude<Model[Key], undefined>> : TypedPropertyOptional<Model[Key]> }>;
352
- /**
353
- * A {@link TypedSchema} variant for optional nested objects, with `$required` fixed to `false`
354
- *
355
- * @template Model - Nested object type
356
- */
357
- type TypedSchemaOptional<Model extends PlainObject> = {
358
- $required: false;
359
- } & TypedSchema<Model>;
360
- /**
361
- * A {@link TypedSchema} variant for required nested objects, with `$required` defaulting to `true`
362
- *
363
- * @template Model - Nested object type
364
- */
365
- type TypedSchemaRequired<Model extends PlainObject> = {
366
- $required?: true;
367
- } & TypedSchema<Model>;
368
- /**
369
- * Converts a union type into an intersection
370
- *
371
- * Uses the contravariance of function parameter types to collapse a union into an intersection
372
- *
373
- * @template Value - Union type to convert
374
- *
375
- * @example
376
- * ```ts
377
- * // UnionToIntersection<{ a: 1 } | { b: 2 }>
378
- * // => { a: 1 } & { b: 2 }
379
- * ```
380
- */
381
- type UnionToIntersection<Value> = (Value extends unknown ? (value: Value) => void : never) extends ((value: infer Item) => void) ? Item : never;
382
- /**
383
- * Converts a union type into an ordered tuple
384
- *
385
- * Repeatedly extracts the {@link LastOfUnion} member and prepends it to the accumulator
386
- *
387
- * @template Value - Union type to convert
388
- * @template Items - Accumulator for the resulting tuple _(internal)_
389
- *
390
- * @example
391
- * ```ts
392
- * // UnionToTuple<'a' | 'b' | 'c'>
393
- * // => ['a', 'b', 'c']
394
- * ```
395
- */
396
- type UnionToTuple<Value, Items extends unknown[] = []> = [Value] extends [never] ? Items : UnionToTuple<Exclude<Value, LastOfUnion<Value>>, [LastOfUnion<Value>, ...Items]>;
397
- /**
398
- * Unwraps a single-element tuple to its inner type
399
- *
400
- * For tuples of length 2–5, returns all {@link TuplePermutations} to allow types in any order. Longer tuples are returned as-is
401
- *
402
- * @template Value - Tuple to potentially unwrap
403
- *
404
- * @example
405
- * ```ts
406
- * // UnwrapSingle<['string']> => 'string'
407
- * // UnwrapSingle<['string', 'number']> => ['string', 'number'] | ['number', 'string']
408
- * ```
409
- */
410
- type UnwrapSingle<Value extends unknown[]> = Value extends [infer Only] ? Only : Value['length'] extends 1 | 2 | 3 | 4 | 5 ? TuplePermutations<Value> : Value;
411
- /**
412
- * The runtime representation of a parsed schema property, used internally during validation
413
- *
414
- * @example
415
- * ```ts
416
- * const parsed: ValidatedProperty = {
417
- * key: 'age',
418
- * required: true,
419
- * types: ['number'],
420
- * validators: { number: [(v) => v > 0] },
421
- * };
422
- * ```
423
- */
424
- type ValidatedProperty = {
425
- /**
426
- * The property name in the schema
427
- */
428
- key: string;
429
- /**
430
- * Whether the property is required
431
- */
432
- required: boolean;
433
- /**
434
- * The allowed types for this property
435
- */
436
- types: ValidatedPropertyType[];
437
- /**
438
- * Custom validators grouped by {@link ValueName}
439
- */
440
- validators: ValidatedPropertyValidators;
441
- };
442
- /**
443
- * A union of valid types for a {@link ValidatedProperty}'s `types` array
444
- *
445
- * Can be a callback _(custom validator)_, a {@link Schematic}, a nested {@link ValidatedProperty}, or a {@link ValueName} string
446
- */
447
- type ValidatedPropertyType = GenericCallback | Schematic<unknown> | ValidatedProperty | ValueName;
448
- /**
449
- * A map of validator functions keyed by {@link ValueName}, used at runtime in {@link ValidatedProperty}
450
- *
451
- * Each key holds an array of validator functions that receive an `unknown` value and return a `boolean`
452
- */
453
- type ValidatedPropertyValidators = { [Key in ValueName]?: Array<(value: unknown) => boolean> };
454
- /**
455
- * Basic value types
456
- */
457
- type ValueName = keyof Values;
458
- /**
459
- * Maps type name strings to their TypeScript equivalents
460
- *
461
- * Used by the type system to resolve {@link ValueName} strings into actual types
462
- *
463
- * @example
464
- * ```ts
465
- * // Values['string'] => string
466
- * // Values['date'] => Date
467
- * // Values['null'] => null
468
- * ```
469
- */
470
- type Values = {
471
- array: unknown[];
472
- bigint: bigint;
473
- boolean: boolean;
474
- date: Date;
475
- function: Function;
476
- null: null;
477
- number: number;
478
- object: object;
479
- string: string;
480
- symbol: symbol;
481
- undefined: undefined;
482
- };
483
- //#endregion
484
- export { Infer, Schema, SchemaProperty, SchematicError, TypedPropertyOptional, TypedPropertyRequired, TypedSchema, ValidatedProperty, ValidatedPropertyType, ValidatedPropertyValidators, ValueName, Values };
package/dist/models.mjs DELETED
@@ -1,13 +0,0 @@
1
- import { ERROR_NAME } from "./constants.mjs";
2
- //#region src/models.ts
3
- /**
4
- * A custom error class for schematic validation failures
5
- */
6
- var SchematicError = class extends Error {
7
- constructor(message) {
8
- super(message);
9
- this.name = ERROR_NAME;
10
- }
11
- };
12
- //#endregion
13
- export { SchematicError };