next-dynamic-sitemap
Version:
A lightweight, zero-touch sitemap generator for any nextjs project
61 lines (60 loc) • 2.97 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recurseAppDir = recurseAppDir;
const promises_1 = require("fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const util_1 = require("./util");
const build_1 = require("./build");
const PAGE_RE_TEXT = "page.[tj]sx?$";
const PAGE_RE_SUFFIX_TEXT = `/?${PAGE_RE_TEXT}`;
const PAGE_RE = new RegExp(PAGE_RE_TEXT);
const PAGE_SUFFIX_RE = new RegExp(PAGE_RE_SUFFIX_TEXT);
function introspectPage(root, page) {
return __awaiter(this, void 0, void 0, function* () {
const pagePath = node_path_1.default.join(root, page);
const pageURLPath = page.replace(PAGE_SUFFIX_RE, "");
const pageStats = yield (0, promises_1.stat)(node_path_1.default.join(process.cwd(), pagePath));
const lastmod = new Date(pageStats.mtime).toISOString();
if (/\[/.test(pagePath)) {
const bundle = yield (0, build_1.bundlePage)(pagePath);
if ("generateStaticParams" in bundle &&
typeof bundle.generateStaticParams === "function") {
const result = yield bundle.generateStaticParams();
return result.map((params) => (0, util_1.parameterizePath)(pageURLPath, lastmod, params));
}
}
return [
{
loc: (0, util_1.generateURL)(pageURLPath),
lastmod,
priority: pageURLPath ? 0.8 : 1, // home page gets higher priority
},
];
});
}
function recurseAppDir(root) {
return __awaiter(this, void 0, void 0, function* () {
const contents = yield (0, promises_1.readdir)(node_path_1.default.join(process.cwd(), root), {
recursive: true,
});
const pages = contents.filter((page) => PAGE_RE.test(page));
const metadata = yield Promise.all(pages.map((page) => __awaiter(this, void 0, void 0, function* () { return introspectPage(root, page); })));
const metadataFlattened = [];
metadata.forEach((page) => {
metadataFlattened.push(...page);
});
return metadataFlattened;
});
}