Repository navigation
Expand file tree
/
Copy pathcompile-database.ts
More file actions
145 lines (132 loc) · 3.54 KB
/
Copy pathcompile-database.ts
File metadata and controls
145 lines (132 loc) · 3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import fs from "node:fs";
import { readdir } from "node:fs/promises";
import path from "node:path";
import { YAML } from "bun";
import type { z } from "zod";
import {
type Database,
DatabaseSchema,
type EntityIcon,
fileNameToId,
type Meta,
MetaSchema,
ResourceSchema,
} from ".";
import { discoverIcons, IconManifestSchema } from "./icons";
import {
andThen,
type Diagnostic,
error,
fail,
fromZod,
hasErrors,
ok,
partition,
report,
type Validation,
warning,
} from "./validation";
type DatabaseMetadata = {
id: string;
icon?: EntityIcon;
} & Meta;
async function readYaml<T>(
filePath: string,
schema: z.ZodType<T>,
where: string,
): Promise<Validation<T>> {
const content = await fs.promises.readFile(filePath, "utf-8");
let parsed: unknown;
try {
parsed = YAML.parse(content);
} catch (cause) {
const reason = cause instanceof Error ? cause.message : String(cause);
return fail([error(where, `invalid YAML: ${reason}`)]);
}
return fromZod(schema.safeParse(parsed), where);
}
async function yamlFiles(dir: string) {
const files = await readdir(dir, { recursive: true });
return files.filter((f) => f.endsWith(".yaml")).toSorted();
}
async function buildDatabase() {
const metaDir = path.join(__dirname, "./metadata");
const resourcesDir = path.join(__dirname, "./resources");
const iconsDir = path.join(__dirname, "./icons");
const manifestPath = path.join(iconsDir, "manifest.yaml");
const diagnostics: Diagnostic[] = [];
const finish = (): never => {
report(diagnostics);
console.error("Build failed due to validation errors.");
process.exit(1);
};
const metaFiles = await yamlFiles(metaDir);
const metaResults = await Promise.all(
metaFiles.map(async (file) =>
andThen(
await readYaml(
path.join(metaDir, file),
MetaSchema,
`metadata/${file}`,
),
(meta) => ok({ id: fileNameToId(file), ...meta }),
),
),
);
const { values: metadata, diagnostics: metaDiagnostics } =
partition<DatabaseMetadata>(metaResults);
diagnostics.push(...metaDiagnostics);
const manifest = fs.existsSync(manifestPath)
? await readYaml(manifestPath, IconManifestSchema, "icons/manifest.yaml")
: ok({});
const icons = andThen(manifest, (m) =>
discoverIcons(
iconsDir,
metaFiles.map(fileNameToId),
m,
),
);
diagnostics.push(...icons.diagnostics);
if (icons.ok) {
for (const meta of metadata) {
const icon = icons.value[meta.id];
if (icon) {
meta.icon = icon;
} else {
diagnostics.push(warning(`metadata/${meta.id}`, "entity has no icon"));
}
}
}
const resourceResults = await Promise.all(
(await yamlFiles(resourcesDir)).map(async (file) =>
readYaml(
path.join(resourcesDir, file),
ResourceSchema,
`resources/${file}`,
),
),
);
const { values: resources, diagnostics: resourceDiagnostics } =
partition(resourceResults);
diagnostics.push(...resourceDiagnostics);
if (hasErrors(diagnostics)) {
return finish();
}
// verify the entire database against the schema before writing
const database = { metadata, resources } satisfies Database;
const final = fromZod(DatabaseSchema.safeParse(database), "database");
diagnostics.push(...final.diagnostics);
if (!final.ok) {
return finish();
}
report(diagnostics);
const outputPath = path.join(__dirname, "./database.json");
await fs.promises.writeFile(outputPath, JSON.stringify(database, null, 2));
console.log(
`Success! Compiled ${metadata.length} entities and ${resources.length} resources.`,
);
}
buildDatabase().catch((err) => {
console.error("Unexpected error during build:", err);
process.exit(1);
});