Skip to content

Commit 6d75219

Browse files
committed
Prototype: Options and RecursiveMap
1 parent 6d54d12 commit 6d75219

File tree

6 files changed

+304
-73
lines changed

6 files changed

+304
-73
lines changed

example/prototypes/index.ts

+2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ THE SOFTWARE.
2828

2929
export * from './discriminated-union'
3030
export * from './from-schema'
31+
export * from './options'
3132
export * from './partial-deep'
3233
export * from './union-enum'
3334
export * from './union-oneof'
35+
export * from './recursive-map'

example/prototypes/options.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*--------------------------------------------------------------------------
2+
3+
@sinclair/typebox/prototypes
4+
5+
The MIT License (MIT)
6+
7+
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]>
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
---------------------------------------------------------------------------*/
28+
29+
import { TSchema, CloneType } from '@sinclair/typebox'
30+
31+
// prettier-ignore
32+
export type TOptions<Type extends TSchema, Options extends Record<PropertyKey, unknown>> = (
33+
Type & Options
34+
)
35+
36+
/** `[Prototype]` Augments a schema with additional generics aware properties */
37+
// prettier-ignore
38+
export function Options<Type extends TSchema, Options extends Record<PropertyKey, unknown>>(type: Type, options: Options): TOptions<Type, Options> {
39+
return CloneType(type, options) as never
40+
}

example/prototypes/readme.md

+50
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,54 @@ const T = UnionOneOf([ // const T = {
6969

7070
type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
7171

72+
```
73+
74+
## Options
75+
76+
By default, TypeBox does not represent arbituary options as generics aware properties. However, there are cases where having options observable to the type system can be useful, for example conditionally mapping schematics based on custom metadata. The Options function makes user defined options generics aware.
77+
78+
```typescript
79+
import { Options } from './prototypes'
80+
81+
const A = Options(Type.String(), { foo: 1 }) // Options<TString, { foo: number }>
82+
83+
type A = typeof A extends { foo: number } ? true : false // true: foo property is observable to the type system
84+
```
85+
86+
## Recursive Map
87+
88+
The Recursive Map type enables deep structural remapping of a type and it's internal constituents. This type accepts a TSchema type and a mapping type function (expressed via HKT). The HKT is applied when traversing the type and it's interior. The mapping HKT can apply conditional tests to each visited type to remap into a new form. The following augments a schematic via Options, and conditionally remaps any schema with an default annotation to make it optional.
89+
90+
```typescript
91+
import { Type, TOptional, Static, TSchema } from '@sinclair/typebox'
92+
93+
import { TRecursiveMap, TMappingType, Options } from './prototypes'
94+
95+
// ------------------------------------------------------------------
96+
// StaticDefault
97+
// ------------------------------------------------------------------
98+
export interface StaticDefaultMapping extends TMappingType {
99+
output: (
100+
this['input'] extends TSchema // if input schematic contains an default
101+
? this['input'] extends { default: unknown } // annotation, remap it to be optional,
102+
? TOptional<this['input']> // otherwise just return the schema as is.
103+
: this['input']
104+
: this['input']
105+
)
106+
}
107+
export type StaticDefault<Type extends TSchema> = (
108+
Static<TRecursiveMap<Type, StaticDefaultMapping>>
109+
)
110+
111+
// ------------------------------------------------------------------
112+
// Usage
113+
// ------------------------------------------------------------------
114+
115+
const T = Type.Object({
116+
x: Options(Type.String(), { default: 'hello' }),
117+
y: Type.String()
118+
})
119+
120+
type T = StaticDefault<typeof T> // { x?: string, y: string }
121+
type S = Static<typeof T> // { x: string, y: string }
72122
```

example/prototypes/recursive-map.ts

+156
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/*--------------------------------------------------------------------------
2+
3+
@sinclair/typebox/prototypes
4+
5+
The MIT License (MIT)
6+
7+
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]>
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
---------------------------------------------------------------------------*/
28+
29+
import * as Types from '@sinclair/typebox'
30+
31+
// ------------------------------------------------------------------
32+
// Mapping: Functions and Type
33+
// ------------------------------------------------------------------
34+
export type TMappingFunction = (schema: Types.TSchema) => Types.TSchema
35+
36+
export interface TMappingType {
37+
input: unknown
38+
output: unknown
39+
}
40+
// ------------------------------------------------------------------
41+
// Record Parameters
42+
// ------------------------------------------------------------------
43+
function GetRecordPattern(record: Types.TRecord): string {
44+
return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0]
45+
}
46+
function GetRecordKey(record: Types.TRecord): Types.TSchema {
47+
const pattern = GetRecordPattern(record)
48+
return (
49+
pattern === Types.PatternStringExact ? Types.String() :
50+
pattern === Types.PatternNumberExact ? Types.Number() :
51+
pattern === Types.PatternBooleanExact ? Types.Boolean() :
52+
Types.String({ pattern })
53+
)
54+
}
55+
function GetRecordValue(record: Types.TRecord): Types.TSchema {
56+
return record.patternProperties[GetRecordPattern(record)]
57+
}
58+
// ------------------------------------------------------------------
59+
// Traversal
60+
// ------------------------------------------------------------------
61+
// prettier-ignore
62+
type TApply<Type extends Types.TSchema, Func extends TMappingType,
63+
Mapped = (Func & { input: Type })['output'],
64+
Result = Mapped extends Types.TSchema ? Mapped : never
65+
> = Result
66+
// prettier-ignore
67+
type TFromProperties<Properties extends Types.TProperties, Func extends TMappingType, Result extends Types.TProperties = {
68+
[Key in keyof Properties]: TRecursiveMap<Properties[Key], Func>
69+
}> = Result
70+
function FromProperties(properties: Types.TProperties, func: TMappingFunction): Types.TProperties {
71+
return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
72+
return {...result, [key]: RecursiveMap(properties[key], func) }
73+
}, {})
74+
}
75+
// prettier-ignore
76+
type TFromRest<Types extends Types.TSchema[], Func extends TMappingType, Result extends Types.TSchema[] = []> = (
77+
Types extends [infer Left extends Types.TSchema, ...infer Right extends Types.TSchema[]]
78+
? TFromRest<Right, Func, [...Result, TRecursiveMap<Left, Func>]>
79+
: Result
80+
)
81+
function FromRest(types: Types.TSchema[], func: TMappingFunction): Types.TSchema[] {
82+
return types.map(type => RecursiveMap(type, func))
83+
}
84+
// prettier-ignore
85+
type TFromType<Type extends Types.TSchema, Func extends TMappingType, Result extends Types.TSchema = (
86+
TApply<Type, Func>
87+
)> = Result
88+
function FromType(type: Types.TSchema, func: TMappingFunction): Types.TSchema {
89+
return func(type)
90+
}
91+
// ------------------------------------------------------------------
92+
// TRecursiveMap<Type, Mapping>
93+
// ------------------------------------------------------------------
94+
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */
95+
// prettier-ignore
96+
export type TRecursiveMap<Type extends Types.TSchema, Func extends TMappingType,
97+
// Maps the Exterior Type
98+
Exterior extends Types.TSchema = TFromType<Type, Func>,
99+
// Maps the Interior Parameterized Types
100+
Interior extends Types.TSchema = (
101+
Exterior extends Types.TConstructor<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TConstructor<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> :
102+
Exterior extends Types.TFunction<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TFunction<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> :
103+
Exterior extends Types.TIntersect<infer Types extends Types.TSchema[]> ? Types.TIntersect<TFromRest<Types, Func>> :
104+
Exterior extends Types.TUnion<infer Types extends Types.TSchema[]> ? Types.TUnion<TFromRest<Types, Func>> :
105+
Exterior extends Types.TTuple<infer Types extends Types.TSchema[]> ? Types.TTuple<TFromRest<Types, Func>> :
106+
Exterior extends Types.TArray<infer Type extends Types.TSchema> ? Types.TArray<TFromType<Type, Func>>:
107+
Exterior extends Types.TAsyncIterator<infer Type extends Types.TSchema> ? Types.TAsyncIterator<TFromType<Type, Func>> :
108+
Exterior extends Types.TIterator<infer Type extends Types.TSchema> ? Types.TIterator<TFromType<Type, Func>> :
109+
Exterior extends Types.TPromise<infer Type extends Types.TSchema> ? Types.TPromise<TFromType<Type, Func>> :
110+
Exterior extends Types.TObject<infer Properties extends Types.TProperties> ? Types.TObject<TFromProperties<Properties, Func>> :
111+
Exterior extends Types.TRecord<infer Key extends Types.TSchema, infer Value extends Types.TSchema> ? Types.TRecordOrObject<TFromType<Key, Func>, TFromType<Value, Func>> :
112+
Exterior
113+
),
114+
// Modifiers Derived from Exterior Type Mapping
115+
IsOptional extends number = Exterior extends Types.TOptional<Types.TSchema> ? 1 : 0,
116+
IsReadonly extends number = Exterior extends Types.TReadonly<Types.TSchema> ? 1 : 0,
117+
Result extends Types.TSchema = (
118+
[IsReadonly, IsOptional] extends [1, 1] ? Types.TReadonlyOptional<Interior> :
119+
[IsReadonly, IsOptional] extends [0, 1] ? Types.TOptional<Interior> :
120+
[IsReadonly, IsOptional] extends [1, 0] ? Types.TReadonly<Interior> :
121+
Interior
122+
)
123+
> = Result
124+
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */
125+
// prettier-ignore
126+
export function RecursiveMap(type: Types.TSchema, func: TMappingFunction): Types.TSchema {
127+
// Maps the Exterior Type
128+
const exterior = Types.CloneType(FromType(type, func), type)
129+
// Maps the Interior Parameterized Types
130+
const interior = (
131+
Types.KindGuard.IsConstructor(type) ? Types.Constructor(FromRest(type.parameters, func), FromType(type.returns, func), exterior) :
132+
Types.KindGuard.IsFunction(type) ? Types.Function(FromRest(type.parameters, func), FromType(type.returns, func), exterior) :
133+
Types.KindGuard.IsIntersect(type) ? Types.Intersect(FromRest(type.allOf, func), exterior) :
134+
Types.KindGuard.IsUnion(type) ? Types.Union(FromRest(type.anyOf, func), exterior) :
135+
Types.KindGuard.IsTuple(type) ? Types.Tuple(FromRest(type.items || [], func), exterior) :
136+
Types.KindGuard.IsArray(type) ? Types.Array(FromType(type.items, func), exterior) :
137+
Types.KindGuard.IsAsyncIterator(type) ? Types.AsyncIterator(FromType(type.items, func), exterior) :
138+
Types.KindGuard.IsIterator(type) ? Types.Iterator(FromType(type.items, func), exterior) :
139+
Types.KindGuard.IsPromise(type) ? Types.Promise(FromType(type.items, func), exterior) :
140+
Types.KindGuard.IsObject(type) ? Types.Object(FromProperties(type.properties, func), exterior) :
141+
Types.KindGuard.IsRecord(type) ? Types.Record(FromType(GetRecordKey(type), func), FromType(GetRecordValue(type), func), exterior) :
142+
Types.CloneType(exterior, exterior)
143+
)
144+
// Modifiers Derived from Exterior Type Mapping
145+
const isOptional = Types.KindGuard.IsOptional(exterior)
146+
const isReadonly = Types.KindGuard.IsOptional(exterior)
147+
return (
148+
isOptional && isReadonly ? Types.ReadonlyOptional(interior) :
149+
isOptional ? Types.Optional(interior) :
150+
isReadonly ? Types.Readonly(interior) :
151+
interior
152+
)
153+
}
154+
155+
156+

example/standard/readme.md

+16-50
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,33 @@
11
### Standard Schema
22

3-
This example is a reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox.
4-
5-
### Overview
6-
7-
This example provides a reference implementation for the Standard Schema specification. Despite the name, this specification is NOT focused on schematics. Rather, it defines a set of common TypeScript interfaces that libraries are expected to implement to be considered "Standard" for framework integration, as defined by the specification's authors.
8-
9-
The TypeBox project has some concerns about the Standard Schema specification, particularly regarding its avoidance to separate concerns between schematics and the logic used to validate those schematics. TypeBox does respect such separation for direct interoperability with industry standard validators as well as to allow intermediate processing of types (Compile). Additionally, augmenting schematics in the way proposed by Standard Schema would render Json Schema invalidated (which is a general concern for interoperability with Json Schema validation infrastructure, such as Ajv).
10-
11-
The Standard Schema specification is currently in its RFC stage. TypeBox advocates for renaming the specification to better reflect its purpose, such as "Common Interface for Type Integration." Additionally, the requirement for type libraries to adopt a common interface for integration warrants review. The reference project link provided below demonstrates an alternative approach that would enable integration of all type libraries (including those not immediately compatible with Standard Schema) to be integrated into frameworks (such as tRPC) without modification to a library's core structure.
12-
13-
[Type Adapters](https://github.com/sinclairzx81/type-adapters)
3+
Reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox.
144

155
### Example
166

17-
The Standard Schema function will augment TypeBox's Json Schema with runtime validation methods. These methods are assigned to the sub property `~standard`. Once a type is augmented, it should no longer be considered valid Json Schema.
7+
The following example augments a TypeBox schema with the required `~standard` interface. The `~standard` interface is applied via non-enumerable configuration enabling the schematics to continue to be used with strict compliant validators such as Ajv that would otherwise reject the non-standard `~standard` keyword.
188

199
```typescript
20-
import { Type } from '@sinclair/typebox'
2110
import { StandardSchema } from './standard'
11+
import { Type } from '@sinclair/typebox'
2212

23-
// The Standard Schema function will augment a TypeBox type with runtime validation
24-
// logic to validate / parse a value (as mandated by the Standard Schema interfaces).
25-
// Calling this function will render the json-schema schematics invalidated, specifically
26-
// the non-standard keyword `~standard` which ideally should be expressed as a non
27-
// serializable symbol (Ajv strict)
28-
29-
const A = StandardSchema(Type.Object({ // const A = {
30-
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
31-
y: Type.Number(), // type: 'object',
32-
z: Type.Number(), // properties: {
33-
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
34-
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
35-
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
13+
const T = StandardSchema(Type.Object({ // const A = {
14+
x: Type.Number(), // (non-enumerable) '~standard': {
15+
y: Type.Number(), // version: 1,
16+
z: Type.Number(), // vendor: 'TypeBox',
17+
})) // validate: [Function: validate]
3618
// },
37-
// required: [ 'x', 'y', 'z' ],
38-
// [Symbol(TypeBox.Kind)]: 'Object'
39-
// }
40-
41-
const R = A['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { value: { x: 1, y: 2, z: 3 }, issues: [] }
42-
```
43-
44-
### Ajv Strict
45-
46-
Applying Standard Schema to a TypeBox types renders them unusable in Ajv. The issue is due to the `~standard` property being un-assignable as a keyword (due to the leading `~`)
47-
48-
```typescript
49-
import Ajv from 'ajv'
50-
51-
const ajv = new Ajv().addKeyword('~standard') // cannot be defined as keyword.
52-
53-
const A = StandardSchema(Type.Object({ // const A = {
54-
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
55-
y: Type.Number(), // type: 'object',
56-
z: Type.Number(), // properties: {
57-
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
19+
// type: 'object',
20+
// properties: {
21+
// x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
5822
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
5923
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
6024
// },
6125
// required: [ 'x', 'y', 'z' ],
6226
// [Symbol(TypeBox.Kind)]: 'Object'
6327
// }
6428

65-
66-
ajv.validate(A, { x: 1, y: 2, z: 3 }) // Error: Keyword ~standard has invalid name
67-
```
29+
const R = T['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = {
30+
// value: { x: 1, y: 2, z: 3 },
31+
// issues: []
32+
// }
33+
```

0 commit comments

Comments
 (0)