Debian Codegraph @

spec/types/jtd-schema.spec.ts

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /* eslint-disable @typescript-eslint/no-empty-interface,no-void,@typescript-eslint/ban-types */
2 import _Ajv from "../ajv_jtd"
3 import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "../../dist/jtd"
4 import chai from "../chai"
5 const should = chai.should()
6
7 /** type is true if T is identically E */
8 type TypeEquality<T, E> = [T] extends [E] ? ([E] extends [T] ? true : false) : false
9
10 interface A {
11 type: "a"
12 a: number
13 }
14
15 interface B {
16 type: "b"
17 b?: string
18 }
19
20 interface C {
21 type: "c"
22 }
23
24 type MyData = A | B
25
26 type Missing = A | C
27
28 interface LinkedList {
29 val: number
30 next?: LinkedList
31 }
32
33 const mySchema: JTDSchemaType<MyData> = {
34 discriminator: "type",
35 mapping: {
36 a: {properties: {a: {type: "float64"}}},
37 b: {optionalProperties: {b: {type: "string"}}},
38 },
39 }
40
41 const missingSchema: JTDSchemaType<Missing> = {
42 discriminator: "type",
43 mapping: {
44 a: {properties: {a: {type: "float64"}}},
45 c: {properties: {}},
46 },
47 }
48
49 describe("JTDSchemaType", () => {
50 it("validation should prove the data type", () => {
51 const ajv = new _Ajv()
52 const validate = ajv.compile(mySchema)
53 const validData: unknown = {type: "a", a: 1}
54 if (validate(validData) && validData.type === "a") {
55 validData.a.should.equal(1)
56 }
57 should.not.exist(validate.errors)
58
59 if (ajv.validate(mySchema, validData) && validData.type === "a") {
60 validData.a.should.equal(1)
61 }
62 should.not.exist(ajv.errors)
63 })
64
65 it("parser should return correct data type", () => {
66 const ajv = new _Ajv()
67 const parse = ajv.compileParser(mySchema)
68 const validJson = '{"type": "a", "a": 1}'
69 const data = parse(validJson)
70 if (data !== undefined && data.type === "a") {
71 data.a.should.equal(1)
72 }
73 should.not.exist(parse.message)
74 })
75
76 it("serializer should only accept correct data type", () => {
77 const ajv = new _Ajv()
78 const serialize = ajv.compileSerializer(mySchema)
79 const validData = {type: "a" as const, a: 1}
80 serialize(validData).should.equal('{"type":"a","a":1}')
81 const invalidData = {type: "a" as const, b: "test"}
82 // @ts-expect-error
83 serialize(invalidData)
84 })
85
86 it("validation should prove the data type for missingSchema", () => {
87 const ajv = new _Ajv()
88 const validate = ajv.compile(missingSchema)
89 const validData: unknown = {type: "c"}
90
91 if (validate(validData)) {
92 validData.type.should.equal("c")
93 }
94 should.not.exist(validate.errors)
95
96 if (ajv.validate(missingSchema, validData)) {
97 validData.type.should.equal("c")
98 }
99 should.not.exist(validate.errors)
100 })
101
102 it("should typecheck number schemas", () => {
103 const numf: JTDSchemaType<number> = {type: "float64"}
104 const numi: JTDSchemaType<number> = {type: "int32"}
105 // @ts-expect-error
106 const numl: JTDSchemaType<number> = {type: "int64"}
107 // number literals don't work
108 // @ts-expect-error
109 const nums: JTDSchemaType<1 | 2 | 3> = {type: "int32"}
110 const numNull: JTDSchemaType<number | null> = {type: "int32", nullable: true}
111 // @ts-expect-error
112 const numNotNull: JTDSchemaType<number | null> = {type: "float32"}
113
114 void [numf, numi, numl, nums, numNull, numNotNull]
115 })
116
117 it("should typecheck boolean schemas", () => {
118 const bool: JTDSchemaType<boolean> = {type: "boolean"}
119 // boolean literals don't
120 // @ts-expect-error
121 const boolTrue: JTDSchemaType<true> = {type: "boolean"}
122 const boolNull: JTDSchemaType<boolean | null> = {type: "boolean", nullable: true}
123
124 void [bool, boolTrue, boolNull]
125 })
126
127 it("should typecheck string schemas", () => {
128 const str: JTDSchemaType<string> = {type: "string"}
129 const time: JTDSchemaType<string> = {type: "timestamp"}
130 const strNull: JTDSchemaType<string | null> = {type: "string", nullable: true}
131
132 void [str, time, strNull]
133 })
134
135 it("should typecheck dates", () => {
136 const time: JTDSchemaType<Date> = {type: "timestamp"}
137 const timeNull: JTDSchemaType<Date | null> = {type: "timestamp", nullable: true}
138
139 void [time, timeNull]
140 })
141
142 it("should typecheck enumeration schemas", () => {
143 const enumerate: JTDSchemaType<"a" | "b"> = {enum: ["a", "b"]}
144 // don't need to specify everything
145 const enumerateMissing: JTDSchemaType<"a" | "b" | "c"> = {enum: ["a", "b"]}
146 // must all be string literals
147 // @ts-expect-error
148 const enumerateNumber: JTDSchemaType<"a" | "b" | 5> = {enum: ["a", "b"]}
149 // can't overgeneralize in schema
150 // @ts-expect-error
151 const enumerateString: JTDSchemaType<"a" | "b"> = {type: "string"}
152 const enumerateNull: JTDSchemaType<"a" | "b" | null> = {enum: ["a", "b"], nullable: true}
153
154 void [enumerate, enumerateMissing, enumerateNumber, enumerateString, enumerateNull]
155 })
156
157 it("should typecheck elements schemas", () => {
158 const elements: JTDSchemaType<number[]> = {elements: {type: "float64"}}
159 const readonlyElements: JTDSchemaType<readonly number[]> = {elements: {type: "float64"}}
160 // tuples don't work
161 // @ts-expect-error
162 const tupleHomo: JTDSchemaType<[number, number]> = {elements: {type: "float64"}}
163 // @ts-expect-error
164 const tupleHeteroNum: JTDSchemaType<[number, string]> = {
165 elements: {type: "float64"},
166 }
167 // @ts-expect-error
168 const tupleHeteroString: JTDSchemaType<[number, string]> = {
169 elements: {type: "string"},
170 }
171 const elemNull: JTDSchemaType<number[] | null> = {elements: {type: "float64"}, nullable: true}
172
173 // can typecheck an array of unions
174 const unionElem: TypeEquality<JTDSchemaType<(A | B)[]>, never> = false
175 // can't typecheck a union of arrays
176 const elemUnion: TypeEquality<JTDSchemaType<A[] | B[]>, never> = true
177
178 void [
179 elements,
180 readonlyElements,
181 tupleHomo,
182 tupleHeteroNum,
183 tupleHeteroString,
184 elemNull,
185 unionElem,
186 elemUnion,
187 ]
188 })
189
190 it("should typecheck values schemas", () => {
191 const values: JTDSchemaType<Record<string, number>> = {values: {type: "float64"}}
192 const readonlyValues: JTDSchemaType<Readonly<Record<string, number>>> = {
193 values: {type: "float64"},
194 }
195 // values must be a whole mapping
196 // @ts-expect-error
197 const valuesDefined: JTDSchemaType<{prop: number}> = {values: {type: "float64"}}
198 const valuesNull: JTDSchemaType<Record<string, number> | null> = {
199 values: {type: "float64"},
200 nullable: true,
201 }
202
203 // can typecheck a values of unions
204 const unionValues: TypeEquality<JTDSchemaType<Record<string, A | B>>, never> = false
205 // can't typecheck a union of values
206 const valuesUnion: TypeEquality<
207 JTDSchemaType<Record<string, A> | Record<string, B>>,
208 never
209 > = true
210
211 void [values, readonlyValues, valuesDefined, valuesNull, unionValues, valuesUnion]
212 })
213
214 it("should typecheck properties schemas", () => {
215 const properties: JTDSchemaType<{a: number; b: string}> = {
216 properties: {a: {type: "float64"}, b: {type: "string"}},
217 }
218 const optionalProperties: JTDSchemaType<{a?: number; b?: string}> = {
219 optionalProperties: {a: {type: "float64"}, b: {type: "string"}},
220 additionalProperties: false,
221 }
222 const mixedProperties: JTDSchemaType<{a: number; b?: string}> = {
223 properties: {a: {type: "float64"}},
224 optionalProperties: {b: {type: "string"}},
225 additionalProperties: true,
226 }
227 const fewerProperties: JTDSchemaType<{a: number; b: string}> = {
228 // @ts-expect-error
229 properties: {a: {type: "float64"}},
230 }
231 const propertiesNull: JTDSchemaType<{a: number; b: string} | null> = {
232 properties: {a: {type: "float64"}, b: {type: "string"}},
233 nullable: true,
234 }
235
236 void [properties, optionalProperties, mixedProperties, fewerProperties, propertiesNull]
237 })
238
239 it("should typecheck discriminator schemas", () => {
240 const union: JTDSchemaType<A | B> = {
241 discriminator: "type",
242 mapping: {
243 a: {properties: {a: {type: "float64"}}},
244 b: {
245 optionalProperties: {b: {type: "string"}},
246 },
247 },
248 }
249 // can't mess up, e.g. value type isn't a union
250 const unionDuplicate: JTDSchemaType<A | B> = {
251 discriminator: "type",
252 mapping: {
253 a: {properties: {a: {type: "float64"}}},
254 // @ts-expect-error
255 b: {properties: {a: {type: "float64"}}},
256 },
257 }
258 // must specify everything
259 const unionMissing: JTDSchemaType<A | B> = {
260 discriminator: "type",
261 // @ts-expect-error
262 mapping: {
263 a: {properties: {a: {type: "float64"}}},
264 },
265 }
266 // can use any valid discrinimator
267 type Mult = JTDSchemaType<(A & {typ: "alpha"}) | (B & {typ: "beta"})>
268 const multOne: Mult = {
269 discriminator: "type",
270 mapping: {
271 a: {properties: {a: {type: "float64"}, typ: {enum: ["alpha"]}}},
272 b: {
273 properties: {typ: {enum: ["beta"]}},
274 optionalProperties: {b: {type: "string"}},
275 },
276 },
277 }
278 const multTwo: Mult = {
279 discriminator: "typ",
280 mapping: {
281 alpha: {properties: {a: {type: "float64"}, type: {enum: ["a"]}}},
282 beta: {
283 properties: {type: {enum: ["b"]}},
284 optionalProperties: {b: {type: "string"}},
285 },
286 },
287 }
288 const unionNull: JTDSchemaType<A | B | null> = {
289 discriminator: "type",
290 mapping: {
291 a: {properties: {a: {type: "float64"}}},
292 b: {
293 optionalProperties: {b: {type: "string"}},
294 },
295 },
296 nullable: true,
297 }
298
299 // properties must have common key
300 const noCommon: TypeEquality<
301 JTDSchemaType<{key1: "a"; a: number} | {key2: "b"; b: string}>,
302 never
303 > = true
304
305 void [union, unionDuplicate, unionMissing, multOne, multTwo, unionNull, noCommon]
306 })
307
308 it("should typecheck empty schemas", () => {
309 const empty: JTDSchemaType<unknown> = {}
310 // unknown can be null
311 const emptyUnknown: JTDSchemaType<unknown> = {nullable: true}
312 // somewhat unintuitively, it can still have nullable: false even though it can be null
313 const falseUnknown: JTDSchemaType<unknown> = {nullable: false}
314 // can only use empty for empty and null
315 // @ts-expect-error
316 const emptyButFull: JTDSchemaType<{a: string}> = {}
317 const emptyMeta: JTDSchemaType<unknown> = {metadata: {}}
318
319 // constant null representable as nullable empty object
320 const emptyNull: TypeEquality<JTDSchemaType<null>, never> = true
321
322 void [empty, emptyUnknown, falseUnknown, emptyButFull, emptyMeta, emptyNull]
323 })
324
325 it("should typecheck empty records", () => {
326 // empty record variants
327 const emptyPro: JTDSchemaType<{}> = {properties: {}}
328 const emptyOpt: JTDSchemaType<{}> = {optionalProperties: {}}
329 const emptyBoth: JTDSchemaType<{}> = {properties: {}, optionalProperties: {}}
330 const emptyRecord: JTDSchemaType<Record<string, never>> = {properties: {}}
331 const notNullable: JTDSchemaType<{}> = {properties: {}, nullable: false}
332
333 // can't be null
334 // @ts-expect-error
335 const nullable: JTDSchemaType<{}> = {properties: {}, nullable: true}
336
337 const emptyNullUnion: JTDSchemaType<null | {}> = {properties: {}, nullable: true}
338 const emptyNullRecord: JTDSchemaType<null | Record<string, never>> = {
339 properties: {},
340 nullable: true,
341 }
342
343 void [
344 emptyPro,
345 emptyOpt,
346 emptyBoth,
347 emptyRecord,
348 notNullable,
349 nullable,
350 emptyNullUnion,
351 emptyNullRecord,
352 ]
353 })
354
355 it("should typecheck ref schemas", () => {
356 const refs: JTDSchemaType<number[], {num: number}> = {
357 definitions: {
358 num: {type: "float64"},
359 },
360 elements: {ref: "num"},
361 }
362 const missingDef: JTDSchemaType<number[], {num: number}> = {
363 // @ts-expect-error
364 definitions: {},
365 elements: {ref: "num"},
366 }
367 const missingType: JTDSchemaType<number[]> = {
368 definitions: {},
369 // @ts-expect-error
370 elements: {ref: "num"},
371 }
372 const nullRefs: JTDSchemaType<number | null, {num: number}> = {
373 definitions: {
374 num: {type: "float64"},
375 },
376 ref: "num",
377 nullable: true,
378 }
379 const refsNullOne: JTDSchemaType<number | null, {num: number | null}> = {
380 definitions: {
381 num: {type: "float64", nullable: true},
382 },
383 ref: "num",
384 }
385 const refsNullTwo: JTDSchemaType<number | null, {num: number | null}> = {
386 definitions: {
387 num: {type: "float64", nullable: true},
388 },
389 ref: "num",
390 nullable: true,
391 }
392
393 void [refs, missingDef, missingType, nullRefs, refsNullOne, refsNullTwo]
394 })
395
396 it("should typecheck metadata schemas", () => {
397 const meta: JTDSchemaType<number> = {type: "float32", metadata: {key: "val"}}
398 const emptyMeta: JTDSchemaType<unknown> = {metadata: {key: "val"}}
399 const unknownMeta: JTDSchemaType<unknown> = {nullable: true, metadata: {key: "val"}}
400
401 void [meta, emptyMeta, unknownMeta]
402 })
403 })
404
405 describe("JTDDataType", () => {
406 it("validation should prove the data type", () => {
407 const ajv = new _Ajv()
408 const mySchema1 = {
409 discriminator: "type",
410 mapping: {
411 a: {properties: {a: {type: "float64"}}},
412 b: {optionalProperties: {b: {type: "string"}}},
413 },
414 } as const
415
416 const validate = ajv.compile(mySchema1)
417 const validData: unknown = {type: "a", a: 1}
418 if (validate(validData) && validData.type === "a") {
419 validData.a.should.equal(1)
420 }
421 should.not.exist(validate.errors)
422
423 if (ajv.validate(mySchema1, validData) && validData.type === "a") {
424 validData.a.should.equal(1)
425 }
426 should.not.exist(ajv.errors)
427 })
428
429 it("should typecheck number schemas", () => {
430 const numSchema = {type: "float64"} as const
431 const num: TypeEquality<JTDDataType<typeof numSchema>, number> = true
432
433 void [num]
434 })
435
436 it("should typecheck boolean schemas", () => {
437 const booleanSchema = {type: "boolean"} as const
438 const bool: TypeEquality<JTDDataType<typeof booleanSchema>, boolean> = true
439
440 void [bool]
441 })
442
443 it("should typecheck string schemas", () => {
444 const strSchema = {type: "string"} as const
445 const str: TypeEquality<JTDDataType<typeof strSchema>, string> = true
446
447 void [str]
448 })
449
450 it("should typecheck timestamp schemas", () => {
451 const timeSchema = {type: "timestamp"} as const
452 const time: TypeEquality<JTDDataType<typeof timeSchema>, string | Date> = true
453
454 void [time]
455 })
456
457 it("should typecheck enum schemas", () => {
458 const enumSchema = {enum: ["a", "b"]} as const
459 const enumerated: TypeEquality<JTDDataType<typeof enumSchema>, "a" | "b"> = true
460
461 // if you forget const on an enum it will error
462 const enumStringSchema = {enum: ["a", "b"]}
463 const enumString: TypeEquality<JTDDataType<typeof enumStringSchema>, never> = true
464 // also if not a string
465 const enumNumSchema = {enum: [3]} as const
466 const enumNum: TypeEquality<JTDDataType<typeof enumNumSchema>, never> = true
467
468 void [enumerated, enumString, enumNum]
469 })
470
471 it("should typecheck elements schemas", () => {
472 const elementsSchema = {elements: {type: "float64"}} as const
473 const elem: TypeEquality<JTDDataType<typeof elementsSchema>, number[]> = true
474
475 void [elem]
476 })
477
478 it("should typecheck properties schemas", () => {
479 const bothPropsSchema = {
480 properties: {a: {type: "float64"}},
481 optionalProperties: {b: {type: "string"}},
482 } as const
483 const both: TypeEquality<JTDDataType<typeof bothPropsSchema>, {a: number; b?: string}> = true
484
485 const reqPropsSchema = {properties: {a: {type: "float64"}}} as const
486 const req: TypeEquality<JTDDataType<typeof reqPropsSchema>, {a: number}> = true
487
488 const optPropsSchema = {optionalProperties: {b: {type: "string"}}} as const
489 const opt: TypeEquality<JTDDataType<typeof optPropsSchema>, {b?: string}> = true
490
491 const noAddSchema = {
492 optionalProperties: {b: {type: "string"}},
493 additionalProperties: false,
494 } as const
495 const noAdd: TypeEquality<JTDDataType<typeof noAddSchema>, {b?: string}> = true
496
497 const addSchema = {
498 optionalProperties: {b: {type: "string"}},
499 additionalProperties: true,
500 } as const
501 const add: TypeEquality<
502 JTDDataType<typeof addSchema>,
503 {b?: string; [key: string]: unknown}
504 > = true
505 const addVal: JTDDataType<typeof addSchema> = {b: "b", additional: 6}
506
507 void [both, req, opt, noAdd, add, addVal]
508 })
509
510 it("should typecheck values schemas", () => {
511 const valuesSchema = {values: {type: "float64"}} as const
512 const values: TypeEquality<JTDDataType<typeof valuesSchema>, Record<string, number>> = true
513
514 void [values]
515 })
516
517 it("should typecheck discriminator schemas", () => {
518 const discriminatorSchema = {
519 discriminator: "type",
520 mapping: {
521 a: {properties: {a: {type: "float64"}}},
522 b: {optionalProperties: {b: {type: "string"}}},
523 },
524 } as const
525 const disc: TypeEquality<JTDDataType<typeof discriminatorSchema>, A | B> = true
526
527 void [disc]
528 })
529
530 it("should typecheck ref schemas", () => {
531 const refSchema = {
532 definitions: {num: {type: "float64", nullable: true}},
533 ref: "num",
534 nullable: true,
535 } as const
536 const ref: TypeEquality<JTDDataType<typeof refSchema>, number | null> = true
537
538 // works for recursive schemas
539 const llSchema = {
540 definitions: {
541 node: {
542 properties: {val: {type: "float64"}},
543 optionalProperties: {next: {ref: "node"}},
544 },
545 },
546 ref: "node",
547 } as const
548 const list: TypeEquality<JTDDataType<typeof llSchema>, LinkedList> = true
549
550 void [ref, list]
551 })
552
553 it("should typecheck empty schemas", () => {
554 const emptySchema = {metadata: {}} as const
555 const empty: TypeEquality<JTDDataType<typeof emptySchema>, unknown> = true
556
557 void [empty]
558 })
559 })
560
561 describe("SomeJTDSchemaType", () => {
562 it("should allow setting unknowns", () => {
563 // This test is basically here to assert that we should be using `{}` in
564 // SomeJTDSchemaType
565 const schema: SomeJTDSchemaType = {}
566
567 void [schema]
568 })
569 })