schema.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env bun
  2. import { z } from "zod"
  3. import { Config } from "../src/config/config"
  4. import { TuiConfig } from "../src/config/tui"
  5. function generate(schema: z.ZodType) {
  6. const result = z.toJSONSchema(schema, {
  7. io: "input", // Generate input shape (treats optional().default() as not required)
  8. /**
  9. * We'll use the `default` values of the field as the only value in `examples`.
  10. * This will ensure no docs are needed to be read, as the configuration is
  11. * self-documenting.
  12. *
  13. * See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.9.5
  14. */
  15. override(ctx) {
  16. const schema = ctx.jsonSchema
  17. // Preserve strictness: set additionalProperties: false for objects
  18. if (
  19. schema &&
  20. typeof schema === "object" &&
  21. schema.type === "object" &&
  22. schema.additionalProperties === undefined
  23. ) {
  24. schema.additionalProperties = false
  25. }
  26. // Add examples and default descriptions for string fields with defaults
  27. if (schema && typeof schema === "object" && "type" in schema && schema.type === "string" && schema?.default) {
  28. if (!schema.examples) {
  29. schema.examples = [schema.default]
  30. }
  31. schema.description = [schema.description || "", `default: \`${schema.default}\``]
  32. .filter(Boolean)
  33. .join("\n\n")
  34. .trim()
  35. }
  36. },
  37. }) as Record<string, unknown> & {
  38. allowComments?: boolean
  39. allowTrailingCommas?: boolean
  40. }
  41. // used for json lsps since config supports jsonc
  42. result.allowComments = true
  43. result.allowTrailingCommas = true
  44. return result
  45. }
  46. const configFile = process.argv[2]
  47. const tuiFile = process.argv[3]
  48. console.log(configFile)
  49. await Bun.write(configFile, JSON.stringify(generate(Config.Info), null, 2))
  50. if (tuiFile) {
  51. console.log(tuiFile)
  52. await Bun.write(tuiFile, JSON.stringify(generate(TuiConfig.Info), null, 2))
  53. }