@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
114 lines (112 loc) • 4.18 kB
JavaScript
import { assert, requireDefined } from "./assertions.js";
import { readSoftrContext } from "./auth/context.js";
import { exportRecordsUpTo } from "./datasource/record.js";
//#region src/search-engines.ts
/** The sitemap protocol's limit for one file. */
const MAX_ENTRIES = 5e4;
/** How long a sitemap stays cached before the next request builds it again. */
const CACHE_SECONDS = 1440 * 60;
/** App workers cannot use the default cache, so the sitemap has a named cache of its own. */
const CACHE_NAME = "softr-sitemap";
const TRAINING_CRAWLERS = [
["Amazonbot"],
["Applebot-Extended"],
["Bytespider"],
["CCBot"],
["ClaudeBot"],
["Diffbot"],
["Google-Extended"],
["GPTBot"],
["omgili"],
["anthropic-ai"],
["Claude-Web"],
["cohere-ai"],
["MistralAI-Training"],
["meta-externalagent"],
["GoogleOther"],
["AwarioSmartBot", "AwarioRssBot"],
["Google-CloudVertexBot"],
["QualifiedBot"],
["Cotoyogi"],
["ICC-Crawler"],
["atlassian-bot"],
["FishBot"],
["BorderxBot"],
["NavuBot"],
["WARDBot"],
["magpie-crawler"],
["KimiBot"],
["CitibotSiteCrawler"]
];
/**
* Answers `/robots.txt`: search engines may crawl the app, AI training crawlers
* may not, and the `Sitemap:` line points to the app's `/sitemap.xml`. An
* app's own `public/robots.txt` wins over this route.
*
* @example
* // src/routes/robots[.]txt.ts
* export const Route = createFileRoute("/robots.txt")({
* server: { handlers: { GET: robotsTxt() } },
* })
*/
function robotsTxt() {
return () => {
const groups = [
"User-agent: *\nContent-Signal: search=yes,ai-train=no,use=reference\nAllow: /",
...TRAINING_CRAWLERS.map((agents) => `${agents.map((agent) => `User-agent: ${agent}`).join("\n")}\nDisallow: /`),
`Sitemap: ${visitorOrigin()}/sitemap.xml`
];
return new Response(`${groups.join("\n\n")}\n`, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
};
}
/**
* Answers `/sitemap.xml` with the app's public pages and one page per public
* record. It reads the records as a signed-out visitor and keeps the file for
* a day, so search engines get only public records and the datasource is read
* at most once a day per region. A new publish starts a new file.
*
* @example
* // src/routes/sitemap[.]xml.ts
* export const Route = createFileRoute("/sitemap.xml")({
* server: {
* handlers: {
* GET: sitemapXml({
* pages: ["/", "/bikes"],
* records: [{ query: bikesQuery, path: (bike) => `/bikes/${bike.id}` }],
* }),
* },
* },
* })
*/
function sitemapXml(sources) {
return async () => {
const origin = visitorOrigin();
const shared = readSoftrContext().user === null;
const cache = shared && typeof caches !== "undefined" ? await caches.open(CACHE_NAME) : null;
const key = new Request(`${origin}/sitemap.xml?build=${typeof __SOFTR_BUILD_ID__ === "undefined" ? "dev" : __SOFTR_BUILD_ID__}`);
const stored = await cache?.match(key);
if (stored !== void 0) return new Response(stored.body, stored);
const paths = [...sources.pages];
for (const { query, path } of sources.records ?? []) {
if (paths.length >= MAX_ENTRIES) break;
const { records } = await exportRecordsUpTo(query, MAX_ENTRIES - paths.length);
paths.push(...records.map(path));
}
const xml = `xml version="1.0" encoding="UTF-8"\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${paths.slice(0, MAX_ENTRIES).map((path) => {
assert(path.startsWith("/"), `A sitemap path starts with "/", got "${path}"`);
return ` <url><loc>${(origin + path).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)}</loc></url>`;
}).join("\n")}\n</urlset>\n`;
const response = new Response(xml, { headers: {
"Content-Type": "application/xml; charset=utf-8",
"Cache-Control": shared ? `max-age=${CACHE_SECONDS}` : "private, no-store"
} });
if (cache !== null) await cache.put(key, response.clone());
return response;
};
}
/** The address the visitor opened the app at, as `softrAuthMiddleware` resolved it for this request. */
function visitorOrigin() {
return requireDefined(readSoftrContext().origin, "softrAuthMiddleware sets the origin on every request");
}
//#endregion
export { robotsTxt, sitemapXml };