From be5a202ad11a01452ea0bcc01c70a7b60f92c900 Mon Sep 17 00:00:00 2001 From: sinclairzx81 Date: Tue, 28 Jan 2025 18:14:33 +0900 Subject: [PATCH] Revision 0.8.6 (#15) * Parameterized Compile Types * Documentation | Tests * Infer Validator via Static * Version --- package-lock.json | 4 +- package.json | 4 +- readme.md | 24 ++++----- src/compile/compile.ts | 107 +++++++++++---------------------------- src/compile/validator.ts | 99 ++++++++++++++++++++++++++++++++++++ src/static.ts | 2 + src/typebox/typebox.ts | 6 +-- test/compile.ts | 39 ++++++++++++++ test/index.ts | 1 + 9 files changed, 189 insertions(+), 97 deletions(-) create mode 100644 src/compile/validator.ts create mode 100644 test/compile.ts diff --git a/package-lock.json b/package-lock.json index 6574ea6..177b0dd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@sinclair/typemap", - "version": "0.8.5", + "version": "0.8.6", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@sinclair/typemap", - "version": "0.8.5", + "version": "0.8.6", "license": "MIT", "devDependencies": { "@arethetypeswrong/cli": "^0.17.2", diff --git a/package.json b/package.json index d5ab2f0..1ac8878 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@sinclair/typemap", - "version": "0.8.5", - "description": "Unified Syntax and Type Compiler for Runtime Type Systems", + "version": "0.8.6", + "description": "Unified Syntax and Type Compiler for Runtime Types", "author": "sinclairzx81", "license": "MIT", "repository": { diff --git a/readme.md b/readme.md index bef3604..16cea1a 100644 --- a/readme.md +++ b/readme.md @@ -34,9 +34,9 @@ const result = Compile('string | null').Parse('Hello World') ## Overview -TypeMap is a syntax frontend and compiler backend for the [TypeBox](https://github.com/sinclairzx81/typebox), [Valibot](https://github.com/fabian-hiller/valibot) and [Zod](https://github.com/colinhacks/zod) type libraries. It provides a common TypeScript syntax for type construction, a runtime compiler for high-performance validation and enables types written in one library to be translated to another. +TypeMap is a syntax frontend and compiler backend for the [TypeBox](https://github.com/sinclairzx81/typebox), [Valibot](https://github.com/fabian-hiller/valibot) and [Zod](https://github.com/colinhacks/zod) type libraries. It provides a common TypeScript syntax for type construction, a runtime compiler for high-performance validation and provides type translation from one library to another. -TypeMap is built as an advanced adapter and integration system for the TypeBox project. It is designed to integrate and accelerate remote libraries by mapping them to TypeBox and Json Schema compatible infrastructure as well as allowing TypeBox to integrate on Zod specific infrastructure via reverse type mapping. This library is also written to offer high-performance validation for systems that orientate around the [Standard Schema](https://github.com/standard-schema/standard-schema) TypeScript interface. +TypeMap is built as an advanced adapter and integration mechanism for the TypeBox project. It is designed to integrate and accelerate remote libraries by mapping them to TypeBox and Json Schema compatible infrastructure as well as allowing TypeBox to integrate on Zod specific infrastructure via reverse type mapping. This library is also written to offer high-performance validation for systems that orientate around the [Standard Schema](https://github.com/standard-schema/standard-schema) TypeScript interface. License: MIT @@ -147,7 +147,7 @@ const R = C.Check({ // Iterations: 10_000_000 ## Mapping -TypeMap is principally a runtime mapping library used for type translation. It provides a mapping function for each translatable library which is used to translate types and schematics into that library. If no translation is possible, these functions return a never representation specific to the library being mapped. +TypeMap is principally a runtime mapping library used for type translation. It provides a mapping function per translatable library which is used to map remote types and schematics into that library. If no translation is possible, these functions return a never representation specific to the library being mapped. ### TypeBox @@ -174,7 +174,6 @@ const S = Valibot('string[]') // const S: v.ArraySchema<.. const T = Valibot(t.Number()) // const T: v.NumberSchema (TypeBox) const V = Valibot(v.string()) // const V: v.StringSchema (Valibot) const Z = Valibot(z.boolean()) // const Z: v.BooleanSchema (Zod) - ``` ### Zod @@ -188,7 +187,6 @@ const S = Zod('string[]') // const S: z.ZodArray<...> const T = Zod(t.Number()) // const T: z.ZodNumber (TypeBox) const V = Zod(v.string()) // const V: z.ZodString (Valibot) const Z = Zod(z.boolean()) // const Z: z.ZodBoolean (Zod) - ``` ## Syntax @@ -289,26 +287,26 @@ type S = Static // string[] ## Compile -Use Compile to build Zod and Valibot on TypeBox validation infrastructure. ([Example](https://www.typescriptlang.org/play/?moduleResolution=99&module=199#code/JYWwDg9gTgLgBAbzgYQuYAbApgGjgLQgBM4BfOAMyjTgHIABAZ2ADsBjDAQ2CgHoYAnmCwhOYWgCgJvXijRhMWOABUhWKWwgtG8AGpwAvHPTYAFISKmABgglx7ADwBccFgFcQAIyxQcd+wIu7l4+fvZwAF5BHt5QEqRWAJSJUjIqagCyYi7IABZYbADWcABibuwwwFpwpiWcOikSmtrwAEoAjIZwugB0eQWFpkjOcO14gXAATHhRcADMZI1pAMownCxEnFAky2z5oi66nBjAmzBKZRVVLDV1DRpaOnCtk126ANq0AH4665vbtAAuj0AG7HU6cc5DOAjMZwCbTSIuBakRJAA)) +Use the `Compile` function to compile Zod and Valibot on TypeBox validation infrastructure. ([Example](https://www.typescriptlang.org/play/?moduleResolution=99&module=199#code/JYWwDg9gTgLgBAbzgYQuYAbApgGjgLQgBM4BfOAMyjTgHIABAZ2ADsBjDAQ2CgHoYAnmCwhOYWgCgJvXijRhMWOABUhWKWwgtG8AGpwAvHPTYAFISKmABgglx7ADwBccFgFcQAIyxQcd+wIu7l4+fvZwAF5BHt5QEqRWAJSJUjIqagCyYi7IABZYbADWcABibuwwwFpwpiWcOikSmtrwAEoAjIZwugB0eQWFpkjOcO14gXAATHhRcADMZI1pAMownCxEnFAky2z5oi66nBjAmzBKZRVVLDV1DRpaOnCtk126ANq0AH4665vbtAAuj0AG7HU6cc5DOAjMZwCbTSIuBakRJAA)) ```typescript import { Compile, Zod } from '@sinclair/typemap' -// Compile Type +// Compile Validator From Zod -const V = Compile(Zod(`{ +const validator = Compile(Zod(`{ x: number, y: number, z: number }`)) -// TypeMap: Check Function (Fast) +const R1 = validator.Check({ x: 1, y: 2, z: 3 }) -const R1 = V.Check({ x: 1, y: 2, z: 3 }) +// Standard Schema +// +// ... which should have been named 'Standard Validator' -// Standard Schema: Validate Function (Fast) - -const R2 = V['~standard'].validate({ x: 1, y: 2, z: 3 }) +const R2 = validator['~standard'].validate({ x: 1, y: 2, z: 3 }) ``` ## Benchmark diff --git a/src/compile/compile.ts b/src/compile/compile.ts index 14dfd94..f6a1fc3 100644 --- a/src/compile/compile.ts +++ b/src/compile/compile.ts @@ -26,79 +26,17 @@ THE SOFTWARE. ---------------------------------------------------------------------------*/ -import { TypeCompiler, TypeCheck, ValueErrorIterator } from '@sinclair/typebox/compiler' +import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler' import { Value } from '@sinclair/typebox/value' -import { TypeBox, TTypeBox } from '../typebox/typebox' import { IsEvalSupported } from './environment' -import { StandardSchemaV1 } from './standard' -import * as t from '@sinclair/typebox' +import { Validator } from './validator' + +import { type TTypeBox, TypeBox } from '../typebox/typebox' +import { type TSyntaxOptions } from '../options' +import { type TParameter } from '../typebox/typebox' +import * as t from '@sinclair/typebox' +import * as g from '../guard' -// ------------------------------------------------------------------ -// StandardSchemaProps -// ------------------------------------------------------------------ -export class StandardSchemaProps implements StandardSchemaV1.Props> { - readonly #check: TypeCheck - constructor(check: TypeCheck) { - this.#check = check - } - // ---------------------------------------------------------------- - // StandardSchemaV1.Props> - // ---------------------------------------------------------------- - public get vendor(): '@sinclair/typemap' { - return '@sinclair/typemap' - } - public get version(): 1 { - return 1 - } - public get types(): { input: Type; output: t.Static } { - return { input: this.#check.Schema(), output: null } - } - public validate(value: unknown): StandardSchemaV1.Result> { - return this.#check.Check(value) ? this.#createValue(value) : this.#createIssues(value) - } - // ---------------------------------------------------------------- - // Internal - // ---------------------------------------------------------------- - #createIssues(value: unknown) { - const errors = [...Value.Errors(this.#check.Schema(), value)] - const issues: StandardSchemaV1.Issue[] = errors.map((error) => ({ ...error, path: [error.path] })) - return { issues } - } - #createValue(value: unknown) { - return { value } - } -} -// ------------------------------------------------------------------ -// Validator -// ------------------------------------------------------------------ -export class Validator implements StandardSchemaV1> { - private readonly _standard: StandardSchemaProps - private readonly _check: TypeCheck - constructor(check: TypeCheck) { - this._standard = new StandardSchemaProps(check) - this._check = check - } - /** Standard Schema Interface */ - public get ['~standard'](): StandardSchemaProps { - return this._standard - } - /** Returns the code used by this validator. */ - public Code(): string { - return this._check.Code() - } - /** Parses this value. Do not use this function for high throughput validation */ - public Parse(value: unknown): t.StaticDecode { - return Value.Parse(this._check.Schema(), value) - } - /** Checks if this value matches the type */ - public Check(value: unknown): value is t.Static { - return this._check.Check(value) - } - /** Returns errors for this value */ - public Errors(value: unknown): ValueErrorIterator { - return this._check.Errors(value) - } -} // ------------------------------------------------------------------ // CompileDynamic // ------------------------------------------------------------------ @@ -107,17 +45,32 @@ function CompileDynamic(type: Type, references: t.TSchem return new TypeCheck(type, references, value => Value.Check(type, references, value), TypeCompiler.Code(type, references)) } // ------------------------------------------------------------------ +// ResolveTypeCheck +// ------------------------------------------------------------------ +function ResolveTypeCheck(type: Type): TypeCheck { + return IsEvalSupported() ? TypeCompiler.Compile(type) : CompileDynamic(type) +} +// ------------------------------------------------------------------ // Compile // ------------------------------------------------------------------ /** Compiles a type for high performance validation */ // prettier-ignore -type TCompile, -> = Validator +type TCompile, + Result = Validator +> = Result + +/** Compiles a type for high performance validation */ +export function Compile(parameter: Parameter, type: Type, options?: TSyntaxOptions): TCompile +/** Compiles a type for high performance validation */ +export function Compile(type: Type, options?: TSyntaxOptions): TCompile<{}, Type> +/** Compiles a type for high performance validation */ +export function Compile(type: Type, options?: TSyntaxOptions): TCompile<{}, Type> /** Compiles a type for high performance validation */ // prettier-ignore -export function Compile(type: Type): TCompile { - const schema = TypeBox(type) - const check = IsEvalSupported() ? TypeCompiler.Compile(schema) : CompileDynamic(schema) - return new Validator(check) +export function Compile(...args: any[]): never { + const [parameter, type, options] = g.Signature(args) + const schema = t.ValueGuard.IsString(type) ? TypeBox(parameter, type, options) : TypeBox(type) + const check = ResolveTypeCheck(schema) + return new Validator(check) as never } diff --git a/src/compile/validator.ts b/src/compile/validator.ts new file mode 100644 index 0000000..6269960 --- /dev/null +++ b/src/compile/validator.ts @@ -0,0 +1,99 @@ +/*-------------------------------------------------------------------------- + +@sinclair/typemap + +The MIT License (MIT) + +Copyright (c) 2024-2025 Haydn Paterson (sinclair) + +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 { TypeCheck, ValueErrorIterator } from '@sinclair/typebox/compiler' +import { Value } from '@sinclair/typebox/value' +import { StandardSchemaV1 } from './standard' +import * as t from '@sinclair/typebox' + +// ------------------------------------------------------------------ +// StandardSchemaProps +// ------------------------------------------------------------------ +export class StandardSchemaProps implements StandardSchemaV1.Props> { + private readonly _check: TypeCheck + constructor(check: TypeCheck) { + this._check = check + } + // ---------------------------------------------------------------- + // StandardSchemaV1.Props> + // ---------------------------------------------------------------- + public get vendor(): '@sinclair/typemap' { + return '@sinclair/typemap' + } + public get version(): 1 { + return 1 + } + public get types(): { input: Type; output: t.Static } { + return { input: this._check.Schema(), output: null } + } + public validate(value: unknown): StandardSchemaV1.Result> { + return this._check.Check(value) ? this._createValue(value) : this._createIssues(value) + } + // ---------------------------------------------------------------- + // Internal + // ---------------------------------------------------------------- + private _createIssues(value: unknown) { + const errors = [...Value.Errors(this._check.Schema(), value)] + const issues: StandardSchemaV1.Issue[] = errors.map((error) => ({ ...error, path: [error.path] })) + return { issues } + } + private _createValue(value: unknown) { + return { value } + } +} +// ------------------------------------------------------------------ +// Validator +// ------------------------------------------------------------------ +export class Validator implements StandardSchemaV1> { + private readonly _standard: StandardSchemaProps + private readonly _check: TypeCheck + constructor(check: TypeCheck) { + this._standard = new StandardSchemaProps(check) + this._check = check + } + /** Standard Schema Interface */ + public get ['~standard'](): StandardSchemaProps { + return this._standard + } + /** Returns the code used by this validator. */ + public Code(): string { + return this._check.Code() + } + /** Parses this value. Do not use this function for high throughput validation */ + public Parse(value: unknown): t.StaticDecode { + return Value.Parse(this._check.Schema(), value) + } + /** Checks if this value matches the type */ + public Check(value: unknown): value is t.Static { + return this._check.Check(value) + } + /** Returns errors for this value */ + public Errors(value: unknown): ValueErrorIterator { + return this._check.Errors(value) + } +} diff --git a/src/static.ts b/src/static.ts index 95e6cf6..d44835a 100644 --- a/src/static.ts +++ b/src/static.ts @@ -26,6 +26,7 @@ THE SOFTWARE. ---------------------------------------------------------------------------*/ +import { Validator } from './compile/validator' import * as s from '@sinclair/typebox/syntax' import * as t from '@sinclair/typebox' import * as v from 'valibot' @@ -37,6 +38,7 @@ type BaseSchema = v.BaseSchema> // prettier-ignore export type Static = ( Type extends string ? s.StaticParseAsType<{}, Type> : + Type extends Validator ? t.Static : Type extends t.TSchema ? t.Static : Type extends BaseSchema ? v.InferInput : Type extends z.ZodTypeAny ? z.infer : diff --git a/src/typebox/typebox.ts b/src/typebox/typebox.ts index bdaec9f..d3cf2e6 100644 --- a/src/typebox/typebox.ts +++ b/src/typebox/typebox.ts @@ -81,13 +81,13 @@ export function TypeBox(type: Type, options?: TSyn // prettier-ignore export function TypeBox(...args: any[]): never { const [parameter, type, options] = g.Signature(args) - return t.CloneType( + return ( t.ValueGuard.IsString(type) ? TypeBoxFromSyntax(ContextFromParameter(parameter), type, options) : g.IsTypeBox(type) ? TypeBoxFromTypeBox(type) : g.IsValibot(type) ? TypeBoxFromValibot(type) : g.IsZod(type) ? TypeBoxFromZod(type) : - t.Never(), - options) as never + t.Never() + ) as never } /** Creates a TypeBox type from Syntax or another Type */ diff --git a/test/compile.ts b/test/compile.ts new file mode 100644 index 0000000..e4ba0c8 --- /dev/null +++ b/test/compile.ts @@ -0,0 +1,39 @@ +import { Assert } from './assert' +import { TypeBox, Valibot, Zod, Compile } from '@sinclair/typemap' + +describe('Compile', () => { + it('Should compile Syntax', () => { + const C = Compile('123') + Assert.IsTrue(C.Check(123)) + }) + it('Should compile Syntax (Parameterized)', () => { + const C = Compile({ T: TypeBox('123') }, 'T') + Assert.IsTrue(C.Check(123)) + }) + it('Should compile TypeBox', () => { + const C = Compile(TypeBox('123')) + Assert.IsTrue(C.Check(123)) + }) + it('Should compile TypeBox (Parameterized)', () => { + const C = Compile({ T: TypeBox('123') }, 'T') + Assert.IsTrue(C.Check(123)) + }) + + it('Should compile Valibot', () => { + const C = Compile(Valibot('123')) + Assert.IsTrue(C.Check(123)) + }) + it('Should compile Valibot (Parameterized)', () => { + const C = Compile({ T: Valibot('123') }, 'T') + Assert.IsTrue(C.Check(123)) + }) + + it('Should compile Zod', () => { + const C = Compile(Zod('123')) + Assert.IsTrue(C.Check(123)) + }) + it('Should compile Zod (Parameterized)', () => { + const C = Compile({ T: Zod('123') }, 'T') + Assert.IsTrue(C.Check(123)) + }) +}) diff --git a/test/index.ts b/test/index.ts index 58b4c2c..a6814d5 100644 --- a/test/index.ts +++ b/test/index.ts @@ -1,3 +1,4 @@ +import './compile' import './options' import './parameters' import './typebox-from-zod'