import { join, relative, ensureFileSync } from "../deps.ts"; const ROUTES_FILE = "routes.generated.ts"; // const ROUTES_PATH = "../src" // An object that links a file to a route // api/auth/token/index.ts -> /api/auth/token interface PageRoute { path: string; route: string; } async function readDir(dir: URL): Promise { // Sort the Entries const entries = [...Deno.readDirSync(dir)] entries.sort((a, b) => a.name.toUpperCase() < b.name.toUpperCase() ? -1 : 1); const routes: PageRoute[] = [] for (const file of entries) { const path = join(dir.pathname, file.name) if (file.isDirectory) { const sub = await readDir(new URL(path, import.meta.url)) routes.push(...sub) continue; } const relativePath = relative( new URL(import.meta.url + "/..").pathname, path ) const route = "/" + relativePath.replaceAll( /\[(.*?)\]/g, ":$1", ).replace(/(\.ts)|(\.js)|(\/index(\.ts|\.js))/, "") .replace(/[\\/]+/g, '/') const filePath = `./${relativePath}`; const replaced = route.replace("/../src/routes", "") let finalRoute = replaced; if (replaced.includes('index') && !replaced.startsWith("/index")) finalRoute = replaced.replace("/index", "") else finalRoute = replaced.replace('/index', '/') routes.push({ route: finalRoute, path: filePath, }); } return routes; } function createFile(routes: PageRoute[]): string { let string = `// This File is Autogenerated by scripts/routes.ts // Do not edit this File manually // run \`vr routes\` to regenerate this File ${routes.map((route, index) => (`import { method as method_${index}, handler as handler_${index} } from "${route.path.replace(/[\\/]+/g, '/')}";`).replace('./../src', ".")).join("\n")} interface PageRoute { method: string | string[] handler: void | any route: string } const routes: PageRoute[] = [ ${routes.map((route, index) => ( `{ method: method_${index}, handler: handler_${index}, route: "${route.route}"}` )).join(",\n ")} ] export default routes ` return string } async function write(folderwithroutes: string | URL, file: string | URL) { if (typeof folderwithroutes === "string") folderwithroutes = new URL(folderwithroutes, import.meta.url); // console.log(folderwithroutes) const routes = await readDir(folderwithroutes) const content = createFile(routes) await Deno.writeTextFile(`./src/${file}`, content) } if (import.meta.main) { console.log(`Writing ${ROUTES_FILE}`) try { ensureFileSync(`./src/${ROUTES_FILE}`) await write('../src/routes', ROUTES_FILE) } catch (error) { console.error(error) Deno.exit(1) } console.log(`File written.`) Deno.exit(0) }