1 const fs = require("fs/promises")
2 const path = require("path")
3 const prettier = require("prettier")
4
5 const translationsDir = path.join(__dirname, "../../src/i18n/translations")
6 const enPath = path.join(translationsDir, "en.json")
7 const schemaPath = path.join(translationsDir, "$schema.json")
8
9 const ALL_PLURAL_FORMS = ["zero", "one", "two", "few", "many", "other"]
10
11 function getBaseKey(key) {
12 for (const form of ALL_PLURAL_FORMS) {
13 if (key.endsWith(`_${form}`)) {
14 return key.slice(0, -(form.length + 1))
15 }
16 }
17 return null
18 }
19
20 function generateSchemaFromObject(obj) {
21 if (typeof obj !== "object" || obj === null) {
22 return { type: typeof obj }
23 }
24
25 if (Array.isArray(obj)) {
26 return {
27 type: "array",
28 items: generateSchemaFromObject(obj[0] || "string"),
29 }
30 }
31
32 const properties = {}
33 const required = []
34 const localePluralBaseKeys = new Set()
35
36 Object.entries(obj).forEach(([key, value]) => {
37 const baseKey = getBaseKey(key)
38 if (baseKey) {
39 if (!localePluralBaseKeys.has(baseKey)) {
40 localePluralBaseKeys.add(baseKey)
41 ALL_PLURAL_FORMS.forEach((form) => {
42 properties[`${baseKey}_${form}`] = { type: "string" }
43 })
44 }
45 return
46 }
47
48 properties[key] = generateSchemaFromObject(value)
49 required.push(key)
50 })
51
52 return {
53 type: "object",
54 properties,
55 required,
56 additionalProperties: false,
57 }
58 }
59
60 async function main() {
61 const enContent = await fs.readFile(enPath, "utf-8")
62 const enJson = JSON.parse(enContent)
63
64 const schema = {
65 $schema: "http://json-schema.org/draft-07/schema#",
66 ...generateSchemaFromObject(enJson),
67 }
68
69 const formattedSchema = await prettier.format(
70 JSON.stringify(schema, null, 2),
71 {
72 parser: "json",
73 }
74 )
75
76 await fs
77 .writeFile(schemaPath, formattedSchema)
78 .then(() => {
79 console.log("Schema generated successfully at:", schemaPath)
80 })
81 .catch((error) => {
82 console.error("Error generating schema:", error.message)
83 process.exit(1)
84 })
85 }
86
87 main()