From 4e2158deb238b1fe958b0f78ad9e05f21e45041c Mon Sep 17 00:00:00 2001 From: sinclair Date: Mon, 11 Nov 2024 20:06:45 +0900 Subject: [PATCH] Standard Schema Reference --- example/standard/index.ts | 29 +++++++++++++++ example/standard/readme.md | 67 +++++++++++++++++++++++++++++++++++ example/standard/standard.ts | 68 ++++++++++++++++++++++++++++++++++++ 3 files changed, 164 insertions(+) create mode 100644 example/standard/index.ts create mode 100644 example/standard/readme.md create mode 100644 example/standard/standard.ts diff --git a/example/standard/index.ts b/example/standard/index.ts new file mode 100644 index 0000000..331f30a --- /dev/null +++ b/example/standard/index.ts @@ -0,0 +1,29 @@ +/*-------------------------------------------------------------------------- + +@sinclair/typebox/standard-schema + +The MIT License (MIT) + +Copyright (c) 2024 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. + +---------------------------------------------------------------------------*/ + +export * from './standard' \ No newline at end of file diff --git a/example/standard/readme.md b/example/standard/readme.md new file mode 100644 index 0000000..343d606 --- /dev/null +++ b/example/standard/readme.md @@ -0,0 +1,67 @@ +### 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) + +### 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. + +```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] }, + 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' + // } + +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 +``` diff --git a/example/standard/standard.ts b/example/standard/standard.ts new file mode 100644 index 0000000..b61dcbb --- /dev/null +++ b/example/standard/standard.ts @@ -0,0 +1,68 @@ +/*-------------------------------------------------------------------------- + +@sinclair/typebox/standard-schema + +The MIT License (MIT) + +Copyright (c) 2024 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 { AssertError, Value, ValueError } from '@sinclair/typebox/value' +import { TSchema, StaticDecode, CloneType } from '@sinclair/typebox' + +// ------------------------------------------------------------------ +// StandardSchema: Common +// ------------------------------------------------------------------ +interface StandardResult { + value: Output + issues: [ValueError[]] +} +interface StandardSchema { + readonly "~standard": StandardSchemaProps; +} + +interface StandardSchemaProps { + readonly version: 1; + readonly vendor: 'TypeBox'; + readonly validate: (value: unknown) => StandardResult; + readonly types?: undefined; +} +// ------------------------------------------------------------------ +// StandardSchema: TypeBox +// ------------------------------------------------------------------ +export type TStandardSchema> = Result +/** + * Augments a Json Schema with runtime validation logic required by StandardSchema. Wrapping a type in this way renders the type + * incompatible with the Json Schema specification. + */ +export function StandardSchema(schema: Type, references: TSchema[] = []): TStandardSchema> { + const validate = (value: unknown) => { + try { + return { value: Value.Parse(schema, references, value) } + } catch (error) { + const asserted = error instanceof AssertError ? error : undefined + return asserted ? { issues: [...asserted.Errors()] } : { issues: ['Unknown error']} + } + } + const standard = { version: 1, vendor: 'TypeBox', validate } + return CloneType(schema, { ['~standard']: standard }) as never +} \ No newline at end of file