propertyNames.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import type {
  2. CodeKeywordDefinition,
  3. ErrorObject,
  4. KeywordErrorDefinition,
  5. AnySchema,
  6. } from "../../types"
  7. import type {KeywordCxt} from "../../compile/validate"
  8. import {_, not} from "../../compile/codegen"
  9. import {alwaysValidSchema} from "../../compile/util"
  10. export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema>
  11. const error: KeywordErrorDefinition = {
  12. message: "property name must be valid",
  13. params: ({params}) => _`{propertyName: ${params.propertyName}}`,
  14. }
  15. const def: CodeKeywordDefinition = {
  16. keyword: "propertyNames",
  17. type: "object",
  18. schemaType: ["object", "boolean"],
  19. error,
  20. code(cxt: KeywordCxt) {
  21. const {gen, schema, data, it} = cxt
  22. if (alwaysValidSchema(it, schema)) return
  23. const valid = gen.name("valid")
  24. gen.forIn("key", data, (key) => {
  25. cxt.setParams({propertyName: key})
  26. cxt.subschema(
  27. {
  28. keyword: "propertyNames",
  29. data: key,
  30. dataTypes: ["string"],
  31. propertyName: key,
  32. compositeRule: true,
  33. },
  34. valid
  35. )
  36. gen.if(not(valid), () => {
  37. cxt.error(true)
  38. if (!it.allErrors) gen.break()
  39. })
  40. })
  41. cxt.ok(valid)
  42. },
  43. }
  44. export default def