runcheck 1.12.0 → 1.14.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.
@@ -1,8 +1,19 @@
1
1
  import { StandardSchemaV1 } from '@standard-schema/spec';
2
2
 
3
3
  /**
4
- * If the schema key value is undefined uses a value from the fallback key as a safe value
5
- * Can be used to rename keys from input
4
+ * Creates a type that uses a fallback key when the primary key is undefined.
5
+ * Can be used to rename keys from input or provide alternative key names.
6
+ * @param fallbackKey - The alternative key to use when the primary key is undefined
7
+ * @param type - The type to validate the value against
8
+ * @returns A runcheck type that supports fallback key lookup
9
+ * @example
10
+ * ```typescript
11
+ * const userSchema = rc_object({
12
+ * name: rc_get_from_key_as_fallback('username', rc_string)
13
+ * })
14
+ * // Will look for 'name' first, then 'username' if 'name' is undefined
15
+ * const result = userSchema.parse({ username: 'john' }) // valid
16
+ * ```
6
17
  */
7
18
  declare function rc_get_from_key_as_fallback<T extends RcType<any>>(fallbackKey: string, type: T): RcType<RcInferType<T>>;
8
19
  type RcObject = {
@@ -25,23 +36,137 @@ type Flatten<T> = Identity<{
25
36
  }>;
26
37
  type ObjOptions = {
27
38
  normalizeKeysFrom?: 'snake_case';
39
+ /** excess keys are not removed if extends is true */
40
+ extends?: boolean;
28
41
  };
29
- declare function rc_object<T extends RcObject>(shape: T, { normalizeKeysFrom }?: ObjOptions): RcObjTypeReturn<T>;
30
- declare function rc_obj_extends<T extends RcObject>(shape: T, options?: ObjOptions): RcObjTypeReturn<T>;
42
+ /**
43
+ * Creates an object type validator with specified shape and options.
44
+ * @param shape - The object shape defining the expected properties and their types
45
+ * @param options - Configuration options for the object validator
46
+ * @param options.normalizeKeysFrom - If 'snake_case', automatically converts camelCase keys to snake_case for lookup
47
+ * @param options.extends - If true, allows excess properties in the input object
48
+ * @returns A runcheck type that validates objects with the specified shape
49
+ * @example
50
+ * ```typescript
51
+ * const userSchema = rc_object({
52
+ * name: rc_string,
53
+ * age: rc_number,
54
+ * email: rc_string.optional()
55
+ * })
56
+ * const result = userSchema.parse({ name: 'John', age: 30 }) // valid
57
+ * ```
58
+ */
59
+ declare function rc_object<T extends RcObject>(shape: T, { normalizeKeysFrom, extends: extendsObj }?: ObjOptions): RcObjTypeReturn<T>;
60
+ type ExtendsOptions = Omit<ObjOptions, 'extends'>;
61
+ /**
62
+ * Creates an object type that extends the input with additional properties.
63
+ * Unlike strict objects, this allows excess properties from the input to be preserved.
64
+ * @param shapeOrSchema - Either an object shape or an existing object type
65
+ * @param options - Configuration options (excluding 'extends' which is always true)
66
+ * @returns A runcheck type that validates and extends objects
67
+ * @example
68
+ * ```typescript
69
+ * const baseSchema = rc_obj_extends({
70
+ * name: rc_string
71
+ * })
72
+ * // Input: { name: 'John', extra: 'data' }
73
+ * // Output: { name: 'John', extra: 'data' } (preserves extra properties)
74
+ * ```
75
+ */
76
+ declare function rc_obj_extends<T extends RcObject>(shape: T, options?: ExtendsOptions): RcObjTypeReturn<T>;
77
+ declare function rc_obj_extends<T extends Record<string, any>>(schema: RcType<T>, options?: ExtendsOptions): RcType<T>;
78
+ /**
79
+ * Extracts the object shape from an object type for inspection or manipulation.
80
+ * @param type - The object type to extract the shape from
81
+ * @returns The object shape containing the property types
82
+ * @throws Error if the type is not an object type
83
+ * @example
84
+ * ```typescript
85
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
86
+ * const shape = rc_get_obj_shape(userSchema)
87
+ * // shape = { name: RcType<string>, age: RcType<number> }
88
+ * ```
89
+ */
31
90
  declare function rc_get_obj_shape<T extends Record<string, any>>(type: RcType<T>): {
32
91
  [K in keyof T]: RcType<T[K]>;
33
92
  };
34
- /** return an error if the obj has more keys than the expected type */
93
+ /**
94
+ * Creates a strict object type that rejects input with excess properties.
95
+ * @param shape - The object shape defining the expected properties and their types
96
+ * @param options - Configuration options for the object validator
97
+ * @returns A runcheck type that validates objects strictly (no excess properties allowed)
98
+ * @example
99
+ * ```typescript
100
+ * const strictUser = rc_obj_strict({
101
+ * name: rc_string,
102
+ * age: rc_number
103
+ * })
104
+ * const result = strictUser.parse({ name: 'John', age: 30 }) // valid
105
+ * const result2 = strictUser.parse({ name: 'John', age: 30, extra: 'data' }) // invalid
106
+ * ```
107
+ */
35
108
  declare function rc_obj_strict<T extends RcObject>(shape: T, options?: ObjOptions): RcObjTypeReturn<T>;
109
+ /**
110
+ * Enables strict object validation for a type, rejecting excess properties.
111
+ * @param type - The type to make strict
112
+ * @param options - Configuration options
113
+ * @param options.nonRecursive - If true, only affects the immediate object type, not nested objects
114
+ * @returns The type with strict object validation enabled
115
+ * @example
116
+ * ```typescript
117
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
118
+ * const strictUser = rc_enable_obj_strict(userSchema)
119
+ * // Now rejects objects with excess properties
120
+ * ```
121
+ */
36
122
  declare function rc_enable_obj_strict<T extends RcType<any>>(type: T, { nonRecursive, }?: {
37
123
  nonRecursive?: boolean;
38
124
  }): T;
39
125
  type AnyObj = Record<string, unknown>;
40
126
  type Extends<T extends AnyObj, W extends AnyObj> = Omit<T, keyof W> & W;
127
+ /**
128
+ * Merges multiple object types into a single object type.
129
+ * Later objects override properties from earlier objects.
130
+ * @param objs - The object types to merge (2-4 objects supported)
131
+ * @returns A runcheck type representing the merged object
132
+ * @example
133
+ * ```typescript
134
+ * const base = rc_object({ name: rc_string, age: rc_number })
135
+ * const extended = rc_object({ email: rc_string, age: rc_string }) // age overrides
136
+ * const merged = rc_obj_merge(base, extended)
137
+ * // Result: { name: string, age: string, email: string }
138
+ * ```
139
+ */
41
140
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj>(...objs: [RcType<A>, RcType<B>]): RcType<Extends<A, B>>;
42
141
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj, C extends AnyObj>(...objs: [RcType<A>, RcType<B>, RcType<C>]): RcType<Extends<Extends<A, B>, C>>;
43
142
  declare function rc_obj_merge<A extends AnyObj, B extends AnyObj, C extends AnyObj, D extends AnyObj>(...objs: [RcType<A>, RcType<B>, RcType<C>, RcType<D>]): RcType<Extends<Extends<Extends<A, B>, C>, D>>;
143
+ /**
144
+ * Creates a new object type with only the specified properties from the original.
145
+ * @param obj - The object type to pick properties from
146
+ * @param keys - The keys to pick from the object
147
+ * @returns A runcheck type containing only the picked properties
148
+ * @throws Error if the input is not an object type
149
+ * @example
150
+ * ```typescript
151
+ * const userSchema = rc_object({ name: rc_string, age: rc_number, email: rc_string })
152
+ * const nameAndAge = rc_obj_pick(userSchema, ['name', 'age'])
153
+ * // Result: { name: string, age: number }
154
+ * ```
155
+ */
44
156
  declare function rc_obj_pick<O extends AnyObj, K extends keyof O>(obj: RcType<O>, keys: K[]): RcType<Pick<O, K>>;
157
+ /**
158
+ * Creates a new object type without the specified properties from the original.
159
+ * @param obj - The object type to omit properties from
160
+ * @param keys - The keys to omit from the object
161
+ * @returns A runcheck type without the omitted properties
162
+ * @throws Error if the input is not an object type
163
+ * @example
164
+ * ```typescript
165
+ * const userSchema = rc_object({ name: rc_string, age: rc_number, email: rc_string })
166
+ * const withoutEmail = rc_obj_omit(userSchema, ['email'])
167
+ * // Result: { name: string, age: number }
168
+ * ```
169
+ */
45
170
  declare function rc_obj_omit<O extends AnyObj, K extends keyof O>(obj: RcType<O>, keys: K[]): RcType<Omit<O, K>>;
46
171
  type ExpectedSchema<T> = (t: T) => T;
47
172
  type RcTypeWithSchemaEqualTo<T> = {
@@ -71,16 +196,88 @@ type StrictTypeToRcType<T> = [
71
196
  type StrictTypeToRcTypeBase<T extends Record<string, any>> = {
72
197
  [K in keyof T]-?: StrictTypeToRcType<T[K]>;
73
198
  };
199
+ /**
200
+ * Creates a type-safe object builder that enforces the structure matches a TypeScript type.
201
+ * Useful for creating schemas that must conform to existing TypeScript interfaces.
202
+ * @returns A builder function that takes a schema matching the specified TypeScript type
203
+ * @example
204
+ * ```typescript
205
+ * interface User {
206
+ * name: string
207
+ * age: number
208
+ * email?: string
209
+ * }
210
+ *
211
+ * const userBuilder = rc_obj_builder<User>()
212
+ * const userSchema = userBuilder({
213
+ * name: rc_string,
214
+ * age: rc_number,
215
+ * email: ['optional', rc_string]
216
+ * })
217
+ * ```
218
+ */
74
219
  declare function rc_obj_builder<T extends Record<string, any>>(): <S extends StrictTypeToRcTypeBase<T>>(schema: { [K in keyof S]: K extends keyof T ? S[K] : never; }, options?: ObjOptions) => RcType<T>;
75
220
 
221
+ /**
222
+ * Creates a discriminated union type validator.
223
+ * Uses a discriminator key to determine which schema to validate against.
224
+ * @param discriminatorKey - The property name used to discriminate between union members
225
+ * @param types - An object mapping discriminator values to their corresponding schemas
226
+ * @returns A runcheck type that validates discriminated union objects
227
+ * @example
228
+ * ```typescript
229
+ * const shapeSchema = rc_discriminated_union('type', {
230
+ * circle: { radius: rc_number },
231
+ * rectangle: { width: rc_number, height: rc_number }
232
+ * })
233
+ *
234
+ * const result1 = shapeSchema.parse({ type: 'circle', radius: 5 }) // valid
235
+ * const result2 = shapeSchema.parse({ type: 'rectangle', width: 10, height: 20 }) // valid
236
+ * const result3 = shapeSchema.parse({ type: 'triangle', sides: 3 }) // invalid - unknown discriminator
237
+ * ```
238
+ */
76
239
  declare function rc_discriminated_union<K extends string, T extends Record<string, RcObject | RcBase<any, any>>>(discriminatorKey: K, types: T): RcType<Prettify<{
77
240
  [P in keyof T]: {
78
241
  [Q in K]: P;
79
242
  } & (T[P] extends RcType<infer U> ? U : T[P] extends RcObject ? TypeOfObjectType<T[P]> : never);
80
243
  }[keyof T]>>;
81
244
  type OmitDiscriminator<K, D extends Record<string, unknown>> = D extends any ? Omit<D, K & string> : never;
245
+ /**
246
+ * Creates a type-safe discriminated union builder that enforces the structure matches a TypeScript type.
247
+ * @param discriminatorKey - The property name used to discriminate between union members
248
+ * @returns A builder function that takes a schema mapping matching the specified TypeScript discriminated union
249
+ * @example
250
+ * ```typescript
251
+ * type Shape =
252
+ * | { type: 'circle', radius: number }
253
+ * | { type: 'rectangle', width: number, height: number }
254
+ *
255
+ * const shapeBuilder = rc_discriminated_union_builder<Shape, 'type'>('type')
256
+ * const shapeSchema = shapeBuilder({
257
+ * circle: { radius: rc_number },
258
+ * rectangle: { width: rc_number, height: rc_number }
259
+ * })
260
+ * ```
261
+ */
82
262
  declare function rc_discriminated_union_builder<D extends Record<string, unknown>, K extends keyof D>(discriminatorKey: K): (schema: { [P in D[K] & string]: StrictTypeToRcTypeBase<OmitDiscriminator<K, D & { [Q in K]: P; }>>; }) => RcType<D>;
83
263
 
264
+ /**
265
+ * Creates an intersection type validator that requires input to satisfy all provided types.
266
+ * For object types, merges the properties from all types.
267
+ * For non-object types, input must be valid for all types simultaneously.
268
+ * @param types - The types to intersect (2-4 types supported)
269
+ * @returns A runcheck type representing the intersection of all input types
270
+ * @example
271
+ * ```typescript
272
+ * const userBase = rc_object({ name: rc_string })
273
+ * const userMeta = rc_object({ createdAt: rc_date })
274
+ * const fullUser = rc_intersection(userBase, userMeta)
275
+ * // Result: { name: string, createdAt: Date }
276
+ *
277
+ * const result = fullUser.parse({ name: 'John', createdAt: new Date() }) // valid
278
+ * const result2 = fullUser.parse({ name: 'John' }) // invalid - missing createdAt
279
+ * ```
280
+ */
84
281
  declare function rc_intersection<A, B>(a: RcType<A>, b: RcType<B>): RcType<A & B>;
85
282
  declare function rc_intersection<A, B, C>(a: RcType<A>, b: RcType<B>, c: RcType<C>): RcType<A & B & C>;
86
283
  declare function rc_intersection<A, B, C, D>(a: RcType<A>, b: RcType<B>, c: RcType<C>, d: RcType<D>): RcType<A & B & C & D>;
@@ -162,6 +359,7 @@ type RcBase<T, RequiredKey extends boolean> = {
162
359
  readonly nullishDefault: <D extends NotNullish<T>>(defaultValue: D | (() => D)) => RcType<NotNullish<T> | RemoveArrayNever<D>>;
163
360
  readonly or: <O>(schema: RcType<O>) => RcType<T | O>;
164
361
  readonly parse: (input: unknown, options?: ParseOptions) => RcParseResult<T>;
362
+ readonly parseJson: (jsonString: string, options?: ParseOptions) => RcParseResult<T>;
165
363
  readonly _optional_key_?: RequiredKey;
166
364
  };
167
365
  type ErrorWithoutPath = string & {
@@ -179,29 +377,53 @@ type IsValid<T> = boolean | {
179
377
  };
180
378
  declare function parse<T>(type: RcType<T>, input: unknown, ctx: ParseResultCtx, checkIfIsValid: () => IsValid<T>): InternalParseResult<T>;
181
379
  declare const defaultProps: Omit<RcType<any>, '_parse_' | '_kind_'>;
380
+ /** Equivalent to ts type: `undefined`. */
182
381
  declare const rc_undefined: RcType<undefined>;
382
+ /** Equivalent to ts type: `null`. */
183
383
  declare const rc_null: RcType<null>;
384
+ /** Equivalent to ts type: `any`. */
184
385
  declare const rc_any: RcType<any>;
386
+ /** Equivalent to ts type: `unknown`. */
185
387
  declare const rc_unknown: RcType<unknown>;
388
+ /** Equivalent to ts type: `boolean`. */
186
389
  declare const rc_boolean: RcType<boolean>;
390
+ /** Equivalent to ts type: `string`. */
187
391
  declare const rc_string: RcType<string>;
392
+ /** Equivalent to ts type: `number`. Excludes `NaN`. */
188
393
  declare const rc_number: RcType<number>;
394
+ /** Equivalent to ts type: `Date`. Excludes invalid dates. */
189
395
  declare const rc_date: RcType<Date>;
190
- declare function rc_instanceof<T extends Function>(classToCheck: T): RcType<T>;
396
+ /** Validates class instances using `instanceof` checks.
397
+ *
398
+ * @example
399
+ * ```typescript
400
+ * const userSchema = rc_instanceof(User) // schema is equivalent to `User` type
401
+ * const result = userSchema.parse(new User('John', 30)) // valid
402
+ * const result2 = userSchema.parse(new Admin('John', 30)) // invalid
403
+ * ```
404
+ */
405
+ declare function rc_instanceof<T extends new (...args: any[]) => any>(classToCheck: T): RcType<InstanceType<T>>;
406
+ /** Validates literal values like `'hello' | true | 1`. */
191
407
  declare function rc_literals<T extends (string | number | boolean)[]>(...literals: T): RcType<T[number]>;
408
+ /** Validates union types like `string | number`. */
192
409
  declare function rc_union<T extends RcType<any>[]>(...types: T): RcType<RcInferType<T[number]>>;
193
410
  type NotUndefined<T> = Exclude<T, undefined>;
194
411
  /** Generate a schema with valid fallback value for undefined inputs */
412
+ /** Provides default value for `undefined` inputs. */
195
413
  declare function rc_default<T>(schema: RcType<T>, defaultValue: NotUndefined<T> | (() => NotUndefined<T>)): RcType<NotUndefined<T>>;
196
414
  type NotNullish<T> = Exclude<T, null | undefined>;
415
+ /** Provides default value for `null | undefined` inputs. */
197
416
  declare function rc_nullish_default<T>(schema: RcType<T>, defaultValue: NotNullish<T> | (() => NotNullish<T>)): RcType<NotNullish<T>>;
198
417
  /** returns a fallback in case of wrong inputs without adding a warning */
418
+ /** Provides fallback value for invalid inputs without warnings. */
199
419
  declare function rc_safe_fallback<T>(schema: RcType<T>, fallback: NoInfer<T> | (() => NoInfer<T>)): RcType<T>;
420
+ /** Validates `Record<string, T>`. Supports key validation and loose checking. */
200
421
  declare function rc_record<V>(valueType: RcType<V>, { checkKey, looseCheck, }?: {
201
422
  checkKey?: (key: string) => boolean;
202
423
  looseCheck?: boolean;
203
424
  }): RcType<Record<string, V>>;
204
425
  /** instead of returning a general error, rejects invalid keys and returns warnings for these items */
426
+ /** Validates `Record<string, T>`. Filters out invalid values instead of rejecting. */
205
427
  declare function rc_loose_record<V>(valueType: RcType<V>, { checkKey }?: {
206
428
  checkKey?: (key: string) => boolean;
207
429
  }): RcType<Record<string, V>>;
@@ -211,13 +433,53 @@ type ArrayOptions<T extends RcType<any>> = {
211
433
  errors: ErrorWithPath[];
212
434
  };
213
435
  };
436
+ /** Validates arrays of type `T[]`. Supports unique value checking. */
214
437
  declare function rc_array<T extends RcType<any>>(type: T, options?: ArrayOptions<T>): RcType<RcInferType<T>[]>;
438
+ /**
439
+ * Extracts the item type from an array type.
440
+ * @param type - The array type to extract the item type from
441
+ * @returns The item type of the array
442
+ * @example
443
+ * ```typescript
444
+ * const stringArray = rc_array(rc_string)
445
+ * const itemType = rc_get_array_item_type(stringArray) // rc_string
446
+ * ```
447
+ */
215
448
  declare function rc_get_array_item_type<T>(type: RcType<T[]>): RcType<T>;
449
+ /**
450
+ * Disables loose array validation for a type.
451
+ * @param type - The type to modify
452
+ * @param options - Configuration options
453
+ * @param options.nonRecursive - If true, only affects the immediate array type
454
+ * @returns The modified type with loose array validation disabled
455
+ * @example
456
+ * ```typescript
457
+ * const strictArray = rc_disable_loose_array(rc_array(rc_string))
458
+ * ```
459
+ */
216
460
  declare function rc_disable_loose_array<T extends RcType<any>>(type: T, { nonRecursive }?: {
217
461
  nonRecursive?: boolean;
218
462
  }): T;
219
463
  /** instead of returning a general error, rejects invalid array items and returns warnings for these items */
464
+ /** Validates arrays of type `T[]`. Filters out invalid elements instead of rejecting the array. */
220
465
  declare function rc_loose_array<T extends RcType<any>>(type: T, options?: ArrayOptions<T>): RcType<RcInferType<T>[]>;
466
+ /**
467
+ * Creates an array validator with schema-based filtering.
468
+ * @param filterSchema - The schema to validate items before filtering
469
+ * @param filterFn - The function to determine if validated items should be included
470
+ * @param type - The type to validate for included array elements
471
+ * @param options - Configuration options
472
+ * @returns A runcheck type that validates and filters arrays based on the schema
473
+ * @example
474
+ * ```typescript
475
+ * const evenNumbers = rc_array_filter_from_schema(
476
+ * rc_number,
477
+ * (n) => n % 2 === 0,
478
+ * rc_number
479
+ * )
480
+ * const result = evenNumbers.parse([1, 2, 3, 4]) // returns [2, 4]
481
+ * ```
482
+ */
221
483
  declare function rc_array_filter_from_schema<B, T>(filterSchema: RcType<B>, filterFn: (item: B) => boolean, type: RcType<T>, options?: Omit<ArrayOptions<RcType<any>>, 'filter'> & {
222
484
  loose?: boolean;
223
485
  }): RcType<T[]>;
@@ -229,6 +491,7 @@ type MapTupleToTypes<T extends readonly [...any[]]> = {
229
491
  *
230
492
  * TS equivalent example: [string, number, boolean]
231
493
  */
494
+ /** Validates tuples like `[T, T]` with fixed length. */
232
495
  declare function rc_tuple<const T extends readonly RcType<any>[]>(types: T): RcType<MapTupleToTypes<T>>;
233
496
  type ParseOptions = {
234
497
  /** ignore fallback and autofix */
@@ -238,9 +501,37 @@ type ParseOptions = {
238
501
  * Parse a runcheck type. If valid return the valid input, with warning for autofix
239
502
  * and fallback, or the errors if invalid
240
503
  */
504
+ /**
505
+ * Parses and validates input against a runcheck type schema.
506
+ * @param input - The input value to validate
507
+ * @param type - The runcheck type schema to validate against
508
+ * @param options - Parse options
509
+ * @param options.noWarnings - If true, disables fallback and autofix warnings
510
+ * @returns The parse result containing either the validated value or errors
511
+ * @example
512
+ * ```typescript
513
+ * const result = rc_parse('hello', rc_string)
514
+ * if (result.ok) {
515
+ * console.log(result.value) // 'hello'
516
+ * } else {
517
+ * console.log(result.errors) // validation errors
518
+ * }
519
+ * ```
520
+ */
241
521
  declare function rc_parse<S>(input: any, type: RcType<S>, { noWarnings }?: ParseOptions): RcParseResult<S>;
242
522
  type RcParser<T> = (input: any) => RcParseResult<T>;
243
523
  /** create a reusable parser for a certain type */
524
+ /**
525
+ * Creates a reusable parser function for a runcheck type.
526
+ * @param type - The runcheck type to create a parser for
527
+ * @returns A parser function that can be called with input values
528
+ * @example
529
+ * ```typescript
530
+ * const parseString = rc_parser(rc_string)
531
+ * const result1 = parseString('hello')
532
+ * const result2 = parseString(123)
533
+ * ```
534
+ */
244
535
  declare function rc_parser<S>(type: RcType<S>): RcParser<S>;
245
536
  /** @deprecated use rc_unwrap_or_null instead */
246
537
  declare function rc_loose_parse<S>(input: any, type: RcType<S>, options?: ParseOptions): {
@@ -270,8 +561,53 @@ declare function rc_unwrap<R>(result: RcParseResult<R>): {
270
561
  value: R;
271
562
  warnings: string[] | false;
272
563
  };
564
+ /**
565
+ * Type guard function that checks if input is valid for a given type.
566
+ * @param input - The input value to validate
567
+ * @param type - The runcheck type to validate against
568
+ * @returns True if input is valid, false otherwise (with type narrowing)
569
+ * @example
570
+ * ```typescript
571
+ * if (rc_is_valid(input, rc_string)) {
572
+ * // input is now typed as string
573
+ * console.log(input.toUpperCase())
574
+ * }
575
+ * ```
576
+ */
273
577
  declare function rc_is_valid<S>(input: any, type: RcType<S>): input is S;
578
+ /**
579
+ * Creates a validator function that acts as a type guard.
580
+ * @param type - The runcheck type to create a validator for
581
+ * @returns A validator function that can be used as a type guard
582
+ * @example
583
+ * ```typescript
584
+ * const isString = rc_validator(rc_string)
585
+ * if (isString(input)) {
586
+ * // input is now typed as string
587
+ * console.log(input.length)
588
+ * }
589
+ * ```
590
+ */
274
591
  declare function rc_validator<S>(type: RcType<S>): (input: any) => input is S;
592
+ /**
593
+ * Creates a recursive type definition for self-referencing data structures.
594
+ * @param type - A function that returns the recursive type definition
595
+ * @returns A runcheck type that can handle recursive structures
596
+ * @example
597
+ * ```typescript
598
+ * type TreeNode = {
599
+ * value: string
600
+ * children?: TreeNode[]
601
+ * }
602
+ *
603
+ * const TreeNode: RcType<TreeNode> = rc_recursive(() =>
604
+ * rc_object({
605
+ * value: rc_string,
606
+ * children: rc_array(TreeNode).optional(),
607
+ * })
608
+ * )
609
+ * ```
610
+ */
275
611
  declare function rc_recursive<T extends RcBase<any, any>>(type: () => T): T;
276
612
  type TransformOptions<T> = {
277
613
  /**
@@ -285,10 +621,62 @@ type TransformOptions<T> = {
285
621
  disableStrictOutputSchema?: boolean;
286
622
  };
287
623
  /** validate a input or subset of input and transform the valid result */
624
+ /**
625
+ * Creates a type that validates input and transforms the result.
626
+ * @param type - The input type to validate against
627
+ * @param transform - Function to transform the validated input
628
+ * @param options - Transform options
629
+ * @param options.outputSchema - Optional schema to validate the transformed output
630
+ * @param options.disableStrictOutputSchema - If true, allows loose validation of output
631
+ * @returns A runcheck type that validates input and applies transformation
632
+ * @example
633
+ * ```typescript
634
+ * const upperCaseString = rc_transform(
635
+ * rc_string,
636
+ * (str) => str.toUpperCase()
637
+ * )
638
+ * const result = upperCaseString.parse('hello') // returns 'HELLO'
639
+ * ```
640
+ */
288
641
  declare function rc_transform<Input, Transformed>(type: RcType<Input>, transform: (input: Input, inputSchema: RcType<Input>) => Transformed, { outputSchema, disableStrictOutputSchema, }?: TransformOptions<Transformed>): RcType<Transformed>;
289
642
  /** Create transforms which result can be validated with the same schema */
643
+ /**
644
+ * Creates a narrowing transformation that refines the input type.
645
+ * @param type - The input type to validate against
646
+ * @param narrow - Function to narrow the validated input to a more specific type
647
+ * @returns A runcheck type that validates and narrows the input
648
+ * @example
649
+ * ```typescript
650
+ * const positiveNumber = rc_narrow(
651
+ * rc_number,
652
+ * (n) => n > 0 ? n : 0
653
+ * )
654
+ * ```
655
+ */
290
656
  declare function rc_narrow<Input, Narrowed extends Input>(type: RcType<Input>, narrow: (input: Input, inputSchema: RcType<Input>) => Narrowed): RcType<Narrowed>;
291
657
  /** Allows the transform function to return a error if transformation is invalid */
658
+ /**
659
+ * Creates a transformation that can fail with custom error messages.
660
+ * @param type - The input type to validate against
661
+ * @param transform - Function that returns either transformed data or errors
662
+ * @param options - Transform options
663
+ * @param options.outputSchema - Optional schema to validate the transformed output
664
+ * @param options.disableStrictOutputSchema - If true, allows loose validation of output
665
+ * @returns A runcheck type that validates input and applies fallible transformation
666
+ * @example
667
+ * ```typescript
668
+ * const parseJson = rc_unsafe_transform(
669
+ * rc_string,
670
+ * (str) => {
671
+ * try {
672
+ * return { ok: true, data: JSON.parse(str) }
673
+ * } catch {
674
+ * return { ok: false, errors: 'Invalid JSON' }
675
+ * }
676
+ * }
677
+ * )
678
+ * ```
679
+ */
292
680
  declare function rc_unsafe_transform<Input, Transformed>(type: RcType<Input>, transform: (input: Input, inputSchema: RcType<Input>) => {
293
681
  ok: true;
294
682
  data: Transformed;
@@ -297,6 +685,18 @@ declare function rc_unsafe_transform<Input, Transformed>(type: RcType<Input>, tr
297
685
  errors: string | string[];
298
686
  }, { outputSchema, disableStrictOutputSchema, }?: TransformOptions<Transformed>): RcType<Transformed>;
299
687
  declare function normalizedTypeOf(input: unknown, showValueInError: boolean): string;
688
+ /**
689
+ * Assertion function that throws if the parse result contains errors.
690
+ * @param result - The parse result to assert validity for
691
+ * @throws Error if the result contains validation errors
692
+ * @example
693
+ * ```typescript
694
+ * const result = rc_parse(input, rc_string)
695
+ * rc_assert_is_valid(result)
696
+ * // result is now typed as successful result
697
+ * console.log(result.value)
698
+ * ```
699
+ */
300
700
  declare function rc_assert_is_valid<S>(result: RcParseResult<S>): asserts result is {
301
701
  ok: true;
302
702
  error: false;
@@ -308,19 +708,86 @@ declare function rc_assert_is_valid<S>(result: RcParseResult<S>): asserts result
308
708
  unwrapOr: (defaultValue: S) => S;
309
709
  unwrapOrNull: () => S | null;
310
710
  };
711
+ /**
712
+ * Parses a JSON string and validates it against a schema.
713
+ * @param jsonString - The JSON string to parse
714
+ * @param schema - The runcheck type to validate the parsed JSON against
715
+ * @param options - Parse options
716
+ * @returns The parse result containing either the validated JSON value or errors
717
+ * @example
718
+ * ```typescript
719
+ * const userSchema = rc_object({ name: rc_string, age: rc_number })
720
+ * const result = rc_parse_json('{"name":"John","age":30}', userSchema)
721
+ * ```
722
+ */
311
723
  declare function rc_parse_json<T>(jsonString: unknown, schema: RcType<T>, options?: ParseOptions): RcParseResult<T>;
312
724
  type Prettify<T> = T extends Record<string, any> ? {
313
725
  [K in keyof T]: Prettify<T[K]>;
314
726
  } : T;
315
727
  type RcPrettyInferType<T extends RcType<any>> = Prettify<RcInferType<T>>;
728
+ /**
729
+ * Type guard function that checks if a value is a runcheck type.
730
+ * @param value - The value to check
731
+ * @returns True if the value is a runcheck type, false otherwise
732
+ * @example
733
+ * ```typescript
734
+ * if (isRcType(someValue)) {
735
+ * // someValue is now typed as RcType<any>
736
+ * const result = someValue.parse(input)
737
+ * }
738
+ * ```
739
+ */
316
740
  declare function isRcType(value: any): value is RcType<any>;
317
741
  /** workaround for the typescript limitation: https://github.com/microsoft/TypeScript/issues/52295 */
742
+ /**
743
+ * Workaround for TypeScript limitation with union types.
744
+ * @param type - The type to cast as a union type
745
+ * @returns The type cast as a proper runcheck union type
746
+ * @example
747
+ * ```typescript
748
+ * const unionType = joinAsRcTypeUnion(someComplexUnionType)
749
+ * ```
750
+ */
318
751
  declare function joinAsRcTypeUnion<T>(type: T): RcType<T extends RcType<infer U> ? U : never>;
752
+ /**
753
+ * Gets the kind/name of a runcheck schema for debugging purposes.
754
+ * @param schema - The runcheck type to get the kind from
755
+ * @returns The string representation of the schema kind
756
+ * @example
757
+ * ```typescript
758
+ * const kind = getSchemaKind(rc_string) // returns 'string'
759
+ * const kind2 = getSchemaKind(rc_array(rc_number)) // returns 'number[]'
760
+ * ```
761
+ */
319
762
  declare function getSchemaKind(schema: RcType<any>): string;
763
+ /**
764
+ * Converts a runcheck type or parse result to a Standard Schema V1.
765
+ * @param schemaOrResult - The runcheck type or parse result to convert
766
+ * @param options - Conversion options
767
+ * @param options.errorOnWarnings - If true, treat warnings as errors
768
+ * @param options.onWarnings - Callback function to handle warnings
769
+ * @returns A Standard Schema V1 compatible object
770
+ * @example
771
+ * ```typescript
772
+ * const standardSchema = rc_to_standard(rc_string)
773
+ * const result = standardSchema['~standard'].validate('hello')
774
+ * ```
775
+ */
320
776
  declare function rc_to_standard<T>(schemaOrResult: RcType<T> | RcParseResult<T>, { errorOnWarnings, onWarnings, }?: {
321
777
  errorOnWarnings?: boolean;
322
778
  onWarnings?: (warnings: string[]) => void;
323
779
  }): StandardSchemaV1<T>;
780
+ /**
781
+ * Converts a Standard Schema V1 to a runcheck type.
782
+ * @param standardSchema - The Standard Schema V1 to convert
783
+ * @param kind - Optional custom kind name for error messages
784
+ * @returns A runcheck type that wraps the standard schema
785
+ * @example
786
+ * ```typescript
787
+ * const rcType = rc_from_standard(someStandardSchema)
788
+ * const result = rcType.parse(input)
789
+ * ```
790
+ */
324
791
  declare function rc_from_standard<T>(standardSchema: StandardSchemaV1<any, T>,
325
792
  /** use this kind instead of the default one in error messages (standard_schema_${standard.vendor}@${standard.version}) */
326
793
  kind?: string): RcType<T>;