1import * as fs from "fs/promises"
2import * as fsSync from "fs"
3import * as path from "path"
4import { compile } from "json-schema-to-typescript"
5
6const BANNER = `/*
7* This file is autogenerated
8*/\n\n`
9const dirname = __dirname
10
11async function main() {
12 const schemasPath = path.join(dirname, "../../", "crates/theme/schemas")
13 const schemaFiles = (await fs.readdir(schemasPath)).filter((x) =>
14 x.endsWith(".json")
15 )
16
17 const compiledTypes = new Set()
18
19 for (const filename of schemaFiles) {
20 const filePath = path.join(schemasPath, filename)
21 const fileContents = await fs.readFile(filePath)
22 const schema = JSON.parse(fileContents.toString())
23 const compiled = await compile(schema, schema.title, {
24 bannerComment: "",
25 })
26 const eachType = compiled.split("export")
27 for (const type of eachType) {
28 if (!type) {
29 continue
30 }
31 compiledTypes.add("export " + type.trim())
32 }
33 }
34
35 const output = BANNER + Array.from(compiledTypes).join("\n\n")
36 const outputPath = path.join(dirname, "../../styles/src/types/zed.ts")
37
38 try {
39 const existing = await fs.readFile(outputPath)
40 if (existing.toString() == output) {
41 // Skip writing if it hasn't changed
42 console.log("Schemas are up to date")
43 return
44 }
45 } catch (e) {
46 // @ts-expect-error - It's fine if there's no output from a previous run.
47 if (e.code !== "ENOENT") {
48 throw e
49 }
50 }
51
52 const typesDic = path.dirname(outputPath)
53 if (!fsSync.existsSync(typesDic)) {
54 await fs.mkdir(typesDic)
55 }
56 await fs.writeFile(outputPath, output)
57 console.log(`Wrote Typescript types to ${outputPath}`)
58}
59
60main().catch((e) => {
61 console.error(e)
62 process.exit(1)
63})