1 import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
2 import type {KeywordCxt} from "../../compile/validate"
3 import {_, or, Code} from "../../compile/codegen"
4 import validTimestamp from "../../runtime/timestamp"
5 import {useFunc} from "../../compile/util"
6 import {checkMetadata} from "./metadata"
7 import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
9 export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>
11 export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"
13 export const intRange: {[T in IntType]: [number, number, number]} = {
16 int16: [-32768, 32767, 5],
17 uint16: [0, 65535, 5],
18 int32: [-2147483648, 2147483647, 10],
19 uint32: [0, 4294967295, 10],
22 export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType
24 const error: KeywordErrorDefinition = {
25 message: (cxt) => typeErrorMessage(cxt, cxt.schema),
26 params: (cxt) => typeErrorParams(cxt, cxt.schema),
29 const def: CodeKeywordDefinition = {
33 code(cxt: KeywordCxt) {
35 const {gen, data, schema, parentSchema} = cxt
40 cond = _`typeof ${data} == ${schema}`
43 const vts = useFunc(gen, validTimestamp)
44 cond = _`${data} instanceof Date || (typeof ${data} == "string" && ${vts}(${data}))`
49 cond = _`typeof ${data} == "number"`
52 const [min, max] = intRange[schema as IntType]
53 cond = _`typeof ${data} == "number" && isFinite(${data}) && ${data} >= ${min} && ${data} <= ${max} && !(${data} % 1)`
56 cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)