Skip to content

Commit

Permalink
Revision 0.32.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sinclairzx81 committed Nov 29, 2023
1 parent a061963 commit 98a8f5d
Show file tree
Hide file tree
Showing 46 changed files with 1,725 additions and 82 deletions.
15 changes: 1 addition & 14 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,8 @@
"exports": {
"./compiler": "./compiler/index.js",
"./errors": "./errors/index.js",
"./type": "./type/index.js",
"./system": "./system/index.js",
"./value/cast": "./value/cast/index.js",
"./value/check": "./value/check/index.js",
"./value/clone": "./value/clone/index.js",
"./value/convert": "./value/convert/index.js",
"./value/create": "./value/create/index.js",
"./value/delta": "./value/delta/index.js",
"./value/deref": "./value/deref/index.js",
"./value/equal": "./value/equal/index.js",
"./value/guard": "./value/guard/index.js",
"./value/hash": "./value/hash/index.js",
"./value/mutate": "./value/mutate/index.js",
"./value/pointer": "./value/pointer/index.js",
"./value/transform": "./value/transform/index.js",
"./type": "./type/index.js",
"./value": "./value/index.js",
".": "./index.js"
},
Expand Down
175 changes: 175 additions & 0 deletions src/value/clean/clean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 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 { IsString, IsObject, IsArray, IsUndefined } from '../guard/index'
import { TSchema as IsSchemaType } from '../../type/guard/type'
import { KeyOfStringResolve } from '../../type/keyof/keyof-string'
import { Check } from '../check/index'
import { Clone } from '../clone/index'
import { Deref } from '../deref/index'
import { Kind } from '../../type/symbols/index'

import type { TSchema } from '../../type/schema/index'
import type { TArray } from '../../type/array/index'
import type { TIntersect } from '../../type/intersect/index'
import type { TObject } from '../../type/object/index'
import type { TRecord } from '../../type/record/index'
import type { TRef } from '../../type/ref/index'
import type { TThis } from '../../type/recursive/index'
import type { TTuple } from '../../type/tuple/index'
import type { TUnion } from '../../type/union/index'

// --------------------------------------------------------------------------
// IsSchema
// --------------------------------------------------------------------------
function IsSchema(schema: unknown): schema is TSchema {
return IsSchemaType(schema)
}
// ----------------------------------------------------------------
// IsCheckable
// ----------------------------------------------------------------
function IsCheckable(schema: unknown): boolean {
return IsSchemaType(schema) && schema[Kind] !== 'Unsafe'
}
// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------
function TArray(schema: TArray, references: TSchema[], value: unknown): any {
if (!IsArray(value)) return value
return value.map((value) => Visit(schema.items, references, value))
}
function TIntersect(schema: TIntersect, references: TSchema[], value: unknown): any {
const unevaluatedProperties = schema.unevaluatedProperties as TSchema
const intersections = schema.allOf.map((schema) => Visit(schema, references, Clone(value)))
const composite = intersections.reduce((acc: any, value: any) => (IsObject(value) ? { ...acc, ...value } : value), {})
if (!IsObject(value) || !IsObject(composite) || !IsSchema(unevaluatedProperties)) return composite
const knownkeys = KeyOfStringResolve(schema) as string[]
for (const key of Object.getOwnPropertyNames(value)) {
if (knownkeys.includes(key)) continue
if (Check(unevaluatedProperties, references, value[key])) {
composite[key] = Visit(unevaluatedProperties, references, value[key])
}
}
return composite
}
function TObject(schema: TObject, references: TSchema[], value: unknown): any {
if (!IsObject(value) || IsArray(value)) return value // Check IsArray for AllowArrayObject configuration
const additionalProperties = schema.additionalProperties as TSchema
for (const key of Object.getOwnPropertyNames(value)) {
if (key in schema.properties) {
value[key] = Visit(schema.properties[key], references, value[key])
continue
}
if (IsSchema(additionalProperties) && Check(additionalProperties, references, value[key])) {
value[key] = Visit(additionalProperties, references, value[key])
continue
}
delete value[key]
}
return value
}
function TRecord(schema: TRecord<any, any>, references: TSchema[], value: unknown): any {
if (!IsObject(value)) return value
const additionalProperties = schema.additionalProperties as TSchema
const propertyKeys = Object.keys(value)
const [propertyKey, propertySchema] = Object.entries(schema.patternProperties)[0]
const propertyKeyTest = new RegExp(propertyKey)
for (const key of propertyKeys) {
if (propertyKeyTest.test(key)) {
value[key] = Visit(propertySchema, references, value[key])
continue
}
if (IsSchema(additionalProperties) && Check(additionalProperties, references, value[key])) {
value[key] = Visit(additionalProperties, references, value[key])
continue
}
delete value[key]
}
return value
}
function TRef(schema: TRef<any>, references: TSchema[], value: unknown): any {
return Visit(Deref(schema, references), references, value)
}
function TThis(schema: TThis, references: TSchema[], value: unknown): any {
return Visit(Deref(schema, references), references, value)
}
function TTuple(schema: TTuple, references: TSchema[], value: unknown): any {
if (!IsArray(value)) return value
if (IsUndefined(schema.items)) return []
const length = Math.min(value.length, schema.items.length)
for (let i = 0; i < length; i++) {
value[i] = Visit(schema.items[i], references, value[i])
}
// prettier-ignore
return value.length > length
? value.slice(0, length)
: value
}
function TUnion(schema: TUnion, references: TSchema[], value: unknown): any {
for (const inner of schema.anyOf) {
if (IsCheckable(inner) && Check(inner, value)) {
return Visit(inner, references, value)
}
}
return value
}
function Visit(schema: TSchema, references: TSchema[], value: unknown): unknown {
const references_ = IsString(schema.$id) ? [...references, schema] : references
const schema_ = schema as any
switch (schema_[Kind]) {
case 'Array':
return TArray(schema_, references_, value)
case 'Intersect':
return TIntersect(schema_, references_, value)
case 'Object':
return TObject(schema_, references_, value)
case 'Record':
return TRecord(schema_, references_, value)
case 'Ref':
return TRef(schema_, references_, value)
case 'This':
return TThis(schema_, references_, value)
case 'Tuple':
return TTuple(schema_, references_, value)
case 'Union':
return TUnion(schema_, references_, value)
default:
return value
}
}
// --------------------------------------------------------------------------
// Clean
// --------------------------------------------------------------------------
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean<T extends TSchema>(schema: T, references: TSchema[], value: unknown): unknown
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean<T extends TSchema>(schema: T): unknown
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean(...args: any[]) {
return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1])
}
29 changes: 29 additions & 0 deletions src/value/clean/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 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.
---------------------------------------------------------------------------*/

export * from './clean'
30 changes: 30 additions & 0 deletions src/value/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export { ValueError, ValueErrorType, ValueErrorIterator } from '../errors/index'
// ------------------------------------------------------------------
export { Cast, ValueCastArrayUniqueItemsTypeError, ValueCastNeverTypeError, ValueCastRecursiveTypeError, ValueCastUnknownTypeError } from './cast/index'
export { Check } from './check/index'
export { Clean } from './clean/index'
export { Clone } from './clone/index'
export { Convert, ValueConvertUnknownTypeError } from './convert/index'
export { Create, ValueCreateIntersectTypeError, ValueCreateNeverTypeError, ValueCreateNotTypeError, ValueCreateRecursiveInstantiationError, ValueCreateTempateLiteralTypeError, ValueCreateUnknownTypeError } from './create/index'
Expand All @@ -46,6 +47,35 @@ export { Mutate, type Mutable, ValueMutateInvalidRootMutationError, ValueMutateT
export { ValuePointer } from './pointer/index'
export { Decode, Encode, HasTransform, TransformDecodeCheckError, TransformDecodeError, TransformEncodeCheckError, TransformEncodeError } from './transform/index'
// ------------------------------------------------------------------
// Value Guards
// ------------------------------------------------------------------
export {
ArrayType,
HasPropertyKey,
IsArray,
IsAsyncIterator,
IsBigInt,
IsBoolean,
IsDate,
IsFunction,
IsInteger,
IsIterator,
IsNull,
IsNumber,
IsObject,
IsPlainObject,
IsPromise,
IsString,
IsSymbol,
IsTypedArray,
IsUint8Array,
IsUndefined,
IsValueType,
ObjectType,
TypedArrayType,
ValueType,
} from './guard/index'
// ------------------------------------------------------------------
// Value Namespace
// ------------------------------------------------------------------
import { Value } from './value/index'
Expand Down
9 changes: 9 additions & 0 deletions src/value/value/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { Cast as CastValue } from '../cast/index'
import { Clone as CloneValue } from '../clone/index'
import { Convert as ConvertValue } from '../convert/index'
import { Create as CreateValue } from '../create/index'
import { Clean as CleanValue } from '../clean/index'
import { Check as CheckValue } from '../check/index'
import { Default as DefaultValue } from '../default/index'
import { Diff as DiffValue, Patch as PatchValue, Edit } from '../delta/index'
Expand Down Expand Up @@ -66,6 +67,14 @@ export function Check<T extends TSchema>(schema: T, value: unknown): value is St
export function Check(...args: any[]) {
return CheckValue.apply(CheckValue, args as any)
}
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean<T extends TSchema>(schema: T, references: TSchema[], value: unknown): unknown
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean<T extends TSchema>(schema: T, value: unknown): unknown
/** Removes excess properties from the input value and returns the result. This function does not type check the input value and may return invalid results for invalid inputs. You should type check the result before use. */
export function Clean(...args: any[]) {
return CleanValue.apply(CleanValue, args as any)
}
/** Converts any type mismatched values to their target type if a reasonable conversion is possible */
export function Convert<T extends TSchema>(schema: T, references: TSchema[], value: unknown): unknown
/** Converts any type mismatched values to their target type if a reasonable conversion is possibl. */
Expand Down
11 changes: 11 additions & 0 deletions test/runtime/value/clean/any.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/Any', () => {
it('Should clean 1', () => {
const T = Type.Any()
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
21 changes: 21 additions & 0 deletions test/runtime/value/clean/array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/Array', () => {
it('Should clean 1', () => {
const T = Type.Any()
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
it('Should clean 2', () => {
const T = Type.Array(
Type.Object({
x: Type.Number(),
y: Type.Number(),
}),
)
const R = Value.Clean(T, [undefined, null, { x: 1 }, { x: 1, y: 2 }, { x: 1, y: 2, z: 3 }])
Assert.IsEqual(R, [undefined, null, { x: 1 }, { x: 1, y: 2 }, { x: 1, y: 2 }])
})
})
11 changes: 11 additions & 0 deletions test/runtime/value/clean/async-iterator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/AsyncIterator', () => {
it('Should clean 1', () => {
const T = Type.AsyncIterator(Type.Number())
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
11 changes: 11 additions & 0 deletions test/runtime/value/clean/bigint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/BigInt', () => {
it('Should clean 1', () => {
const T = Type.BigInt()
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
11 changes: 11 additions & 0 deletions test/runtime/value/clean/boolean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/Boolean', () => {
it('Should clean 1', () => {
const T = Type.Boolean()
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
11 changes: 11 additions & 0 deletions test/runtime/value/clean/composite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/Composite', () => {
it('Should clean 1', () => {
const T = Type.Composite([Type.Object({ x: Type.Number() }), Type.Object({ y: Type.Number() })])
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
11 changes: 11 additions & 0 deletions test/runtime/value/clean/constructor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/clean/Constructor', () => {
it('Should clean 1', () => {
const T = Type.Constructor([Type.Object({ x: Type.Number() }), Type.Object({ y: Type.Number() })], Type.Object({ z: Type.Number() }))
const R = Value.Clean(T, null)
Assert.IsEqual(R, null)
})
})
Loading

0 comments on commit 98a8f5d

Please sign in to comment.