const.ts 863 B

12345678910111213141516171819202122232425262728
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type {KeywordCxt} from "../../compile/validate"
  3. import {_} from "../../compile/codegen"
  4. import {useFunc} from "../../compile/util"
  5. import equal from "../../runtime/equal"
  6. export type ConstError = ErrorObject<"const", {allowedValue: any}>
  7. const error: KeywordErrorDefinition = {
  8. message: "must be equal to constant",
  9. params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,
  10. }
  11. const def: CodeKeywordDefinition = {
  12. keyword: "const",
  13. $data: true,
  14. error,
  15. code(cxt: KeywordCxt) {
  16. const {gen, data, $data, schemaCode, schema} = cxt
  17. if ($data || (schema && typeof schema == "object")) {
  18. cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)
  19. } else {
  20. cxt.fail(_`${schema} !== ${data}`)
  21. }
  22. },
  23. }
  24. export default def