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