items2020.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import type {
  2. CodeKeywordDefinition,
  3. KeywordErrorDefinition,
  4. ErrorObject,
  5. AnySchema,
  6. } from "../../types"
  7. import type {KeywordCxt} from "../../compile/validate"
  8. import {_, str} from "../../compile/codegen"
  9. import {alwaysValidSchema} from "../../compile/util"
  10. import {validateArray} from "../code"
  11. import {validateAdditionalItems} from "./additionalItems"
  12. export type ItemsError = ErrorObject<"items", {limit: number}, AnySchema>
  13. const error: KeywordErrorDefinition = {
  14. message: ({params: {len}}) => str`must NOT have more than ${len} items`,
  15. params: ({params: {len}}) => _`{limit: ${len}}`,
  16. }
  17. const def: CodeKeywordDefinition = {
  18. keyword: "items",
  19. type: "array",
  20. schemaType: ["object", "boolean"],
  21. before: "uniqueItems",
  22. error,
  23. code(cxt: KeywordCxt) {
  24. const {schema, parentSchema, it} = cxt
  25. const {prefixItems} = parentSchema
  26. it.items = true
  27. if (alwaysValidSchema(it, schema)) return
  28. if (prefixItems) validateAdditionalItems(cxt, prefixItems)
  29. else cxt.ok(validateArray(cxt))
  30. },
  31. }
  32. export default def