@sinclair/typebox 0.28.8 → 0.28.10

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.
@@ -257,7 +257,7 @@ var TypeCompiler;
257
257
  }
258
258
  else if (Types.TypeGuard.TSchema(schema.unevaluatedProperties)) {
259
259
  const keyCheck = PushLocal(`${new RegExp(Types.KeyResolver.ResolvePattern(schema))};`);
260
- const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key) || ${CreateExpression(schema.unevaluatedProperties, references, 'value[key]')})`;
260
+ const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key) || ${CreateExpression(schema.unevaluatedProperties, references, `${value}[key]`)})`;
261
261
  yield `${check1} && ${check2}`;
262
262
  }
263
263
  else {
@@ -326,7 +326,7 @@ var TypeCompiler;
326
326
  }
327
327
  }
328
328
  if (typeof schema.additionalProperties === 'object') {
329
- const expression = CreateExpression(schema.additionalProperties, references, 'value[key]');
329
+ const expression = CreateExpression(schema.additionalProperties, references, `${value}[key]`);
330
330
  const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
331
331
  yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
332
332
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sinclair/typebox",
3
- "version": "0.28.8",
3
+ "version": "0.28.10",
4
4
  "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
5
5
  "keywords": [
6
6
  "typescript",
package/readme.md CHANGED
@@ -11,9 +11,8 @@
11
11
 
12
12
  [![npm version](https://badge.fury.io/js/%40sinclair%2Ftypebox.svg)](https://badge.fury.io/js/%40sinclair%2Ftypebox)
13
13
  [![Downloads](https://img.shields.io/npm/dm/%40sinclair%2Ftypebox.svg)](https://www.npmjs.com/package/%40sinclair%2Ftypebox)
14
- [![Install Size](https://packagephobia.com/badge?p=@sinclair/typebox)](https://packagephobia.com/result?p=@sinclair/typebox)
15
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
16
14
  [![GitHub CI](https://github.com/sinclairzx81/typebox/workflows/GitHub%20CI/badge.svg)](https://github.com/sinclairzx81/typebox/actions)
15
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
17
16
 
18
17
  </div>
19
18
 
@@ -83,7 +82,7 @@ License MIT
83
82
  - [References](#types-references)
84
83
  - [Recursive](#types-recursive)
85
84
  - [Conditional](#types-conditional)
86
- - [Template](#types-template-literal)
85
+ - [Template Literal](#types-template-literal)
87
86
  - [Indexed](#types-indexed)
88
87
  - [Rest](#types-rest)
89
88
  - [Guards](#types-guards)
@@ -109,6 +108,7 @@ License MIT
109
108
  - [Types](#typesystem-types)
110
109
  - [Formats](#typesystem-formats)
111
110
  - [Policies](#typesystem-policies)
111
+ - [Workbench](#workbench)
112
112
  - [Benchmark](#benchmark)
113
113
  - [Compile](#benchmark-compile)
114
114
  - [Validate](#benchmark-validate)
@@ -814,11 +814,13 @@ type T2 = Static<typeof T2> // type T2 = string
814
814
 
815
815
  ### Template Literal Types
816
816
 
817
- Template Literal types are supported with `Type.TemplateLiteral`
817
+ TypeBox supports Template Literal types using `Type.TemplateLiteral`. These types can be created using a simple template DSL syntax, however more complex template literals can be created by passing an array of literal and union types. The examples below show the template DSL syntax.
818
818
 
819
819
  ```typescript
820
820
  // TypeScript
821
821
 
822
+ type P = `/post/${string}/user/${number}` // type P = `/post/${string}/user/${number}`
823
+
822
824
  type T = `option${'A'|'B'}` // type T = 'optionA' | 'optionB'
823
825
 
824
826
  type R = Record<T, string> // type R = {
@@ -828,13 +830,17 @@ type R = Record<T, string> // type R = {
828
830
 
829
831
  // TypeBox
830
832
 
831
- const T = Type.TemplateLiteral([ // const T = {
832
- Type.Literal('option'), // pattern: '^option(A|B)$',
833
- Type.Union([ // type: 'string'
834
- Type.Literal('A'), // }
835
- Type.Literal('B')
836
- ])
837
- ])
833
+ const P = Type.TemplateLiteral('/post/${string}/user/${number}')
834
+
835
+ // const P = {
836
+ // type: 'string',
837
+ // pattern: '^/post/(.*)/user/(0|[1-9][0-9]*)$'
838
+ // }
839
+
840
+ const T = Type.TemplateLiteral('option${A|B}') // const T = {
841
+ // pattern: '^option(A|B)$',
842
+ // type: 'string'
843
+ // }
838
844
 
839
845
  const R = Type.Record(T, Type.String()) // const R = {
840
846
  // type: 'object',
@@ -848,37 +854,48 @@ const R = Type.Record(T, Type.String()) // const R = {
848
854
  // }
849
855
  // }
850
856
  // }
851
-
852
- type T = Static<typeof T> // type T = 'optionA' | 'optionB'
853
-
854
- type R = Static<typeof R> // type R = {
855
- // optionA: string
856
- // optionB: string
857
- // }
858
857
  ```
859
858
 
860
859
  <a name='types-indexed'></a>
861
860
 
862
861
  ### Indexed Access Types
863
862
 
864
- Indexed Access types are supported with `Type.Index`
863
+ TypeBox supports Indexed Access types using `Type.Index`. This feature provides a consistent way to access property types without having to extract them from the underlying schema representation. Indexed accessors are supported for object and tuples, as well as nested union and intersect types.
865
864
 
866
865
  ```typescript
867
- const T = Type.Object({ // type T = {
868
- x: Type.Number(), // x: number
869
- y: Type.String(), // y: string
870
- z: Type.Boolean() // z: boolean
871
- }) // }
866
+ const T = Type.Object({ // const T = {
867
+ x: Type.Number(), // type: 'object',
868
+ y: Type.String(), // required: ['x', 'y', 'z'],
869
+ z: Type.Boolean() // properties: {
870
+ }) // x: { type: 'number' },
871
+ // y: { type: 'string' },
872
+ // z: { type: 'string' },
873
+ // }
874
+ // }
872
875
 
873
- const A = Type.Index(T, ['x']) // type A = T['x']
876
+ const A = Type.Index(T, ['x']) // const A = { type: 'number' }
874
877
 
875
- const B = Type.Index(T, Type.KeyOf(T)) // type B = T[keyof T]
878
+ const B = Type.Index(T, ['x', 'y']) // const B = {
879
+ // anyOf: [
880
+ // { type: 'number' },
881
+ // { type: 'string' }
882
+ // ]
883
+ // }
884
+
885
+ const C = Type.Index(T, Type.KeyOf(T)) // const C = {
886
+ // anyOf: [
887
+ // { type: 'number' },
888
+ // { type: 'string' },
889
+ // { type: 'boolean' }
890
+ // ]
891
+ // }
876
892
  ```
893
+
877
894
  <a name='types-rest'></a>
878
895
 
879
896
  ### Rest Types
880
897
 
881
- Rest parameters are supported with `Type.Rest`. This function is used to extract interior arrays from tuples to allow them to compose with the JavaScript spread operator `...`. This type can be used for tuple concatination and variadic function composition.
898
+ Rest parameters are supported with `Type.Rest`. This function is used to extract interior type elements from tuples which enables them to compose with the JavaScript spread operator `...`. This type can be used for tuple concatination as well as for variadic functions.
882
899
 
883
900
  ```typescript
884
901
  // TypeScript
@@ -1329,26 +1346,31 @@ import { TypeSystem } from '@sinclair/typebox/system'
1329
1346
 
1330
1347
  ### Types
1331
1348
 
1332
- Use the `Type(...)` function to create a custom type. This function will return a type factory function that can be used to construct the type. The following creates a Point type.
1349
+ Use the `Type(...)` function to create custom types. This function lets you specify custom value assertion logic and will return a type factory function which is used to instance the type. This function accepts two generic arguments, the first is the inference type, the second is options used to constrain the type. The following creates a Vector type.
1333
1350
 
1334
1351
  ```typescript
1335
- type PointOptions = { } // The Type Options
1352
+ type VectorOptions = { abs: boolean }
1336
1353
 
1337
- type PointType = { x: number, y: number } // The Static<T> Type
1354
+ type Vector = { x: number, y: number }
1338
1355
 
1339
- const Point = TypeSystem.Type<PointType, PointOptions>('Point', (options, value) => {
1356
+ const Vector = TypeSystem.Type<Vector, VectorOptions>('Vector', (options, value) => {
1340
1357
  return (
1341
1358
  typeof value === 'object' && value !== null &&
1342
- typeof value.x === 'number' &&
1343
- typeof value.y === 'number'
1359
+ 'x' in value && typeof value.x === 'number' &&
1360
+ 'y' in value && typeof value.y === 'number' &&
1361
+ (options.abs ? (value.x === Math.abs(value.x) && value.y === Math.abs(value.y)) : true)
1344
1362
  )
1345
1363
  })
1346
1364
 
1347
- const T = Point()
1365
+ const T = Vector({ abs: true })
1366
+
1367
+ type T = Static<typeof T> // type T = Vector
1368
+
1369
+ const R1 = Value.Check(T, { x: 1, y: 1 }) // const R1 = true
1348
1370
 
1349
- type T = Static<typeof T> // type T = { x: number, y: number }
1371
+ const R2 = Value.Check(T, { x: 1, y: '1' }) // const R2 = false
1350
1372
 
1351
- const R = Value.Check(T, { x: 1, y: 2 }) // const R = true
1373
+ const R3 = Value.Check(T, { x: 1, y: -1 }) // const R3 = false
1352
1374
  ```
1353
1375
 
1354
1376
  <a name='typesystem-formats'></a>
@@ -1393,6 +1415,20 @@ TypeSystem.AllowArrayObjects = true
1393
1415
  TypeSystem.AllowNaN = true
1394
1416
  ```
1395
1417
 
1418
+ <a name='workbench'></a>
1419
+
1420
+ ## Workbench
1421
+
1422
+ TypeBox offers a web based code generation tool that can be used to create TypeBox types from TypeScript type definitions. This tool is written to prototype new TypeBox features, but can be used to rapidly convert TypeScript type definitions in to TypeBox types as well as raw JSON Schema.
1423
+
1424
+ [Workbench Link Here](https://sinclairzx81.github.io/typebox-workbench/)
1425
+
1426
+ <div align='center'>
1427
+
1428
+ <a href="https://sinclairzx81.github.io/typebox-workbench/"><img src="https://github.com/sinclairzx81/typebox/blob/master/workbench.png?raw=true" /></a>
1429
+
1430
+ </div>
1431
+
1396
1432
  <a name='benchmark'></a>
1397
1433
 
1398
1434
  ## Benchmark
package/typebox.d.ts CHANGED
@@ -16,6 +16,7 @@ export type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : ne
16
16
  export type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
17
17
  export type Discard<T extends unknown[], D extends unknown> = T extends [infer L, ...infer R] ? (L extends D ? Discard<R, D> : [L, ...Discard<R, D>]) : [];
18
18
  export type Flat<T> = T extends [] ? [] : T extends [infer L] ? [...Flat<L>] : T extends [infer L, ...infer R] ? [...Flat<L>, ...Flat<R>] : [T];
19
+ export type Trim<T> = T extends `${' '}${infer U}` ? Trim<U> : T extends `${infer U}${' '}` ? Trim<U> : T;
19
20
  export type Assert<T, E> = T extends E ? T : never;
20
21
  export type Evaluate<T> = T extends infer O ? {
21
22
  [K in keyof O]: O[K];
@@ -358,6 +359,13 @@ export interface TSymbol extends TSchema, SchemaOptions {
358
359
  type: 'null';
359
360
  typeOf: 'Symbol';
360
361
  }
362
+ export type TTemplateLiteralDslParserUnionLiteral<T extends string> = T extends `${infer L}|${infer R}` ? [TLiteral<Trim<L>>, ...TTemplateLiteralDslParserUnionLiteral<R>] : T extends `${infer L}` ? [TLiteral<Trim<L>>] : [
363
+ ];
364
+ export type TTemplateLiteralDslParserUnion<T extends string> = UnionType<TTemplateLiteralDslParserUnionLiteral<T>>;
365
+ export type TTemplateLiteralDslParserTerminal<T extends string> = T extends 'boolean' ? TBoolean : T extends 'bigint' ? TBigInt : T extends 'number' ? TNumber : T extends 'string' ? TString : TTemplateLiteralDslParserUnion<T>;
366
+ export type TTemplateLiteralDslParserTemplate<T extends string> = T extends `{${infer L}}${infer R}` ? [TTemplateLiteralDslParserTerminal<L>, ...TTemplateLiteralDslParserTemplate<R>] : T extends `${infer L}$${infer R}` ? [TLiteral<L>, ...TTemplateLiteralDslParserTemplate<R>] : T extends `${infer L}` ? [TLiteral<L>] : [
367
+ ];
368
+ export type TTemplateLiteralDslParser<T extends string> = Ensure<TTemplateLiteral<Assert<TTemplateLiteralDslParserTemplate<T>, TTemplateLiteralKind[]>>>;
361
369
  export type IsTemplateLiteralFiniteCheck<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TUnion<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TString ? false : T extends TBoolean ? false : T extends TNumber ? false : T extends TInteger ? false : T extends TBigInt ? false : T extends TLiteral ? true : false;
362
370
  export type IsTemplateLiteralFiniteArray<T extends TTemplateLiteralKind[]> = T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : IsTemplateLiteralFiniteArray<Assert<R, TTemplateLiteralKind[]>> : true;
363
371
  export type IsTemplateLiteralFinite<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<U> : false;
@@ -621,6 +629,9 @@ export declare namespace TemplateLiteralFinite {
621
629
  export declare namespace TemplateLiteralGenerator {
622
630
  function Generate(expression: TemplateLiteralParser.Expression): IterableIterator<string>;
623
631
  }
632
+ export declare namespace TemplateLiteralDslParser {
633
+ function Parse(template_dsl: string): TTemplateLiteralKind[];
634
+ }
624
635
  export declare class TypeBuilder {
625
636
  /** `[Utility]` Creates a schema without `static` and `params` types */
626
637
  protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
@@ -717,6 +728,8 @@ export declare class StandardTypeBuilder extends TypeBuilder {
717
728
  Rest<T extends TSchema>(schema: T): TRest<T>;
718
729
  /** `[Standard]` Creates a String type */
719
730
  String(options?: StringOptions): TString;
731
+ /** `[Experimental]` Creates a template literal type from dsl string */
732
+ TemplateLiteral<T extends string>(dsl: T, options?: SchemaOptions): TTemplateLiteralDslParser<T>;
720
733
  /** `[Standard]` Creates a template literal type */
721
734
  TemplateLiteral<T extends TTemplateLiteralKind[]>(kinds: [...T], options?: SchemaOptions): TTemplateLiteral<T>;
722
735
  /** `[Standard]` Creates a Tuple type */
package/typebox.js CHANGED
@@ -27,7 +27,7 @@ THE SOFTWARE.
27
27
 
28
28
  ---------------------------------------------------------------------------*/
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.Type = exports.StandardType = exports.ExtendedTypeBuilder = exports.StandardTypeBuilder = exports.TypeBuilder = exports.TemplateLiteralGenerator = exports.TemplateLiteralFinite = exports.TemplateLiteralParser = exports.TemplateLiteralParserError = exports.TemplateLiteralResolver = exports.TemplateLiteralPattern = exports.UnionResolver = exports.KeyArrayResolver = exports.KeyResolver = exports.ObjectMap = exports.IndexedAccessor = exports.TypeClone = exports.TypeExtends = exports.TypeExtendsResult = exports.ExtendsUndefined = exports.TypeGuard = exports.TypeGuardUnknownTypeError = exports.FormatRegistry = exports.TypeRegistry = exports.PatternStringExact = exports.PatternNumberExact = exports.PatternBooleanExact = exports.PatternString = exports.PatternNumber = exports.PatternBoolean = exports.Kind = exports.Hint = exports.Modifier = void 0;
30
+ exports.Type = exports.StandardType = exports.ExtendedTypeBuilder = exports.StandardTypeBuilder = exports.TypeBuilder = exports.TemplateLiteralDslParser = exports.TemplateLiteralGenerator = exports.TemplateLiteralFinite = exports.TemplateLiteralParser = exports.TemplateLiteralParserError = exports.TemplateLiteralResolver = exports.TemplateLiteralPattern = exports.UnionResolver = exports.KeyArrayResolver = exports.KeyResolver = exports.ObjectMap = exports.IndexedAccessor = exports.TypeClone = exports.TypeExtends = exports.TypeExtendsResult = exports.ExtendsUndefined = exports.TypeGuard = exports.TypeGuardUnknownTypeError = exports.FormatRegistry = exports.TypeRegistry = exports.PatternStringExact = exports.PatternNumberExact = exports.PatternBooleanExact = exports.PatternString = exports.PatternNumber = exports.PatternBoolean = exports.Kind = exports.Hint = exports.Modifier = void 0;
31
31
  // --------------------------------------------------------------------------
32
32
  // Symbols
33
33
  // --------------------------------------------------------------------------
@@ -1847,6 +1847,54 @@ var TemplateLiteralGenerator;
1847
1847
  }
1848
1848
  TemplateLiteralGenerator.Generate = Generate;
1849
1849
  })(TemplateLiteralGenerator = exports.TemplateLiteralGenerator || (exports.TemplateLiteralGenerator = {}));
1850
+ // ---------------------------------------------------------------------
1851
+ // TemplateLiteralDslParser
1852
+ // ---------------------------------------------------------------------
1853
+ var TemplateLiteralDslParser;
1854
+ (function (TemplateLiteralDslParser) {
1855
+ function* ParseUnion(template) {
1856
+ const trim = template.trim().replace(/"|'/g, '');
1857
+ if (trim === 'boolean')
1858
+ return yield exports.Type.Boolean();
1859
+ if (trim === 'number')
1860
+ return yield exports.Type.Number();
1861
+ if (trim === 'bigint')
1862
+ return yield exports.Type.BigInt();
1863
+ if (trim === 'string')
1864
+ return yield exports.Type.String();
1865
+ const literals = trim.split('|').map((literal) => exports.Type.Literal(literal.trim()));
1866
+ return yield literals.length === 0 ? exports.Type.Never() : literals.length === 1 ? literals[0] : exports.Type.Union(literals);
1867
+ }
1868
+ function* ParseTerminal(template) {
1869
+ if (template[1] !== '{') {
1870
+ const L = exports.Type.Literal('$');
1871
+ const R = ParseLiteral(template.slice(1));
1872
+ return yield* [L, ...R];
1873
+ }
1874
+ for (let i = 2; i < template.length; i++) {
1875
+ if (template[i] === '}') {
1876
+ const L = ParseUnion(template.slice(2, i));
1877
+ const R = ParseLiteral(template.slice(i + 1));
1878
+ return yield* [...L, ...R];
1879
+ }
1880
+ }
1881
+ yield exports.Type.Literal(template);
1882
+ }
1883
+ function* ParseLiteral(template) {
1884
+ for (let i = 0; i < template.length; i++) {
1885
+ if (template[i] === '$') {
1886
+ const L = exports.Type.Literal(template.slice(0, i));
1887
+ const R = ParseTerminal(template.slice(i));
1888
+ return yield* [L, ...R];
1889
+ }
1890
+ }
1891
+ yield exports.Type.Literal(template);
1892
+ }
1893
+ function Parse(template_dsl) {
1894
+ return [...ParseLiteral(template_dsl)];
1895
+ }
1896
+ TemplateLiteralDslParser.Parse = Parse;
1897
+ })(TemplateLiteralDslParser = exports.TemplateLiteralDslParser || (exports.TemplateLiteralDslParser = {}));
1850
1898
  // --------------------------------------------------------------------------
1851
1899
  // TypeOrdinal: Used for auto $id generation
1852
1900
  // --------------------------------------------------------------------------
@@ -2198,8 +2246,11 @@ class StandardTypeBuilder extends TypeBuilder {
2198
2246
  return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' });
2199
2247
  }
2200
2248
  /** `[Standard]` Creates a template literal type */
2201
- TemplateLiteral(kinds, options = {}) {
2202
- const pattern = TemplateLiteralPattern.Create(kinds);
2249
+ TemplateLiteral(unresolved, options = {}) {
2250
+ // prettier-ignore
2251
+ const pattern = (typeof unresolved === 'string')
2252
+ ? TemplateLiteralPattern.Create(TemplateLiteralDslParser.Parse(unresolved))
2253
+ : TemplateLiteralPattern.Create(unresolved);
2203
2254
  return this.Create({ ...options, [exports.Kind]: 'TemplateLiteral', type: 'string', pattern });
2204
2255
  }
2205
2256
  /** `[Standard]` Creates a Tuple type */