@regle/core 1.0.1 → 1.0.3

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.
@@ -139,6 +139,36 @@ Unfortunately, `Record<string, never>`, `Record<keyof any, never>` and `Record<n
139
139
  */
140
140
  type EmptyObject = {[emptyObjectSymbol]?: never};
141
141
 
142
+ /**
143
+ Extract all required keys from the given type.
144
+
145
+ This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...
146
+
147
+ @example
148
+ ```
149
+ import type {RequiredKeysOf} from 'type-fest';
150
+
151
+ declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
152
+
153
+ interface User {
154
+ name: string;
155
+ surname: string;
156
+
157
+ luckyNumber?: number;
158
+ }
159
+
160
+ const validator1 = createValidation<User>('name', value => value.length < 25);
161
+ const validator2 = createValidation<User>('surname', value => value.length < 25);
162
+ ```
163
+
164
+ @category Utilities
165
+ */
166
+ type RequiredKeysOf<BaseType extends object> = Exclude<{
167
+ [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
168
+ ? Key
169
+ : never
170
+ }[keyof BaseType], undefined>;
171
+
142
172
  /**
143
173
  Returns a boolean for whether the given type is `never`.
144
174
 
@@ -182,11 +212,381 @@ endIfEqual('abc', '123');
182
212
  */
183
213
  type IsNever$1<T> = [T] extends [never] ? true : false;
184
214
 
215
+ /**
216
+ An if-else-like type that resolves depending on whether the given type is `never`.
217
+
218
+ @see {@link IsNever}
219
+
220
+ @example
221
+ ```
222
+ import type {IfNever} from 'type-fest';
223
+
224
+ type ShouldBeTrue = IfNever<never>;
225
+ //=> true
226
+
227
+ type ShouldBeBar = IfNever<'not never', 'foo', 'bar'>;
228
+ //=> 'bar'
229
+ ```
230
+
231
+ @category Type Guard
232
+ @category Utilities
233
+ */
234
+ type IfNever<T, TypeIfNever = true, TypeIfNotNever = false> = (
235
+ IsNever$1<T> extends true ? TypeIfNever : TypeIfNotNever
236
+ );
237
+
238
+ // Can eventually be replaced with the built-in once this library supports
239
+ // TS5.4+ only. Tracked in https://github.com/sindresorhus/type-fest/issues/848
240
+ type NoInfer<T> = T extends infer U ? U : never;
241
+
242
+ /**
243
+ Returns a boolean for whether the given type is `any`.
244
+
245
+ @link https://stackoverflow.com/a/49928360/1490091
246
+
247
+ Useful in type utilities, such as disallowing `any`s to be passed to a function.
248
+
249
+ @example
250
+ ```
251
+ import type {IsAny} from 'type-fest';
252
+
253
+ const typedObject = {a: 1, b: 2} as const;
254
+ const anyObject: any = {a: 1, b: 2};
255
+
256
+ function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) {
257
+ return obj[key];
258
+ }
259
+
260
+ const typedA = get(typedObject, 'a');
261
+ //=> 1
262
+
263
+ const anyA = get(anyObject, 'a');
264
+ //=> any
265
+ ```
266
+
267
+ @category Type Guard
268
+ @category Utilities
269
+ */
270
+ type IsAny$1<T> = 0 extends 1 & NoInfer<T> ? true : false;
271
+
185
272
  /**
186
273
  Disallows any of the given keys.
187
274
  */
188
275
  type RequireNone<KeysType extends PropertyKey> = Partial<Record<KeysType, never>>;
189
276
 
277
+ /**
278
+ Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
279
+
280
+ @example
281
+ ```
282
+ import type {Simplify} from 'type-fest';
283
+
284
+ type PositionProps = {
285
+ top: number;
286
+ left: number;
287
+ };
288
+
289
+ type SizeProps = {
290
+ width: number;
291
+ height: number;
292
+ };
293
+
294
+ // In your editor, hovering over `Props` will show a flattened object with all the properties.
295
+ type Props = Simplify<PositionProps & SizeProps>;
296
+ ```
297
+
298
+ Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.
299
+
300
+ If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.
301
+
302
+ @example
303
+ ```
304
+ import type {Simplify} from 'type-fest';
305
+
306
+ interface SomeInterface {
307
+ foo: number;
308
+ bar?: string;
309
+ baz: number | undefined;
310
+ }
311
+
312
+ type SomeType = {
313
+ foo: number;
314
+ bar?: string;
315
+ baz: number | undefined;
316
+ };
317
+
318
+ const literal = {foo: 123, bar: 'hello', baz: 456};
319
+ const someType: SomeType = literal;
320
+ const someInterface: SomeInterface = literal;
321
+
322
+ function fn(object: Record<string, unknown>): void {}
323
+
324
+ fn(literal); // Good: literal object type is sealed
325
+ fn(someType); // Good: type is sealed
326
+ fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
327
+ fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
328
+ ```
329
+
330
+ @link https://github.com/microsoft/TypeScript/issues/15300
331
+ @see SimplifyDeep
332
+ @category Object
333
+ */
334
+ type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
335
+
336
+ /**
337
+ Omit any index signatures from the given object type, leaving only explicitly defined properties.
338
+
339
+ This is the counterpart of `PickIndexSignature`.
340
+
341
+ Use-cases:
342
+ - Remove overly permissive signatures from third-party types.
343
+
344
+ This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
345
+
346
+ It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
347
+
348
+ (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
349
+
350
+ ```
351
+ const indexed: Record<string, unknown> = {}; // Allowed
352
+
353
+ const keyed: Record<'foo', unknown> = {}; // Error
354
+ // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
355
+ ```
356
+
357
+ Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another:
358
+
359
+ ```
360
+ type Indexed = {} extends Record<string, unknown>
361
+ ? '✅ `{}` is assignable to `Record<string, unknown>`'
362
+ : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
363
+ // => '✅ `{}` is assignable to `Record<string, unknown>`'
364
+
365
+ type Keyed = {} extends Record<'foo' | 'bar', unknown>
366
+ ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
367
+ : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
368
+ // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
369
+ ```
370
+
371
+ Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`...
372
+
373
+ ```
374
+ import type {OmitIndexSignature} from 'type-fest';
375
+
376
+ type OmitIndexSignature<ObjectType> = {
377
+ [KeyType in keyof ObjectType // Map each key of `ObjectType`...
378
+ ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
379
+ };
380
+ ```
381
+
382
+ ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
383
+
384
+ ```
385
+ import type {OmitIndexSignature} from 'type-fest';
386
+
387
+ type OmitIndexSignature<ObjectType> = {
388
+ [KeyType in keyof ObjectType
389
+ // Is `{}` assignable to `Record<KeyType, unknown>`?
390
+ as {} extends Record<KeyType, unknown>
391
+ ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
392
+ : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
393
+ ]: ObjectType[KeyType];
394
+ };
395
+ ```
396
+
397
+ If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
398
+
399
+ @example
400
+ ```
401
+ import type {OmitIndexSignature} from 'type-fest';
402
+
403
+ interface Example {
404
+ // These index signatures will be removed.
405
+ [x: string]: any
406
+ [x: number]: any
407
+ [x: symbol]: any
408
+ [x: `head-${string}`]: string
409
+ [x: `${string}-tail`]: string
410
+ [x: `head-${string}-tail`]: string
411
+ [x: `${bigint}`]: string
412
+ [x: `embedded-${number}`]: string
413
+
414
+ // These explicitly defined keys will remain.
415
+ foo: 'bar';
416
+ qux?: 'baz';
417
+ }
418
+
419
+ type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
420
+ // => { foo: 'bar'; qux?: 'baz' | undefined; }
421
+ ```
422
+
423
+ @see PickIndexSignature
424
+ @category Object
425
+ */
426
+ type OmitIndexSignature<ObjectType> = {
427
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
428
+ ? never
429
+ : KeyType]: ObjectType[KeyType];
430
+ };
431
+
432
+ /**
433
+ Pick only index signatures from the given object type, leaving out all explicitly defined properties.
434
+
435
+ This is the counterpart of `OmitIndexSignature`.
436
+
437
+ @example
438
+ ```
439
+ import type {PickIndexSignature} from 'type-fest';
440
+
441
+ declare const symbolKey: unique symbol;
442
+
443
+ type Example = {
444
+ // These index signatures will remain.
445
+ [x: string]: unknown;
446
+ [x: number]: unknown;
447
+ [x: symbol]: unknown;
448
+ [x: `head-${string}`]: string;
449
+ [x: `${string}-tail`]: string;
450
+ [x: `head-${string}-tail`]: string;
451
+ [x: `${bigint}`]: string;
452
+ [x: `embedded-${number}`]: string;
453
+
454
+ // These explicitly defined keys will be removed.
455
+ ['kebab-case-key']: string;
456
+ [symbolKey]: string;
457
+ foo: 'bar';
458
+ qux?: 'baz';
459
+ };
460
+
461
+ type ExampleIndexSignature = PickIndexSignature<Example>;
462
+ // {
463
+ // [x: string]: unknown;
464
+ // [x: number]: unknown;
465
+ // [x: symbol]: unknown;
466
+ // [x: `head-${string}`]: string;
467
+ // [x: `${string}-tail`]: string;
468
+ // [x: `head-${string}-tail`]: string;
469
+ // [x: `${bigint}`]: string;
470
+ // [x: `embedded-${number}`]: string;
471
+ // }
472
+ ```
473
+
474
+ @see OmitIndexSignature
475
+ @category Object
476
+ */
477
+ type PickIndexSignature<ObjectType> = {
478
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
479
+ ? KeyType
480
+ : never]: ObjectType[KeyType];
481
+ };
482
+
483
+ // Merges two objects without worrying about index signatures.
484
+ type SimpleMerge<Destination, Source> = {
485
+ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
486
+ } & Source;
487
+
488
+ /**
489
+ Merge two types into a new type. Keys of the second type overrides keys of the first type.
490
+
491
+ @example
492
+ ```
493
+ import type {Merge} from 'type-fest';
494
+
495
+ interface Foo {
496
+ [x: string]: unknown;
497
+ [x: number]: unknown;
498
+ foo: string;
499
+ bar: symbol;
500
+ }
501
+
502
+ type Bar = {
503
+ [x: number]: number;
504
+ [x: symbol]: unknown;
505
+ bar: Date;
506
+ baz: boolean;
507
+ };
508
+
509
+ export type FooBar = Merge<Foo, Bar>;
510
+ // => {
511
+ // [x: string]: unknown;
512
+ // [x: number]: number;
513
+ // [x: symbol]: unknown;
514
+ // foo: string;
515
+ // bar: Date;
516
+ // baz: boolean;
517
+ // }
518
+ ```
519
+
520
+ @category Object
521
+ */
522
+ type Merge<Destination, Source> =
523
+ Simplify<
524
+ SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
525
+ & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
526
+ >;
527
+
528
+ /**
529
+ An if-else-like type that resolves depending on whether the given type is `any`.
530
+
531
+ @see {@link IsAny}
532
+
533
+ @example
534
+ ```
535
+ import type {IfAny} from 'type-fest';
536
+
537
+ type ShouldBeTrue = IfAny<any>;
538
+ //=> true
539
+
540
+ type ShouldBeBar = IfAny<'not any', 'foo', 'bar'>;
541
+ //=> 'bar'
542
+ ```
543
+
544
+ @category Type Guard
545
+ @category Utilities
546
+ */
547
+ type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = (
548
+ IsAny$1<T> extends true ? TypeIfAny : TypeIfNotAny
549
+ );
550
+
551
+ /**
552
+ Extract all optional keys from the given type.
553
+
554
+ This is useful when you want to create a new type that contains different type values for the optional keys only.
555
+
556
+ @example
557
+ ```
558
+ import type {OptionalKeysOf, Except} from 'type-fest';
559
+
560
+ interface User {
561
+ name: string;
562
+ surname: string;
563
+
564
+ luckyNumber?: number;
565
+ }
566
+
567
+ const REMOVE_FIELD = Symbol('remove field symbol');
568
+ type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
569
+ [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
570
+ };
571
+
572
+ const update1: UpdateOperation<User> = {
573
+ name: 'Alice'
574
+ };
575
+
576
+ const update2: UpdateOperation<User> = {
577
+ name: 'Bob',
578
+ luckyNumber: REMOVE_FIELD
579
+ };
580
+ ```
581
+
582
+ @category Utilities
583
+ */
584
+ type OptionalKeysOf<BaseType extends object> = Exclude<{
585
+ [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
586
+ ? never
587
+ : Key
588
+ }[keyof BaseType], undefined>;
589
+
190
590
  /**
191
591
  Matches any primitive, `void`, `Date`, or `RegExp` value.
192
592
  */
@@ -209,6 +609,72 @@ type HasMultipleCallSignatures<T extends (...arguments_: any[]) => unknown> =
209
609
  : true
210
610
  : false;
211
611
 
612
+ /**
613
+ Merges user specified options with default options.
614
+
615
+ @example
616
+ ```
617
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
618
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
619
+ type SpecifiedOptions = {leavesOnly: true};
620
+
621
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
622
+ //=> {maxRecursionDepth: 10; leavesOnly: true}
623
+ ```
624
+
625
+ @example
626
+ ```
627
+ // Complains if default values are not provided for optional options
628
+
629
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
630
+ type DefaultPathsOptions = {maxRecursionDepth: 10};
631
+ type SpecifiedOptions = {};
632
+
633
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
634
+ // ~~~~~~~~~~~~~~~~~~~
635
+ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
636
+ ```
637
+
638
+ @example
639
+ ```
640
+ // Complains if an option's default type does not conform to the expected type
641
+
642
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
643
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
644
+ type SpecifiedOptions = {};
645
+
646
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
647
+ // ~~~~~~~~~~~~~~~~~~~
648
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
649
+ ```
650
+
651
+ @example
652
+ ```
653
+ // Complains if an option's specified type does not conform to the expected type
654
+
655
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
656
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
657
+ type SpecifiedOptions = {leavesOnly: 'yes'};
658
+
659
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
660
+ // ~~~~~~~~~~~~~~~~
661
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
662
+ ```
663
+ */
664
+ type ApplyDefaultOptions<
665
+ Options extends object,
666
+ Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
667
+ SpecifiedOptions extends Options,
668
+ > =
669
+ IfAny<SpecifiedOptions, Defaults,
670
+ IfNever<SpecifiedOptions, Defaults,
671
+ Simplify<Merge<Defaults, {
672
+ [Key in keyof SpecifiedOptions
673
+ as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key
674
+ ]: SpecifiedOptions[Key]
675
+ }> & Required<Options>> // `& Required<Options>` ensures that `ApplyDefaultOptions<SomeOption, ...>` is always assignable to `Required<SomeOption>`
676
+ >>;
677
+
212
678
  /**
213
679
  Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.
214
680
 
@@ -317,6 +783,11 @@ type PartialDeepOptions = {
317
783
  readonly allowUndefinedInNonTupleArrays?: boolean;
318
784
  };
319
785
 
786
+ type DefaultPartialDeepOptions = {
787
+ recurseIntoArrays: false;
788
+ allowUndefinedInNonTupleArrays: true;
789
+ };
790
+
320
791
  /**
321
792
  Create a type from another type with all keys and nested keys set to optional.
322
793
 
@@ -366,7 +837,10 @@ const partialSettings: PartialDeep<Settings, {recurseIntoArrays: true}> = {
366
837
  @category Set
367
838
  @category Map
368
839
  */
369
- type PartialDeep<T, Options extends PartialDeepOptions = {}> = T extends BuiltIns | (((...arguments_: any[]) => unknown)) | (new (...arguments_: any[]) => unknown)
840
+ type PartialDeep<T, Options extends PartialDeepOptions = {}> =
841
+ _PartialDeep<T, ApplyDefaultOptions<PartialDeepOptions, DefaultPartialDeepOptions, Options>>;
842
+
843
+ type _PartialDeep<T, Options extends Required<PartialDeepOptions>> = T extends BuiltIns | (((...arguments_: any[]) => unknown)) | (new (...arguments_: any[]) => unknown)
370
844
  ? T
371
845
  : T extends Map<infer KeyType, infer ValueType>
372
846
  ? PartialMapDeep<KeyType, ValueType, Options>
@@ -381,8 +855,8 @@ type PartialDeep<T, Options extends PartialDeepOptions = {}> = T extends BuiltIn
381
855
  ? Options['recurseIntoArrays'] extends true
382
856
  ? ItemType[] extends T // Test for arrays (non-tuples) specifically
383
857
  ? readonly ItemType[] extends T // Differentiate readonly and mutable arrays
384
- ? ReadonlyArray<PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
385
- : Array<PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
858
+ ? ReadonlyArray<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
859
+ : Array<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
386
860
  : PartialObjectDeep<T, Options> // Tuples behave properly
387
861
  : T // If they don't opt into array testing, just use the original type
388
862
  : PartialObjectDeep<T, Options>
@@ -391,28 +865,28 @@ type PartialDeep<T, Options extends PartialDeepOptions = {}> = T extends BuiltIn
391
865
  /**
392
866
  Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
393
867
  */
394
- type PartialMapDeep<KeyType, ValueType, Options extends PartialDeepOptions> = {} & Map<PartialDeep<KeyType, Options>, PartialDeep<ValueType, Options>>;
868
+ type PartialMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & Map<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
395
869
 
396
870
  /**
397
871
  Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
398
872
  */
399
- type PartialSetDeep<T, Options extends PartialDeepOptions> = {} & Set<PartialDeep<T, Options>>;
873
+ type PartialSetDeep<T, Options extends Required<PartialDeepOptions>> = {} & Set<_PartialDeep<T, Options>>;
400
874
 
401
875
  /**
402
876
  Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
403
877
  */
404
- type PartialReadonlyMapDeep<KeyType, ValueType, Options extends PartialDeepOptions> = {} & ReadonlyMap<PartialDeep<KeyType, Options>, PartialDeep<ValueType, Options>>;
878
+ type PartialReadonlyMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & ReadonlyMap<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
405
879
 
406
880
  /**
407
881
  Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
408
882
  */
409
- type PartialReadonlySetDeep<T, Options extends PartialDeepOptions> = {} & ReadonlySet<PartialDeep<T, Options>>;
883
+ type PartialReadonlySetDeep<T, Options extends Required<PartialDeepOptions>> = {} & ReadonlySet<_PartialDeep<T, Options>>;
410
884
 
411
885
  /**
412
886
  Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
413
887
  */
414
- type PartialObjectDeep<ObjectType extends object, Options extends PartialDeepOptions> = {
415
- [KeyType in keyof ObjectType]?: PartialDeep<ObjectType[KeyType], Options>
888
+ type PartialObjectDeep<ObjectType extends object, Options extends Required<PartialDeepOptions>> = {
889
+ [KeyType in keyof ObjectType]?: _PartialDeep<ObjectType[KeyType], Options>
416
890
  };
417
891
 
418
892
  type ExcludeUndefined<T> = Exclude<T, undefined>;
@@ -663,6 +1137,10 @@ type ResetOptions<TState extends unknown> = RequireOneOrNone<{
663
1137
  * Reset validation status and reset form state to the given state
664
1138
  */
665
1139
  toState?: TState | (() => TState);
1140
+ /**
1141
+ * Clears the $externalErrors state back to an empty object.
1142
+ */
1143
+ clearExternalErrors?: boolean;
666
1144
  }, 'toInitialState' | 'toState'>;
667
1145
 
668
1146
  interface useRegleFn<TCustomRules extends Partial<AllRulesDeclarations>, TShortcuts extends RegleShortcutDefinition<any> = never, TAdditionalReturnProperties extends Record<string, any> = {}, TAdditionalOptions extends Record<string, any> = {}> {
@@ -1184,6 +1662,7 @@ type EnumLike = {
1184
1662
  [k: string]: string | number;
1185
1663
  [nu: number]: string;
1186
1664
  };
1665
+ type UnwrapMaybeRef<T extends MaybeRef<any> | DeepReactiveState<any>> = T extends Ref<any> ? UnwrapRef<T> : UnwrapNestedRefs<T>;
1187
1666
 
1188
1667
  type CreateFn<T extends any[]> = (...args: T) => any;
1189
1668
  /**
@@ -1221,7 +1700,7 @@ declare enum InternalRuleType {
1221
1700
  /**
1222
1701
  * Returned typed of rules created with `createRule`
1223
1702
  * */
1224
- interface RegleRuleDefinition<TValue extends any = any, TParams extends any[] = [], TAsync extends boolean = boolean, TMetaData extends RegleRuleMetadataDefinition = RegleRuleMetadataDefinition, TFilteredValue extends any = TValue extends Date & File & infer M ? M : TValue> extends RegleInternalRuleDefs<TFilteredValue, TParams, TAsync, TMetaData> {
1703
+ interface RegleRuleDefinition<TValue extends any = unknown, TParams extends any[] = [], TAsync extends boolean = boolean, TMetaData extends RegleRuleMetadataDefinition = RegleRuleMetadataDefinition, TFilteredValue extends any = TValue extends Date & File & infer M ? M : TValue> extends RegleInternalRuleDefs<TFilteredValue, TParams, TAsync, TMetaData> {
1225
1704
  validator: RegleRuleDefinitionProcessor<TFilteredValue, TParams, TAsync extends false ? TMetaData : Promise<TMetaData>>;
1226
1705
  message: (metadata: PossibleRegleRuleMetadataConsumer<TFilteredValue>) => string | string[];
1227
1706
  active: (metadata: PossibleRegleRuleMetadataConsumer<TFilteredValue>) => boolean;
@@ -1232,8 +1711,8 @@ interface RegleRuleDefinition<TValue extends any = any, TParams extends any[] =
1232
1711
  /**
1233
1712
  * Rules with params created with `createRules` are callable while being customizable
1234
1713
  */
1235
- interface RegleRuleWithParamsDefinition<TValue extends any = any, TParams extends any[] = [], TAsync extends boolean = false, TMetadata extends RegleRuleMetadataDefinition = boolean> extends RegleRuleCore<TValue, TParams, TAsync, TMetadata>, RegleInternalRuleDefs<TValue, TParams, TAsync, TMetadata> {
1236
- (...params: RegleUniversalParams<TParams>): RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>;
1714
+ interface RegleRuleWithParamsDefinition<TValue extends any = any, TParams extends any[] = [], TAsync extends boolean = false, TMetadata extends RegleRuleMetadataDefinition = boolean, TFilteredValue extends any = TValue extends Date & File & infer M ? M : TValue> extends RegleRuleCore<TFilteredValue, TParams, TAsync, TMetadata>, RegleInternalRuleDefs<TFilteredValue, TParams, TAsync, TMetadata> {
1715
+ (...params: RegleUniversalParams<TParams>): RegleRuleDefinition<TFilteredValue, TParams, TAsync, TMetadata>;
1237
1716
  }
1238
1717
  type RegleRuleMetadataExtended = {
1239
1718
  $valid: boolean;
@@ -1259,7 +1738,7 @@ type DefaultMetadataProperties = DefaultMetadataPropertiesCommon & {
1259
1738
  type RegleRuleMetadataConsumer<TValue extends any, TParams extends any[] = never, TMetadata extends RegleRuleMetadataDefinition = boolean> = {
1260
1739
  $value: Maybe<TValue>;
1261
1740
  } & DefaultMetadataProperties & (TParams extends never ? {} : {
1262
- $params: TParams;
1741
+ $params: [...TParams];
1263
1742
  }) & (Exclude<TMetadata, boolean> extends RegleRuleMetadataExtended ? TMetadata extends boolean ? Partial<Omit<Exclude<TMetadata, boolean>, '$valid'>> : Omit<Exclude<TMetadata, boolean>, '$valid'> : {});
1264
1743
  /**
1265
1744
  * Will be used to consumme metadata on related helpers and rule status
@@ -1280,7 +1759,7 @@ type RegleRuleRaw<TValue extends any = any, TParams extends any[] = [], TAsync e
1280
1759
  */
1281
1760
  type InferRegleRule<TValue extends any = any, TParams extends any[] = [], TAsync extends boolean = false, TMetaData extends RegleRuleMetadataDefinition = boolean> = [TParams] extends [[]] ? RegleRuleDefinition<TValue, TParams, TAsync, TMetaData> : RegleRuleWithParamsDefinition<TValue, TParams, TAsync, TMetaData>;
1282
1761
  type RegleRuleDefinitionProcessor<TValue extends any = any, TParams extends any[] = [], TReturn = any> = (value: Maybe<TValue>, ...params: TParams) => TReturn;
1283
- type RegleRuleDefinitionWithMetadataProcessor<TValue extends any, TMetadata extends RegleRuleMetadataConsumer<TValue, any>, TReturn = any> = ((metadata: TMetadata) => TReturn) | TReturn;
1762
+ type RegleRuleDefinitionWithMetadataProcessor<TValue extends any, TMetadata extends RegleRuleMetadataConsumer<TValue, any[]>, TReturn = any> = ((metadata: TMetadata) => TReturn) | TReturn;
1284
1763
  type RegleCollectionRuleDefinition<TValue = any[], TCustomRules extends Partial<AllRulesDeclarations> = Partial<AllRulesDeclarations>> = (RegleRuleDecl<NonNullable<TValue>, TCustomRules> & {
1285
1764
  $each: MaybeGetter<RegleFormPropertyType<ArrayElement<NonNullable<TValue>>, TCustomRules>, ArrayElement<TValue>>;
1286
1765
  }) | ({
@@ -1452,16 +1931,16 @@ type InlineRuleDeclaration<TValue extends any = any, TParams extends any[] = any
1452
1931
  * */
1453
1932
  type FormRuleDeclaration<TValue extends any, TParams extends any[], TReturn extends RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition> = RegleRuleMetadataDefinition | Promise<RegleRuleMetadataDefinition>, TMetadata extends RegleRuleMetadataDefinition = TReturn extends Promise<infer M> ? M : TReturn, TAsync extends boolean = boolean> = InlineRuleDeclaration<TValue, TParams, TReturn> | RegleRuleDefinition<TValue, TParams, TAsync, TMetadata>;
1454
1933
 
1455
- type RegleErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = {
1456
- readonly [K in keyof JoinDiscriminatedUnions<UnwrapNestedRefs<TState>>]: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapNestedRefs<TState>>[K]>;
1934
+ type RegleErrorTree<TState = MaybeRef<Record<string, any> | any[]>, TRules extends ReglePartialRuleTree<any> = {}, TSchemaMode extends boolean = false> = {
1935
+ readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], false, K extends keyof TRules ? TRules[K] : {}, TSchemaMode>;
1457
1936
  };
1458
1937
  type RegleExternalErrorTree<TState = MaybeRef<Record<string, any> | any[]>> = {
1459
- readonly [K in keyof JoinDiscriminatedUnions<UnwrapNestedRefs<TState>>]?: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapNestedRefs<TState>>[K], true>;
1938
+ readonly [K in keyof JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>]?: RegleValidationErrors<JoinDiscriminatedUnions<UnwrapMaybeRef<TState>>[K], true>;
1460
1939
  };
1461
- type RegleValidationErrors<TState extends Record<string, any> | any[] | unknown = never, TExternal extends boolean = false> = NonNullable<TState> extends Array<infer U extends Record<string, any>> ? TExternal extends false ? RegleCollectionErrors<U> : RegleExternalCollectionErrors<U> : NonNullable<TState> extends Date | File ? string[] : NonNullable<TState> extends Record<string, any> ? TExternal extends false ? RegleErrorTree<TState> : RegleExternalErrorTree<TState> : string[];
1462
- type RegleCollectionErrors<TState extends Record<string, any>> = {
1940
+ type RegleValidationErrors<TState extends Record<string, any> | any[] | unknown = never, TExternal extends boolean = false, TRule extends RegleCollectionRuleDecl | RegleRuleDecl | ReglePartialRuleTree<any> | undefined = {}, TSchemaMode extends boolean = false> = NonNullable<TState> extends Array<infer U extends Record<string, any>> ? ExtendOnlyRealRecord<U> extends true ? TExternal extends false ? TRule extends RegleCollectionRuleDefinition<any, any> ? ExtractFromGetter<TRule['$each']> extends ReglePartialRuleTree<any> ? RegleCollectionErrors<U, ExtractFromGetter<TRule['$each']>, TSchemaMode> : string[] : TSchemaMode extends true ? RegleExternalCollectionErrors<U> : string[] : RegleExternalCollectionErrors<U> : string[] : NonNullable<TState> extends Date | File ? string[] : NonNullable<TState> extends Record<string, any> ? TExternal extends false ? TRule extends ReglePartialRuleTree<any> ? RegleErrorTree<TState, TRule, TSchemaMode> : RegleErrorTree<TState, {}, TSchemaMode> : RegleExternalErrorTree<TState> : string[];
1941
+ type RegleCollectionErrors<TState extends Record<string, any>, TRule extends ReglePartialRuleTree<any> = {}, TSchemaMode extends boolean = false> = {
1463
1942
  readonly $self: string[];
1464
- readonly $each: RegleValidationErrors<TState>[];
1943
+ readonly $each: RegleValidationErrors<TState, false, TRule, TSchemaMode>[];
1465
1944
  };
1466
1945
  type RegleExternalCollectionErrors<TState extends Record<string, any>> = {
1467
1946
  readonly $self?: string[];
@@ -1523,8 +2002,8 @@ interface SuperCompatibleRegleStatus extends SuperCompatibleRegleCommonStatus {
1523
2002
  $fields: {
1524
2003
  [x: string]: unknown;
1525
2004
  };
1526
- readonly $errors: Record<string, RegleValidationErrors<any>>;
1527
- readonly $silentErrors: Record<string, RegleValidationErrors<any>>;
2005
+ readonly $errors: Record<string, RegleValidationErrors<any, false, any, any>>;
2006
+ readonly $silentErrors: Record<string, RegleValidationErrors<any, false, any, any>>;
1528
2007
  $extractDirtyFields: (filterNullishValues?: boolean) => Record<string, any>;
1529
2008
  $validate?: () => Promise<SuperCompatibleRegleResult>;
1530
2009
  }
@@ -1567,9 +2046,9 @@ type RegleStatus<TState extends Record<string, any> | undefined = Record<string,
1567
2046
  * Collection of all the error messages, collected for all children properties and nested forms.
1568
2047
  *
1569
2048
  * Only contains errors from properties where $dirty equals true. */
1570
- readonly $errors: RegleErrorTree<TState>;
2049
+ readonly $errors: RegleErrorTree<TState, TRules>;
1571
2050
  /** Collection of all the error messages, collected for all children properties. */
1572
- readonly $silentErrors: RegleErrorTree<TState>;
2051
+ readonly $silentErrors: RegleErrorTree<TState, TRules>;
1573
2052
  /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */
1574
2053
  $extractDirtyFields: (filterNullishValues?: boolean) => PartialDeep<TState>;
1575
2054
  /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */
@@ -1593,7 +2072,7 @@ interface $InternalRegleStatus extends $InternalRegleCommonStatus {
1593
2072
  /**
1594
2073
  * @public
1595
2074
  */
1596
- type InferRegleStatusType<TRule extends RegleCollectionRuleDecl | RegleRuleDecl | ReglePartialRuleTree<any>, TState extends Record<PropertyKey, any> = any, TKey extends PropertyKey = string, TShortcuts extends RegleShortcutDefinition = {}> = NonNullable<TState[TKey]> extends Array<Record<string, any> | any> ? TRule extends RegleCollectionRuleDefinition<any, any> ? ExtractFromGetter<TRule['$each']> extends ReglePartialRuleTree<any> ? RegleCollectionStatus<TState[TKey], ExtractFromGetter<TRule['$each']>, TRule, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts> : RegleCollectionStatus<TState[TKey], {}, TRule, TShortcuts> : TRule extends ReglePartialRuleTree<any> ? NonNullable<TState[TKey]> extends Array<any> ? RegleCommonStatus<TState[TKey]> : NonNullable<TState[TKey]> extends Date | File ? RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Record<PropertyKey, any> ? RegleStatus<TState[TKey], TRule, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Date | File ? RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Record<PropertyKey, any> ? RegleStatus<TState[TKey], ReglePartialRuleTree<TState[TKey]>, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts>;
2075
+ type InferRegleStatusType<TRule extends RegleCollectionRuleDecl | RegleRuleDecl | ReglePartialRuleTree<any>, TState extends Record<PropertyKey, any> = any, TKey extends PropertyKey = string, TShortcuts extends RegleShortcutDefinition = {}> = NonNullable<TState[TKey]> extends Array<Record<string, any> | any> ? TRule extends RegleCollectionRuleDefinition<any, any> ? ExtractFromGetter<TRule['$each']> extends ReglePartialRuleTree<any> ? RegleCollectionStatus<TState[TKey], ExtractFromGetter<TRule['$each']>, TRule, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts> : TRule extends ReglePartialRuleTree<any> ? NonNullable<TState[TKey]> extends Array<any> ? RegleCommonStatus<TState[TKey]> : NonNullable<TState[TKey]> extends Date | File ? RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Record<PropertyKey, any> ? RegleStatus<TState[TKey], TRule, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Date | File ? RegleFieldStatus<TState[TKey], TRule, TShortcuts> : NonNullable<TState[TKey]> extends Record<PropertyKey, any> ? RegleStatus<TState[TKey], ReglePartialRuleTree<TState[TKey]>, TShortcuts> : RegleFieldStatus<TState[TKey], TRule, TShortcuts>;
1597
2076
  /**
1598
2077
  * @internal
1599
2078
  * @reference {@link InferRegleStatusType}
@@ -1686,7 +2165,7 @@ interface RegleCommonStatus<TValue = any> {
1686
2165
  */
1687
2166
  $reset(): void;
1688
2167
  $reset(options?: ResetOptions<TValue>): void;
1689
- /** Clears the $externalResults state back to an empty object. */
2168
+ /** Clears the $externalErrors state back to an empty object. */
1690
2169
  $clearExternalErrors(): void;
1691
2170
  }
1692
2171
  interface $InternalRegleCommonStatus extends Omit<RegleCommonStatus, '$touch' | '$reset'> {
@@ -1724,7 +2203,7 @@ type RegleRuleStatus<TValue = any, TParams extends any[] = any[], TMetadata exte
1724
2203
  } & ([TParams] extends [never[]] ? {} : [unknown[]] extends [TParams] ? {
1725
2204
  readonly $params?: any[];
1726
2205
  } : {
1727
- readonly $params: TParams;
2206
+ readonly $params: [...TParams];
1728
2207
  });
1729
2208
  /**
1730
2209
  * @internal
@@ -1769,9 +2248,9 @@ type RegleCollectionStatus<TState extends any[] = any[], TRules extends ReglePar
1769
2248
  /** Collection of all the error messages, collected for all children properties and nested forms.
1770
2249
  *
1771
2250
  * Only contains errors from properties where $dirty equals true. */
1772
- readonly $errors: RegleCollectionErrors<TState>;
2251
+ readonly $errors: RegleCollectionErrors<TState, TRules>;
1773
2252
  /** Collection of all the error messages, collected for all children properties and nested forms. */
1774
- readonly $silentErrors: RegleCollectionErrors<TState>;
2253
+ readonly $silentErrors: RegleCollectionErrors<TState, TRules>;
1775
2254
  /** Will return a copy of your state with only the fields that are dirty. By default it will filter out nullish values or objects, but you can override it with the first parameter $extractDirtyFields(false). */
1776
2255
  $extractDirtyFields: (filterNullishValues?: boolean) => PartialDeep<TState>;
1777
2256
  /** Sets all properties as dirty, triggering all rules. It returns a promise that will either resolve to false or a type safe copy of your form state. Values that had the required rule will be transformed into a non-nullable value (type only). */