maisongr-sitemap 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +70 -12
  2. package/dist/build/crawl.d.ts +32 -0
  3. package/dist/build/crawl.js +210 -0
  4. package/dist/build/css-fonts.d.ts +1 -0
  5. package/dist/build/css-fonts.js +35 -6
  6. package/dist/build/detect.d.ts +7 -0
  7. package/dist/build/detect.js +10 -1
  8. package/dist/build/fonts.d.ts +2 -0
  9. package/dist/build/fonts.js +14 -2
  10. package/dist/build/framework-build.d.ts +6 -0
  11. package/dist/build/framework-build.js +5 -3
  12. package/dist/build/manifest.d.ts +2 -0
  13. package/dist/build/next-build.d.ts +12 -0
  14. package/dist/build/next-build.js +86 -8
  15. package/dist/build/next-routes.js +5 -3
  16. package/dist/build/node-build.d.ts +39 -0
  17. package/dist/build/node-build.js +171 -0
  18. package/dist/build/palette.js +1 -1
  19. package/dist/build/project.d.ts +6 -0
  20. package/dist/build/project.js +29 -5
  21. package/dist/build/route-rules.d.ts +9 -0
  22. package/dist/build/route-rules.js +16 -0
  23. package/dist/build/scripts.js +2 -2
  24. package/dist/build/spa-routes.d.ts +20 -0
  25. package/dist/build/spa-routes.js +135 -0
  26. package/dist/build/static.d.ts +35 -3
  27. package/dist/build/static.js +112 -34
  28. package/dist/cli/main.d.ts +3 -0
  29. package/dist/cli/main.js +397 -108
  30. package/dist/cli/routes.d.ts +6 -0
  31. package/dist/cli/routes.js +52 -1
  32. package/dist/cli/ui.d.ts +59 -0
  33. package/dist/cli/ui.js +87 -0
  34. package/dist/entries.d.ts +13 -2
  35. package/dist/entries.js +23 -7
  36. package/dist/handler.d.ts +15 -1
  37. package/dist/handler.js +55 -19
  38. package/dist/next.d.ts +16 -4
  39. package/dist/next.js +56 -1
  40. package/dist/node.d.ts +4 -1
  41. package/dist/node.js +4 -2
  42. package/dist/types.d.ts +3 -2
  43. package/package.json +1 -1
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
  ![Runtime dependencies: 0](https://img.shields.io/badge/runtime_dependencies-0-1b1a17)
9
9
  ![Node 20.9+](https://img.shields.io/badge/node-%E2%89%A520.9-1b1a17)
10
10
 
11
- ![The same /sitemap.xml: the XML a crawler gets, and the page people get on three different sites, each in its own design.](.github/assets/hero.png)
11
+ ![One address, two answers: at https://your.site/sitemap.xml, Google and Bing get the standard XML sitemap, and a person opening the same address in a browser gets a page in the site's own design.](.github/assets/hero.png)
12
12
 
13
13
  ```sh
14
14
  npx maisongr-sitemap init
@@ -16,11 +16,17 @@ npx maisongr-sitemap init
16
16
 
17
17
  `init` detects your framework, finds your pages, dates each one from Git, reads your theme, and writes one route file. There's nothing to design and nothing to keep in sync.
18
18
 
19
+ ## It takes your site's design
20
+
21
+ The page reads your colours, fonts and dark mode from your own stylesheets. The same package, on three example sites:
22
+
23
+ ![The sitemap page on three example sites, an architecture studio, a software company and a nature blog, each in its own colours and fonts.](.github/assets/themes.png)
24
+
19
25
  ## How it compares
20
26
 
21
27
  | | **maisongr-sitemap** | next-sitemap | @astrojs/sitemap |
22
28
  |---|---|---|---|
23
- | Frameworks | Next.js, Astro, SvelteKit, Nuxt, Express, any `Request`/`Response` server, any static site | Next.js | Astro |
29
+ | Frameworks | Next.js, Astro, SvelteKit, Nuxt, Express, any `Request`/`Response` server, single-page apps, any static site, any language through `crawl` | Next.js | Astro |
24
30
  | What a person sees at `/sitemap.xml` | A page in your site's design | Raw XML | XML styled with your own XSL |
25
31
  | `lastmod` | The last commit that changed each page | Build time, by default | What you set |
26
32
  | `hreflang` alternates | Read from your routes and i18n config | Configured | From its `i18n` option |
@@ -45,11 +51,13 @@ npx maisongr-sitemap init
45
51
  | **SvelteKit** | `src/routes/sitemap.xml/+server.ts` |
46
52
  | **Nuxt** 3 and 4 | `server/routes/sitemap.xml.ts` |
47
53
  | **Static builds**: Astro without an adapter, SvelteKit with `adapter-static`, `nuxt generate` | Static mode, run after your build |
48
- | **Express**, Connect, Polka, `node:http` | The [Node adapter](#express-and-nodehttp), with the addresses you give it |
54
+ | **Express**, Connect, Polka, `node:http` | `sitemap.js` beside the server's entry, themed from the frontend it serves (see [Express](#express-and-nodehttp)) |
49
55
  | **Anything that speaks `Request` and `Response`**: Hono, Cloudflare Workers, Bun, Deno, React Router | The [handler](#any-other-server) itself |
50
- | **Any static site**, from any generator | [`static`](#static-sites) on the build output |
56
+ | **Single-page apps**: Vite (React, Vue, Solid, Svelte, Preact) and Create React App | Static mode after your build, with the pages read from your router (see [Single-page apps](#single-page-apps)) |
57
+ | **Any static site**: hand-written HTML, Eleventy, Hugo, Jekyll, any generator | [`static`](#static-sites) on the build output |
58
+ | **Any other language**: PHP (Laravel, WordPress, Symfony), Python, Ruby, Go, Java, .NET, a CMS | [`crawl`](#any-site-in-any-language) reads the running site |
51
59
 
52
- Each one has been checked on a real production build: Next.js 15 and 16 (with `cacheComponents`), Astro 7, SvelteKit 3, Nuxt 4 (with `@nuxtjs/i18n`), Express 5, Hono 4 and React Router 8. The handler also runs on Bun 1.4 and Deno 2.9.
60
+ Each one has been checked on a real production build: Next.js 15 and 16 (App Router, Pages Router and `cacheComponents`), Astro 7, SvelteKit 3, Nuxt 4 (with `@nuxtjs/i18n`), Express 5, Hono 4, React Router 8, a Vite React app, Eleventy 3, a hand-written HTML site and a server that renders each page on request. The handler also runs on Bun 1.4 and Deno 2.9.
53
61
 
54
62
  ## What `init` does
55
63
 
@@ -97,6 +105,8 @@ export const GET = sitemap({
97
105
  });
98
106
  ```
99
107
 
108
+ A dynamic page that exports `generateStaticParams` needs no `params` entry: the route lists the values that function returns.
109
+
100
110
  With Next.js 16's `cacheComponents`, `init` leaves out the `dynamic` line, which that mode refuses. The route stays dynamic because it reads the request.
101
111
 
102
112
  Astro, SvelteKit and Nuxt routes call `createSitemap` from `maisongr-sitemap` with the same options.
@@ -108,10 +118,11 @@ Astro, SvelteKit and Nuxt routes call `createSitemap` from `maisongr-sitemap` wi
108
118
  | `entries` | Extra addresses no route file describes. A `loc` may be a path (`"/press"`). Each may carry `images`, `videos` and `news`. |
109
119
  | `sitemaps` | More sitemaps, by name (see [Several sitemaps](#several-sitemaps)). |
110
120
  | `exclude` | Paths to leave out, from routes and `entries` alike: exact (`"/thanks"`), prefix (`"/drafts/"`) or `RegExp`. |
121
+ | `transform` | Called with each entry before it's listed. Return it changed (to add `images`, say) or `null` to leave it out. |
111
122
  | `site` | The address the site is served at. Defaults to the manifest's, then the request's. |
112
123
  | `basePath`, `trailingSlash` | Override what was read from your config. |
113
124
  | `locales` | Override the detected languages: `{ list, default, prefix?, prefixDefault?, folders? }`. |
114
- | `revalidate` | Seconds the list is kept before `params` and `entries` run again. Default 3600. A failed load is not kept. |
125
+ | `revalidate` | Seconds the list is kept before `params` and `entries` run again. Default 3600. A failed load is not kept. To list new content at once, call the handler's `invalidate()` when it is published. |
115
126
  | `theme` | Override any detected colour, font, name or icon. |
116
127
  | `credit` | The "Sitemap by Maison GR" footer line. Default `true`. |
117
128
 
@@ -170,7 +181,23 @@ Rows from `params` take `images` too.
170
181
 
171
182
  ## Express and `node:http`
172
183
 
173
- A server whose routes live in code has nothing to scan, so you give it the addresses:
184
+ A server's routes live in code, but its look lives in the frontend it serves. `npx maisongr-sitemap init` in the server's folder:
185
+
186
+ - follows its `express.static(...)` folders to that frontend: a `public/` folder, or the project a `dist/` is built from (a Vite app beside an API, in a workspace or not);
187
+ - reads the theme there (CSS tokens, light and dark, `index.html`, a Tailwind `fontFamily`, Fontsource packages even when a workspace hoists them) and copies the fonts to its `public/_sitemap/`;
188
+ - writes `sitemap.manifest.json` and `sitemap.js` beside the server's entry, as CommonJS or an ES module to match it, and prints the line that mounts it.
189
+
190
+ You list the pages in `sitemap.js`, since only your code knows them:
191
+
192
+ ```js
193
+ async function entries() {
194
+ return [{ loc: "/" }, ...(await db.posts()).map((p) => ({ loc: `/blog/${p.slug}`, lastmod: p.updatedAt }))];
195
+ }
196
+ ```
197
+
198
+ Call `sitemap.invalidate()` when a post is published, so it is listed at once. `maisongr-sitemap build` reads the frontend's theme again after a redesign.
199
+
200
+ Without the CLI, the adapter takes the same options as everything else:
174
201
 
175
202
  ```ts
176
203
  import { sitemap } from "maisongr-sitemap/node";
@@ -241,11 +268,40 @@ npx maisongr-sitemap static dist --site https://www.example.com
241
268
  - `sitemap.xml`, styled with CSS, for crawlers;
242
269
  - the designed page at `/sitemap/`, for people.
243
270
 
244
- It reads the built HTML, so each page's language and `hreflang` links come from the pages themselves. It leaves out pages marked `noindex`, redirects, and sign-in and account pages. The theme comes from your stylesheets and the CSS your build inlined. For a static build of Astro, SvelteKit or Nuxt, `init` adds this step to the end of your `build` script.
271
+ It reads the built HTML, so each page's language and `hreflang` links come from the pages themselves. It leaves out pages marked `noindex`, redirects, and sign-in and account pages. The theme comes from your stylesheets and the CSS your build inlined, and the name from what your pages say (`og:site_name`, or the part their titles share). For a static build of Astro, SvelteKit or Nuxt, `init` adds this step to the end of your `build` script; for another generator with a `build` script, `init --site https://your.site` does the same.
272
+
273
+ - **Addresses** follow your links. A site that links to `/about.html` gets `/about.html` (plain Apache and nginx serve nothing at `/about`); one that links to `/about` gets `/about`. `--clean-urls` forces the second.
274
+ - **Dates.** Hand-written HTML that Git tracks is dated from Git, file by file. A build output Git ignores gets no `lastmod`: built files don't say when their content changed, and a build date would be false.
275
+ - `--add /press,/jobs` lists addresses no HTML file holds.
276
+ - With `--images`, each page's `og:image` and `<img>` sources go into an image sitemap. It's off by default, so icons and tracking pixels aren't listed unless you ask for them.
277
+
278
+ ## Single-page apps
279
+
280
+ A Vite or Create React App build is one `index.html`; its pages live in your router. `init` reads them from the router's table and adds static mode to your `build` script:
281
+
282
+ ```sh
283
+ npx maisongr-sitemap init --site https://www.example.com
284
+ ```
285
+
286
+ It reads React Router, Vue Router, TanStack Router, Solid Router, Wouter, Preact Router and svelte-spa-router, in route objects (`{ path: "docs", children: [...] }`) and `<Route path>` elements, nested routes joined. Dynamic routes (`/blog/:slug`) and sign-in or account pages are left out and named; list a dynamic route's pages with `--add` in the build script.
287
+
288
+ Your host must serve `index.html` for paths it has no file for (the usual single-page app setting on Netlify, Vercel, Cloudflare Pages and the rest), so every listed page answers.
289
+
290
+ ## Any site, in any language
291
+
292
+ For a site no file describes, PHP, Python, Ruby, Go, a CMS, `crawl` reads it the way a search engine does: from the home page, along its own links.
293
+
294
+ ```sh
295
+ npx maisongr-sitemap crawl http://localhost:8000 --out public --site https://www.example.com
296
+ ```
245
297
 
246
- Static mode writes no `lastmod`: built files don't say when their content changed, and a build date would be false.
298
+ - `--out` is the folder your server serves files from (`public/` in Laravel and Symfony, the web root in WordPress). The files are the same as static mode's: `sitemap.xml` and the page at `/sitemap/`.
299
+ - `--site` is the public address, when you crawl a local or staging copy. Without it, the address crawled is the one listed.
300
+ - It follows `robots.txt`, `noindex` (in the page or its `X-Robots-Tag` header), `nofollow`, canonicals, redirects and `hreflang` alternates. It leaves out sign-in and account pages, and addresses with a query string, which search engines treat as copies.
301
+ - **Dates** come only from what each page states: `article:modified_time`, `dateModified` in its JSON-LD, or a `Last-Modified` header. A header that says "now" on every response is ignored.
302
+ - `--max 5000` stops after that many pages (default 10,000). It reads four pages at a time, gently.
247
303
 
248
- With `--images`, each page's `og:image` and `<img>` sources go into an image sitemap. It's off by default, so icons and tracking pixels aren't listed unless you ask for them.
304
+ Run it again whenever content changes, after a deploy or from a daily cron, so the list stays current. It needs Node 20.9 or later on the machine that runs it, not on your server.
249
305
 
250
306
  ## Telling search engines
251
307
 
@@ -261,19 +317,21 @@ With `--images`, each page's `og:image` and `<img>` sources go into an image sit
261
317
  - `--since 2026-11-01` picks the date.
262
318
  - `--all` sends everything.
263
319
  - `--dry-run` lists the addresses without sending them.
320
+ - `--wait` waits up to 180 seconds (or the number you give) for a fresh deploy to serve the key.
264
321
 
265
322
  The key is yours to choose: 8 to 128 letters, digits or dashes. The site must serve it at `/<key>.txt`, and the command checks that before it sends anything.
266
323
 
267
324
  ## Limits
268
325
 
269
- - **Dynamic routes** are listed only when the route is given their values through `params`. The build report names every route that needs them.
326
+ - **Dynamic routes** are listed only when the route is given their values through `params`, or by the page's own `generateStaticParams` or `getStaticPaths`. The build report names every route that needs them.
327
+ - **`crawl` finds only what is linked.** A page nothing links to, or one reached only by a form or a script, isn't found. Link it, or add it to the site's navigation or footer.
270
328
  - **The URL is the language code.** An Astro locale written as `{ path: "spanish", codes: ["es"] }` is listed with `hreflang="spanish"`. Pass `locales` to the route to correct it.
271
329
 
272
330
  ## Requirements
273
331
 
274
332
  Node 20.9 or later. No runtime dependencies.
275
333
 
276
- The package is an ES module. A CommonJS project (`require("maisongr-sitemap/node")`) needs Node 20.19 or 22.12 or later, which load ES modules through `require`.
334
+ The package is an ES module. A CommonJS project that calls `require("maisongr-sitemap/node")` itself needs Node 20.19 or 22.12 or later, which load ES modules through `require`; the `sitemap.js` that `init` writes loads it with `import()`, which works on every supported version.
277
335
 
278
336
  ## License
279
337
 
@@ -0,0 +1,32 @@
1
+ import type { Entry, Theme } from "../types.js";
2
+ /**
3
+ * For a site no file describes (PHP, Python, Ruby, Go, a CMS…): reads it the
4
+ * way a search engine does, from the home page along its own links, and lists
5
+ * the pages a search engine would keep. It follows robots.txt, noindex (in the
6
+ * page or its X-Robots-Tag), nofollow, canonicals and redirects.
7
+ */
8
+ export type CrawlOptions = {
9
+ /** The address the site is served at publicly, when the crawl reads another (http://localhost:8000). */
10
+ site?: string;
11
+ /** Stop after this many pages. Default 10,000. */
12
+ max?: number;
13
+ /** Requests at a time. Default 4, gentle on a small server. */
14
+ concurrency?: number;
15
+ images?: boolean;
16
+ fetch?: typeof fetch;
17
+ /** Called after each page is read, with the pages listed and the addresses seen so far. */
18
+ onPage?: (listed: number, seen: number) => void;
19
+ };
20
+ export type CrawlReport = {
21
+ entries: Entry[];
22
+ skipped: {
23
+ path: string;
24
+ reason: string;
25
+ }[];
26
+ theme: Theme;
27
+ capped: boolean;
28
+ queries: number;
29
+ };
30
+ /** robots.txt's rules for every crawler (User-agent: *), longest match wins, Allow over Disallow on a tie. */
31
+ export declare function robotsRules(text: string): (path: string) => boolean;
32
+ export declare function crawl(start: string, options?: CrawlOptions): Promise<CrawlReport>;
@@ -0,0 +1,210 @@
1
+ import { trimSlashes } from "../entries.js";
2
+ import { styleBlocks } from "./project.js";
3
+ import { privateOf } from "./route-rules.js";
4
+ import { attr, holds, pageFacts, themeOf } from "./static.js";
5
+ const NOT_PAGES = /\.(?:pdf|jpe?g|png|gif|webp|avif|svg|ico|bmp|css|js|mjs|json|xml|txt|csv|zip|gz|rar|7z|mp4|webm|mov|mp3|wav|ogg|woff2?|ttf|otf|eot|map|docx?|xlsx?|pptx?)$/i;
6
+ const AGENT = "maisongr-sitemap (+https://github.com/maison-gr/sitemap)";
7
+ const tags = (html, name) => [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => m[0]);
8
+ const unescape = (s) => s.replace(/&amp;/g, "&");
9
+ /** robots.txt's rules for every crawler (User-agent: *), longest match wins, Allow over Disallow on a tie. */
10
+ export function robotsRules(text) {
11
+ const rules = [];
12
+ let applies = false;
13
+ let inAgents = false;
14
+ for (const raw of text.split(/\r?\n/)) {
15
+ const line = raw.split("#")[0];
16
+ const colon = line.indexOf(":");
17
+ if (colon < 0)
18
+ continue;
19
+ const [key, value] = [line.slice(0, colon).trim().toLowerCase(), line.slice(colon + 1).trim()];
20
+ if (key === "user-agent") {
21
+ if (!inAgents)
22
+ applies = false;
23
+ inAgents = true;
24
+ if (value === "*")
25
+ applies = true;
26
+ continue;
27
+ }
28
+ inAgents = false;
29
+ if (applies && (key === "allow" || key === "disallow") && value)
30
+ rules.push({ allow: key === "allow", prefix: value.replace(/\*$/, "").replace(/\$$/, "") });
31
+ }
32
+ return (path) => {
33
+ let best;
34
+ for (const r of rules) {
35
+ if (!path.startsWith(r.prefix))
36
+ continue;
37
+ if (!best || r.prefix.length > best.prefix.length || (r.prefix.length === best.prefix.length && r.allow))
38
+ best = r;
39
+ }
40
+ return best ? best.allow : true;
41
+ };
42
+ }
43
+ /** The date a page states for its last change, if it states one. */
44
+ function statedDate(html, lastModified) {
45
+ const meta = tags(html, "meta").find((t) => ["property", "name", "itemprop"].some((n) => /^(?:article:modified_time|og:updated_time|datemodified|last-modified)$/i.test(attr(t, n) ?? "")));
46
+ const ld = html.match(/"dateModified"\s*:\s*"([^"]+)"/)?.[1];
47
+ for (const value of [meta && attr(meta, "content"), ld]) {
48
+ if (value && !Number.isNaN(Date.parse(value)))
49
+ return value;
50
+ }
51
+ // A Last-Modified that is "now" is a dynamic page stamping every response, not a real date.
52
+ if (lastModified) {
53
+ const t = Date.parse(lastModified);
54
+ if (!Number.isNaN(t) && Date.now() - t > 5 * 60_000)
55
+ return new Date(t).toISOString();
56
+ }
57
+ return undefined;
58
+ }
59
+ /** url(...) in a stylesheet made absolute, so the page served from the site's root finds the same fonts. */
60
+ const absoluteUrls = (css, from, origin) => css.replace(/url\(([^)]*)\)/g, (whole, inner) => {
61
+ const href = inner.trim().replace(/^(["'])(.*)\1$/, "$2");
62
+ if (!href || href.startsWith("data:"))
63
+ return whole;
64
+ let url;
65
+ try {
66
+ url = new URL(href, from);
67
+ }
68
+ catch {
69
+ return whole;
70
+ }
71
+ return url.origin === origin ? `url("${url.pathname}")` : whole;
72
+ });
73
+ export async function crawl(start, options = {}) {
74
+ const get = options.fetch ?? fetch;
75
+ const startUrl = new URL(start);
76
+ const origin = startUrl.origin;
77
+ const base = trimSlashes(options.site ?? origin);
78
+ const publicOrigin = new URL(base).origin;
79
+ const max = options.max ?? 10_000;
80
+ const request = (url) => get(url, { redirect: "manual", headers: { "user-agent": AGENT, accept: "text/html,*/*;q=0.5" }, signal: AbortSignal.timeout(20_000) });
81
+ const robotsRes = await request(`${origin}/robots.txt`).catch(() => null);
82
+ const allowed = robotsRules(robotsRes?.ok ? await robotsRes.text() : "");
83
+ /** A link as a path on this site, or null when it leaves the site or isn't a page. */
84
+ const queries = new Set();
85
+ const pathOf = (href, from) => {
86
+ let url;
87
+ try {
88
+ url = new URL(unescape(href), from);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ if (url.origin !== origin && url.origin !== publicOrigin)
94
+ return null;
95
+ if (!/^https?:$/.test(url.protocol) || NOT_PAGES.test(url.pathname))
96
+ return null;
97
+ if (url.search) {
98
+ queries.add(url.pathname + url.search);
99
+ return null;
100
+ }
101
+ return url.pathname;
102
+ };
103
+ const seen = new Set();
104
+ const queue = [];
105
+ const add = (path) => {
106
+ if (path === null || seen.has(path) || path === "/sitemap.xml" || path.startsWith("/sitemap/"))
107
+ return;
108
+ seen.add(path);
109
+ queue.push(path);
110
+ };
111
+ add(startUrl.pathname);
112
+ const entries = [];
113
+ const skipped = [];
114
+ const pages = [];
115
+ let home = "";
116
+ async function visit(path) {
117
+ if (!allowed(path))
118
+ return void skipped.push({ path, reason: "robots.txt disallows it" });
119
+ const privateSegment = privateOf(path.split("/").filter(Boolean));
120
+ if (privateSegment)
121
+ return void skipped.push({ path, reason: `private page (${privateSegment})` });
122
+ const res = await request(`${origin}${path}`).catch((error) => ({ error }));
123
+ if ("error" in res)
124
+ return void skipped.push({ path, reason: `could not be read (${res.error.message})` });
125
+ if (res.status >= 300 && res.status < 400) {
126
+ const to = res.headers.get("location");
127
+ const target = to ? pathOf(to, `${origin}${path}`) : null;
128
+ skipped.push({ path, reason: `redirects${target ? ` to ${target}` : ""}` });
129
+ return add(target);
130
+ }
131
+ if (res.status !== 200)
132
+ return void skipped.push({ path, reason: `answers ${res.status}` });
133
+ if (!/text\/html|application\/xhtml/i.test(res.headers.get("content-type") ?? ""))
134
+ return;
135
+ const html = await res.text();
136
+ if (path === startUrl.pathname)
137
+ home = html;
138
+ pages.push(html);
139
+ const robots = tags(html, "meta").find((t) => attr(t, "name")?.toLowerCase() === "robots");
140
+ const directives = `${attr(robots ?? "", "content") ?? ""},${res.headers.get("x-robots-tag") ?? ""}`;
141
+ if (!/nofollow/i.test(directives)) {
142
+ for (const a of tags(html, "a")) {
143
+ if (holds(a, "rel", "nofollow"))
144
+ continue;
145
+ const href = attr(a, "href");
146
+ if (href && !href.startsWith("#"))
147
+ add(pathOf(href, `${origin}${path}`));
148
+ }
149
+ }
150
+ // Language versions named only in hreflang are followed too, as search engines do.
151
+ for (const link of tags(html, "link").filter((t) => holds(t, "rel", "alternate") && attr(t, "hreflang"))) {
152
+ const href = attr(link, "href");
153
+ if (href)
154
+ add(pathOf(href, `${origin}${path}`));
155
+ }
156
+ if (/noindex/i.test(directives))
157
+ return void skipped.push({ path, reason: "noindex" });
158
+ // A page whose canonical is another address is a copy: the canonical one is listed instead.
159
+ const canonical = tags(html, "link").find((t) => holds(t, "rel", "canonical"));
160
+ const canonicalPath = canonical && attr(canonical, "href") ? pathOf(attr(canonical, "href"), `${origin}${path}`) : null;
161
+ if (canonicalPath !== null && canonicalPath !== path) {
162
+ skipped.push({ path, reason: `canonical is ${canonicalPath}` });
163
+ return add(canonicalPath);
164
+ }
165
+ const facts = pageFacts(html, `${base}${path}`, base, options.images);
166
+ if ("skip" in facts)
167
+ return void skipped.push({ path, reason: facts.skip });
168
+ // Alternates the page writes with the address the crawl reads are given the public one.
169
+ const alternates = facts.entry.alternates?.map((a) => (a.href.startsWith(origin) ? { ...a, href: `${base}${a.href.slice(origin.length)}` } : a));
170
+ const lastmod = statedDate(html, res.headers.get("last-modified"));
171
+ entries.push({ ...facts.entry, ...(alternates ? { alternates } : {}), ...(lastmod ? { lastmod } : {}) });
172
+ }
173
+ // A few requests at a time, as the queue grows.
174
+ let capped = false;
175
+ let next = 0;
176
+ async function worker() {
177
+ while (next < queue.length) {
178
+ if (entries.length >= max) {
179
+ capped = true;
180
+ return;
181
+ }
182
+ await visit(queue[next++]);
183
+ options.onPage?.(entries.length, seen.size);
184
+ }
185
+ }
186
+ // Workers stop when the queue is momentarily empty, so start more until nothing new is found.
187
+ while (next < queue.length && !capped)
188
+ await Promise.all(Array.from({ length: options.concurrency ?? 4 }, worker));
189
+ // The theme, from the home page's own stylesheets and <style> blocks.
190
+ const css = [];
191
+ for (const link of tags(home, "link").filter((t) => holds(t, "rel", "stylesheet"))) {
192
+ const href = attr(link, "href");
193
+ if (!href)
194
+ continue;
195
+ const url = new URL(unescape(href), `${origin}/`);
196
+ if (url.origin !== origin)
197
+ continue;
198
+ const res = await request(url.href).catch(() => null);
199
+ if (res?.ok)
200
+ css.push(absoluteUrls(await res.text(), url, origin));
201
+ }
202
+ css.push(absoluteUrls(styleBlocks(home), new URL(`${origin}/`), origin));
203
+ const iconTag = tags(home, "link").find((t) => holds(t, "rel", "icon"));
204
+ const iconHref = iconTag && attr(iconTag, "href");
205
+ const iconUrl = iconHref ? new URL(unescape(iconHref), `${origin}/`) : undefined;
206
+ const icon = iconUrl && iconUrl.origin === origin ? iconUrl.pathname : undefined;
207
+ entries.sort((a, b) => a.loc.localeCompare(b.loc));
208
+ skipped.sort((a, b) => a.path.localeCompare(b.path));
209
+ return { entries, skipped, theme: themeOf({ css: css.join("\n"), pages, home, icon, base }), capped, queries: queries.size };
210
+ }
@@ -21,5 +21,6 @@ export declare function cssFonts(options: {
21
21
  sources: string[];
22
22
  publicDir: string;
23
23
  astroConfig?: string;
24
+ tailwindConfig?: string;
24
25
  }): FontSource[];
25
26
  export {};
@@ -28,14 +28,25 @@ function group(faces, role) {
28
28
  families.set(f.family, [...(families.get(f.family) ?? []), f]);
29
29
  return [...families].map(([family, list]) => ({ kind: "local", family, role: role(family), files: list.map(({ family: _, ...file }) => file) }));
30
30
  }
31
+ /** A package's folder as Node finds it: in node_modules here, or in a parent's, where workspaces hoist it. */
32
+ function packageDir(root, name) {
33
+ for (let dir = resolve(root);; dir = dirname(dir)) {
34
+ const candidate = join(dir, "node_modules", name);
35
+ if (existsSync(candidate))
36
+ return candidate;
37
+ if (dirname(dir) === dir)
38
+ return undefined;
39
+ }
40
+ }
31
41
  /** Fontsource packages the code or the CSS imports: their Latin files are already in node_modules. */
32
42
  function fontsource(root, sources) {
33
43
  const faces = [];
34
44
  const seen = new Set();
35
45
  for (const src of sources) {
36
46
  for (const m of src.matchAll(/["'](@fontsource(?:-variable)?\/[\w-]+)(\/[\w./-]+\.css)?["']/g)) {
37
- const css = join(root, "node_modules", m[1], m[2] ?? "index.css");
38
- if (seen.has(css) || !existsSync(css))
47
+ const dir = packageDir(root, m[1]);
48
+ const css = dir ? join(dir, m[2] ?? "index.css") : "";
49
+ if (!css || seen.has(css) || !existsSync(css))
39
50
  continue;
40
51
  seen.add(css);
41
52
  faces.push(...fontFaces(readFileSync(css, "utf8"), css, ""));
@@ -54,6 +65,23 @@ function astroConfigFonts(config) {
54
65
  }
55
66
  return out;
56
67
  }
68
+ /** Tailwind's theme.fontFamily (v3 config): { display: ['"Fraunces Variable"', "serif"], sans: [...], mono: [...] }. */
69
+ function tailwindFamilies(config) {
70
+ const start = config.search(/\bfontFamily\s*:\s*\{/);
71
+ if (start === -1)
72
+ return [];
73
+ const body = config.slice(config.indexOf("{", start) + 1);
74
+ const out = [];
75
+ // Each key and the first quoted family in its list, until the block closes.
76
+ for (const m of body.matchAll(/(?:^|[,{\s])["']?([\w-]+)["']?\s*:\s*\[\s*["'`]+([^"'`]+)["'`]+|\}/g)) {
77
+ if (m[0] === "}")
78
+ break;
79
+ const family = unquote(m[2]);
80
+ if (!GENERIC.test(family))
81
+ out.push({ kind: "google", family, role: hintOf(m[1], family) });
82
+ }
83
+ return out;
84
+ }
57
85
  /** The first real family each role's CSS asks for: body text, headings, code, and --font-* tokens. */
58
86
  function askedFamilies(css) {
59
87
  const out = [];
@@ -82,16 +110,17 @@ function askedFamilies(css) {
82
110
  */
83
111
  export function cssFonts(options) {
84
112
  const tokens = new Map();
85
- for (const { css } of options.stylesheets) {
86
- for (const f of askedFamilies(css))
87
- if (f.role && !tokens.has(f.family))
88
- tokens.set(f.family, f.role);
113
+ const tailwind = options.tailwindConfig ? tailwindFamilies(options.tailwindConfig) : [];
114
+ for (const f of [...tailwind, ...options.stylesheets.flatMap(({ css }) => askedFamilies(css))]) {
115
+ if (f.role && !tokens.has(f.family))
116
+ tokens.set(f.family, f.role);
89
117
  }
90
118
  const roleOf = (family) => tokens.get(family) ?? hintOf(undefined, family);
91
119
  const found = [
92
120
  ...group(options.stylesheets.flatMap(({ file, css }) => fontFaces(css, file, options.publicDir)), roleOf),
93
121
  ...group(fontsource(options.root, [...options.sources, ...options.stylesheets.map((s) => s.css)]), roleOf),
94
122
  ...(options.astroConfig ? astroConfigFonts(options.astroConfig) : []),
123
+ ...tailwind,
95
124
  ...options.stylesheets.flatMap(({ css }) => askedFamilies(css)),
96
125
  ];
97
126
  const unique = found.filter((f, i) => found.findIndex((g) => g.family === f.family) === i);
@@ -29,6 +29,12 @@ export type Detected = {
29
29
  | {
30
30
  kind: "node";
31
31
  name: string;
32
+ }
33
+ /** A single-page app (Vite, Create React App): one index.html, its pages in a client-side router's table. */
34
+ | {
35
+ kind: "spa";
36
+ name: string;
37
+ outDir: string;
32
38
  } | {
33
39
  kind: "static";
34
40
  outDir: string;
@@ -47,4 +53,5 @@ export declare function configOf(root: string, names: string[]): {
47
53
  export declare const ASTRO_CONFIGS: string[];
48
54
  export declare const SVELTE_CONFIGS: string[];
49
55
  export declare const NUXT_CONFIGS: string[];
56
+ export declare const TAILWIND_CONFIGS: string[];
50
57
  export declare function detect(root: string): Detected;
@@ -3,7 +3,8 @@ import { join } from "node:path";
3
3
  /** Frameworks recognised but without their own adapter yet: they can use static mode on their build output. */
4
4
  const LATER = [
5
5
  ["@remix-run/react", "Remix"],
6
- ["react-router", "React Router"],
6
+ // React Router's framework mode; the library alone is a single-page app's router.
7
+ ["@react-router/dev", "React Router"],
7
8
  ["gatsby", "Gatsby"],
8
9
  ];
9
10
  const BUILD_DIRS = ["out", "dist", "build", "_site", "public"];
@@ -30,6 +31,7 @@ export function configOf(root, names) {
30
31
  export const ASTRO_CONFIGS = ["astro.config.mjs", "astro.config.ts", "astro.config.mts", "astro.config.js", "astro.config.cjs"];
31
32
  export const SVELTE_CONFIGS = ["svelte.config.js", "svelte.config.ts", "vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"];
32
33
  export const NUXT_CONFIGS = ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs"];
34
+ export const TAILWIND_CONFIGS = ["tailwind.config.js", "tailwind.config.ts", "tailwind.config.cjs", "tailwind.config.mjs"];
33
35
  export function detect(root) {
34
36
  const pkg = readPackage(root);
35
37
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
@@ -60,6 +62,13 @@ export function detect(root) {
60
62
  if (deps[name])
61
63
  return { kind: "node", name: label };
62
64
  }
65
+ if (deps.vite && existsSync(join(root, "index.html"))) {
66
+ const outDir = /\boutDir\s*:\s*["'`]([^"'`]+)["'`]/.exec(configOf(root, ["vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"])?.source ?? "")?.[1] ?? "dist";
67
+ const name = deps.vue ? "Vue" : deps["solid-js"] ? "Solid" : deps.svelte ? "Svelte" : deps.preact ? "Preact" : deps.react ? "React" : "Vite";
68
+ return { kind: "spa", name: `${name} (Vite)`, outDir };
69
+ }
70
+ if (deps["react-scripts"])
71
+ return { kind: "spa", name: "Create React App", outDir: "build" };
63
72
  const outDir = BUILD_DIRS.find((d) => existsSync(join(root, d, "index.html")));
64
73
  if (outDir)
65
74
  return { kind: "static", outDir };
@@ -25,6 +25,8 @@ export declare function assignRoles<T extends {
25
25
  })[];
26
26
  /** Fonts the root layout loads through next/font, with the role each plays. */
27
27
  export declare function nextFonts(layoutSource: string, layoutDir: string): FontSource[];
28
+ /** A WOFF2 file starts with the signature "wOF2". */
29
+ export declare const isWoff2: (bytes: Uint8Array) => boolean;
28
30
  /** Brings each font into public/_sitemap/ and returns the ones the page can use. */
29
31
  export declare function materialize(sources: FontSource[], publicDir: string, offline?: boolean): Promise<{
30
32
  fonts: Font[];
@@ -50,12 +50,20 @@ export function nextFonts(layoutSource, layoutDir) {
50
50
  if (!files.length)
51
51
  continue;
52
52
  const variable = variableOf(opts);
53
- const family = variable ? variable.replace(/^--(font-)?/, "").replace(/-/g, " ") : basename(files[0].path).replace(/\.\w+$/, "");
53
+ // Named after its file ("instrument-sans.woff2" → "Instrument Sans"): a variable like --app-font-display names a role, not a font.
54
+ const family = basename(files[0].path)
55
+ .replace(/\.\w+$/, "")
56
+ .split(/[-_]+/)
57
+ .filter(Boolean)
58
+ .map((w) => w[0].toUpperCase() + w.slice(1))
59
+ .join(" ");
54
60
  out.push({ kind: "local", family, role: hintOf(variable, family), files });
55
61
  }
56
62
  }
57
63
  return assignRoles(out);
58
64
  }
65
+ /** A WOFF2 file starts with the signature "wOF2". */
66
+ export const isWoff2 = (bytes) => bytes.length > 4 && bytes[0] === 0x77 && bytes[1] === 0x4f && bytes[2] === 0x46 && bytes[3] === 0x32;
59
67
  const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36";
60
68
  const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
61
69
  /** Downloads a Google font's Latin files once, at build time, so the page serves them from the site itself. */
@@ -102,7 +110,11 @@ async function google(family, role, publicDir) {
102
110
  const res = await fetch(url, { headers: { "User-Agent": UA } });
103
111
  if (!res.ok)
104
112
  continue;
105
- writeFileSync(join(dir, file), Buffer.from(await res.arrayBuffer()));
113
+ const bytes = Buffer.from(await res.arrayBuffer());
114
+ // Only a real WOFF2 file is written: an error page or anything else served at that address is not.
115
+ if (!isWoff2(bytes))
116
+ continue;
117
+ writeFileSync(join(dir, file), bytes);
106
118
  files.push({ url: `/${FONT_DIR}/${file}`, weight, style });
107
119
  }
108
120
  catch {
@@ -5,6 +5,12 @@ type Server = Extract<Detected, {
5
5
  }>;
6
6
  /** Where each framework's sitemap route keeps its manifest. */
7
7
  export declare function manifestPathFor(root: string, detected: Server): string;
8
+ /** The facts every framework shares: stylesheets and fonts from its source directories. */
9
+ export declare function themeFacts(root: string, dirs: string[], layouts: string[], publicDir: string, astroConfig?: string): {
10
+ stylesheets: string[];
11
+ inlineStyles: string[];
12
+ fonts: import("./fonts.js").FontSource[];
13
+ };
8
14
  /** The address the project's own config gives the site (Astro's `site`, Nuxt's `site.url`), or the environment's. */
9
15
  export declare function configuredSite(root: string, kind: Server["kind"]): string | undefined;
10
16
  /** Builds the manifest for an Astro, SvelteKit or Nuxt site that runs a server. */
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
+ import { trimSlashes } from "../entries.js";
3
4
  import { astroRoutes } from "./astro-routes.js";
4
5
  import { cssFonts } from "./css-fonts.js";
5
- import { ASTRO_CONFIGS, configOf, NUXT_CONFIGS, readPackage, SVELTE_CONFIGS } from "./detect.js";
6
+ import { ASTRO_CONFIGS, configOf, NUXT_CONFIGS, readPackage, SVELTE_CONFIGS, TAILWIND_CONFIGS } from "./detect.js";
6
7
  import { read, writeManifest } from "./manifest.js";
7
8
  import { nuxtRoutes } from "./nuxt-routes.js";
8
9
  import { filesIn, findIcon, findLocales, findName, findSite, sourceFiles, styleBlocks } from "./project.js";
@@ -69,10 +70,10 @@ function nuxtLocales(root, config) {
69
70
  return { list: codes, default: codes.includes(fallback) ? fallback : codes[0], prefix: true, prefixDefault: strategy !== "prefix_except_default" };
70
71
  }
71
72
  const firstMatch = (source, ...patterns) => patterns.map((p) => source.match(p)?.[1]).find(Boolean);
72
- const httpSite = (url) => (url && !/localhost|127\.0\.0\.1|example\.com/.test(url) ? url.replace(/\/+$/, "") : undefined);
73
+ const httpSite = (url) => (url && !/localhost|127\.0\.0\.1|example\.com/.test(url) ? trimSlashes(url) : undefined);
73
74
  const base = (path) => (path && path !== "/" ? `/${path.replace(/^\/+|\/+$/g, "")}` : undefined);
74
75
  /** The facts every framework shares: stylesheets and fonts from its source directories. */
75
- function themeFacts(root, dirs, layouts, publicDir, astroConfig) {
76
+ export function themeFacts(root, dirs, layouts, publicDir, astroConfig) {
76
77
  const stylesheets = dirs.flatMap((d) => filesIn(root, d, CSS));
77
78
  const inlineStyles = layouts.filter(existsSync).map((f) => styleBlocks(read(f)));
78
79
  const code = dirs.flatMap((d) => filesIn(root, d, CODE));
@@ -82,6 +83,7 @@ function themeFacts(root, dirs, layouts, publicDir, astroConfig) {
82
83
  sources: code.map(read),
83
84
  publicDir,
84
85
  astroConfig,
86
+ tailwindConfig: configOf(root, TAILWIND_CONFIGS)?.source,
85
87
  });
86
88
  return { stylesheets, inlineStyles, fonts };
87
89
  }
@@ -8,6 +8,8 @@ export type BuildReport = {
8
8
  skipped: Skipped[];
9
9
  /** Dynamic routes that need `params` in the route file to be listed. */
10
10
  needParams: string[];
11
+ /** Dynamic routes listed from their page's own generateStaticParams (Next.js). */
12
+ fromPages?: string[];
11
13
  missedFonts: string[];
12
14
  /** The manifest already there could not be read (a merge conflict, say), so it was rebuilt from the project. */
13
15
  rebuilt: boolean;