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 e3e0abd commit a061963
Show file tree
Hide file tree
Showing 41 changed files with 1,307 additions and 0 deletions.
179 changes: 179 additions & 0 deletions src/value/default/default.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
/*--------------------------------------------------------------------------
@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 { Check } from '../check/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'

// ------------------------------------------------------------------
// ValueOrDefault
// ------------------------------------------------------------------
function ValueOrDefault(schema: TSchema, value: unknown) {
return !(value === undefined) || !('default' in schema) ? value : schema.default
}
// ------------------------------------------------------------------
// IsCheckable
// ------------------------------------------------------------------
function IsCheckable(schema: unknown): boolean {
return IsSchemaType(schema) && schema[Kind] !== 'Unsafe'
}
// ------------------------------------------------------------------
// IsDefaultSchema
// ------------------------------------------------------------------
function IsDefaultSchema(value: unknown): value is TSchema {
return IsSchemaType(value) && 'default' in value
}
// ------------------------------------------------------------------
// Types
// ------------------------------------------------------------------
function TArray(schema: TArray, references: TSchema[], value: unknown): any {
const defaulted = ValueOrDefault(schema, value)
if (!IsArray(defaulted)) return defaulted
for (let i = 0; i < defaulted.length; i++) {
defaulted[i] = Visit(schema.items, references, defaulted[i])
}
return defaulted
}
function TIntersect(schema: TIntersect, references: TSchema[], value: unknown): any {
const defaulted = ValueOrDefault(schema, value)
return schema.allOf.reduce((acc, schema) => {
const next = Visit(schema, references, defaulted)
return IsObject(next) ? { ...acc, ...next } : next
}, {})
}
function TObject(schema: TObject, references: TSchema[], value: unknown): any {
const defaulted = ValueOrDefault(schema, value)
if (!IsObject(defaulted)) return defaulted
const additionalPropertiesSchema = schema.additionalProperties as TSchema
const knownPropertyKeys = Object.getOwnPropertyNames(schema.properties)
// properties
for (const key of knownPropertyKeys) {
if (!IsDefaultSchema(schema.properties[key])) continue
defaulted[key] = Visit(schema.properties[key], references, defaulted[key])
}
// return if not additional properties
if (!IsDefaultSchema(additionalPropertiesSchema)) return defaulted
// additional properties
for (const key of Object.getOwnPropertyNames(defaulted)) {
if (knownPropertyKeys.includes(key)) continue
defaulted[key] = Visit(additionalPropertiesSchema, references, defaulted[key])
}
return defaulted
}
function TRecord(schema: TRecord<any, any>, references: TSchema[], value: unknown): any {
const defaulted = ValueOrDefault(schema, value)
if (!IsObject(defaulted)) return defaulted
const additionalPropertiesSchema = schema.additionalProperties as TSchema
const [propertyKeyPattern, propertySchema] = Object.entries(schema.patternProperties)[0]
const knownPropertyKey = new RegExp(propertyKeyPattern)
// properties
for (const key of Object.getOwnPropertyNames(defaulted)) {
if (!(knownPropertyKey.test(key) && IsDefaultSchema(propertySchema))) continue
defaulted[key] = Visit(propertySchema, references, defaulted[key])
}
// return if not additional properties
if (!IsDefaultSchema(additionalPropertiesSchema)) return defaulted
// additional properties
for (const key of Object.getOwnPropertyNames(defaulted)) {
if (knownPropertyKey.test(key)) continue
defaulted[key] = Visit(additionalPropertiesSchema, references, defaulted[key])
}
return defaulted
}
function TRef(schema: TRef<any>, references: TSchema[], value: unknown): any {
return Visit(Deref(schema, references), references, ValueOrDefault(schema, 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 {
const defaulted = ValueOrDefault(schema, value)
if (!IsArray(defaulted) || IsUndefined(schema.items)) return defaulted
const [items, max] = [schema.items!, Math.max(schema.items!.length, defaulted.length)]
for (let i = 0; i < max; i++) {
if (i < items.length) defaulted[i] = Visit(items[i], references, defaulted[i])
}
return defaulted
}
function TUnion(schema: TUnion, references: TSchema[], value: unknown): any {
const defaulted = ValueOrDefault(schema, value)
for (const inner of schema.anyOf) {
const result = Visit(inner, references, defaulted)
if (IsCheckable(inner) && Check(inner, result)) {
return result
}
}
return defaulted
}
function Visit(schema: TSchema, references: TSchema[], value: unknown): any {
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 ValueOrDefault(schema_, value)
}
}
// ------------------------------------------------------------------
// Default
// ------------------------------------------------------------------
/** Applies default annotations to missing values 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 Default<T extends TSchema>(schema: T, references: TSchema[], value: unknown): unknown
/** Applies default annotations to missing values 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 Default<T extends TSchema>(schema: T, value: unknown): unknown
/** Applies default annotations to missing values 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 Default(...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/default/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 './default'
1 change: 1 addition & 0 deletions src/value/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export { Check } from './check/index'
export { Clone } from './clone/index'
export { Convert, ValueConvertUnknownTypeError } from './convert/index'
export { Create, ValueCreateIntersectTypeError, ValueCreateNeverTypeError, ValueCreateNotTypeError, ValueCreateRecursiveInstantiationError, ValueCreateTempateLiteralTypeError, ValueCreateUnknownTypeError } from './create/index'
export { Default } from './default/index'
export { Diff, Patch, Edit, Delete, Insert, Update, ValueDeltaObjectWithSymbolKeyError, ValueDeltaUnableToDiffUnknownValue } from './delta/index'
export { Equal } from './equal/index'
export { Hash, ValueHashError } from './hash/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 @@ -35,6 +35,7 @@ import { Clone as CloneValue } from '../clone/index'
import { Convert as ConvertValue } from '../convert/index'
import { Create as CreateValue } from '../create/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'
import { Errors as ValueErrors, ValueErrorIterator } from '../../errors/index'

Expand Down Expand Up @@ -87,6 +88,14 @@ export function Decode(...args: any[]) {
if (!Check(schema, references, value)) throw new TransformDecodeCheckError(schema, value, Errors(schema, references, value).First()!)
return DecodeValue(schema, references, value)
}
/** Applies default annotations to missing values 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 Default<T extends TSchema>(schema: T, references: TSchema[], value: unknown): unknown
/** Applies default annotations to missing values 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 Default<T extends TSchema>(schema: T, value: unknown): unknown
/** Applies default annotations to missing values 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 Default(...args: any[]) {
return DefaultValue.apply(DefaultValue, args as any)
}
/** Encodes a value or throws if error */
export function Encode<T extends TSchema, R = StaticEncode<T>>(schema: T, references: TSchema[], value: unknown): R
/** Encodes a value or throws if error */
Expand Down
16 changes: 16 additions & 0 deletions test/runtime/value/default/any.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

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

describe('value/default/Array', () => {
it('Should use default', () => {
const T = Type.Array(Type.Number(), { default: 1 })
const R = Value.Default(T, undefined)
Assert.IsEqual(R, 1)
})
it('Should use value', () => {
const T = Type.Array(Type.Number(), { default: 1 })
const R = Value.Default(T, null)
Assert.IsEqual(R, null)
})
// ----------------------------------------------------------------
// Elements
// ----------------------------------------------------------------
it('Should use default on elements', () => {
const T = Type.Array(Type.Number({ default: 2 }))
const R = Value.Default(T, [1, undefined, 3])
Assert.IsEqual(R, [1, 2, 3])
})
})
16 changes: 16 additions & 0 deletions test/runtime/value/default/async-iterator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

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

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

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

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

describe('value/default/Constructor', () => {
it('Should use default', () => {
const T = Type.Constructor([], Type.Number(), { default: 1 })
const R = Value.Default(T, undefined)
Assert.IsEqual(R, 1)
})
it('Should use value', () => {
const T = Type.Constructor([], Type.Number(), { default: 1 })
const R = Value.Default(T, null)
Assert.IsEqual(R, null)
})
})
16 changes: 16 additions & 0 deletions test/runtime/value/default/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Assert } from '../../assert/index'

describe('value/default/Date', () => {
it('Should use default', () => {
const T = Type.Date({ default: 1 })
const R = Value.Default(T, undefined)
Assert.IsEqual(R, 1)
})
it('Should use value', () => {
const T = Type.Date({ default: 1 })
const R = Value.Default(T, null)
Assert.IsEqual(R, null)
})
})
Loading

0 comments on commit a061963

Please sign in to comment.