@sinclair/typebox 0.24.7 → 0.24.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/compiler/compiler.d.ts +5 -5
- package/compiler/compiler.js +98 -98
- package/compiler/index.d.ts +1 -1
- package/compiler/index.js +1 -1
- package/package.json +1 -1
- package/readme.md +30 -17
- package/typebox.d.ts +1 -3
- package/value/cast.d.ts +5 -0
- package/value/cast.js +251 -0
- package/value/check.d.ts +2 -3
- package/value/check.js +172 -118
- package/value/create.d.ts +3 -4
- package/value/create.js +79 -94
- package/value/errors.d.ts +10 -0
- package/{compiler → value}/errors.js +70 -91
- package/value/value.d.ts +17 -13
- package/value/value.js +20 -32
- package/compiler/errors.d.ts +0 -10
- package/value/clone.d.ts +0 -3
- package/value/clone.js +0 -94
- package/value/delta.d.ts +0 -13
- package/value/delta.js +0 -191
- package/value/pointer.d.ts +0 -12
- package/value/pointer.js +0 -110
- package/value/reflect.d.ts +0 -2
- package/value/reflect.js +0 -42
- package/value/upcast.d.ts +0 -4
- package/value/upcast.js +0 -247
package/compiler/compiler.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ValueError } from '../value/errors';
|
|
2
2
|
import * as Types from '../typebox';
|
|
3
3
|
export declare type CheckFunction = (value: unknown) => boolean;
|
|
4
4
|
export declare class TypeCheck<T extends Types.TSchema> {
|
|
@@ -7,14 +7,14 @@ export declare class TypeCheck<T extends Types.TSchema> {
|
|
|
7
7
|
private readonly checkFunc;
|
|
8
8
|
private readonly code;
|
|
9
9
|
constructor(schema: T, additional: Types.TSchema[], checkFunc: CheckFunction, code: string);
|
|
10
|
-
/** Returns the generated validation code used to validate this type */
|
|
10
|
+
/** Returns the generated validation code used to validate this type. */
|
|
11
11
|
Code(): string;
|
|
12
|
-
/** Returns an iterator for each
|
|
13
|
-
Errors(value: unknown):
|
|
12
|
+
/** Returns an iterator for each error in this value. */
|
|
13
|
+
Errors(value: unknown): IterableIterator<ValueError>;
|
|
14
14
|
/** Returns true if the value matches the given type. */
|
|
15
15
|
Check(value: unknown): value is Types.Static<T>;
|
|
16
16
|
}
|
|
17
17
|
export declare namespace TypeCompiler {
|
|
18
18
|
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
|
19
|
-
function Compile<T extends Types.TSchema>(schema: T,
|
|
19
|
+
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
|
|
20
20
|
}
|
package/compiler/compiler.js
CHANGED
|
@@ -28,7 +28,7 @@ THE SOFTWARE.
|
|
|
28
28
|
---------------------------------------------------------------------------*/
|
|
29
29
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
30
|
exports.TypeCompiler = exports.TypeCheck = void 0;
|
|
31
|
-
const errors_1 = require("
|
|
31
|
+
const errors_1 = require("../value/errors");
|
|
32
32
|
const Types = require("../typebox");
|
|
33
33
|
// -------------------------------------------------------------------
|
|
34
34
|
// TypeCheck
|
|
@@ -44,13 +44,13 @@ class TypeCheck {
|
|
|
44
44
|
this.checkFunc = checkFunc;
|
|
45
45
|
this.code = code;
|
|
46
46
|
}
|
|
47
|
-
/** Returns the generated validation code used to validate this type */
|
|
47
|
+
/** Returns the generated validation code used to validate this type. */
|
|
48
48
|
Code() {
|
|
49
49
|
return this.code;
|
|
50
50
|
}
|
|
51
|
-
/** Returns an iterator for each
|
|
51
|
+
/** Returns an iterator for each error in this value. */
|
|
52
52
|
Errors(value) {
|
|
53
|
-
return errors_1.
|
|
53
|
+
return errors_1.ValueErrors.Errors(this.schema, this.additional, value);
|
|
54
54
|
}
|
|
55
55
|
/** Returns true if the value matches the given type. */
|
|
56
56
|
Check(value) {
|
|
@@ -66,65 +66,65 @@ var TypeCompiler;
|
|
|
66
66
|
// -------------------------------------------------------------------
|
|
67
67
|
// Schemas
|
|
68
68
|
// -------------------------------------------------------------------
|
|
69
|
-
function* Any(schema,
|
|
69
|
+
function* Any(schema, value) {
|
|
70
70
|
yield '(true)';
|
|
71
71
|
}
|
|
72
|
-
function* Array(schema,
|
|
72
|
+
function* Array(schema, value) {
|
|
73
73
|
const expr = [...Visit(schema.items, `value`)].map((condition) => condition).join(' && ');
|
|
74
|
-
yield `(Array.isArray(${
|
|
74
|
+
yield `(Array.isArray(${value}) && ${value}.every(value => ${expr}))`;
|
|
75
75
|
}
|
|
76
|
-
function* Boolean(schema,
|
|
77
|
-
yield `(typeof ${
|
|
76
|
+
function* Boolean(schema, value) {
|
|
77
|
+
yield `(typeof ${value} === 'boolean')`;
|
|
78
78
|
}
|
|
79
|
-
function* Constructor(schema,
|
|
80
|
-
yield* Visit(schema.
|
|
79
|
+
function* Constructor(schema, value) {
|
|
80
|
+
yield* Visit(schema.returns, value);
|
|
81
81
|
}
|
|
82
|
-
function* Function(schema,
|
|
83
|
-
yield `(typeof ${
|
|
82
|
+
function* Function(schema, value) {
|
|
83
|
+
yield `(typeof ${value} === 'function')`;
|
|
84
84
|
}
|
|
85
|
-
function* Integer(schema,
|
|
86
|
-
yield `(typeof ${
|
|
85
|
+
function* Integer(schema, value) {
|
|
86
|
+
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
|
|
87
87
|
if (schema.multipleOf)
|
|
88
|
-
yield `(${
|
|
88
|
+
yield `(${value} % ${schema.multipleOf} === 0)`;
|
|
89
89
|
if (schema.exclusiveMinimum)
|
|
90
|
-
yield `(${
|
|
90
|
+
yield `(${value} > ${schema.exclusiveMinimum})`;
|
|
91
91
|
if (schema.exclusiveMaximum)
|
|
92
|
-
yield `(${
|
|
92
|
+
yield `(${value} < ${schema.exclusiveMaximum})`;
|
|
93
93
|
if (schema.minimum)
|
|
94
|
-
yield `(${
|
|
94
|
+
yield `(${value} >= ${schema.minimum})`;
|
|
95
95
|
if (schema.maximum)
|
|
96
|
-
yield `(${
|
|
96
|
+
yield `(${value} <= ${schema.maximum})`;
|
|
97
97
|
}
|
|
98
|
-
function* Literal(schema,
|
|
98
|
+
function* Literal(schema, value) {
|
|
99
99
|
if (typeof schema.const === 'string') {
|
|
100
|
-
yield `(${
|
|
100
|
+
yield `(${value} === '${schema.const}')`;
|
|
101
101
|
}
|
|
102
102
|
else {
|
|
103
|
-
yield `(${
|
|
103
|
+
yield `(${value} === ${schema.const})`;
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
|
-
function* Null(schema,
|
|
107
|
-
yield `(${
|
|
106
|
+
function* Null(schema, value) {
|
|
107
|
+
yield `(${value} === null)`;
|
|
108
108
|
}
|
|
109
|
-
function* Number(schema,
|
|
110
|
-
yield `(typeof ${
|
|
109
|
+
function* Number(schema, value) {
|
|
110
|
+
yield `(typeof ${value} === 'number')`;
|
|
111
111
|
if (schema.multipleOf)
|
|
112
|
-
yield `(${
|
|
112
|
+
yield `(${value} % ${schema.multipleOf} === 0)`;
|
|
113
113
|
if (schema.exclusiveMinimum)
|
|
114
|
-
yield `(${
|
|
114
|
+
yield `(${value} > ${schema.exclusiveMinimum})`;
|
|
115
115
|
if (schema.exclusiveMaximum)
|
|
116
|
-
yield `(${
|
|
116
|
+
yield `(${value} < ${schema.exclusiveMaximum})`;
|
|
117
117
|
if (schema.minimum)
|
|
118
|
-
yield `(${
|
|
118
|
+
yield `(${value} >= ${schema.minimum})`;
|
|
119
119
|
if (schema.maximum)
|
|
120
|
-
yield `(${
|
|
120
|
+
yield `(${value} <= ${schema.maximum})`;
|
|
121
121
|
}
|
|
122
|
-
function* Object(schema,
|
|
123
|
-
yield `(typeof ${
|
|
122
|
+
function* Object(schema, value) {
|
|
123
|
+
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
|
|
124
124
|
if (schema.minProperties !== undefined)
|
|
125
|
-
yield `(Object.keys(${
|
|
125
|
+
yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
|
|
126
126
|
if (schema.maxProperties !== undefined)
|
|
127
|
-
yield `(Object.keys(${
|
|
127
|
+
yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
|
|
128
128
|
const propertyKeys = globalThis.Object.keys(schema.properties);
|
|
129
129
|
if (schema.additionalProperties === false) {
|
|
130
130
|
// optimization: If the property key length matches the required keys length
|
|
@@ -132,36 +132,36 @@ var TypeCompiler;
|
|
|
132
132
|
// of the property key length. This is because exhaustive testing for values
|
|
133
133
|
// will occur in subsequent property tests.
|
|
134
134
|
if (schema.required && schema.required.length === propertyKeys.length) {
|
|
135
|
-
yield `(Object.keys(${
|
|
135
|
+
yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
|
|
136
136
|
}
|
|
137
137
|
else {
|
|
138
138
|
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
|
|
139
|
-
yield `(Object.keys(${
|
|
139
|
+
yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
142
|
for (const propertyKey of propertyKeys) {
|
|
143
143
|
const propertySchema = schema.properties[propertyKey];
|
|
144
144
|
if (schema.required && schema.required.includes(propertyKey)) {
|
|
145
|
-
yield* Visit(propertySchema, `${
|
|
145
|
+
yield* Visit(propertySchema, `${value}.${propertyKey}`);
|
|
146
146
|
}
|
|
147
147
|
else {
|
|
148
|
-
const expr = [...Visit(propertySchema, `${
|
|
149
|
-
yield `(${
|
|
148
|
+
const expr = [...Visit(propertySchema, `${value}.${propertyKey}`)].map((condition) => condition).join(' && ');
|
|
149
|
+
yield `(${value}.${propertyKey} === undefined ? true : (${expr}))`;
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
}
|
|
153
|
-
function* Promise(schema,
|
|
154
|
-
yield `(typeof value === 'object' && typeof ${
|
|
153
|
+
function* Promise(schema, value) {
|
|
154
|
+
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
|
|
155
155
|
}
|
|
156
|
-
function* Record(schema,
|
|
157
|
-
yield `(typeof ${
|
|
156
|
+
function* Record(schema, value) {
|
|
157
|
+
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
|
|
158
158
|
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
|
159
159
|
const local = PushLocal(`const local = new RegExp(/${keyPattern}/)`);
|
|
160
|
-
yield `(Object.keys(${
|
|
160
|
+
yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
|
|
161
161
|
const expr = [...Visit(valueSchema, 'value')].map((condition) => condition).join(' && ');
|
|
162
|
-
yield `(Object.values(${
|
|
162
|
+
yield `(Object.values(${value}).every(value => ${expr}))`;
|
|
163
163
|
}
|
|
164
|
-
function* Ref(schema,
|
|
164
|
+
function* Ref(schema, value) {
|
|
165
165
|
// reference: referenced schemas can originate from either additional
|
|
166
166
|
// schemas or inline in the schema itself. Ideally the recursive
|
|
167
167
|
// path should align to reference path. Consider for review.
|
|
@@ -174,50 +174,50 @@ var TypeCompiler;
|
|
|
174
174
|
PushLocal(body);
|
|
175
175
|
}
|
|
176
176
|
const func = CreateFunctionName(schema.$ref);
|
|
177
|
-
yield `(${func}(${
|
|
177
|
+
yield `(${func}(${value}))`;
|
|
178
178
|
}
|
|
179
|
-
function* Self(schema,
|
|
179
|
+
function* Self(schema, value) {
|
|
180
180
|
const func = CreateFunctionName(schema.$ref);
|
|
181
|
-
yield `(${func}(${
|
|
181
|
+
yield `(${func}(${value}))`;
|
|
182
182
|
}
|
|
183
|
-
function* String(schema,
|
|
184
|
-
yield `(typeof ${
|
|
183
|
+
function* String(schema, value) {
|
|
184
|
+
yield `(typeof ${value} === 'string')`;
|
|
185
185
|
if (schema.pattern !== undefined) {
|
|
186
186
|
const local = PushLocal(`const local = new RegExp('${schema.pattern}');`);
|
|
187
|
-
yield `(${local}.test(${
|
|
187
|
+
yield `(${local}.test(${value}))`;
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
|
-
function* Tuple(schema,
|
|
191
|
-
yield `(Array.isArray(${
|
|
190
|
+
function* Tuple(schema, value) {
|
|
191
|
+
yield `(Array.isArray(${value}))`;
|
|
192
192
|
if (schema.items === undefined)
|
|
193
|
-
return yield `(${
|
|
194
|
-
yield `(${
|
|
193
|
+
return yield `(${value}.length === 0)`;
|
|
194
|
+
yield `(${value}.length === ${schema.maxItems})`;
|
|
195
195
|
for (let i = 0; i < schema.items.length; i++) {
|
|
196
|
-
const expr = [...Visit(schema.items[i], `${
|
|
196
|
+
const expr = [...Visit(schema.items[i], `${value}[${i}]`)].map((condition) => condition).join(' && ');
|
|
197
197
|
yield `(${expr})`;
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
|
-
function* Undefined(schema,
|
|
201
|
-
yield
|
|
200
|
+
function* Undefined(schema, value) {
|
|
201
|
+
yield `(${value} === undefined)`;
|
|
202
202
|
}
|
|
203
|
-
function* Union(schema,
|
|
204
|
-
const exprs = schema.anyOf.map((schema) => [...Visit(schema,
|
|
203
|
+
function* Union(schema, value) {
|
|
204
|
+
const exprs = schema.anyOf.map((schema) => [...Visit(schema, value)].map((condition) => condition).join(' && '));
|
|
205
205
|
yield `(${exprs.join(' || ')})`;
|
|
206
206
|
}
|
|
207
|
-
function* Uint8Array(schema,
|
|
208
|
-
yield `(${
|
|
207
|
+
function* Uint8Array(schema, value) {
|
|
208
|
+
yield `(${value} instanceof Uint8Array)`;
|
|
209
209
|
if (schema.maxByteLength)
|
|
210
|
-
yield `(${
|
|
210
|
+
yield `(${value}.length <= ${schema.maxByteLength})`;
|
|
211
211
|
if (schema.minByteLength)
|
|
212
|
-
yield `(${
|
|
212
|
+
yield `(${value}.length >= ${schema.minByteLength})`;
|
|
213
213
|
}
|
|
214
|
-
function* Unknown(schema,
|
|
214
|
+
function* Unknown(schema, value) {
|
|
215
215
|
yield '(true)';
|
|
216
216
|
}
|
|
217
|
-
function* Void(schema,
|
|
218
|
-
yield `(${
|
|
217
|
+
function* Void(schema, value) {
|
|
218
|
+
yield `(${value} === null)`;
|
|
219
219
|
}
|
|
220
|
-
function* Visit(schema,
|
|
220
|
+
function* Visit(schema, value) {
|
|
221
221
|
// reference: referenced schemas can originate from either additional
|
|
222
222
|
// schemas or inline in the schema itself. Ideally the recursive
|
|
223
223
|
// path should align to reference path. Consider for review.
|
|
@@ -227,53 +227,53 @@ var TypeCompiler;
|
|
|
227
227
|
const name = CreateFunctionName(schema.$id);
|
|
228
228
|
const body = CreateFunction(name, conditions);
|
|
229
229
|
PushLocal(body);
|
|
230
|
-
yield `(${name}(${
|
|
230
|
+
yield `(${name}(${value}))`;
|
|
231
231
|
return;
|
|
232
232
|
}
|
|
233
233
|
const anySchema = schema;
|
|
234
234
|
switch (anySchema[Types.Kind]) {
|
|
235
235
|
case 'Any':
|
|
236
|
-
return yield* Any(anySchema,
|
|
236
|
+
return yield* Any(anySchema, value);
|
|
237
237
|
case 'Array':
|
|
238
|
-
return yield* Array(anySchema,
|
|
238
|
+
return yield* Array(anySchema, value);
|
|
239
239
|
case 'Boolean':
|
|
240
|
-
return yield* Boolean(anySchema,
|
|
240
|
+
return yield* Boolean(anySchema, value);
|
|
241
241
|
case 'Constructor':
|
|
242
|
-
return yield* Constructor(anySchema,
|
|
242
|
+
return yield* Constructor(anySchema, value);
|
|
243
243
|
case 'Function':
|
|
244
|
-
return yield* Function(anySchema,
|
|
244
|
+
return yield* Function(anySchema, value);
|
|
245
245
|
case 'Integer':
|
|
246
|
-
return yield* Integer(anySchema,
|
|
246
|
+
return yield* Integer(anySchema, value);
|
|
247
247
|
case 'Literal':
|
|
248
|
-
return yield* Literal(anySchema,
|
|
248
|
+
return yield* Literal(anySchema, value);
|
|
249
249
|
case 'Null':
|
|
250
|
-
return yield* Null(anySchema,
|
|
250
|
+
return yield* Null(anySchema, value);
|
|
251
251
|
case 'Number':
|
|
252
|
-
return yield* Number(anySchema,
|
|
252
|
+
return yield* Number(anySchema, value);
|
|
253
253
|
case 'Object':
|
|
254
|
-
return yield* Object(anySchema,
|
|
254
|
+
return yield* Object(anySchema, value);
|
|
255
255
|
case 'Promise':
|
|
256
|
-
return yield* Promise(anySchema,
|
|
256
|
+
return yield* Promise(anySchema, value);
|
|
257
257
|
case 'Record':
|
|
258
|
-
return yield* Record(anySchema,
|
|
258
|
+
return yield* Record(anySchema, value);
|
|
259
259
|
case 'Ref':
|
|
260
|
-
return yield* Ref(anySchema,
|
|
260
|
+
return yield* Ref(anySchema, value);
|
|
261
261
|
case 'Self':
|
|
262
|
-
return yield* Self(anySchema,
|
|
262
|
+
return yield* Self(anySchema, value);
|
|
263
263
|
case 'String':
|
|
264
|
-
return yield* String(anySchema,
|
|
264
|
+
return yield* String(anySchema, value);
|
|
265
265
|
case 'Tuple':
|
|
266
|
-
return yield* Tuple(anySchema,
|
|
266
|
+
return yield* Tuple(anySchema, value);
|
|
267
267
|
case 'Undefined':
|
|
268
|
-
return yield* Undefined(anySchema,
|
|
268
|
+
return yield* Undefined(anySchema, value);
|
|
269
269
|
case 'Union':
|
|
270
|
-
return yield* Union(anySchema,
|
|
270
|
+
return yield* Union(anySchema, value);
|
|
271
271
|
case 'Uint8Array':
|
|
272
|
-
return yield* Uint8Array(anySchema,
|
|
272
|
+
return yield* Uint8Array(anySchema, value);
|
|
273
273
|
case 'Unknown':
|
|
274
|
-
return yield* Unknown(anySchema,
|
|
274
|
+
return yield* Unknown(anySchema, value);
|
|
275
275
|
case 'Void':
|
|
276
|
-
return yield* Void(anySchema,
|
|
276
|
+
return yield* Void(anySchema, value);
|
|
277
277
|
default:
|
|
278
278
|
throw Error(`Unknown schema kind '${schema[Types.Kind]}'`);
|
|
279
279
|
}
|
|
@@ -319,18 +319,18 @@ var TypeCompiler;
|
|
|
319
319
|
// -------------------------------------------------------------------
|
|
320
320
|
// Compile
|
|
321
321
|
// -------------------------------------------------------------------
|
|
322
|
-
function Build(schema,
|
|
322
|
+
function Build(schema, references = []) {
|
|
323
323
|
ClearLocals();
|
|
324
|
-
PushReferences(
|
|
324
|
+
PushReferences(references);
|
|
325
325
|
const conditions = [...Visit(schema, 'value')]; // locals populated during yield
|
|
326
326
|
const locals = GetLocals();
|
|
327
327
|
return `${locals.join('\n')}\nreturn ${CreateFunction('check', conditions)}`;
|
|
328
328
|
}
|
|
329
329
|
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
|
330
|
-
function Compile(schema,
|
|
331
|
-
const code = Build(schema,
|
|
330
|
+
function Compile(schema, references = []) {
|
|
331
|
+
const code = Build(schema, references);
|
|
332
332
|
const func = globalThis.Function(code);
|
|
333
|
-
return new TypeCheck(schema,
|
|
333
|
+
return new TypeCheck(schema, references, func(), code);
|
|
334
334
|
}
|
|
335
335
|
TypeCompiler.Compile = Compile;
|
|
336
336
|
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
|
package/compiler/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export * from './compiler';
|
|
2
|
-
export * from '
|
|
2
|
+
export * from '../value/errors';
|
package/compiler/index.js
CHANGED
|
@@ -38,4 +38,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
38
38
|
};
|
|
39
39
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
40
40
|
__exportStar(require("./compiler"), exports);
|
|
41
|
-
__exportStar(require("
|
|
41
|
+
__exportStar(require("../value/errors"), exports);
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -450,7 +450,7 @@ In addition to JSON schema types, TypeBox provides several extended types that a
|
|
|
450
450
|
│ │ │ │
|
|
451
451
|
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
|
|
452
452
|
│ const T = Type.Undefined() │ type T = undefined │ const T = { │
|
|
453
|
-
│ │ │ type: 'object'
|
|
453
|
+
│ │ │ type: 'object', │
|
|
454
454
|
│ │ │ specialized: 'Undefined' │
|
|
455
455
|
│ │ │ } │
|
|
456
456
|
│ │ │ │
|
|
@@ -607,36 +607,51 @@ type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
|
|
|
607
607
|
|
|
608
608
|
### Values
|
|
609
609
|
|
|
610
|
-
TypeBox can
|
|
610
|
+
TypeBox can create values from types. It creates reasonable defaults for each value which can overrided by specifying a `default` value.
|
|
611
611
|
|
|
612
612
|
```typescript
|
|
613
613
|
import { Value } from '@sinclair/typebox/value'
|
|
614
|
-
import { Type }
|
|
614
|
+
import { Type } from '@sinclair/typebox'
|
|
615
615
|
|
|
616
616
|
const T = Type.Object({
|
|
617
617
|
x: Type.Number({ default: 1 }),
|
|
618
|
-
y: Type.Number(
|
|
619
|
-
z: Type.Number()
|
|
618
|
+
y: Type.Number(),
|
|
620
619
|
})
|
|
621
620
|
|
|
622
621
|
const V = Value.Create(T) // const V = {
|
|
623
622
|
// x: 1,
|
|
624
|
-
// y:
|
|
625
|
-
// z: 0
|
|
623
|
+
// y: 0,
|
|
626
624
|
// }
|
|
627
625
|
```
|
|
626
|
+
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.
|
|
627
|
+
|
|
628
|
+
```typescript
|
|
629
|
+
import { Value } from '@sinclair/typebox/value'
|
|
630
|
+
import { Type } from '@sinclair/typebox'
|
|
631
|
+
|
|
632
|
+
const T = Type.Object({
|
|
633
|
+
x: Type.Number(),
|
|
634
|
+
y: Type.Number()
|
|
635
|
+
})
|
|
636
|
+
|
|
637
|
+
const A = Value.Cast(T, null) // const A = { x: 0, y: 0 }
|
|
638
|
+
|
|
639
|
+
const B = Value.Cast(T, { x: 1 }) // const B = { x: 1, y: 0 }
|
|
640
|
+
|
|
641
|
+
const C = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const C = { x: 1, y: 2 }
|
|
642
|
+
```
|
|
628
643
|
|
|
629
644
|
<a name="Guards"></a>
|
|
630
645
|
|
|
631
646
|
### Guards
|
|
632
647
|
|
|
633
|
-
|
|
648
|
+
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.
|
|
634
649
|
|
|
635
650
|
```typescript
|
|
636
651
|
import { TypeGuard } from '@sinclair/typebox/guard'
|
|
637
652
|
import { Type } from '@sinclair/typebox'
|
|
638
653
|
|
|
639
|
-
const T: any =
|
|
654
|
+
const T: any = {} // T is any
|
|
640
655
|
|
|
641
656
|
const { type } = T // unsafe: type is any
|
|
642
657
|
|
|
@@ -647,8 +662,6 @@ if(TypeGuard.TString(T)) {
|
|
|
647
662
|
|
|
648
663
|
```
|
|
649
664
|
|
|
650
|
-
|
|
651
|
-
|
|
652
665
|
<a name="Strict"></a>
|
|
653
666
|
|
|
654
667
|
### Strict
|
|
@@ -728,7 +741,7 @@ const ajv = addFormats(new Ajv({}), [
|
|
|
728
741
|
//
|
|
729
742
|
//--------------------------------------------------------------------------------------------
|
|
730
743
|
|
|
731
|
-
const
|
|
744
|
+
const T = Type.Object({
|
|
732
745
|
x: Type.Number(),
|
|
733
746
|
y: Type.Number(),
|
|
734
747
|
z: Type.Number(),
|
|
@@ -740,7 +753,7 @@ const Vector = Type.Object({
|
|
|
740
753
|
//
|
|
741
754
|
//--------------------------------------------------------------------------------------------
|
|
742
755
|
|
|
743
|
-
const OK = ajv.validate(
|
|
756
|
+
const OK = ajv.validate(T, {
|
|
744
757
|
x: 1,
|
|
745
758
|
y: 2,
|
|
746
759
|
z: 3
|
|
@@ -753,7 +766,7 @@ Please refer to the official AJV [documentation](https://ajv.js.org/guide/gettin
|
|
|
753
766
|
|
|
754
767
|
### Compiler
|
|
755
768
|
|
|
756
|
-
TypeBox includes a specialized
|
|
769
|
+
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.
|
|
757
770
|
|
|
758
771
|
```typescript
|
|
759
772
|
import { TypeCompiler } from '@sinclair/typebox/compiler'
|
|
@@ -773,7 +786,7 @@ const OK = C.Check({
|
|
|
773
786
|
z: 3
|
|
774
787
|
}) // -> true
|
|
775
788
|
```
|
|
776
|
-
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
|
|
789
|
+
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`.
|
|
777
790
|
```typescript
|
|
778
791
|
const C = TypeCompiler.Compile(Type.Object({
|
|
779
792
|
x: Type.Number(),
|
|
@@ -789,7 +802,7 @@ if(!C.Check(V)) {
|
|
|
789
802
|
}
|
|
790
803
|
}
|
|
791
804
|
```
|
|
792
|
-
|
|
805
|
+
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.
|
|
793
806
|
|
|
794
807
|
```typescript
|
|
795
808
|
const C = TypeCompiler.Compile(Type.String())
|
|
@@ -809,4 +822,4 @@ console.log(C.Code())
|
|
|
809
822
|
|
|
810
823
|
### Contribute
|
|
811
824
|
|
|
812
|
-
TypeBox is open to community contribution
|
|
825
|
+
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.
|
package/typebox.d.ts
CHANGED
|
@@ -22,12 +22,10 @@ export interface SchemaOptions {
|
|
|
22
22
|
title?: string;
|
|
23
23
|
/** Description of this schema */
|
|
24
24
|
description?: string;
|
|
25
|
-
/** Default value
|
|
25
|
+
/** Default value for this schema */
|
|
26
26
|
default?: any;
|
|
27
27
|
/** Example values matching this schema. */
|
|
28
28
|
examples?: any;
|
|
29
|
-
/** Design metadata for this schema */
|
|
30
|
-
design?: DesignType;
|
|
31
29
|
[prop: string]: any;
|
|
32
30
|
}
|
|
33
31
|
export interface TSchema extends SchemaOptions {
|
package/value/cast.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import * as Types from '../typebox';
|
|
2
|
+
export declare namespace ValueCast {
|
|
3
|
+
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
|
|
4
|
+
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): Types.Static<T>;
|
|
5
|
+
}
|