Skip to content

Commit

Permalink
Prototype: Options and RecursiveMap
Browse files Browse the repository at this point in the history
  • Loading branch information
sinclairzx81 committed Jan 14, 2025
1 parent 6d54d12 commit 32a1a49
Show file tree
Hide file tree
Showing 6 changed files with 294 additions and 70 deletions.
2 changes: 2 additions & 0 deletions example/prototypes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ THE SOFTWARE.

export * from './discriminated-union'
export * from './from-schema'
export * from './options'
export * from './partial-deep'
export * from './union-enum'
export * from './union-oneof'
export * from './recursive-map'
40 changes: 40 additions & 0 deletions example/prototypes/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/prototypes
The MIT License (MIT)
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/

import { TSchema, CloneType } from '@sinclair/typebox'

// prettier-ignore
export type TOptions<Type extends TSchema, Options extends Record<PropertyKey, unknown>> = (
Type & Options
)

/** `[Prototype]` Augments a schema with additional generics aware properties */
// prettier-ignore
export function Options<Type extends TSchema, Options extends Record<PropertyKey, unknown>>(type: Type, options: Options): TOptions<Type, Options> {
return CloneType(type, options) as never
}
50 changes: 50 additions & 0 deletions example/prototypes/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,54 @@ const T = UnionOneOf([ // const T = {

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

```

## Options

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.

```typescript
import { Options } from './prototypes'

const A = Options(Type.String(), { foo: 1 }) // Options<TString, { foo: number }>

type A = typeof A extends { foo: number } ? true : false // true: foo property is observable to the type system
```
## Recursive Map
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.
```typescript
import { Type, TOptional, Static, TSchema } from '@sinclair/typebox'

import { TRecursiveMap, TMappingType, Options } from './prototypes'

// ------------------------------------------------------------------
// StaticDefault
// ------------------------------------------------------------------
export interface StaticDefaultMapping extends TMappingType {
output: (
this['input'] extends TSchema // if input schematic contains an default
? this['input'] extends { default: unknown } // annotation, remap it to be optional,
? TOptional<this['input']> // otherwise just return the schema as is.
: this['input']
: this['input']
)
}
export type StaticDefault<Type extends TSchema> = (
Static<TRecursiveMap<Type, StaticDefaultMapping>>
)

// ------------------------------------------------------------------
// Usage
// ------------------------------------------------------------------

const T = Type.Object({
x: Options(Type.String(), { default: 'hello' }),
y: Type.String()
})

type T = StaticDefault<typeof T> // { x?: string, y: string }
type S = Static<typeof T> // { x: string, y: string }
```
156 changes: 156 additions & 0 deletions example/prototypes/recursive-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/prototypes
The MIT License (MIT)
Copyright (c) 2017-2024 Haydn Paterson (sinclair) <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/

import * as Types from '@sinclair/typebox'

// ------------------------------------------------------------------
// Mapping: Functions and Type
// ------------------------------------------------------------------
export type TMappingFunction = (schema: Types.TSchema) => Types.TSchema

export interface TMappingType {
input: unknown
output: unknown
}
// ------------------------------------------------------------------
// Record Parameters
// ------------------------------------------------------------------
function GetRecordPattern(record: Types.TRecord): string {
return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0]
}
function GetRecordKey(record: Types.TRecord): Types.TSchema {
const pattern = GetRecordPattern(record)
return (
pattern === Types.PatternStringExact ? Types.String() :
pattern === Types.PatternNumberExact ? Types.Number() :
pattern === Types.PatternBooleanExact ? Types.Boolean() :
Types.String({ pattern })
)
}
function GetRecordValue(record: Types.TRecord): Types.TSchema {
return record.patternProperties[GetRecordPattern(record)]
}
// ------------------------------------------------------------------
// Traversal
// ------------------------------------------------------------------
// prettier-ignore
type TApply<Type extends Types.TSchema, Func extends TMappingType,
Mapped = (Func & { input: Type })['output'],
Result = Mapped extends Types.TSchema ? Mapped : never
> = Result
// prettier-ignore
type TFromProperties<Properties extends Types.TProperties, Func extends TMappingType, Result extends Types.TProperties = {
[Key in keyof Properties]: TRecursiveMap<Properties[Key], Func>
}> = Result
function FromProperties(properties: Types.TProperties, func: TMappingFunction): Types.TProperties {
return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
return {...result, [key]: RecursiveMap(properties[key], func) }
}, {})
}
// prettier-ignore
type TFromRest<Types extends Types.TSchema[], Func extends TMappingType, Result extends Types.TSchema[] = []> = (
Types extends [infer Left extends Types.TSchema, ...infer Right extends Types.TSchema[]]
? TFromRest<Right, Func, [...Result, TRecursiveMap<Left, Func>]>
: Result
)
function FromRest(types: Types.TSchema[], func: TMappingFunction): Types.TSchema[] {
return types.map(type => RecursiveMap(type, func))
}
// prettier-ignore
type TFromType<Type extends Types.TSchema, Func extends TMappingType, Result extends Types.TSchema = (
TApply<Type, Func>
)> = Result
function FromType(type: Types.TSchema, func: TMappingFunction): Types.TSchema {
return func(type)
}
// ------------------------------------------------------------------
// TRecursiveMap<Type, Mapping>
// ------------------------------------------------------------------
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */
// prettier-ignore
export type TRecursiveMap<Type extends Types.TSchema, Func extends TMappingType,
// Maps the Exterior Type
Exterior extends Types.TSchema = TFromType<Type, Func>,
// Maps the Interior Parameterized Types
Interior extends Types.TSchema = (
Exterior extends Types.TConstructor<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TConstructor<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> :
Exterior extends Types.TFunction<infer Parameters extends Types.TSchema[], infer ReturnType extends Types.TSchema> ? Types.TFunction<TFromRest<Parameters, Func>, TFromType<ReturnType, Func>> :
Exterior extends Types.TIntersect<infer Types extends Types.TSchema[]> ? Types.TIntersect<TFromRest<Types, Func>> :
Exterior extends Types.TUnion<infer Types extends Types.TSchema[]> ? Types.TUnion<TFromRest<Types, Func>> :
Exterior extends Types.TTuple<infer Types extends Types.TSchema[]> ? Types.TTuple<TFromRest<Types, Func>> :
Exterior extends Types.TArray<infer Type extends Types.TSchema> ? Types.TArray<TFromType<Type, Func>>:
Exterior extends Types.TAsyncIterator<infer Type extends Types.TSchema> ? Types.TAsyncIterator<TFromType<Type, Func>> :
Exterior extends Types.TIterator<infer Type extends Types.TSchema> ? Types.TIterator<TFromType<Type, Func>> :
Exterior extends Types.TPromise<infer Type extends Types.TSchema> ? Types.TPromise<TFromType<Type, Func>> :
Exterior extends Types.TObject<infer Properties extends Types.TProperties> ? Types.TObject<TFromProperties<Properties, Func>> :
Exterior extends Types.TRecord<infer Key extends Types.TSchema, infer Value extends Types.TSchema> ? Types.TRecordOrObject<TFromType<Key, Func>, TFromType<Value, Func>> :
Exterior
),
// Modifiers Derived from Exterior Type Mapping
IsOptional extends number = Exterior extends Types.TOptional<Types.TSchema> ? 1 : 0,
IsReadonly extends number = Exterior extends Types.TReadonly<Types.TSchema> ? 1 : 0,
Result extends Types.TSchema = (
[IsReadonly, IsOptional] extends [1, 1] ? Types.TReadonlyOptional<Interior> :
[IsReadonly, IsOptional] extends [0, 1] ? Types.TOptional<Interior> :
[IsReadonly, IsOptional] extends [1, 0] ? Types.TReadonly<Interior> :
Interior
)
> = Result
/** `[Prototype]` Applies a deep recursive map across the given type and sub types. */
// prettier-ignore
export function RecursiveMap(type: Types.TSchema, func: TMappingFunction): Types.TSchema {
// Maps the Exterior Type
const exterior = Types.CloneType(FromType(type, func), type)
// Maps the Interior Parameterized Types
const interior = (
Types.KindGuard.IsConstructor(type) ? Types.Constructor(FromRest(type.parameters, func), FromType(type.returns, func), exterior) :
Types.KindGuard.IsFunction(type) ? Types.Function(FromRest(type.parameters, func), FromType(type.returns, func), exterior) :
Types.KindGuard.IsIntersect(type) ? Types.Intersect(FromRest(type.allOf, func), exterior) :
Types.KindGuard.IsUnion(type) ? Types.Union(FromRest(type.anyOf, func), exterior) :
Types.KindGuard.IsTuple(type) ? Types.Tuple(FromRest(type.items || [], func), exterior) :
Types.KindGuard.IsArray(type) ? Types.Array(FromType(type.items, func), exterior) :
Types.KindGuard.IsAsyncIterator(type) ? Types.AsyncIterator(FromType(type.items, func), exterior) :
Types.KindGuard.IsIterator(type) ? Types.Iterator(FromType(type.items, func), exterior) :
Types.KindGuard.IsPromise(type) ? Types.Promise(FromType(type.items, func), exterior) :
Types.KindGuard.IsObject(type) ? Types.Object(FromProperties(type.properties, func), exterior) :
Types.KindGuard.IsRecord(type) ? Types.Record(FromType(GetRecordKey(type), func), FromType(GetRecordValue(type), func), exterior) :
Types.CloneType(exterior, exterior)
)
// Modifiers Derived from Exterior Type Mapping
const isOptional = Types.KindGuard.IsOptional(exterior)
const isReadonly = Types.KindGuard.IsOptional(exterior)
return (
isOptional && isReadonly ? Types.ReadonlyOptional(interior) :
isOptional ? Types.Optional(interior) :
isReadonly ? Types.Readonly(interior) :
interior
)
}



53 changes: 6 additions & 47 deletions example/standard/readme.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,17 @@
### Standard Schema

This example is a reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox.

### Overview

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.

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).

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.

[Type Adapters](https://github.com/sinclairzx81/type-adapters)
Reference implementation of [Standard Schema](https://github.com/standard-schema/standard-schema) for TypeBox.

### Example

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.
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 be used with strict compliant validators such as Ajv.

```typescript
import { Type } from '@sinclair/typebox'
import { StandardSchema } from './standard'

// The Standard Schema function will augment a TypeBox type with runtime validation
// logic to validate / parse a value (as mandated by the Standard Schema interfaces).
// Calling this function will render the json-schema schematics invalidated, specifically
// the non-standard keyword `~standard` which ideally should be expressed as a non
// serializable symbol (Ajv strict)

const A = StandardSchema(Type.Object({ // const A = {
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
const T = StandardSchema(Type.Object({ // const A = {
x: Type.Number(), // (non-enumerable) '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
y: Type.Number(), // type: 'object',
z: Type.Number(), // properties: {
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
Expand All @@ -38,30 +22,5 @@ const A = StandardSchema(Type.Object({ // const A = {
// [Symbol(TypeBox.Kind)]: 'Object'
// }

const R = A['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { value: { x: 1, y: 2, z: 3 }, issues: [] }
```

### Ajv Strict

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 `~`)

```typescript
import Ajv from 'ajv'

const ajv = new Ajv().addKeyword('~standard') // cannot be defined as keyword.

const A = StandardSchema(Type.Object({ // const A = {
x: Type.Number(), // '~standard': { version: 1, vendor: 'TypeBox', validate: [Function: validate] },
y: Type.Number(), // type: 'object',
z: Type.Number(), // properties: {
})) // x: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
// y: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' },
// z: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
// },
// required: [ 'x', 'y', 'z' ],
// [Symbol(TypeBox.Kind)]: 'Object'
// }


ajv.validate(A, { x: 1, y: 2, z: 3 }) // Error: Keyword ~standard has invalid name
```
const R = T['~standard'].validate({ x: 1, y: 2, z: 3 }) // const R = { value: { x: 1, y: 2, z: 3 }, issues: [] }
```
Loading

0 comments on commit 32a1a49

Please sign in to comment.