@sinclair/typebox 0.26.0-dev → 0.26.0-dev.1

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.
@@ -6,7 +6,7 @@ export declare class TypeCheck<T extends Types.TSchema> {
6
6
  private readonly checkFunc;
7
7
  private readonly code;
8
8
  constructor(schema: T, checkFunc: CheckFunction, code: string);
9
- /** Returns the generated validation code used to validate this type. */
9
+ /** Returns the generated assertion code used to validate this type. */
10
10
  Code(): string;
11
11
  /** Returns an iterator for each error in this value. */
12
12
  Errors(value: unknown): IterableIterator<ValueError>;
@@ -26,7 +26,7 @@ export declare class TypeCompilerPreflightCheckError extends Error {
26
26
  }
27
27
  /** Compiles Types for Runtime Type Checking */
28
28
  export declare namespace TypeCompiler {
29
- /** Returns the generated validation code used to validate this type. */
29
+ /** Returns the generated assertion code used to validate this type. */
30
30
  function Code<T extends Types.TSchema>(schema: T): string;
31
31
  /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
32
32
  function Compile<T extends Types.TSchema>(schema: T): TypeCheck<T>;
@@ -41,7 +41,7 @@ class TypeCheck {
41
41
  this.checkFunc = checkFunc;
42
42
  this.code = code;
43
43
  }
44
- /** Returns the generated validation code used to validate this type. */
44
+ /** Returns the generated assertion code used to validate this type. */
45
45
  Code() {
46
46
  return this.code;
47
47
  }
@@ -504,7 +504,7 @@ var TypeCompiler;
504
504
  const locals = GetLocals();
505
505
  return `${locals.join('\n')}\nreturn ${check}`;
506
506
  }
507
- /** Returns the generated validation code used to validate this type. */
507
+ /** Returns the generated assertion code used to validate this type. */
508
508
  function Code(schema) {
509
509
  if (!Types.TypeGuard.TSchema(schema))
510
510
  throw new TypeCompilerPreflightCheckError(schema);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sinclair/typebox",
3
- "version": "0.26.0-dev",
3
+ "version": "0.26.0-dev.1",
4
4
  "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
5
5
  "keywords": [
6
6
  "typescript",
package/readme.md CHANGED
@@ -777,7 +777,7 @@ const T = Type.Unsafe<string>({ type: 'number' }) // const T = {
777
777
  type T = Static<typeof T> // type T = string
778
778
  ```
779
779
 
780
- The `Type.Unsafe(...)` type allows specific or non-standard OpenAPI schematics can be constructed.
780
+ The `Type.Unsafe(...)` type allows for the expression of specific OpenAPI schema representations.
781
781
 
782
782
  ```typescript
783
783
  import { Type, Static, TSchema } from '@sinclair/typebox'
@@ -812,7 +812,7 @@ type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
812
812
 
813
813
  ### Guards
814
814
 
815
- TypeBox provides a `TypeGuard` module used for type value assertions and reflection.
815
+ TypeBox provides a `TypeGuard` module for reflection and type assertion.
816
816
 
817
817
  ```typescript
818
818
  import { Type, TypeGuard } from '@sinclair/typebox'
@@ -1029,15 +1029,15 @@ ValuePointer.Set(A, '/z', 1) // const A = { x: 1, y: 1,
1029
1029
 
1030
1030
  ## TypeCheck
1031
1031
 
1032
- TypeBox types targets JSON Schema draft 6 so is immediately compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for high performance compilation and value assertion.
1032
+ TypeBox types target JSON Schema draft 6 so are compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for high performance compilation and value assertion.
1033
1033
 
1034
- The following details using both Ajv and TypeBox's compiler infrastructure.
1034
+ The following sections detail using Ajv and TypeBox's compiler infrastructure.
1035
1035
 
1036
1036
  <a name='typecheck-ajv'></a>
1037
1037
 
1038
1038
  ## Ajv
1039
1039
 
1040
- The following shows the recommended setup for Ajv with additional string formats.
1040
+ The following shows the recommended setup for Ajv.
1041
1041
 
1042
1042
  ```bash
1043
1043
  $ npm install ajv ajv-formats --save
@@ -1078,7 +1078,7 @@ const R = C({ x: 1, y: 2, z: 3 }) // const R = true
1078
1078
 
1079
1079
  ### TypeCompiler
1080
1080
 
1081
- The TypeBox TypeCompiler is a high performance JIT compiler that compiles TypeBox types into optimized JavaScript validation routines. The compiler is tuned both for fast compilation and value assertion. It is designed primarily for integrating into application frameworks but can also be used as a general purpose validator.
1081
+ The TypeBox TypeCompiler is a high performance JIT compiler that transforms TypeBox types into optimized JavaScript validation routines. The compiler is tuned for fast compilation as well as fast value assertion. It is designed to serve as a validation backend that can be integrated into larger applications; but can also be used as a general purpose validator.
1082
1082
 
1083
1083
  The TypeCompiler is provided as an optional import.
1084
1084
 
@@ -1098,7 +1098,7 @@ const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObje
1098
1098
  const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true
1099
1099
  ```
1100
1100
 
1101
- Use the `Errors(...)` function to produce diagnostics for a value. The `Errors(...)` function will return an iterator that will perform an exhaustive check across the value and yield any error found. For performance, this function should only be called after failed `Check(...)`.
1101
+ Use the `Errors(...)` function to produce diagnostic errors for a value. The `Errors(...)` function will return an iterator that if enumerated; will perform an exhaustive check across the entire value and yield any error found. For performance, this function should only be called after failed `Check(...)`. Applications may also choose to yield only the first value to avoid exhaustive error generation.
1102
1102
 
1103
1103
  ```typescript
1104
1104
  const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{
@@ -1181,7 +1181,7 @@ const R = Value.Check(T, { x: 1, y: 2 }) // const R = true
1181
1181
 
1182
1182
  ### Formats
1183
1183
 
1184
- Use the `Format(...)` function to create a custom string formats. The following creates a custom string format that checks for lowercase strings.
1184
+ Use the `Format(...)` function to create a custom string format. The following creates a custom string format that checks for lowercase strings.
1185
1185
 
1186
1186
  ```typescript
1187
1187
  TypeSystem.Format('lowercase', value => value === value.toLowerCase()) // format should be lowercase
package/typebox.d.ts CHANGED
@@ -520,6 +520,8 @@ export declare namespace KeyResolver {
520
520
  export declare class TypeBuilder {
521
521
  /** `[Utility]` Creates a schema without `static` and `params` types */
522
522
  protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
523
+ /** `[Utility]` Clones a schema or properties object */
524
+ protected Clone<T extends TSchema | TProperties>(schema: T, options?: SchemaOptions): T;
523
525
  /** `[Standard]` Omits compositing symbols from this schema */
524
526
  Strict<T extends TSchema>(schema: T): T;
525
527
  }
@@ -542,11 +544,11 @@ export declare class StandardTypeBuilder extends TypeBuilder {
542
544
  Deref<T extends TRef>(schema: T): TDeref<T>;
543
545
  /** `[Standard]` Creates a Enum type */
544
546
  Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
545
- /** `[Standard]` A conditional type expression that will return the true type if the left extends the right */
547
+ /** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */
546
548
  Extends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema>(left: L, right: R, trueType: T, falseType: U, options?: SchemaOptions): TExtends<L, R, T, U>;
547
- /** `[Standard]` Excludes from left any type that is not assignable to the right. */
549
+ /** `[Standard]` Excludes from the left type any type that is not assignable to the right */
548
550
  Exclude<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExclude<L, R>;
549
- /** `[Standard]` Extracts from left any type that is assignable to the right. */
551
+ /** `[Standard]` Extracts from left left any type that is assignable to the right */
550
552
  Extract<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExtract<L, R>;
551
553
  /** `[Standard]` Creates an Integer type */
552
554
  Integer(options?: NumericOptions<number>): TInteger;
@@ -567,7 +569,7 @@ export declare class StandardTypeBuilder extends TypeBuilder {
567
569
  Null(options?: SchemaOptions): TNull;
568
570
  /** `[Standard]` Creates a Number type */
569
571
  Number(options?: NumericOptions<number>): TNumber;
570
- /** `[Standard]` Creates a Object type */
572
+ /** `[Standard]` Creates an Object type */
571
573
  Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
572
574
  /** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
573
575
  Omit<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TOmit<T, K[number]>;
@@ -607,7 +609,7 @@ export declare class StandardTypeBuilder extends TypeBuilder {
607
609
  Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
608
610
  }
609
611
  export declare class ExtendedTypeBuilder extends StandardTypeBuilder {
610
- /** `[Extended]` Creates a BigInt */
612
+ /** `[Extended]` Creates a BigInt type */
611
613
  BigInt(options?: NumericOptions<bigint>): TBigInt;
612
614
  /** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */
613
615
  ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
package/typebox.js CHANGED
@@ -85,7 +85,7 @@ var ReferenceRegistry;
85
85
  function DerefOne(schema) {
86
86
  if (TypeGuard.TRef(schema) || TypeGuard.TSelf(schema)) {
87
87
  if (!references.has(schema.$ref))
88
- throw Error(`ReferenceRegistry: Cannot deref schema with $id '${schema.$ref}`);
88
+ throw Error(`ReferenceRegistry: Cannot deref schema with $id '${schema.$ref}'`);
89
89
  return references.get(schema.$ref);
90
90
  }
91
91
  else {
@@ -1469,6 +1469,12 @@ class TypeBuilder {
1469
1469
  ReferenceRegistry.Set(schema);
1470
1470
  return schema;
1471
1471
  }
1472
+ /** `[Utility]` Clones a schema or properties object */
1473
+ Clone(schema, options = {}) {
1474
+ const clone = TypeClone.Clone(schema, options);
1475
+ ReferenceRegistry.Set(clone);
1476
+ return clone;
1477
+ }
1472
1478
  /** `[Standard]` Omits compositing symbols from this schema */
1473
1479
  Strict(schema) {
1474
1480
  return JSON.parse(JSON.stringify(schema));
@@ -1484,11 +1490,11 @@ class StandardTypeBuilder extends TypeBuilder {
1484
1490
  // ----------------------------------------------------------------------
1485
1491
  /** `[Modifier]` Creates a Optional property */
1486
1492
  Optional(schema) {
1487
- return { [exports.Modifier]: 'Optional', ...TypeClone.Clone(schema, {}) };
1493
+ return { [exports.Modifier]: 'Optional', ...this.Clone(schema, {}) };
1488
1494
  }
1489
1495
  /** `[Modifier]` Creates a ReadonlyOptional property */
1490
1496
  ReadonlyOptional(schema) {
1491
- return { [exports.Modifier]: 'ReadonlyOptional', ...TypeClone.Clone(schema, {}) };
1497
+ return { [exports.Modifier]: 'ReadonlyOptional', ...this.Clone(schema, {}) };
1492
1498
  }
1493
1499
  /** `[Modifier]` Creates a Readonly object or property */
1494
1500
  Readonly(schema) {
@@ -1538,35 +1544,35 @@ class StandardTypeBuilder extends TypeBuilder {
1538
1544
  const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value }));
1539
1545
  return this.Create({ ...options, [exports.Kind]: 'Union', anyOf });
1540
1546
  }
1541
- /** `[Standard]` A conditional type expression that will return the true type if the left extends the right */
1547
+ /** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */
1542
1548
  Extends(left, right, trueType, falseType, options = {}) {
1543
1549
  switch (TypeExtends.Extends(ReferenceRegistry.Deref(left), ReferenceRegistry.Deref(right))) {
1544
1550
  case TypeExtendsResult.Union:
1545
- return this.Union([TypeClone.Clone(trueType, options), TypeClone.Clone(falseType, options)]);
1551
+ return this.Union([this.Clone(trueType, options), this.Clone(falseType, options)]);
1546
1552
  case TypeExtendsResult.True:
1547
- return TypeClone.Clone(trueType, options);
1553
+ return this.Clone(trueType, options);
1548
1554
  case TypeExtendsResult.False:
1549
- return TypeClone.Clone(falseType, options);
1555
+ return this.Clone(falseType, options);
1550
1556
  }
1551
1557
  }
1552
- /** `[Standard]` Excludes from left any type that is not assignable to the right. */
1558
+ /** `[Standard]` Excludes from the left type any type that is not assignable to the right */
1553
1559
  Exclude(left, right, options = {}) {
1554
1560
  if (TypeGuard.TUnion(left)) {
1555
1561
  const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) === TypeExtendsResult.False);
1556
- return (narrowed.length === 1 ? TypeClone.Clone(narrowed[0], options) : this.Union(narrowed, options));
1562
+ return (narrowed.length === 1 ? this.Clone(narrowed[0], options) : this.Union(narrowed, options));
1557
1563
  }
1558
1564
  else {
1559
- return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? this.Never(options) : TypeClone.Clone(left, options));
1565
+ return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? this.Never(options) : this.Clone(left, options));
1560
1566
  }
1561
1567
  }
1562
- /** `[Standard]` Extracts from left any type that is assignable to the right. */
1568
+ /** `[Standard]` Extracts from left left any type that is assignable to the right */
1563
1569
  Extract(left, right, options = {}) {
1564
1570
  if (TypeGuard.TUnion(left)) {
1565
1571
  const narrowed = left.anyOf.filter((inner) => TypeExtends.Extends(inner, right) !== TypeExtendsResult.False);
1566
- return (narrowed.length === 1 ? TypeClone.Clone(narrowed[0], options) : this.Union(narrowed, options));
1572
+ return (narrowed.length === 1 ? this.Clone(narrowed[0], options) : this.Union(narrowed, options));
1567
1573
  }
1568
1574
  else {
1569
- return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? TypeClone.Clone(left, options) : this.Never(options));
1575
+ return (TypeExtends.Extends(left, right) !== TypeExtendsResult.False ? this.Clone(left, options) : this.Never(options));
1570
1576
  }
1571
1577
  }
1572
1578
  /** `[Standard]` Creates an Integer type */
@@ -1577,9 +1583,9 @@ class StandardTypeBuilder extends TypeBuilder {
1577
1583
  if (allOf.length === 0)
1578
1584
  return exports.Type.Never();
1579
1585
  if (allOf.length === 1)
1580
- return TypeClone.Clone(allOf[0], options);
1586
+ return this.Clone(allOf[0], options);
1581
1587
  const objects = allOf.every((schema) => TypeGuard.TObject(schema));
1582
- const cloned = allOf.map((schema) => TypeClone.Clone(schema, {}));
1588
+ const cloned = allOf.map((schema) => this.Clone(schema, {}));
1583
1589
  if (options.unevaluatedProperties === false || TypeGuard.TSchema(options.unevaluatedProperties) || objects) {
1584
1590
  return this.Create({ ...options, [exports.Kind]: 'Intersect', type: 'object', allOf: cloned });
1585
1591
  }
@@ -1618,22 +1624,22 @@ class StandardTypeBuilder extends TypeBuilder {
1618
1624
  Number(options = {}) {
1619
1625
  return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' });
1620
1626
  }
1621
- /** `[Standard]` Creates a Object type */
1627
+ /** `[Standard]` Creates an Object type */
1622
1628
  Object(properties, options = {}) {
1623
1629
  const keys = globalThis.Object.keys(properties);
1624
1630
  const optional = keys.filter((key) => TypeGuard.TOptional(properties[key]) || TypeGuard.TReadonlyOptional(properties[key]));
1625
1631
  const required = keys.filter((name) => !optional.includes(name));
1626
1632
  if (required.length > 0) {
1627
- return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties: TypeClone.Clone(properties, {}), required });
1633
+ return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties: this.Clone(properties, {}), required });
1628
1634
  }
1629
1635
  else {
1630
- return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties: TypeClone.Clone(properties, {}) });
1636
+ return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties: this.Clone(properties, {}) });
1631
1637
  }
1632
1638
  }
1633
1639
  Omit(schema, unresolved, options = {}) {
1634
1640
  const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) : unresolved;
1635
1641
  // prettier-ignore
1636
- return ObjectMap.Map(TypeClone.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1642
+ return ObjectMap.Map(this.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1637
1643
  if (schema.required) {
1638
1644
  schema.required = schema.required.filter((key) => !keys.includes(key));
1639
1645
  if (schema.required.length === 0)
@@ -1666,7 +1672,7 @@ class StandardTypeBuilder extends TypeBuilder {
1666
1672
  }
1667
1673
  }
1668
1674
  // prettier-ignore
1669
- return ObjectMap.Map(TypeClone.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1675
+ return ObjectMap.Map(this.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1670
1676
  delete schema.required;
1671
1677
  globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key]));
1672
1678
  return schema;
@@ -1675,7 +1681,7 @@ class StandardTypeBuilder extends TypeBuilder {
1675
1681
  Pick(schema, unresolved, options = {}) {
1676
1682
  const keys = TypeGuard.TUnionLiteral(unresolved) ? unresolved.anyOf.map((schema) => schema.const) : unresolved;
1677
1683
  // prettier-ignore
1678
- return ObjectMap.Map(TypeClone.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1684
+ return ObjectMap.Map(this.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1679
1685
  if (schema.required) {
1680
1686
  schema.required = schema.required.filter((key) => keys.includes(key));
1681
1687
  if (schema.required.length === 0)
@@ -1698,7 +1704,7 @@ class StandardTypeBuilder extends TypeBuilder {
1698
1704
  }
1699
1705
  if (TypeGuard.TUnion(key)) {
1700
1706
  if (key.anyOf.every((schema) => TypeGuard.TLiteral(schema) && (typeof schema.const === 'string' || typeof schema.const === 'number'))) {
1701
- const properties = key.anyOf.reduce((acc, literal) => ({ ...acc, [literal.const]: TypeClone.Clone(schema, {}) }), {});
1707
+ const properties = key.anyOf.reduce((acc, literal) => ({ ...acc, [literal.const]: this.Clone(schema, {}) }), {});
1702
1708
  return this.Object(properties, { ...options, [exports.Hint]: 'Record' });
1703
1709
  }
1704
1710
  else
@@ -1748,7 +1754,7 @@ class StandardTypeBuilder extends TypeBuilder {
1748
1754
  }
1749
1755
  }
1750
1756
  // prettier-ignore
1751
- return ObjectMap.Map(TypeClone.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1757
+ return ObjectMap.Map(this.Clone(ReferenceRegistry.Deref(schema), {}), (schema) => {
1752
1758
  schema.required = globalThis.Object.keys(schema.properties);
1753
1759
  globalThis.Object.keys(schema.properties).forEach(key => Apply(schema.properties[key]));
1754
1760
  return schema;
@@ -1771,8 +1777,8 @@ class StandardTypeBuilder extends TypeBuilder {
1771
1777
  if (anyOf.length === 0)
1772
1778
  return this.Never(options);
1773
1779
  if (anyOf.length === 1)
1774
- return TypeClone.Clone(anyOf[0], options);
1775
- const cloned = anyOf.map((schema) => TypeClone.Clone(schema, {}));
1780
+ return this.Clone(anyOf[0], options);
1781
+ const cloned = anyOf.map((schema) => this.Clone(schema, {}));
1776
1782
  return this.Create({ ...options, [exports.Kind]: 'Union', anyOf: cloned });
1777
1783
  }
1778
1784
  /** `[Standard]` Creates an Unknown type */
@@ -1789,7 +1795,7 @@ exports.StandardTypeBuilder = StandardTypeBuilder;
1789
1795
  // TypeBuilder
1790
1796
  // -------------------------------------------------------------------------------------
1791
1797
  class ExtendedTypeBuilder extends StandardTypeBuilder {
1792
- /** `[Extended]` Creates a BigInt */
1798
+ /** `[Extended]` Creates a BigInt type */
1793
1799
  BigInt(options = {}) {
1794
1800
  return this.Create({ ...options, [exports.Kind]: 'BigInt', type: 'null', typeOf: 'BigInt' });
1795
1801
  }
@@ -1827,7 +1833,7 @@ class ExtendedTypeBuilder extends StandardTypeBuilder {
1827
1833
  }
1828
1834
  /** `[Extended]` Extracts the InstanceType from the given Constructor */
1829
1835
  InstanceType(schema, options = {}) {
1830
- return TypeClone.Clone(schema.returns, options);
1836
+ return this.Clone(schema.returns, options);
1831
1837
  }
1832
1838
  /** `[Extended]` Extracts the Parameters from the given Function type */
1833
1839
  Parameters(schema, options = {}) {
@@ -1843,7 +1849,7 @@ class ExtendedTypeBuilder extends StandardTypeBuilder {
1843
1849
  }
1844
1850
  /** `[Extended]` Extracts the ReturnType from the given Function */
1845
1851
  ReturnType(schema, options = {}) {
1846
- return TypeClone.Clone(schema.returns, options);
1852
+ return this.Clone(schema.returns, options);
1847
1853
  }
1848
1854
  /** `[Extended]` Creates a Symbol type */
1849
1855
  Symbol(options) {