1 import fs from "fs/promises"
2 import { File, parse, ParseResult, traverse } from "../babel"
3 import { logger } from "../logger"
4 import {
5 crawl,
6 generateHash,
7 getConfigObjectProperties,
8 getParserOptions,
9 } from "../utils"
10
11 export async function generateRouteHashes(
12 sources: Set<string>
13 ): Promise<{ defaultExportHash: string; configHash: string }> {
14 const files = await getFilesFromSources(sources)
15 const contents = await Promise.all(files.map(getRouteContents))
16
17 const defaultExportContents = contents
18 .map((c) => c.defaultExport)
19 .filter(Boolean)
20 const configContents = contents.map((c) => c.config).filter(Boolean)
21
22 const totalDefaultExportContent = defaultExportContents.join("")
23 const totalConfigContent = configContents.join("")
24
25 return {
26 defaultExportHash: generateHash(totalDefaultExportContent),
27 configHash: generateHash(totalConfigContent),
28 }
29 }
30
31 async function getFilesFromSources(sources: Set<string>): Promise<string[]> {
32 return (
33 await Promise.all(
34 Array.from(sources).map(async (source) =>
35 crawl(`${source}/routes`, "page", { min: 1 })
36 )
37 )
38 ).flat()
39 }
40
41 async function getRouteContents(
42 file: string
43 ): Promise<{ defaultExport: string | null; config: string | null }> {
44 const code = await fs.readFile(file, "utf-8")
45
46 let ast: ParseResult<File> | null = null
47
48 try {
49 ast = parse(code, getParserOptions(file))
50 } catch (e) {
51 logger.error(`An error occurred while parsing the file.`, {
52 file,
53 error: e,
54 })
55 return { defaultExport: null, config: null }
56 }
57
58 let defaultExportContent: string | null = null
59 let configContent: string | null = null
60
61 try {
62 traverse(ast, {
63 ExportDefaultDeclaration(path) {
64 defaultExportContent = code.slice(path.node.start!, path.node.end!)
65 },
66 ExportNamedDeclaration(path) {
67 const properties = getConfigObjectProperties(path)
68 if (properties) {
69 configContent = code.slice(path.node.start!, path.node.end!)
70 }
71 },
72 })
73 } catch (e) {
74 logger.error(
75 `An error occurred while processing ${file}. See the below error for more details:\n${e}`,
76 { file, error: e }
77 )
78 return { defaultExport: null, config: null }
79 }
80
81 return { defaultExport: defaultExportContent, config: configContent }
82 }