Socket
Socket
Sign inDemoInstall

@sinclair/typebox

Package Overview
Dependencies
Maintainers
1
Versions
326
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sinclair/typebox - npm Package Compare versions

Comparing version 0.24.7 to 0.24.8

value/cast.d.ts

10

compiler/compiler.d.ts

@@ -1,2 +0,2 @@

import { TypeError } from './errors';
import { ValueError } from '../value/errors';
import * as Types from '../typebox';

@@ -10,6 +10,6 @@ export declare type CheckFunction = (value: unknown) => boolean;

constructor(schema: T, additional: Types.TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated validation code used to validate this type */
/** Returns the generated validation code used to validate this type. */
Code(): string;
/** Returns an iterator for each type error found in this value */
Errors(value: unknown): Generator<TypeError>;
/** Returns an iterator for each error in this value. */
Errors(value: unknown): IterableIterator<ValueError>;
/** Returns true if the value matches the given type. */

@@ -20,3 +20,3 @@ Check(value: unknown): value is Types.Static<T>;

/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile<T extends Types.TSchema>(schema: T, additional?: Types.TSchema[]): TypeCheck<T>;
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
}

@@ -31,3 +31,3 @@ "use strict";

exports.TypeCompiler = exports.TypeCheck = void 0;
const errors_1 = require("./errors");
const errors_1 = require("../value/errors");
const Types = require("../typebox");

@@ -48,9 +48,9 @@ // -------------------------------------------------------------------

}
/** Returns the generated validation code used to validate this type */
/** Returns the generated validation code used to validate this type. */
Code() {
return this.code;
}
/** Returns an iterator for each type error found in this value */
/** Returns an iterator for each error in this value. */
Errors(value) {
return errors_1.TypeErrors.Errors(this.schema, this.additional, value);
return errors_1.ValueErrors.Errors(this.schema, this.additional, value);
}

@@ -71,61 +71,61 @@ /** Returns true if the value matches the given type. */

// -------------------------------------------------------------------
function* Any(schema, path) {
function* Any(schema, value) {
yield '(true)';
}
function* Array(schema, path) {
function* Array(schema, value) {
const expr = [...Visit(schema.items, `value`)].map((condition) => condition).join(' && ');
yield `(Array.isArray(${path}) && ${path}.every(value => ${expr}))`;
yield `(Array.isArray(${value}) && ${value}.every(value => ${expr}))`;
}
function* Boolean(schema, path) {
yield `(typeof ${path} === 'boolean')`;
function* Boolean(schema, value) {
yield `(typeof ${value} === 'boolean')`;
}
function* Constructor(schema, path) {
yield* Visit(schema.yields, path);
function* Constructor(schema, value) {
yield* Visit(schema.returns, value);
}
function* Function(schema, path) {
yield `(typeof ${path} === 'function')`;
function* Function(schema, value) {
yield `(typeof ${value} === 'function')`;
}
function* Integer(schema, path) {
yield `(typeof ${path} === 'number' && Number.isInteger(${path}))`;
function* Integer(schema, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (schema.multipleOf)
yield `(${path} % ${schema.multipleOf} === 0)`;
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum)
yield `(${path} > ${schema.exclusiveMinimum})`;
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum)
yield `(${path} < ${schema.exclusiveMaximum})`;
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum)
yield `(${path} >= ${schema.minimum})`;
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum)
yield `(${path} <= ${schema.maximum})`;
yield `(${value} <= ${schema.maximum})`;
}
function* Literal(schema, path) {
function* Literal(schema, value) {
if (typeof schema.const === 'string') {
yield `(${path} === '${schema.const}')`;
yield `(${value} === '${schema.const}')`;
}
else {
yield `(${path} === ${schema.const})`;
yield `(${value} === ${schema.const})`;
}
}
function* Null(schema, path) {
yield `(${path} === null)`;
function* Null(schema, value) {
yield `(${value} === null)`;
}
function* Number(schema, path) {
yield `(typeof ${path} === 'number')`;
function* Number(schema, value) {
yield `(typeof ${value} === 'number')`;
if (schema.multipleOf)
yield `(${path} % ${schema.multipleOf} === 0)`;
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum)
yield `(${path} > ${schema.exclusiveMinimum})`;
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum)
yield `(${path} < ${schema.exclusiveMaximum})`;
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum)
yield `(${path} >= ${schema.minimum})`;
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum)
yield `(${path} <= ${schema.maximum})`;
yield `(${value} <= ${schema.maximum})`;
}
function* Object(schema, path) {
yield `(typeof ${path} === 'object' && ${path} !== null && !Array.isArray(${path}))`;
function* Object(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
if (schema.minProperties !== undefined)
yield `(Object.keys(${path}).length >= ${schema.minProperties})`;
yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
if (schema.maxProperties !== undefined)
yield `(Object.keys(${path}).length <= ${schema.maxProperties})`;
yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
const propertyKeys = globalThis.Object.keys(schema.properties);

@@ -138,7 +138,7 @@ if (schema.additionalProperties === false) {

if (schema.required && schema.required.length === propertyKeys.length) {
yield `(Object.keys(${path}).length === ${propertyKeys.length})`;
yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
}
else {
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${path}).every(key => ${keys}.includes(key)))`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
}

@@ -149,22 +149,22 @@ }

if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, `${path}.${propertyKey}`);
yield* Visit(propertySchema, `${value}.${propertyKey}`);
}
else {
const expr = [...Visit(propertySchema, `${path}.${propertyKey}`)].map((condition) => condition).join(' && ');
yield `(${path}.${propertyKey} === undefined ? true : (${expr}))`;
const expr = [...Visit(propertySchema, `${value}.${propertyKey}`)].map((condition) => condition).join(' && ');
yield `(${value}.${propertyKey} === undefined ? true : (${expr}))`;
}
}
}
function* Promise(schema, path) {
yield `(typeof value === 'object' && typeof ${path}.then === 'function')`;
function* Promise(schema, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
}
function* Record(schema, path) {
yield `(typeof ${path} === 'object' && ${path} !== null && !Array.isArray(${path}))`;
function* Record(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`const local = new RegExp(/${keyPattern}/)`);
yield `(Object.keys(${path}).every(key => ${local}.test(key)))`;
yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
const expr = [...Visit(valueSchema, 'value')].map((condition) => condition).join(' && ');
yield `(Object.values(${path}).every(value => ${expr}))`;
yield `(Object.values(${value}).every(value => ${expr}))`;
}
function* Ref(schema, path) {
function* Ref(schema, value) {
// reference: referenced schemas can originate from either additional

@@ -182,46 +182,46 @@ // schemas or inline in the schema itself. Ideally the recursive

const func = CreateFunctionName(schema.$ref);
yield `(${func}(${path}))`;
yield `(${func}(${value}))`;
}
function* Self(schema, path) {
function* Self(schema, value) {
const func = CreateFunctionName(schema.$ref);
yield `(${func}(${path}))`;
yield `(${func}(${value}))`;
}
function* String(schema, path) {
yield `(typeof ${path} === 'string')`;
function* String(schema, value) {
yield `(typeof ${value} === 'string')`;
if (schema.pattern !== undefined) {
const local = PushLocal(`const local = new RegExp('${schema.pattern}');`);
yield `(${local}.test(${path}))`;
yield `(${local}.test(${value}))`;
}
}
function* Tuple(schema, path) {
yield `(Array.isArray(${path}))`;
function* Tuple(schema, value) {
yield `(Array.isArray(${value}))`;
if (schema.items === undefined)
return yield `(${path}.length === 0)`;
yield `(${path}.length === ${schema.maxItems})`;
return yield `(${value}.length === 0)`;
yield `(${value}.length === ${schema.maxItems})`;
for (let i = 0; i < schema.items.length; i++) {
const expr = [...Visit(schema.items[i], `${path}[${i}]`)].map((condition) => condition).join(' && ');
const expr = [...Visit(schema.items[i], `${value}[${i}]`)].map((condition) => condition).join(' && ');
yield `(${expr})`;
}
}
function* Undefined(schema, path) {
yield `${path} === undefined`;
function* Undefined(schema, value) {
yield `(${value} === undefined)`;
}
function* Union(schema, path) {
const exprs = schema.anyOf.map((schema) => [...Visit(schema, path)].map((condition) => condition).join(' && '));
function* Union(schema, value) {
const exprs = schema.anyOf.map((schema) => [...Visit(schema, value)].map((condition) => condition).join(' && '));
yield `(${exprs.join(' || ')})`;
}
function* Uint8Array(schema, path) {
yield `(${path} instanceof Uint8Array)`;
function* Uint8Array(schema, value) {
yield `(${value} instanceof Uint8Array)`;
if (schema.maxByteLength)
yield `(${path}.length <= ${schema.maxByteLength})`;
yield `(${value}.length <= ${schema.maxByteLength})`;
if (schema.minByteLength)
yield `(${path}.length >= ${schema.minByteLength})`;
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* Unknown(schema, path) {
function* Unknown(schema, value) {
yield '(true)';
}
function* Void(schema, path) {
yield `(${path} === null)`;
function* Void(schema, value) {
yield `(${value} === null)`;
}
function* Visit(schema, path) {
function* Visit(schema, value) {
// reference: referenced schemas can originate from either additional

@@ -236,3 +236,3 @@ // schemas or inline in the schema itself. Ideally the recursive

PushLocal(body);
yield `(${name}(${path}))`;
yield `(${name}(${value}))`;
return;

@@ -243,43 +243,43 @@ }

case 'Any':
return yield* Any(anySchema, path);
return yield* Any(anySchema, value);
case 'Array':
return yield* Array(anySchema, path);
return yield* Array(anySchema, value);
case 'Boolean':
return yield* Boolean(anySchema, path);
return yield* Boolean(anySchema, value);
case 'Constructor':
return yield* Constructor(anySchema, path);
return yield* Constructor(anySchema, value);
case 'Function':
return yield* Function(anySchema, path);
return yield* Function(anySchema, value);
case 'Integer':
return yield* Integer(anySchema, path);
return yield* Integer(anySchema, value);
case 'Literal':
return yield* Literal(anySchema, path);
return yield* Literal(anySchema, value);
case 'Null':
return yield* Null(anySchema, path);
return yield* Null(anySchema, value);
case 'Number':
return yield* Number(anySchema, path);
return yield* Number(anySchema, value);
case 'Object':
return yield* Object(anySchema, path);
return yield* Object(anySchema, value);
case 'Promise':
return yield* Promise(anySchema, path);
return yield* Promise(anySchema, value);
case 'Record':
return yield* Record(anySchema, path);
return yield* Record(anySchema, value);
case 'Ref':
return yield* Ref(anySchema, path);
return yield* Ref(anySchema, value);
case 'Self':
return yield* Self(anySchema, path);
return yield* Self(anySchema, value);
case 'String':
return yield* String(anySchema, path);
return yield* String(anySchema, value);
case 'Tuple':
return yield* Tuple(anySchema, path);
return yield* Tuple(anySchema, value);
case 'Undefined':
return yield* Undefined(anySchema, path);
return yield* Undefined(anySchema, value);
case 'Union':
return yield* Union(anySchema, path);
return yield* Union(anySchema, value);
case 'Uint8Array':
return yield* Uint8Array(anySchema, path);
return yield* Uint8Array(anySchema, value);
case 'Unknown':
return yield* Unknown(anySchema, path);
return yield* Unknown(anySchema, value);
case 'Void':
return yield* Void(anySchema, path);
return yield* Void(anySchema, value);
default:

@@ -330,5 +330,5 @@ throw Error(`Unknown schema kind '${schema[Types.Kind]}'`);

// -------------------------------------------------------------------
function Build(schema, additional = []) {
function Build(schema, references = []) {
ClearLocals();
PushReferences(additional);
PushReferences(references);
const conditions = [...Visit(schema, 'value')]; // locals populated during yield

@@ -339,8 +339,8 @@ const locals = GetLocals();

/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, additional = []) {
const code = Build(schema, additional);
function Compile(schema, references = []) {
const code = Build(schema, references);
const func = globalThis.Function(code);
return new TypeCheck(schema, additional, func(), code);
return new TypeCheck(schema, references, func(), code);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
export * from './compiler';
export * from './errors';
export * from '../value/errors';

@@ -41,2 +41,2 @@ "use strict";

__exportStar(require("./compiler"), exports);
__exportStar(require("./errors"), exports);
__exportStar(require("../value/errors"), exports);
{
"name": "@sinclair/typebox",
"version": "0.24.7",
"version": "0.24.8",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",

@@ -5,0 +5,0 @@ "keywords": [

@@ -453,3 +453,3 @@ <div align='center'>

│ const T = Type.Undefined() │ type T = undefined │ const T = { │
│ │ │ type: 'object' │
│ │ │ type: 'object', │
│ │ │ specialized: 'Undefined' │

@@ -611,12 +611,11 @@ │ │ │ } │

TypeBox can construct default values for types. TypeBox will create reasonable defaults for any given type, or produce values based on the schemas the `default` value if specified.
TypeBox can create values from types. It creates reasonable defaults for each value which can overrided by specifying a `default` value.
```typescript
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
const T = Type.Object({
x: Type.Number({ default: 1 }),
y: Type.Number({ default: 2 }),
z: Type.Number()
y: Type.Number(),
})

@@ -626,7 +625,23 @@

// x: 1,
// y: 2,
// z: 0
// y: 0,
// }
```
TypeBox also allows values to be upgraded to match the schematics of a given type. The `Value.Cast(...)` function can be used to upgrade a value into a target type while retaining as much information of the original value as possible. Casts are immutable operations.
```typescript
import { Value } from '@sinclair/typebox/value'
import { Type } from '@sinclair/typebox'
const T = Type.Object({
x: Type.Number(),
y: Type.Number()
})
const A = Value.Cast(T, null) // const A = { x: 0, y: 0 }
const B = Value.Cast(T, { x: 1 }) // const B = { x: 1, y: 0 }
const C = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const C = { x: 1, y: 2 }
```
<a name="Guards"></a>

@@ -636,3 +651,3 @@

In some scenarios it may be helpful to test if an object is a valid TypeBox type. You can use the TypeGuard module to check an object conforms to a valid TypeBox schema representation. Consider the following.
If reflecting on TypeBox types, it can be helpful to test if a value matches a TypeBox schematic. This can be achieved using the TypeGuard namespace. The TypeGuard namespace offers exhaustive checks for each known TypeBox type.

@@ -643,3 +658,3 @@ ```typescript

const T: any = Type.String() // T is any
const T: any = {} // T is any

@@ -655,4 +670,2 @@ const { type } = T // unsafe: type is any

<a name="Strict"></a>

@@ -737,3 +750,3 @@

const Vector = Type.Object({
const T = Type.Object({
x: Type.Number(),

@@ -750,3 +763,3 @@ y: Type.Number(),

const OK = ajv.validate(Vector, {
const OK = ajv.validate(T, {
x: 1,

@@ -764,3 +777,3 @@ y: 2,

TypeBox includes a specialized type compiler that can be used as a runtime type checker in absense of a JSON Schema validator. This compiler is optimized for high throughput validation scenarios and generally performs better than AJV for most structural checks. Please note that this compiler is not fully JSON Schema compliant and is limited to TypeBox types only. The `TypeCompiler` contains a `Compile(T)` function that returns a `TypeCheck<T>` object that can be used to test the validity of a value as well as obtain errors.
TypeBox includes a specialized `TypeCompiler` that can be used as a runtime type checker in lieu of a JSON Schema validator. This compiler is optimized for high throughput Web Socket messaging and can perform better than AJV for some structural checks. Please note that this compiler is not fully JSON Schema compliant and is limited to known TypeBox types only. The `TypeCompiler` contains a `Compile(T)` function that returns a `TypeCheck<T>` object that can be used to test the validity of a value as well as obtain errors.

@@ -785,3 +798,3 @@ ```typescript

```
Errors can be obtained by calling the `Errors(...)` function. This function returns an iterator that may contain zero or more errors for the given value. For performance, you should only call `Errors(V)` if the `Check(V)` function returns false.
Errors can be obtained by calling the `Errors(...)` function. This function returns an iterator that may contain zero or more errors for the given value. For performance, you should only call `Errors(V)` if the `Check(V)` function returns `false`.
```typescript

@@ -802,3 +815,3 @@ const C = TypeCompiler.Compile(Type.Object({

```
To inspect the generated validation code created by the compiler. You can call the `Code()` function on the `TypeCheck<T>` object.
The TypeCompiler generates JavaScript validation routines types that are evaluated at runtime. You can inspect the generated code by calling the `Code()` function of the `TypeCheck<T>` object.

@@ -823,2 +836,2 @@ ```typescript

TypeBox is open to community contribution, however please ensure you submit an open issue before submitting your pull request. The TypeBox project does preference open community discussion prior to accepting new features.
TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project preferences open community discussion prior to accepting new features.

@@ -25,8 +25,6 @@ export declare const Kind: unique symbol;

description?: string;
/** Default value hint for this schema */
/** Default value for this schema */
default?: any;
/** Example values matching this schema. */
examples?: any;
/** Design metadata for this schema */
design?: DesignType;
[prop: string]: any;

@@ -33,0 +31,0 @@ }

import * as Types from '../typebox';
export declare namespace CheckValue {
function Visit<T extends Types.TSchema>(schema: T, value: any): boolean;
function Check<T extends Types.TSchema>(schema: T, value: any): boolean;
export declare namespace ValueCheck {
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): boolean;
}

@@ -30,59 +30,98 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CheckValue = void 0;
exports.ValueCheck = void 0;
const Types = require("../typebox");
var CheckValue;
(function (CheckValue) {
const referenceMap = new Map();
function Any(schema, value) {
var ValueCheck;
(function (ValueCheck) {
function Any(schema, references, value) {
return true;
}
function Array(schema, value) {
if (typeof value !== 'object' || !globalThis.Array.isArray(value))
function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
for (let i = 0; i < value.length; i++) {
if (!Visit(schema.items, value[i]))
return false;
}
return true;
return value.every((val) => Visit(schema.items, references, val));
}
function Boolean(schema, value) {
function Boolean(schema, references, value) {
return typeof value === 'boolean';
}
function Constructor(schema, value) {
return Visit(schema.returns, value.prototype); // check return type only (as an object)
function Constructor(schema, references, value) {
return Visit(schema.returns, references, value);
}
function Enum(schema, value) {
for (const subschema of schema.anyOf) {
if (subschema.const === value)
return true;
}
return false;
}
function Function(schema, value) {
function Function(schema, references, value) {
return typeof value === 'function';
}
function Integer(schema, value) {
return typeof value === 'number' && globalThis.Number.isInteger(value);
function Integer(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (!globalThis.Number.isInteger(value)) {
return false;
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Intersect(schema, value) {
return Object(schema, value);
function Literal(schema, references, value) {
return value === schema.const;
}
function Literal(schema, value) {
return schema.const === value;
}
function Null(schema, value) {
function Null(schema, references, value) {
return value === null;
}
function Number(schema, value) {
return typeof value === 'number';
function Number(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Object(schema, value) {
if (typeof value !== 'object' || value === null)
function Object(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
}
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
return false;
}
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
return false;
}
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
const valueKeys = globalThis.Object.keys(value);
for (const valueKey of valueKeys) {
if (!propertyKeys.includes(valueKey))
// optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that
// of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) {
return false;
}
else {
if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) {
return false;
}
}

@@ -92,20 +131,31 @@ }

const propertySchema = schema.properties[propertyKey];
const propertyValue = value[propertyKey];
if (propertyValue === undefined && schema.required !== undefined && !schema.required.includes(propertyKey))
return true;
if (!Visit(propertySchema, propertyValue))
return false;
if (schema.required && schema.required.includes(propertyKey)) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
else {
if (value[propertyKey] !== undefined) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
}
}
return true;
}
function Promise(schema, value) {
return typeof value === 'object' && typeof value['then'] === 'function';
function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function';
}
function Record(schema, value) {
if (typeof value !== 'object' || value === null)
function Record(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
const propertySchema = globalThis.Object.values(schema.patternProperties)[0];
for (const key of globalThis.Object.keys(value)) {
const propertyValue = value[key];
if (!Visit(propertySchema, propertyValue))
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(value).every((key) => regex.test(key))) {
return false;
}
for (const propValue of globalThis.Object.values(value)) {
if (!Visit(valueSchema, references, propValue))
return false;

@@ -115,34 +165,40 @@ }

}
function Recursive(schema, value) {
throw new Error('Cannot typeof recursive types');
function Ref(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`CheckValue.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function Ref(schema, value) {
throw new Error('Cannot typeof reference types');
function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`CheckValue.Self: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function Self(schema, value) {
if (!referenceMap.has(schema.$ref))
throw new Error(`Check: Cannot locate schema with $id '${schema.$id}' for referenced type`);
const referenced = referenceMap.get(schema.$ref);
return Visit(referenced, value);
}
function String(schema, value) {
if (typeof value !== 'string')
function String(schema, references, value) {
if (!(typeof value === 'string')) {
return false;
}
if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern);
return value.match(regex) !== null;
if (!regex.test(value))
return false;
}
return true;
}
function Tuple(schema, value) {
if (typeof value !== 'object' || !globalThis.Array.isArray(value))
function Tuple(schema, references, value) {
if (!global.Array.isArray(value)) {
return false;
if (schema.items === undefined && value.length === 0)
return true;
if (schema.items === undefined)
}
if (schema.items === undefined && !(value.length === 0)) {
return false;
if (value.length < schema.minItems || value.length > schema.maxItems)
}
if (!(value.length === schema.maxItems)) {
return false;
}
if (!schema.items) {
return true;
}
for (let i = 0; i < schema.items.length; i++) {
if (!Visit(schema.items[i], value[i]))
if (!Visit(schema.items[i], references, value[i]))
return false;

@@ -152,74 +208,72 @@ }

}
function Undefined(schema, value) {
function Undefined(schema, references, value) {
return value === undefined;
}
function Union(schema, value) {
for (let i = 0; i < schema.anyOf.length; i++) {
if (Visit(schema.anyOf[i], value))
return true;
function Union(schema, references, value) {
return schema.anyOf.some((inner) => Visit(inner, references, value));
}
function Uint8Array(schema, references, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return false;
}
return false;
if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) {
return false;
}
if (schema.minByteLength && !(value.length >= schema.minByteLength)) {
return false;
}
return true;
}
function Uint8Array(schema, value) {
return value instanceof globalThis.Uint8Array;
}
function Unknown(schema, value) {
function Unknown(schema, references, value) {
return true;
}
function Void(schema, value) {
function Void(schema, references, value) {
return value === null;
}
function Visit(schema, value) {
if (schema.$id !== undefined)
referenceMap.set(schema.$id, schema);
function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema, value);
return Any(anySchema, anyReferences, value);
case 'Array':
return Array(anySchema, value);
return Array(anySchema, anyReferences, value);
case 'Boolean':
return Boolean(anySchema, value);
return Boolean(anySchema, anyReferences, value);
case 'Constructor':
return Constructor(anySchema, value);
case 'Enum':
return Enum(anySchema, value);
return Constructor(anySchema, anyReferences, value);
case 'Function':
return Function(anySchema, value);
return Function(anySchema, anyReferences, value);
case 'Integer':
return Integer(anySchema, value);
case 'Intersect':
return Intersect(anySchema, value);
return Integer(anySchema, anyReferences, value);
case 'Literal':
return Literal(anySchema, value);
return Literal(anySchema, anyReferences, value);
case 'Null':
return Null(anySchema, value);
return Null(anySchema, anyReferences, value);
case 'Number':
return Number(anySchema, value);
return Number(anySchema, anyReferences, value);
case 'Object':
return Object(anySchema, value);
return Object(anySchema, anyReferences, value);
case 'Promise':
return Promise(anySchema, value);
return Promise(anySchema, anyReferences, value);
case 'Record':
return Record(anySchema, value);
case 'Rec':
return Recursive(anySchema, value);
return Record(anySchema, anyReferences, value);
case 'Ref':
return Ref(anySchema, value);
return Ref(anySchema, anyReferences, value);
case 'Self':
return Self(anySchema, value);
return Self(anySchema, anyReferences, value);
case 'String':
return String(anySchema, value);
return String(anySchema, anyReferences, value);
case 'Tuple':
return Tuple(anySchema, value);
return Tuple(anySchema, anyReferences, value);
case 'Undefined':
return Undefined(anySchema, value);
return Undefined(anySchema, anyReferences, value);
case 'Union':
return Union(anySchema, value);
return Union(anySchema, anyReferences, value);
case 'Uint8Array':
return Uint8Array(anySchema, value);
return Uint8Array(anySchema, anyReferences, value);
case 'Unknown':
return Unknown(anySchema, value);
return Unknown(anySchema, anyReferences, value);
case 'Void':
return Void(anySchema, value);
return Void(anySchema, anyReferences, value);
default:

@@ -229,9 +283,9 @@ throw Error(`Unknown schema kind '${schema[Types.Kind]}'`);

}
CheckValue.Visit = Visit;
function Check(schema, value) {
if (referenceMap.size > 0)
referenceMap.clear();
return Visit(schema, value);
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
function Check(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
}
CheckValue.Check = Check;
})(CheckValue = exports.CheckValue || (exports.CheckValue = {}));
ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));
import * as Types from '../typebox';
export declare namespace CreateValue {
export declare namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit<T extends Types.TSchema>(schema: T): Types.Static<T>;
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Create<T extends Types.TSchema>(schema: T): Types.Static<T>;
function Visit<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
}

@@ -30,9 +30,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateValue = void 0;
exports.ValueCreate = void 0;
const Types = require("../typebox");
var CreateValue;
(function (CreateValue) {
const referenceMap = new Map();
let recursionDepth = 0;
function Any(schema) {
var ValueCreate;
(function (ValueCreate) {
function Any(schema, references) {
if (schema.default !== undefined) {

@@ -45,3 +43,3 @@ return schema.default;

}
function Array(schema) {
function Array(schema, references) {
if (schema.default !== undefined) {

@@ -52,3 +50,3 @@ return schema.default;

return globalThis.Array.from({ length: schema.minItems }).map((item) => {
return CreateValue.Create(schema.items);
return ValueCreate.Create(schema.items, references);
});

@@ -60,3 +58,3 @@ }

}
function Boolean(schema) {
function Boolean(schema, references) {
if (schema.default !== undefined) {

@@ -69,3 +67,3 @@ return schema.default;

}
function Constructor(schema) {
function Constructor(schema, references) {
if (schema.default !== undefined) {

@@ -75,3 +73,3 @@ return schema.default;

else {
const value = CreateValue.Create(schema.returns);
const value = ValueCreate.Create(schema.returns, references);
if (typeof value === 'object' && !globalThis.Array.isArray(value)) {

@@ -93,3 +91,3 @@ return class {

}
function Enum(schema) {
function Enum(schema, references) {
if (schema.default !== undefined) {

@@ -105,3 +103,3 @@ return schema.default;

}
function Function(schema) {
function Function(schema, references) {
if (schema.default !== undefined) {

@@ -111,6 +109,6 @@ return schema.default;

else {
return () => CreateValue.Create(schema.returns);
return () => ValueCreate.Create(schema.returns, references);
}
}
function Integer(schema) {
function Integer(schema, references) {
if (schema.default !== undefined) {

@@ -126,20 +124,9 @@ return schema.default;

}
function Intersect(schema) {
if (schema.default !== undefined) {
return schema.default;
}
else {
return (schema.default ||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
return { ...acc, [key]: CreateValue.Create(schema) };
}, {}));
}
}
function Literal(schema) {
function Literal(schema, references) {
return schema.const;
}
function Null(schema) {
function Null(schema, references) {
return null;
}
function Number(schema) {
function Number(schema, references) {
if (schema.default !== undefined) {

@@ -155,3 +142,3 @@ return schema.default;

}
function Object(schema) {
function Object(schema, references) {
if (schema.default !== undefined) {

@@ -161,18 +148,10 @@ return schema.default;

else {
// StackOverflow Prevention
if (schema['$dynamicAnchor'] !== undefined) {
for (const [key, value] of globalThis.Object.entries(schema.properties)) {
if (value['$dynamicRef'] !== undefined && schema.required && schema.required.includes(key)) {
throw Error(`Cannot create recursive object with immediate recursive property`);
}
}
}
const required = new Set(schema.required);
return (schema.default ||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
return required.has(key) ? { ...acc, [key]: CreateValue.Create(schema) } : { ...acc };
return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc };
}, {}));
}
}
function Promise(schema) {
function Promise(schema, references) {
if (schema.default !== undefined) {

@@ -182,6 +161,6 @@ return schema.default;

else {
return globalThis.Promise.resolve(CreateValue.Create(schema.item));
return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references));
}
}
function Record(schema) {
function Record(schema, references) {
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];

@@ -194,3 +173,3 @@ if (schema.default !== undefined) {

return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema) };
return { ...acc, [key]: Create(valueSchema, references) };
}, {});

@@ -202,3 +181,3 @@ }

}
function Recursive(schema) {
function Recursive(schema, references) {
if (schema.default !== undefined) {

@@ -211,3 +190,3 @@ return schema.default;

}
function Ref(schema) {
function Ref(schema, references) {
if (schema.default !== undefined) {

@@ -217,6 +196,20 @@ return schema.default;

else {
throw new Error('Ref types require a default value');
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references);
}
}
function String(schema) {
function Self(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`);
return Visit(reference, references);
}
}
function String(schema, references) {
if (schema.pattern !== undefined) {

@@ -239,3 +232,3 @@ if (schema.default === undefined) {

}
function Tuple(schema) {
function Tuple(schema, references) {
if (schema.default !== undefined) {

@@ -248,9 +241,9 @@ return schema.default;

else {
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => CreateValue.Create(schema.items[index]));
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references));
}
}
function Undefined(schema) {
function Undefined(schema, references) {
return undefined;
}
function Union(schema) {
function Union(schema, references) {
if (schema.default !== undefined) {

@@ -263,6 +256,6 @@ return schema.default;

else {
return CreateValue.Create(schema.anyOf[0]);
return ValueCreate.Create(schema.anyOf[0], references);
}
}
function Uint8Array(schema) {
function Uint8Array(schema, references) {
if (schema.default !== undefined) {

@@ -278,3 +271,3 @@ return schema.default;

}
function Unknown(schema) {
function Unknown(schema, references) {
if (schema.default !== undefined) {

@@ -287,62 +280,56 @@ return schema.default;

}
function Void(schema) {
function Void(schema, references) {
return null;
}
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema) {
recursionDepth += 1;
if (recursionDepth >= 1000)
throw new Error('Cannot create value as schema contains a infinite expansion');
function Visit(schema, references) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
if (anySchema.$id !== undefined)
referenceMap.set(anySchema.$id, anySchema);
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema);
return Any(anySchema, anyReferences);
case 'Array':
return Array(anySchema);
return Array(anySchema, anyReferences);
case 'Boolean':
return Boolean(anySchema);
return Boolean(anySchema, anyReferences);
case 'Constructor':
return Constructor(anySchema);
return Constructor(anySchema, anyReferences);
case 'Enum':
return Enum(anySchema);
return Enum(anySchema, anyReferences);
case 'Function':
return Function(anySchema);
return Function(anySchema, anyReferences);
case 'Integer':
return Integer(anySchema);
case 'Intersect':
return Intersect(anySchema);
return Integer(anySchema, anyReferences);
case 'Literal':
return Literal(anySchema);
return Literal(anySchema, anyReferences);
case 'Null':
return Null(anySchema);
return Null(anySchema, anyReferences);
case 'Number':
return Number(anySchema);
return Number(anySchema, anyReferences);
case 'Object':
return Object(anySchema);
return Object(anySchema, anyReferences);
case 'Promise':
return Promise(anySchema);
return Promise(anySchema, anyReferences);
case 'Record':
return Record(anySchema);
return Record(anySchema, anyReferences);
case 'Rec':
return Recursive(anySchema);
return Recursive(anySchema, anyReferences);
case 'Ref':
return Ref(anySchema);
return Ref(anySchema, anyReferences);
case 'Self':
return Self(anySchema, anyReferences);
case 'String':
return String(anySchema);
return String(anySchema, anyReferences);
case 'Tuple':
return Tuple(anySchema);
return Tuple(anySchema, anyReferences);
case 'Undefined':
return Undefined(anySchema);
return Undefined(anySchema, anyReferences);
case 'Union':
return Union(anySchema);
return Union(anySchema, anyReferences);
case 'Uint8Array':
return Uint8Array(anySchema);
return Uint8Array(anySchema, anyReferences);
case 'Unknown':
return Unknown(anySchema);
return Unknown(anySchema, anyReferences);
case 'Void':
return Void(anySchema);
case 'Self':
return Visit(referenceMap.get(anySchema.$ref));
return Void(anySchema, anyReferences);
default:

@@ -352,9 +339,7 @@ throw Error(`Unknown schema kind '${schema[Types.Kind]}'`);

}
CreateValue.Visit = Visit;
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Create(schema) {
recursionDepth = 0;
return Visit(schema);
ValueCreate.Visit = Visit;
function Create(schema, references) {
return Visit(schema, references);
}
CreateValue.Create = Create;
})(CreateValue = exports.CreateValue || (exports.CreateValue = {}));
ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));
import * as Types from '../typebox';
import { Edit } from './delta';
export { Edit, EditType } from './delta';
import { ValueError } from './errors';
/** Creates Values from TypeBox Types */
export declare namespace Value {
/** Returns true if the value conforms to the given schema */
function Check<T extends Types.TSchema>(schema: T, value: any): value is Types.Static<T>;
/** Returns a deep clone of the given value */
function Clone<T>(value: T): T;
/** Creates a value from the given schema type */
/** Creates a value from the given type */
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema>(schema: T): Types.Static<T>;
/** Diffs the value and produces edits to transform the value into the next value */
function Diff(value: any, next: any): Edit[];
/** Patches a value by applying a series of edits */
function Patch(value: any, edits: Edit[]): any;
/** Upcasts a value to match a schema while preserving as much information from the original value as possible. */
function Upcast<T extends Types.TSchema>(schema: T, value: any): Types.Static<T>;
/** Checks a value matches the given type */
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): value is Types.Static<T>;
/** Checks a value matches the given type */
function Check<T extends Types.TSchema>(schema: T, value: unknown): value is Types.Static<T>;
/** Casts a value into a structure matching the given type. The result will be a new value that retains as much information of the original value as possible. */
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): Types.Static<T>;
/** Casts a value into a structure matching the given type. The result will be a new value that retains as much information of the original value as possible. */
function Cast<T extends Types.TSchema>(schema: T, value: unknown): Types.Static<T>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): IterableIterator<ValueError>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema>(schema: T, value: unknown): IterableIterator<ValueError>;
}
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox
@sinclair/typebox/value

@@ -30,42 +30,30 @@ The MIT License (MIT)

Object.defineProperty(exports, "__esModule", { value: true });
exports.Value = exports.EditType = void 0;
exports.Value = void 0;
const errors_1 = require("./errors");
const cast_1 = require("./cast");
const create_1 = require("./create");
const check_1 = require("./check");
const clone_1 = require("./clone");
const delta_1 = require("./delta");
const upcast_1 = require("./upcast");
var delta_2 = require("./delta");
Object.defineProperty(exports, "EditType", { enumerable: true, get: function () { return delta_2.EditType; } });
/** Creates Values from TypeBox Types */
var Value;
(function (Value) {
/** Returns true if the value conforms to the given schema */
function Check(schema, value) {
return check_1.CheckValue.Check(schema, value);
function Create(...args) {
const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []];
return create_1.ValueCreate.Create(schema, references);
}
Value.Check = Check;
/** Returns a deep clone of the given value */
function Clone(value) {
return clone_1.CloneValue.Create(value);
}
Value.Clone = Clone;
/** Creates a value from the given schema type */
function Create(schema) {
return create_1.CreateValue.Create(schema);
}
Value.Create = Create;
/** Diffs the value and produces edits to transform the value into the next value */
function Diff(value, next) {
return delta_1.DeltaValue.Diff(value, next);
function Check(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return check_1.ValueCheck.Check(schema, references, value);
}
Value.Diff = Diff;
/** Patches a value by applying a series of edits */
function Patch(value, edits) {
return delta_1.DeltaValue.Edit(value, edits);
Value.Check = Check;
function Cast(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return cast_1.ValueCast.Cast(schema, references, value);
}
Value.Patch = Patch;
/** Upcasts a value to match a schema while preserving as much information from the original value as possible. */
function Upcast(schema, value) {
return upcast_1.UpcastValue.Create(schema, value);
Value.Cast = Cast;
function* Errors(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
yield* errors_1.ValueErrors.Errors(schema, references, value);
}
Value.Upcast = Upcast;
Value.Errors = Errors;
})(Value = exports.Value || (exports.Value = {}));
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc