1 import type {CodeKeywordDefinition, KeywordErrorDefinition, ErrorObject} from "../../types"
2 import type {KeywordCxt} from "../../compile/validate"
3 import {_, or, and, Code} from "../../compile/codegen"
4 import {checkMetadata} from "./metadata"
5 import {checkNullable} from "./nullable"
7 export type JTDEnumError = ErrorObject<"enum", {allowedValues: string[]}, string[]>
9 const error: KeywordErrorDefinition = {
10 message: "must be equal to one of the allowed values",
11 params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,
14 const def: CodeKeywordDefinition = {
18 code(cxt: KeywordCxt) {
20 const {gen, data, schema, schemaValue, parentSchema, it} = cxt
21 if (schema.length === 0) throw new Error("enum must have non-empty array")
22 if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique")
24 const isString = _`typeof ${data} == "string"`
25 if (schema.length >= it.opts.loopEnum) {
27 ;[valid, cond] = checkNullable(cxt, isString)
28 gen.if(cond, loopEnum)
30 /* istanbul ignore if */
31 if (!Array.isArray(schema)) throw new Error("ajv implementation error")
32 valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`)))
33 if (parentSchema.nullable) valid = or(_`${data} === null`, valid)
37 function loopEnum(): void {
38 gen.forOf("v", schemaValue as Code, (v) =>
39 gen.if(_`${valid} = ${data} === ${v}`, () => gen.break())