-
Notifications
You must be signed in to change notification settings - Fork 169
/
generate.ts
54 lines (49 loc) · 1.81 KB
/
generate.ts
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
import { parseExportNames } from "https://deno.land/x/aleph_compiler@0.1.0/mod.ts";
import type { Route } from "../framework/core/route.ts";
/** generate the `routes.gen.ts` follow the routes config */
export async function generate(routes: Route[]) {
const routeFiles = await Promise.all(routes.map(async ([_, { filename }]) => {
const code = await Deno.readTextFile(filename);
const exportNames = await parseExportNames(filename, code);
return [filename, exportNames];
}));
const imports: string[] = [];
const revives: string[] = [];
routeFiles.forEach(([filename, exportNames], idx) => {
const hasDefaultExport = exportNames.includes("default");
const hasDataExport = exportNames.includes("data");
if (!hasDefaultExport && !hasDataExport) {
return [];
}
imports.push(`import { ${
[
hasDefaultExport && `default as $${idx}`,
hasDataExport && `data as $$${idx}`,
].filter(Boolean).join(", ")
} } from ${JSON.stringify(filename)};`);
revives.push(`revive(${JSON.stringify(filename)}, { ${
[
hasDefaultExport && `default: $${idx}`,
hasDataExport && `data: $$${idx}`,
].filter(Boolean).join(", ")
} });`);
});
if (imports.length) {
const code = [
"/*! Generated by Aleph.js, do **NOT** change and ensure the file is **NOT** in the `.gitignore`. */",
"",
`import { revive } from "aleph/server";`,
...imports,
"",
...revives,
].join("\n");
await Deno.writeTextFile("routes.gen.ts", code);
const serverEntry = Deno.env.get("ALEPH_SERVER_ENTRY");
if (serverEntry) {
const code = await Deno.readTextFile(serverEntry);
if (!code.includes(`import "./routes.gen.ts"`)) {
await Deno.writeTextFile(serverEntry, `import "./routes.gen.ts"\n${code}`);
}
}
}
}