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 let schemasPath = path.join(dirname, "../../", "crates/theme/schemas")
13 let schemaFiles = (await fs.readdir(schemasPath)).filter((x) =>
14 x.endsWith(".json")
15 )
16
17 let compiledTypes = new Set()
18
19 for (let filename of schemaFiles) {
20 let filePath = path.join(schemasPath, filename)
21 const fileContents = await fs.readFile(filePath)
22 let schema = JSON.parse(fileContents.toString())
23 let compiled = await compile(schema, schema.title, {
24 bannerComment: "",
25 })
26 let eachType = compiled.split("export")
27 for (let type of eachType) {
28 if (!type) {
29 continue
30 }
31 compiledTypes.add("export " + type.trim())
32 }
33 }
34
35 let output = BANNER + Array.from(compiledTypes).join("\n\n")
36 let outputPath = path.join(dirname, "../../styles/src/types/zed.ts")
37
38 try {
39 let 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 // It's fine if there's no output from a previous run.
47 // @ts-ignore
48 if (e.code !== "ENOENT") {
49 throw e
50 }
51 }
52
53 const typesDic = path.dirname(outputPath)
54 if (!fsSync.existsSync(typesDic)) {
55 await fs.mkdir(typesDic)
56 }
57 await fs.writeFile(outputPath, output)
58 console.log(`Wrote Typescript types to ${outputPath}`)
59}
60
61main().catch((e) => {
62 console.error(e)
63 process.exit(1)
64})