summaryrefslogtreecommitdiff
path: root/scripts/generate-sitemap.ts
blob: e9f711f93f7ec993fbf3994d91c82b5a9e90e5c2 (plain)
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
import { promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const SITE_URL = (process.env.SITE_URL ?? "https://wsap.dev").replace(
  /\/+$/,
  "",
);
const STATIC_ROUTES = ["/", "/about", "/apps"];

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, "..");
const postsDir = path.join(projectRoot, "src", "posts");
const sitemapPath = path.join(projectRoot, "static", "sitemap.txt");

async function getPostRoutes(): Promise<string[]> {
  const files = await fs.readdir(postsDir);

  return files
    .filter((file) => file.endsWith(".svx"))
    .map((file) => `/posts/${file.replace(/\.svx$/, "")}`)
    .sort();
}

async function main(): Promise<void> {
  const postRoutes = await getPostRoutes();
  const urls = [...STATIC_ROUTES, ...postRoutes].map(
    (route) => `${SITE_URL}${route}`,
  );
  const body = `${urls.join("\n")}\n`;

  await fs.writeFile(sitemapPath, body, "utf8");
  console.log(
    `Generated sitemap: ${path.relative(projectRoot, sitemapPath)} (${urls.length} URLs)`,
  );
}

main().catch((error: unknown) => {
  console.error("Failed to generate sitemap.txt");
  console.error(error);
  process.exit(1);
});