@hamur/seo 0.0.0-stage → 0.0.1

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 (112) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +26 -2
  3. package/dist/chunks/bun-index-rnjhv41c.js +62 -0
  4. package/dist/chunks/bun-index-xf4srhvn.js +97 -0
  5. package/dist/src/adapters/html.js +40 -0
  6. package/dist/src/adapters/preact.js +36 -0
  7. package/dist/src/adapters/react.js +36 -0
  8. package/dist/src/adapters/solid.js +35 -0
  9. package/dist/src/adapters/svelte.js +35 -0
  10. package/dist/src/adapters/vue.js +43 -0
  11. package/dist/src/index.js +1375 -0
  12. package/dist/src/schema.js +51 -0
  13. package/dist/src/server/index.js +1 -0
  14. package/dist/src/share.js +40 -0
  15. package/dist/types/src/adapters/html.d.ts +6 -0
  16. package/dist/types/src/adapters/preact.d.ts +5 -0
  17. package/dist/types/src/adapters/react.d.ts +5 -0
  18. package/dist/types/src/adapters/solid.d.ts +6 -0
  19. package/dist/types/src/adapters/svelte.d.ts +5 -0
  20. package/dist/types/src/adapters/vue.d.ts +9 -0
  21. package/dist/types/src/build/links.d.ts +4 -0
  22. package/dist/types/src/build/llms.d.ts +6 -0
  23. package/dist/types/src/build/own.d.ts +5 -0
  24. package/dist/types/src/build/robots.d.ts +3 -0
  25. package/dist/types/src/build/schema.d.ts +4 -0
  26. package/dist/types/src/build/sitemap.d.ts +7 -0
  27. package/dist/types/src/index.d.ts +2 -0
  28. package/dist/types/src/links/check.d.ts +7 -0
  29. package/dist/types/src/links/external.d.ts +6 -0
  30. package/dist/types/src/links/options.d.ts +12 -0
  31. package/dist/types/src/links/report.d.ts +4 -0
  32. package/dist/types/src/links/scan.d.ts +24 -0
  33. package/dist/types/src/llms/options.d.ts +9 -0
  34. package/dist/types/src/llms/paths.d.ts +8 -0
  35. package/dist/types/src/llms/text.d.ts +12 -0
  36. package/dist/types/src/module.d.ts +3 -0
  37. package/dist/types/src/robots/ai-bots.d.ts +2 -0
  38. package/dist/types/src/robots/body.d.ts +16 -0
  39. package/dist/types/src/robots/options.d.ts +9 -0
  40. package/dist/types/src/runtime/breadcrumbs.d.ts +37 -0
  41. package/dist/types/src/runtime/markdown.d.ts +15 -0
  42. package/dist/types/src/runtime/schema-plugin.d.ts +2 -0
  43. package/dist/types/src/runtime/schema-store.d.ts +34 -0
  44. package/dist/types/src/schema/graph.d.ts +13 -0
  45. package/dist/types/src/schema/helpers.d.ts +358 -0
  46. package/dist/types/src/schema/options.d.ts +7 -0
  47. package/dist/types/src/schema.d.ts +10 -0
  48. package/dist/types/src/server/agent.d.ts +4 -0
  49. package/dist/types/src/server/door.d.ts +5 -0
  50. package/dist/types/src/server/index.d.ts +1 -0
  51. package/dist/types/src/server/llms.d.ts +2 -0
  52. package/dist/types/src/server/render.d.ts +9 -0
  53. package/dist/types/src/server/robots.d.ts +1 -0
  54. package/dist/types/src/server/sitemap.d.ts +5 -0
  55. package/dist/types/src/share.d.ts +18 -0
  56. package/dist/types/src/sitemap/alternates.d.ts +14 -0
  57. package/dist/types/src/sitemap/answer.d.ts +6 -0
  58. package/dist/types/src/sitemap/entries.d.ts +9 -0
  59. package/dist/types/src/sitemap/options.d.ts +7 -0
  60. package/dist/types/src/sitemap/paths.d.ts +13 -0
  61. package/dist/types/src/sitemap/xml.d.ts +23 -0
  62. package/dist/types/src/types.d.ts +73 -0
  63. package/package.json +106 -4
  64. package/src/adapters/html.ts +43 -0
  65. package/src/adapters/preact.ts +37 -0
  66. package/src/adapters/react.ts +37 -0
  67. package/src/adapters/solid.ts +38 -0
  68. package/src/adapters/svelte.ts +37 -0
  69. package/src/adapters/vue.ts +55 -0
  70. package/src/build/links.ts +13 -0
  71. package/src/build/llms.ts +79 -0
  72. package/src/build/own.ts +46 -0
  73. package/src/build/robots.ts +58 -0
  74. package/src/build/schema.ts +23 -0
  75. package/src/build/sitemap.ts +101 -0
  76. package/src/env.d.ts +44 -0
  77. package/src/index.ts +14 -0
  78. package/src/links/check.ts +233 -0
  79. package/src/links/external.ts +41 -0
  80. package/src/links/options.ts +69 -0
  81. package/src/links/report.ts +49 -0
  82. package/src/links/scan.ts +123 -0
  83. package/src/llms/options.ts +49 -0
  84. package/src/llms/paths.ts +33 -0
  85. package/src/llms/text.ts +26 -0
  86. package/src/module.ts +22 -0
  87. package/src/robots/ai-bots.ts +14 -0
  88. package/src/robots/body.ts +51 -0
  89. package/src/robots/options.ts +75 -0
  90. package/src/runtime/breadcrumbs.ts +84 -0
  91. package/src/runtime/markdown.ts +381 -0
  92. package/src/runtime/schema-plugin.ts +22 -0
  93. package/src/runtime/schema-store.ts +144 -0
  94. package/src/schema/graph.ts +125 -0
  95. package/src/schema/helpers.ts +372 -0
  96. package/src/schema/options.ts +39 -0
  97. package/src/schema.ts +5 -0
  98. package/src/server/agent.ts +45 -0
  99. package/src/server/door.ts +8 -0
  100. package/src/server/index.ts +1 -0
  101. package/src/server/llms.ts +139 -0
  102. package/src/server/render.ts +33 -0
  103. package/src/server/robots.ts +19 -0
  104. package/src/server/sitemap.ts +222 -0
  105. package/src/share.ts +56 -0
  106. package/src/sitemap/alternates.ts +66 -0
  107. package/src/sitemap/answer.ts +42 -0
  108. package/src/sitemap/entries.ts +136 -0
  109. package/src/sitemap/options.ts +47 -0
  110. package/src/sitemap/paths.ts +39 -0
  111. package/src/sitemap/xml.ts +71 -0
  112. package/src/types.ts +89 -0
@@ -0,0 +1,1375 @@
1
+ // packages/seo/src/module.ts
2
+ import { addServer, createResolver as createResolver2, defineModule } from "hamur/kit";
3
+
4
+ // packages/seo/src/links/check.ts
5
+ import {
6
+ DiagnosticError as DiagnosticError2,
7
+ createRouteRules,
8
+ diagnostic,
9
+ useLogger
10
+ } from "hamur/kit";
11
+ import { formatLinkFindings, slashForm } from "hamur/server/internal";
12
+
13
+ // packages/seo/src/links/external.ts
14
+ var EXTERNAL_TIMEOUT_MS = 5000;
15
+ var EXTERNAL_CONCURRENCY = 8;
16
+ var REASONS = new Set([405, 501]);
17
+ async function ask(url, method) {
18
+ const response = await globalThis.fetch(url, {
19
+ method,
20
+ headers: { "user-agent": "hamur-link-checker" },
21
+ signal: AbortSignal.timeout(EXTERNAL_TIMEOUT_MS),
22
+ redirect: "follow"
23
+ });
24
+ await response.body?.cancel();
25
+ return response.status;
26
+ }
27
+ async function probe(url) {
28
+ try {
29
+ let status = await ask(url, "HEAD");
30
+ if (REASONS.has(status))
31
+ status = await ask(url, "GET");
32
+ return status >= 400 ? `external link ${url} answered ${status}` : undefined;
33
+ } catch (error) {
34
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
35
+ return `external link ${url} failed: ${timedOut ? `no answer in ${EXTERNAL_TIMEOUT_MS / 1000} s` : error instanceof Error ? error.message : String(error)}`;
36
+ }
37
+ }
38
+ async function probeAll(urls) {
39
+ const queue = [...new Set(urls)];
40
+ const failed = new Map;
41
+ const worker = async () => {
42
+ for (let url = queue.shift();url !== undefined; url = queue.shift()) {
43
+ const message = await probe(url);
44
+ if (message !== undefined)
45
+ failed.set(url, message);
46
+ }
47
+ };
48
+ await Promise.all(Array.from({ length: Math.min(EXTERNAL_CONCURRENCY, queue.length) }, worker));
49
+ return failed;
50
+ }
51
+
52
+ // packages/seo/src/links/options.ts
53
+ import { DiagnosticError } from "hamur/kit";
54
+ var LINK_RULES = {
55
+ broken: "error",
56
+ "missing-anchor": "warning",
57
+ redirect: "warning",
58
+ "trailing-slash": "warning",
59
+ "absolute-site-url": "warning",
60
+ "javascript-href": "error",
61
+ "empty-text": "warning",
62
+ "double-slash": "warning",
63
+ uppercase: "warning",
64
+ whitespace: "warning",
65
+ "external-broken": "warning"
66
+ };
67
+ var KEYS = ["failOnError", "external", "report", "exclude", "rules"];
68
+ var FORMATS = ["json", "markdown", "html"];
69
+ var show = (value) => JSON.stringify(value) ?? String(value);
70
+ function fail(message) {
71
+ throw new DiagnosticError("HAMUR_E6401", message);
72
+ }
73
+ function resolveLinkChecker(input) {
74
+ const base = { failOnError: false, external: false, report: [], exclude: [], rules: {} };
75
+ if (input === undefined || input === true)
76
+ return base;
77
+ if (input === false)
78
+ return;
79
+ if (typeof input !== "object" || input === null || Array.isArray(input))
80
+ fail(`seo.linkChecker must be a boolean or an object (got ${show(input)})`);
81
+ for (const key of Object.keys(input))
82
+ if (!KEYS.includes(key))
83
+ fail(`seo.linkChecker.${key} is not an option`);
84
+ const { failOnError = false, external = false, report = [], exclude = [], rules = {} } = input;
85
+ if (typeof failOnError !== "boolean")
86
+ fail(`seo.linkChecker.failOnError must be a boolean (got ${show(failOnError)})`);
87
+ if (typeof external !== "boolean")
88
+ fail(`seo.linkChecker.external must be a boolean (got ${show(external)})`);
89
+ if (!Array.isArray(report))
90
+ fail(`seo.linkChecker.report must be an array of "json", "markdown" or "html" (got ${show(report)})`);
91
+ report.forEach((format, index) => {
92
+ if (!FORMATS.includes(format))
93
+ fail(`seo.linkChecker.report[${index}] must be "json", "markdown" or "html" (got ${show(format)})`);
94
+ });
95
+ if (!Array.isArray(exclude))
96
+ fail(`seo.linkChecker.exclude must be an array of route rule patterns (got ${show(exclude)})`);
97
+ exclude.forEach((pattern, index) => {
98
+ if (typeof pattern !== "string" || !pattern.startsWith("/"))
99
+ fail(`seo.linkChecker.exclude[${index}] must be a route rule pattern starting with "/"`);
100
+ });
101
+ if (typeof rules !== "object" || rules === null || Array.isArray(rules))
102
+ fail(`seo.linkChecker.rules must be an object (got ${show(rules)})`);
103
+ for (const [id, level] of Object.entries(rules)) {
104
+ if (!Object.hasOwn(LINK_RULES, id))
105
+ fail(`seo.linkChecker.rules.${id} is not a link rule (have: ${Object.keys(LINK_RULES).join(", ")})`);
106
+ if (level !== "error" && level !== "warning" && level !== false)
107
+ fail(`seo.linkChecker.rules.${id} must be "error", "warning" or false (got ${show(level)})`);
108
+ }
109
+ return { failOnError, external, report: [...report], exclude: [...exclude], rules: { ...rules } };
110
+ }
111
+
112
+ // packages/seo/src/links/report.ts
113
+ import { mkdir, writeFile } from "node:fs/promises";
114
+ import { join } from "node:path";
115
+ import { escapeXml } from "hamur/server/internal";
116
+ var FILES = {
117
+ json: "link-checker.json",
118
+ markdown: "link-checker.md",
119
+ html: "link-checker.html"
120
+ };
121
+ var cell = (text) => text.replace(/\|/g, "\\|").replace(/\n/g, " ");
122
+ function markdown(findings) {
123
+ const rows = findings.map(({ page, level, rule, link, message }) => `| ${[page, level, rule, link, message].map(cell).join(" | ")} |`);
124
+ return ["| Page | Level | Rule | Link | Message |", "|---|---|---|---|---|", ...rows, ""].join(`
125
+ `);
126
+ }
127
+ function html(pages, findings) {
128
+ const rows = findings.map(({ page, level, rule, link, message }) => `<tr><td>${[page, level, rule, link, message].map(escapeXml).join("</td><td>")}</td></tr>`);
129
+ return `<!doctype html>
130
+ <html lang="en"><head><meta charset="utf-8"><title>Link checker</title><style>body{font:14px system-ui,sans-serif;margin:2rem}table{border-collapse:collapse}td,th{border:1px solid #888;padding:.25rem .5rem;text-align:left}</style></head><body><h1>Link checker</h1><p>${pages} pages, ${findings.length} findings</p><table><thead><tr><th>Page</th><th>Level</th><th>Rule</th><th>Link</th><th>Message</th></tr></thead><tbody>${rows.join("")}</tbody></table></body></html>
131
+ `;
132
+ }
133
+ async function writeReports(buildDir, formats, pages, findings) {
134
+ if (!formats.length)
135
+ return;
136
+ const dir = join(buildDir, "reports");
137
+ await mkdir(dir, { recursive: true });
138
+ for (const format of new Set(formats)) {
139
+ const body = format === "json" ? `${JSON.stringify({ pages, findings }, null, 2)}
140
+ ` : format === "markdown" ? markdown(findings) : html(pages, findings);
141
+ await writeFile(join(dir, FILES[format]), body);
142
+ }
143
+ }
144
+
145
+ // packages/seo/src/links/scan.ts
146
+ var INERT = /<(script|style)\b[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/gi;
147
+ var TAG = /<(\/?)([a-zA-Z][^\s>/]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
148
+ var ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
149
+ var ENTITY = /&(?:#x([0-9a-f]+)|#(\d+)|([a-z]+));/gi;
150
+ var NAMED = {
151
+ amp: "&",
152
+ quot: '"',
153
+ lt: "<",
154
+ gt: ">",
155
+ apos: "'",
156
+ nbsp: " ",
157
+ copy: "©",
158
+ reg: "®",
159
+ trade: "™",
160
+ hellip: "…",
161
+ mdash: "—",
162
+ ndash: "–",
163
+ lsquo: "‘",
164
+ rsquo: "’",
165
+ ldquo: "“",
166
+ rdquo: "”",
167
+ laquo: "«",
168
+ raquo: "»",
169
+ middot: "·",
170
+ bull: "•",
171
+ times: "×"
172
+ };
173
+ function decode(text) {
174
+ return text.replace(ENTITY, (whole, hex, decimal, name) => {
175
+ if (name)
176
+ return Object.hasOwn(NAMED, name.toLowerCase()) ? NAMED[name.toLowerCase()] : whole;
177
+ const code = Number.parseInt(hex ?? decimal, hex ? 16 : 10);
178
+ return code >= 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
179
+ });
180
+ }
181
+ function attributes(source) {
182
+ const found = new Map;
183
+ for (const [, name, quoted, single, bare] of source.matchAll(ATTRIBUTE)) {
184
+ const key = name.toLowerCase();
185
+ if (!found.has(key))
186
+ found.set(key, decode(quoted ?? single ?? bare ?? ""));
187
+ }
188
+ return found;
189
+ }
190
+ function scanPage(html) {
191
+ const links = [];
192
+ const ids = new Set;
193
+ const source = html.replace(INERT, (match) => " ".repeat(match.length));
194
+ let open;
195
+ const close = () => {
196
+ if (open)
197
+ links.push({ href: open.href, named: open.named || open.text.trim() !== "" });
198
+ open = undefined;
199
+ };
200
+ let last = 0;
201
+ for (const match of source.matchAll(TAG)) {
202
+ if (open)
203
+ open.text += decode(source.slice(last, match.index));
204
+ last = match.index + match[0].length;
205
+ const [, closing, rawName, rest] = match;
206
+ const name = rawName.toLowerCase();
207
+ if (closing) {
208
+ if (name === "a")
209
+ close();
210
+ continue;
211
+ }
212
+ const attrs = attributes(rest);
213
+ const id = attrs.get("id");
214
+ if (id)
215
+ ids.add(id);
216
+ if (name === "a") {
217
+ close();
218
+ const anchor = attrs.get("name");
219
+ if (anchor)
220
+ ids.add(anchor);
221
+ const href = attrs.get("href");
222
+ if (href !== undefined)
223
+ open = {
224
+ href,
225
+ named: ["aria-label", "aria-labelledby", "title"].some((key) => (attrs.get(key) ?? "").trim() !== ""),
226
+ text: ""
227
+ };
228
+ } else if (name === "img" && open && (attrs.get("alt") ?? "").trim() !== "") {
229
+ open.named = true;
230
+ }
231
+ }
232
+ if (open)
233
+ open.text += decode(source.slice(last));
234
+ close();
235
+ return { links, ids };
236
+ }
237
+ var DECLARATION = /<![^>]*>|<\?[\s\S]*?\?>/g;
238
+ function tokenize(html) {
239
+ const source = html.replace(INERT, "").replace(DECLARATION, "");
240
+ const tokens = [];
241
+ let last = 0;
242
+ const text = (to) => {
243
+ if (to > last)
244
+ tokens.push({ text: source.slice(last, to) });
245
+ };
246
+ for (const match of source.matchAll(TAG)) {
247
+ text(match.index);
248
+ last = match.index + match[0].length;
249
+ const [, closing, rawName, rest] = match;
250
+ const name = rawName.toLowerCase();
251
+ if (closing)
252
+ tokens.push({ close: name });
253
+ else
254
+ tokens.push({ open: name, attrs: attributes(rest), selfClosing: rest.trimEnd().endsWith("/") });
255
+ }
256
+ text(source.length);
257
+ return tokens;
258
+ }
259
+
260
+ // packages/seo/src/links/check.ts
261
+ var ORIGIN = "http://localhost";
262
+ var REDIRECTS = new Set([301, 302, 303, 307, 308]);
263
+ var SCRIPT = /^[\s\u0000-\u001f]*javascript:/i;
264
+ var trimSlash = (path) => path.replace(/(.)\/+$/, "$1");
265
+ var keyOf = (path) => trimSlash(path);
266
+ function stripBase(pathname, baseURL) {
267
+ const base = baseURL.replace(/\/+$/, "");
268
+ if (base === "")
269
+ return pathname;
270
+ if (pathname === base)
271
+ return "/";
272
+ return pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : undefined;
273
+ }
274
+ var decodeFragment = (hash) => {
275
+ let value = hash.slice(1);
276
+ try {
277
+ value = decodeURIComponent(value);
278
+ } catch {}
279
+ return value === "" || value === "top" || value.startsWith(":~:") ? undefined : value;
280
+ };
281
+ function createLinkChecker(hamur, options) {
282
+ const log = useLogger("seo");
283
+ const { baseURL, trailingSlash } = hamur.options.app;
284
+ const buildAssets = `/${hamur.options.app.buildAssetsDir.replace(/^\/+|\/+$/g, "")}/`;
285
+ const excluded = options.exclude.length ? createRouteRules(Object.fromEntries(options.exclude.map((pattern) => [pattern, {}]))) : undefined;
286
+ const routeRules = createRouteRules(hamur.routeRules);
287
+ let pages = new Map;
288
+ let findings = [];
289
+ let externals = new Map;
290
+ let scanned = 0;
291
+ const levelOf = (rule) => options.rules[rule] ?? LINK_RULES[rule];
292
+ const add = (page, rule, link, message, at = Number.MAX_SAFE_INTEGER) => {
293
+ const level = levelOf(rule);
294
+ if (level === false)
295
+ return;
296
+ if (!findings.some((found) => found.page === page && found.rule === rule && found.message === message))
297
+ findings.push({ page, rule, level, link, message, at });
298
+ };
299
+ const siteOrigin = () => {
300
+ try {
301
+ const url = hamur.options.site.url ?? process.env.HAMUR_SITE_URL;
302
+ return url === undefined ? undefined : new URL(url).origin;
303
+ } catch {
304
+ return;
305
+ }
306
+ };
307
+ function scanLinks(page, html) {
308
+ const scan = scanPage(html);
309
+ scanned++;
310
+ const seen = { path: page.path, status: page.status, ids: scan.ids, pending: [] };
311
+ const from = `${ORIGIN}${baseURL.replace(/\/+$/, "")}${page.path}`;
312
+ const site = siteOrigin();
313
+ for (const [at, { href: raw, named }] of scan.links.entries()) {
314
+ const href = raw.trim();
315
+ if (raw !== href || /\s/.test(href.split(/[?#]/)[0]))
316
+ add(page.path, "whitespace", raw, `link href ${JSON.stringify(raw)} holds white space`, at);
317
+ if (SCRIPT.test(raw)) {
318
+ add(page.path, "javascript-href", href, `link href ${JSON.stringify(href)} runs script; use a button`, at);
319
+ if (!named)
320
+ add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at);
321
+ continue;
322
+ }
323
+ let url;
324
+ try {
325
+ url = new URL(href, from);
326
+ } catch {
327
+ continue;
328
+ }
329
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
330
+ if (!named)
331
+ add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at);
332
+ continue;
333
+ }
334
+ const absolute = /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href);
335
+ const onSite = absolute && site !== undefined && url.origin === site;
336
+ if (url.origin !== ORIGIN && !onSite) {
337
+ if (!named)
338
+ add(page.path, "empty-text", href, `link to ${href} has no text, aria-label or image alt`, at);
339
+ const key = `${url.origin}${url.pathname}${url.search}`;
340
+ if (options.external)
341
+ externals.set(key, (externals.get(key) ?? new Set).add(page.path));
342
+ continue;
343
+ }
344
+ const appPath = stripBase(url.pathname, baseURL);
345
+ if (appPath === undefined || appPath.startsWith(buildAssets))
346
+ continue;
347
+ if (excluded?.match(appPath).matches.length)
348
+ continue;
349
+ const own = /^[#?]/.test(href);
350
+ const shown = own ? href : url.pathname;
351
+ if (!named)
352
+ add(page.path, "empty-text", shown, `link to ${shown} has no text, aria-label or image alt`, at);
353
+ if (onSite)
354
+ add(page.path, "absolute-site-url", href, `link to ${href} is absolute on site.url; write ${url.pathname}`, at);
355
+ if (!own) {
356
+ if (url.pathname.includes("//"))
357
+ add(page.path, "double-slash", shown, `link to ${shown} has a double slash in its path`, at);
358
+ if (/[A-Z]/.test(url.pathname.replace(/%[\da-f]{2}/gi, "")))
359
+ add(page.path, "uppercase", shown, `link to ${shown} has upper-case letters in its path`, at);
360
+ const ends = appPath.length > 1 && appPath.endsWith("/");
361
+ if (trailingSlash === "always" ? !ends && slashForm(appPath, "/") !== undefined : ends) {
362
+ const fixed = trailingSlash === "always" ? `${url.pathname}/` : url.pathname.replace(/\/+$/, "");
363
+ add(page.path, "trailing-slash", shown, `link to ${shown} does not follow app.trailingSlash ${JSON.stringify(trailingSlash)}; write ${fixed}`, at);
364
+ }
365
+ }
366
+ const fragment = decodeFragment(url.hash);
367
+ seen.pending.push({
368
+ at,
369
+ shown: own ? url.hash || href : `${url.pathname}${url.hash}`,
370
+ target: appPath,
371
+ ...fragment === undefined ? {} : { fragment }
372
+ });
373
+ }
374
+ return seen;
375
+ }
376
+ function page(current) {
377
+ const html = typeof current.body === "string" && (current.headers.get("content-type") ?? "").startsWith("text/html");
378
+ const ok = current.status >= 200 && current.status <= 299;
379
+ const seen = html && ok ? scanLinks(current, current.body) : { path: current.path, status: current.status, pending: [] };
380
+ const location = current.headers.get("location");
381
+ pages.set(keyOf(current.path), { ...seen, ...location ? { location } : {} });
382
+ }
383
+ async function done(_pages, run) {
384
+ if (run.checkNext) {
385
+ reset();
386
+ return;
387
+ }
388
+ run.linksReported = true;
389
+ const failed = new Map(run.failed.map((answer) => [keyOf(answer.path), answer]));
390
+ const known = new Map;
391
+ const exists = async (path) => {
392
+ if (!known.has(path))
393
+ known.set(path, await run.exists(path));
394
+ return known.get(path);
395
+ };
396
+ for (const seen of [...pages.values()].sort((a, b) => a.path < b.path ? -1 : 1)) {
397
+ for (const { at, shown, target, fragment } of seen.pending) {
398
+ const key = keyOf(target);
399
+ const there = pages.get(key);
400
+ const path = target;
401
+ const answer = failed.get(key);
402
+ if (answer)
403
+ add(seen.path, "broken", shown, `link to ${path} answers ${answer.status}`, at);
404
+ else if (!there && !await exists(key))
405
+ add(seen.path, "broken", shown, `link to ${path} matches no route`, at);
406
+ const redirect = REDIRECTS.has(there?.status ?? 0) ? there?.location : there ? undefined : ruleRedirect(key);
407
+ if (redirect)
408
+ add(seen.path, "redirect", shown, `link to ${path} redirects to ${redirect}; link to ${redirect}`, at);
409
+ if (fragment !== undefined && there?.ids && !there.ids.has(fragment))
410
+ add(seen.path, "missing-anchor", shown, `link to ${shown}: ${path} has no element with id ${JSON.stringify(fragment)}`, at);
411
+ }
412
+ }
413
+ if (externals.size) {
414
+ const bad = await probeAll(externals.keys());
415
+ for (const [url, message] of bad)
416
+ for (const from of externals.get(url))
417
+ add(from, "external-broken", url, message);
418
+ }
419
+ const ordered = findings.toSorted((a, b) => a.page < b.page ? -1 : a.page > b.page ? 1 : a.at - b.at).map(({ at: _, ...finding }) => finding);
420
+ const errors = ordered.filter((finding) => finding.level === "error").length;
421
+ const count = scanned;
422
+ reset();
423
+ if (ordered.length)
424
+ log.warn(diagnostic("HAMUR_W6410", formatLinkFindings(ordered)));
425
+ else if (run.checkOnly)
426
+ log.info(`link checker: no findings on ${count} page${count === 1 ? "" : "s"}`);
427
+ await writeReports(hamur.options.buildDir, options.report, count, ordered);
428
+ if (options.failOnError && errors)
429
+ throw new DiagnosticError2("HAMUR_E6407", `[seo] link checker found ${errors} error${errors === 1 ? "" : "s"} (seo.linkChecker.failOnError)`);
430
+ }
431
+ function ruleRedirect(path) {
432
+ const { redirect } = routeRules.match(path).rule;
433
+ if (redirect === undefined)
434
+ return;
435
+ return typeof redirect === "string" ? redirect : redirect.to;
436
+ }
437
+ function reset() {
438
+ pages = new Map;
439
+ findings = [];
440
+ externals = new Map;
441
+ scanned = 0;
442
+ }
443
+ return { page, done };
444
+ }
445
+
446
+ // packages/seo/src/build/links.ts
447
+ function setupLinkChecker(value, hamur) {
448
+ const options = resolveLinkChecker(value);
449
+ if (!options)
450
+ return;
451
+ const checker = createLinkChecker(hamur, options);
452
+ hamur.hooks.hook("prerender:page", checker.page);
453
+ hamur.hooks.hook("prerender:done", checker.done);
454
+ }
455
+
456
+ // packages/seo/src/build/llms.ts
457
+ import { existsSync as existsSync2 } from "node:fs";
458
+ import { join as join3 } from "node:path";
459
+ import { addTemplate, createRouteRules as createRouteRules2 } from "hamur/kit";
460
+ import { absoluteUrl } from "hamur/server/internal";
461
+
462
+ // packages/seo/src/runtime/markdown.ts
463
+ var VOID = new Set([
464
+ "area",
465
+ "base",
466
+ "br",
467
+ "col",
468
+ "embed",
469
+ "hr",
470
+ "img",
471
+ "input",
472
+ "link",
473
+ "meta",
474
+ "param",
475
+ "source",
476
+ "track",
477
+ "wbr"
478
+ ]);
479
+ var DROPPED = new Set(["script", "style", "nav", "noscript", "template", "svg", "iframe", "form", "button"]);
480
+ var HEADINGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
481
+ var PARAGRAPH_ENDS = new Set([
482
+ "address",
483
+ "article",
484
+ "aside",
485
+ "blockquote",
486
+ "div",
487
+ "dl",
488
+ "fieldset",
489
+ "footer",
490
+ "form",
491
+ "header",
492
+ "hr",
493
+ "main",
494
+ "nav",
495
+ "ol",
496
+ "p",
497
+ "pre",
498
+ "section",
499
+ "table",
500
+ "ul",
501
+ ...HEADINGS
502
+ ]);
503
+ var BLOCKS = new Set([
504
+ ...PARAGRAPH_ENDS,
505
+ "body",
506
+ "details",
507
+ "dd",
508
+ "dt",
509
+ "figcaption",
510
+ "figure",
511
+ "hgroup",
512
+ "html",
513
+ "li",
514
+ "summary",
515
+ "tbody",
516
+ "td",
517
+ "tfoot",
518
+ "th",
519
+ "thead",
520
+ "tr"
521
+ ]);
522
+ var IMPLICIT = {
523
+ li: new Set(["li"]),
524
+ tr: new Set(["td", "th", "tr"]),
525
+ td: new Set(["td", "th"]),
526
+ th: new Set(["td", "th"]),
527
+ dt: new Set(["dt", "dd"]),
528
+ dd: new Set(["dt", "dd"])
529
+ };
530
+ var P_ONLY = new Set(["p"]);
531
+ function parse(html) {
532
+ const root = { name: "#root", attrs: new Map, children: [] };
533
+ const stack = [root];
534
+ const top = () => stack[stack.length - 1];
535
+ for (const token of tokenize(html)) {
536
+ if ("text" in token) {
537
+ top().children.push(token.text);
538
+ } else if ("open" in token) {
539
+ const closes = IMPLICIT[token.open] ?? (PARAGRAPH_ENDS.has(token.open) ? P_ONLY : undefined);
540
+ while (closes && stack.length > 1 && closes.has(top().name))
541
+ stack.pop();
542
+ const element = { name: token.open, attrs: token.attrs, children: [] };
543
+ top().children.push(element);
544
+ if (!VOID.has(token.open) && !token.selfClosing)
545
+ stack.push(element);
546
+ } else {
547
+ const at = stack.findLastIndex((element, index) => index > 0 && element.name === token.close);
548
+ if (at !== -1)
549
+ stack.length = at;
550
+ }
551
+ }
552
+ return root;
553
+ }
554
+ function find(node, test, skip) {
555
+ if (typeof node === "string")
556
+ return;
557
+ if (node.name !== "#root" && test(node))
558
+ return node;
559
+ if (skip?.(node))
560
+ return;
561
+ for (const child of node.children) {
562
+ const found = find(child, test, skip);
563
+ if (found)
564
+ return found;
565
+ }
566
+ return;
567
+ }
568
+ var oneLine = (text) => text.replace(/\s+/g, " ").trim();
569
+ class Run {
570
+ trimStart;
571
+ text = "";
572
+ constructor(trimStart = true) {
573
+ this.trimStart = trimStart;
574
+ }
575
+ add(piece) {
576
+ if (piece === "")
577
+ return;
578
+ const spaced = this.text === "" ? this.trimStart : /[ \n]$/.test(this.text);
579
+ this.text += spaced && piece.startsWith(" ") ? piece.slice(1) : piece;
580
+ }
581
+ }
582
+ var fence = (text, char, least) => char.repeat(Math.max(least, Math.max(0, ...(text.match(new RegExp(`${char}+`, "g")) ?? []).map((run) => run.length)) + 1));
583
+ var indent = (text, by) => text.split(`
584
+ `).map((line, index) => index === 0 || line === "" ? line : by + line).join(`
585
+ `);
586
+ function rawText(nodes) {
587
+ return nodes.map((node) => typeof node === "string" ? decode(node) : node.name === "br" ? `
588
+ ` : DROPPED.has(node.name) ? "" : rawText(node.children)).join("");
589
+ }
590
+
591
+ class Converter {
592
+ base;
593
+ constructor(base) {
594
+ this.base = base;
595
+ }
596
+ url(value) {
597
+ try {
598
+ return new URL(value.trim(), this.base).href;
599
+ } catch {
600
+ return value.trim();
601
+ }
602
+ }
603
+ inline(nodes, trimStart = true) {
604
+ const run = new Run(trimStart);
605
+ for (const node of nodes)
606
+ this.addInline(run, node);
607
+ return run.text;
608
+ }
609
+ addInline(run, node) {
610
+ if (typeof node === "string") {
611
+ run.add(decode(node).replace(/\s+/g, " "));
612
+ return;
613
+ }
614
+ if (DROPPED.has(node.name))
615
+ return;
616
+ switch (node.name) {
617
+ case "br":
618
+ run.text = run.text.replace(/ +$/, "");
619
+ run.text += `
620
+ `;
621
+ return;
622
+ case "img": {
623
+ const src = node.attrs.get("src")?.trim();
624
+ if (src)
625
+ run.add(`![${oneLine(node.attrs.get("alt") ?? "")}](${this.url(src)})`);
626
+ return;
627
+ }
628
+ case "strong":
629
+ case "b":
630
+ run.add(this.emphasis(node, "**"));
631
+ return;
632
+ case "em":
633
+ case "i":
634
+ run.add(this.emphasis(node, "*"));
635
+ return;
636
+ case "code": {
637
+ const code = oneLine(rawText(node.children));
638
+ if (code === "")
639
+ return;
640
+ const ticks = fence(code, "`", 1);
641
+ run.add(code.startsWith("`") || code.endsWith("`") ? `${ticks} ${code} ${ticks}` : `${ticks}${code}${ticks}`);
642
+ return;
643
+ }
644
+ case "a": {
645
+ const text = oneLine(this.inline(node.children));
646
+ const href = node.attrs.get("href")?.trim();
647
+ if (text === "")
648
+ return;
649
+ run.add(href && !/^javascript:/i.test(href) ? `[${text}](${this.url(href)})` : text);
650
+ return;
651
+ }
652
+ }
653
+ if (BLOCKS.has(node.name)) {
654
+ run.add(" ");
655
+ for (const child of node.children)
656
+ this.addInline(run, child);
657
+ run.add(" ");
658
+ return;
659
+ }
660
+ for (const child of node.children)
661
+ this.addInline(run, child);
662
+ }
663
+ emphasis(node, mark) {
664
+ const text = this.inline(node.children, false);
665
+ const core = text.trim();
666
+ if (core === "")
667
+ return text;
668
+ return `${text.slice(0, text.length - text.trimStart().length)}${mark}${core}${mark}${text.slice(text.trimEnd().length)}`;
669
+ }
670
+ flow(nodes) {
671
+ const chunks = [];
672
+ let run = new Run;
673
+ const flush = () => {
674
+ const text = run.text.trim().replace(/\n{3,}/g, `
675
+
676
+ `);
677
+ if (text !== "")
678
+ chunks.push(text);
679
+ run = new Run;
680
+ };
681
+ for (const node of nodes) {
682
+ if (typeof node !== "string" && BLOCKS.has(node.name) && !DROPPED.has(node.name)) {
683
+ flush();
684
+ chunks.push(...this.block(node));
685
+ } else {
686
+ this.addInline(run, node);
687
+ }
688
+ }
689
+ flush();
690
+ return chunks;
691
+ }
692
+ block(node) {
693
+ const name = node.name;
694
+ if (HEADINGS.has(name)) {
695
+ const text = oneLine(this.inline(node.children));
696
+ return text === "" ? [] : [`${"#".repeat(Number(name.slice(1)))} ${text}`];
697
+ }
698
+ switch (name) {
699
+ case "hr":
700
+ return ["---"];
701
+ case "pre":
702
+ return [this.pre(node)];
703
+ case "blockquote": {
704
+ const body = this.flow(node.children).join(`
705
+
706
+ `);
707
+ return body === "" ? [] : [
708
+ body.split(`
709
+ `).map((line) => line === "" ? ">" : `> ${line}`).join(`
710
+ `)
711
+ ];
712
+ }
713
+ case "ul":
714
+ case "ol":
715
+ return this.list(node);
716
+ case "table":
717
+ return this.table(node);
718
+ }
719
+ return this.flow(node.children);
720
+ }
721
+ pre(node) {
722
+ const code = find(node, (element) => element.name === "code");
723
+ const language = /(?:^|\s)language-(\S+)/.exec(code?.attrs.get("class") ?? "")?.[1] ?? "";
724
+ const text = rawText(node.children).replace(/^\n/, "").replace(/\s+$/, "");
725
+ const ticks = fence(text, "`", 3);
726
+ return `${ticks}${language}
727
+ ${text}
728
+ ${ticks}`;
729
+ }
730
+ list(node) {
731
+ const ordered = node.name === "ol";
732
+ const start = Number.parseInt(node.attrs.get("start") ?? "1", 10);
733
+ let number = Number.isNaN(start) ? 1 : start;
734
+ const items = [];
735
+ for (const child of node.children) {
736
+ if (typeof child === "string" || child.name !== "li")
737
+ continue;
738
+ const body = this.flow(child.children).join(`
739
+ `);
740
+ const marker = ordered ? `${number++}.` : "-";
741
+ items.push(`${marker} ${indent(body, " ".repeat(marker.length + 1))}`.trimEnd());
742
+ }
743
+ return items.length ? [items.join(`
744
+ `)] : [];
745
+ }
746
+ table(node) {
747
+ const rows = [];
748
+ const walk = (parent) => {
749
+ for (const child of parent.children) {
750
+ if (typeof child === "string")
751
+ continue;
752
+ if (child.name === "tr") {
753
+ rows.push(child.children.flatMap((cell) => typeof cell !== "string" && (cell.name === "td" || cell.name === "th") ? [oneLine(this.inline(cell.children)).replaceAll("|", "\\|")] : []));
754
+ } else if (child.name === "thead" || child.name === "tbody" || child.name === "tfoot") {
755
+ walk(child);
756
+ }
757
+ }
758
+ };
759
+ walk(node);
760
+ const width = Math.max(0, ...rows.map((row) => row.length));
761
+ if (width === 0)
762
+ return [];
763
+ const line = (row) => `| ${Array.from({ length: width }, (_, index) => row[index] ?? "").join(" | ")} |`;
764
+ const [header, ...body] = rows;
765
+ return [[line(header), line(Array.from({ length: width }, () => "---")), ...body.map(line)].join(`
766
+ `)];
767
+ }
768
+ }
769
+ function htmlToMarkdown(html, { base, rootId }) {
770
+ const tree = parse(html);
771
+ const root = find(tree, (element) => element.name === "main") ?? (rootId === undefined ? undefined : find(tree, (element) => element.attrs.get("id") === rootId)) ?? find(tree, (element) => element.name === "body") ?? tree;
772
+ const text = new Converter(base).flow(root.children).join(`
773
+
774
+ `).trim();
775
+ return text === "" ? "" : `${text}
776
+ `;
777
+ }
778
+
779
+ // packages/seo/src/llms/options.ts
780
+ import { DiagnosticError as DiagnosticError3 } from "hamur/kit";
781
+ var KEYS2 = ["title", "description", "exclude"];
782
+ var show2 = (value) => JSON.stringify(value) ?? String(value);
783
+ function fail2(message) {
784
+ throw new DiagnosticError3("HAMUR_E6404", message);
785
+ }
786
+ function resolveLlms(input) {
787
+ if (input === undefined || input === false)
788
+ return;
789
+ if (input === true)
790
+ return { exclude: [] };
791
+ if (typeof input !== "object" || input === null || Array.isArray(input))
792
+ fail2(`seo.llms must be a boolean or an object (got ${show2(input)})`);
793
+ for (const key of Object.keys(input))
794
+ if (!KEYS2.includes(key))
795
+ fail2(`seo.llms.${key} is not an option`);
796
+ const { title, description, exclude = [] } = input;
797
+ for (const [key, value] of [
798
+ ["title", title],
799
+ ["description", description]
800
+ ]) {
801
+ if (value !== undefined && (typeof value !== "string" || value === ""))
802
+ fail2(`seo.llms.${key} must be a non-empty string (got ${show2(value)})`);
803
+ }
804
+ if (!Array.isArray(exclude))
805
+ fail2(`seo.llms.exclude must be an array of route rule patterns (got ${show2(exclude)})`);
806
+ exclude.forEach((pattern, index) => {
807
+ if (typeof pattern !== "string" || !pattern.startsWith("/"))
808
+ fail2(`seo.llms.exclude[${index}] must be a route rule pattern starting with "/"`);
809
+ });
810
+ return {
811
+ ...title === undefined ? {} : { title },
812
+ ...description === undefined ? {} : { description },
813
+ exclude: [...exclude]
814
+ };
815
+ }
816
+ function checkOwner(contentLlms) {
817
+ if (contentLlms !== undefined && contentLlms !== false)
818
+ fail2("seo.llms and content.llms both serve /llms.txt; set one");
819
+ }
820
+
821
+ // packages/seo/src/llms/paths.ts
822
+ var markdownPath = (path) => path === "/" ? "/index.md" : `${path.replace(/\/+$/, "")}.md`;
823
+
824
+ // packages/seo/src/build/own.ts
825
+ import { existsSync } from "node:fs";
826
+ import { join as join2, relative } from "node:path";
827
+ import { useLogger as useLogger2 } from "hamur/kit";
828
+ function yieldToApp(hamur, path, enabled, companions = []) {
829
+ const log = useLogger2("seo");
830
+ const file = path.slice(1);
831
+ const { rootDir, layers } = hamur.options;
832
+ const serverDirs = [hamur.options.serverDir, ...layers.map((layer) => layer.serverDir)];
833
+ const publicDirs = [hamur.options.publicDir, ...layers.map((layer) => layer.publicDir)];
834
+ const answers = (record) => record.path === path && (record.method === undefined || record.method === "GET");
835
+ const ours = (record) => answers(record) || companions.includes(record.path) && (record.method === undefined || record.method === "GET");
836
+ const said = new Set;
837
+ let served = true;
838
+ hamur.hooks.hook("server:extend", (records) => {
839
+ const dir = publicDirs.find((publicDir) => existsSync(join2(publicDir, file)));
840
+ const own = records.find((record) => answers(record) && serverDirs.some((serverDir) => record.file.startsWith(`${serverDir}/`)));
841
+ const reason = dir ? `${relative(rootDir, join2(dir, file))} exists; @hamur/seo serves no ${path}` : own ? `${relative(rootDir, own.file)}#${own.fn.export} answers ${path}; @hamur/seo serves none` : undefined;
842
+ served = enabled && reason === undefined;
843
+ if (served)
844
+ return;
845
+ if (reason !== undefined && enabled && !said.has(reason)) {
846
+ said.add(reason);
847
+ log.info(reason);
848
+ }
849
+ for (let index = records.length - 1;index >= 0; index--) {
850
+ const record = records[index];
851
+ if (ours(record) && !serverDirs.some((serverDir) => record.file.startsWith(`${serverDir}/`)))
852
+ records.splice(index, 1);
853
+ }
854
+ });
855
+ return { served: () => served };
856
+ }
857
+
858
+ // packages/seo/src/build/llms.ts
859
+ var PATH = "/llms.txt";
860
+ var FULL = "/llms-full.txt";
861
+ function readLlms(input, hamur) {
862
+ const llms = resolveLlms(input);
863
+ if (llms)
864
+ checkOwner(hamur.options.content?.llms);
865
+ return llms;
866
+ }
867
+ function setupLlms(llms, hamur) {
868
+ const { baseURL, trailingSlash, rootId } = hamur.options.app;
869
+ const own = yieldToApp(hamur, PATH, llms !== undefined, [FULL]);
870
+ if (!llms) {
871
+ addTemplate({
872
+ filename: "seo/llms",
873
+ getContents: () => `export const enabled = false;
874
+ export const title = null;
875
+ export const description = null;
876
+ export const exclude = [];
877
+ export const baseURL = "/";
878
+ export const trailingSlash = "ignore";
879
+ export const rootId = "";
880
+ `
881
+ });
882
+ return;
883
+ }
884
+ addTemplate({
885
+ filename: "seo/llms",
886
+ getContents: () => `${Object.entries({
887
+ enabled: true,
888
+ title: llms.title ?? null,
889
+ description: llms.description ?? null,
890
+ exclude: llms.exclude,
891
+ baseURL,
892
+ trailingSlash,
893
+ rootId
894
+ }).map(([name, value]) => `export const ${name} = ${JSON.stringify(value)};
895
+ `).join("")}`
896
+ });
897
+ const excluded = llms.exclude.length ? createRouteRules2(Object.fromEntries(llms.exclude.map((pattern) => [pattern, {}]))) : undefined;
898
+ hamur.hooks.hook("prerender:routes", (routes) => {
899
+ if (hamur.options.preset !== "static" || !own.served())
900
+ return;
901
+ routes.add(PATH);
902
+ routes.add(FULL);
903
+ });
904
+ const converted = new Map;
905
+ hamur.hooks.hook("prerender:page", (page) => {
906
+ if (page.status !== 200 || typeof page.body !== "string" || !(page.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html"))
907
+ return;
908
+ if (excluded?.match(page.path).matches.length)
909
+ return;
910
+ const origin = hamur.options.site.url ?? process.env.HAMUR_SITE_URL ?? "http://localhost";
911
+ const text = htmlToMarkdown(page.body, { base: absoluteUrl(origin, baseURL, page.path), rootId });
912
+ if (text !== "")
913
+ converted.set(markdownPath(page.path), text);
914
+ });
915
+ hamur.hooks.hook("prerender:done", async () => {
916
+ const publicDirs = [hamur.options.publicDir, ...hamur.options.layers.map((layer) => layer.publicDir)];
917
+ const out = join3(hamur.options.outputDir, "public");
918
+ for (const [path, text] of converted) {
919
+ const name = path.slice(1);
920
+ if ([out, ...publicDirs].some((dir) => existsSync2(join3(dir, name))))
921
+ continue;
922
+ await Bun.write(join3(out, name), text);
923
+ }
924
+ converted.clear();
925
+ });
926
+ }
927
+
928
+ // packages/seo/src/build/robots.ts
929
+ import { addRouteRules, addTemplate as addTemplate2, diagnostic as diagnostic2, useLogger as useLogger3 } from "hamur/kit";
930
+
931
+ // packages/seo/src/robots/ai-bots.ts
932
+ var AI_BOTS = [
933
+ "GPTBot",
934
+ "ClaudeBot",
935
+ "anthropic-ai",
936
+ "CCBot",
937
+ "Google-Extended",
938
+ "Applebot-Extended",
939
+ "PerplexityBot",
940
+ "Bytespider",
941
+ "meta-externalagent",
942
+ "Amazonbot",
943
+ "cohere-ai"
944
+ ];
945
+
946
+ // packages/seo/src/robots/body.ts
947
+ function rulePath(pattern, prefix) {
948
+ const segments = pattern.split("/").map((segment) => segment.startsWith(":") || segment === "**" ? "*" : segment);
949
+ if (pattern.endsWith("/**") || pattern.endsWith("/*"))
950
+ return `${prefix}${segments.slice(0, -1).join("/")}/`;
951
+ return `${prefix}${segments.join("/")}$`;
952
+ }
953
+ function ruleLines({ noindex, baseURL, prefixes }) {
954
+ const base = baseURL.replace(/\/$/, "");
955
+ const lines = new Set;
956
+ for (const pattern of noindex) {
957
+ lines.add(`Disallow: ${rulePath(pattern, base)}`);
958
+ for (const code of prefixes)
959
+ lines.add(`Disallow: ${pattern === "/" ? `${base}/${code}$` : rulePath(pattern, `${base}/${code}`)}`);
960
+ }
961
+ return [...lines];
962
+ }
963
+ function robotsBody(input) {
964
+ const { robots } = input;
965
+ const rules = robots.fromRules ? ruleLines(input) : [];
966
+ const groups = robots.groups.map((group) => {
967
+ const agents = Array.isArray(group.userAgent) ? group.userAgent : [group.userAgent];
968
+ const own = (group.disallow ?? []).map((path) => `Disallow: ${path}`);
969
+ return [
970
+ ...agents.map((agent) => `User-agent: ${agent}`),
971
+ ...(group.allow ?? []).map((path) => `Allow: ${path}`),
972
+ ...new Set([...own, ...rules]),
973
+ ...group.crawlDelay === undefined ? [] : [`Crawl-delay: ${group.crawlDelay}`]
974
+ ].join(`
975
+ `);
976
+ });
977
+ if (robots.blockAiBots)
978
+ for (const bot of AI_BOTS)
979
+ groups.push(`User-agent: ${bot}
980
+ Disallow: /`);
981
+ return `${groups.join(`
982
+
983
+ `)}
984
+ `;
985
+ }
986
+
987
+ // packages/seo/src/robots/options.ts
988
+ import { DiagnosticError as DiagnosticError4 } from "hamur/kit";
989
+ var DEFAULT_GROUPS = [{ userAgent: "*", allow: ["/"] }];
990
+ var KEYS3 = ["groups", "blockAiBots", "fromRules"];
991
+ var GROUP_KEYS = ["userAgent", "allow", "disallow", "crawlDelay"];
992
+ var show3 = (value) => JSON.stringify(value) ?? String(value);
993
+ function fail3(message) {
994
+ throw new DiagnosticError4("HAMUR_E6403", message);
995
+ }
996
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
997
+ function checkLine(path, value) {
998
+ if (/[\r\n]/.test(value))
999
+ fail3(`${path} cannot contain a line break`);
1000
+ }
1001
+ function checkPaths(path, value) {
1002
+ if (!Array.isArray(value))
1003
+ fail3(`${path} must be an array of paths (got ${show3(value)})`);
1004
+ value.forEach((entry, index) => {
1005
+ const at = `${path}[${index}]`;
1006
+ if (typeof entry !== "string")
1007
+ fail3(`${at} must be a string (got ${show3(entry)})`);
1008
+ checkLine(at, entry);
1009
+ if (!entry.startsWith("/") && !entry.startsWith("*"))
1010
+ fail3(`${at} ${show3(entry)} must be a path starting with "/" or "*"`);
1011
+ });
1012
+ }
1013
+ function checkGroup(group, index) {
1014
+ const path = `seo.robots.groups[${index}]`;
1015
+ if (!isObject(group))
1016
+ fail3(`${path} must be an object (got ${show3(group)})`);
1017
+ for (const key of Object.keys(group))
1018
+ if (!GROUP_KEYS.includes(key))
1019
+ fail3(`${path}.${key} is not an option`);
1020
+ const agent = group.userAgent;
1021
+ const agents = Array.isArray(agent) ? agent : [agent];
1022
+ if (!agents.length || agents.some((name) => typeof name !== "string" || name === ""))
1023
+ fail3(`${path}.userAgent must be a non-empty string or an array of them (got ${show3(agent)})`);
1024
+ for (const name of agents)
1025
+ checkLine(`${path}.userAgent`, name);
1026
+ if (group.allow !== undefined)
1027
+ checkPaths(`${path}.allow`, group.allow);
1028
+ if (group.disallow !== undefined)
1029
+ checkPaths(`${path}.disallow`, group.disallow);
1030
+ const delay = group.crawlDelay;
1031
+ if (delay !== undefined && (typeof delay !== "number" || !Number.isFinite(delay) || delay <= 0))
1032
+ fail3(`${path}.crawlDelay must be a positive number (got ${show3(delay)})`);
1033
+ }
1034
+ function resolveRobots(input) {
1035
+ if (input === undefined || input === true)
1036
+ return { groups: DEFAULT_GROUPS, blockAiBots: false, fromRules: true };
1037
+ if (input === false)
1038
+ return;
1039
+ if (!isObject(input))
1040
+ fail3(`seo.robots must be a boolean or an object (got ${show3(input)})`);
1041
+ for (const key of Object.keys(input))
1042
+ if (!KEYS3.includes(key))
1043
+ fail3(`seo.robots.${key} is not an option`);
1044
+ for (const key of ["blockAiBots", "fromRules"]) {
1045
+ if (input[key] !== undefined && typeof input[key] !== "boolean")
1046
+ fail3(`seo.robots.${key} must be a boolean (got ${show3(input[key])})`);
1047
+ }
1048
+ const { groups } = input;
1049
+ if (groups !== undefined) {
1050
+ if (!Array.isArray(groups))
1051
+ fail3(`seo.robots.groups must be an array of groups (got ${show3(groups)})`);
1052
+ groups.forEach(checkGroup);
1053
+ }
1054
+ return {
1055
+ groups: groups?.length ? groups : DEFAULT_GROUPS,
1056
+ blockAiBots: input.blockAiBots === true,
1057
+ fromRules: input.fromRules !== false
1058
+ };
1059
+ }
1060
+
1061
+ // packages/seo/src/build/robots.ts
1062
+ var PATH2 = "/robots.txt";
1063
+ function localePrefixes(hamur) {
1064
+ const i18n = hamur.options.i18n;
1065
+ if (!i18n || !Array.isArray(i18n.locales))
1066
+ return [];
1067
+ const codes = i18n.locales.map((locale) => typeof locale === "string" ? locale : locale?.code).filter((code) => typeof code === "string");
1068
+ return i18n.strategy === "prefix" ? codes : codes.filter((code) => code !== i18n.defaultLocale);
1069
+ }
1070
+ function setupRobots(input, hamur, sitemap) {
1071
+ const robots = resolveRobots(input);
1072
+ const own = yieldToApp(hamur, PATH2, robots !== undefined);
1073
+ if (!robots) {
1074
+ addTemplate2({
1075
+ filename: "seo/robots",
1076
+ getContents: () => `export const body = "";
1077
+ export const sitemap = null;
1078
+ `
1079
+ });
1080
+ return;
1081
+ }
1082
+ const log = useLogger3("seo");
1083
+ const { baseURL } = hamur.options.app;
1084
+ if (baseURL !== "/")
1085
+ log.warn(diagnostic2("HAMUR_W6409", `app.baseURL is "${baseURL}": crawlers read robots.txt only at the origin's root, so ${baseURL}robots.txt is not read`));
1086
+ addTemplate2({
1087
+ filename: "seo/robots",
1088
+ getContents: (ctx) => {
1089
+ const noindex = Object.entries(ctx.routeRules).flatMap(([pattern, rule]) => !Array.isArray(rule) && !/\s/.test(pattern) && rule.noindex === true ? [pattern] : []);
1090
+ const body = robotsBody({ robots, noindex, baseURL, prefixes: localePrefixes(ctx) });
1091
+ return `export const body = ${JSON.stringify(body)};
1092
+ export const sitemap = ${JSON.stringify(sitemap ? `${baseURL}sitemap.xml` : null)};
1093
+ `;
1094
+ }
1095
+ });
1096
+ addRouteRules({ [PATH2]: { swr: 600 } });
1097
+ if (hamur.options.preset === "static") {
1098
+ hamur.hooks.hook("prerender:routes", (routes) => {
1099
+ if (own.served())
1100
+ routes.add(PATH2);
1101
+ });
1102
+ }
1103
+ }
1104
+
1105
+ // packages/seo/src/build/schema.ts
1106
+ import { addAppPlugin, addTemplate as addTemplate3, createResolver } from "hamur/kit";
1107
+
1108
+ // packages/seo/src/schema/options.ts
1109
+ import { DiagnosticError as DiagnosticError5 } from "hamur/kit";
1110
+ var show4 = (value) => JSON.stringify(value) ?? String(value);
1111
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1112
+ var IDENTITY_TYPES = ["Organization", "Person", "LocalBusiness"];
1113
+ function resolveSchemaOrg(value) {
1114
+ if (value === undefined || value === true)
1115
+ return { enabled: true };
1116
+ if (value === false)
1117
+ return { enabled: false };
1118
+ if (!isObject2(value))
1119
+ throw new DiagnosticError5("HAMUR_E6405", `seo.schemaOrg must be a boolean or an object (got ${show4(value)})`);
1120
+ for (const key of Object.keys(value))
1121
+ if (key !== "identity")
1122
+ throw new DiagnosticError5("HAMUR_E6405", `seo.schemaOrg.${key} is not an option`);
1123
+ const identity = value.identity;
1124
+ if (identity === undefined)
1125
+ return { enabled: true };
1126
+ const type = isObject2(identity) ? identity["@type"] : undefined;
1127
+ if (!isObject2(identity) || typeof type !== "string" || !IDENTITY_TYPES.includes(type)) {
1128
+ throw new DiagnosticError5("HAMUR_E6405", `seo.schemaOrg.identity must be an object whose @type is Organization, Person or LocalBusiness (got ${show4(isObject2(identity) ? type : identity)})`);
1129
+ }
1130
+ if (typeof identity.name !== "string" || identity.name === "")
1131
+ throw new DiagnosticError5("HAMUR_E6405", `seo.schemaOrg.identity.name must be a non-empty string (got ${show4(identity.name)})`);
1132
+ if ("@id" in identity)
1133
+ throw new DiagnosticError5("HAMUR_E6406", "seo.schemaOrg.identity.@id is set by @hamur/seo; remove it");
1134
+ return { enabled: true, identity };
1135
+ }
1136
+
1137
+ // packages/seo/src/build/schema.ts
1138
+ var titlesOf = (routes) => Object.fromEntries(routes.flatMap((route) => [
1139
+ ...route.title === undefined ? [] : [[route.name, route.title]],
1140
+ ...Object.entries(titlesOf(route.children))
1141
+ ]));
1142
+ function setupSchemaOrg(value, hamur) {
1143
+ const { enabled, identity } = resolveSchemaOrg(value);
1144
+ const { baseURL, trailingSlash } = hamur.options.app;
1145
+ addTemplate3({
1146
+ filename: "seo/schema-org",
1147
+ getContents: (ctx) => `export default ${JSON.stringify({ enabled, identity: identity ?? null, baseURL, trailingSlash, titles: titlesOf(ctx.routes) })};
1148
+ `
1149
+ });
1150
+ addAppPlugin({ src: createResolver(new URL("../../src/build/schema.ts", import.meta.url).href).resolve("../runtime/schema-plugin.ts"), mode: "all" });
1151
+ }
1152
+
1153
+ // packages/seo/src/build/sitemap.ts
1154
+ import { DiagnosticError as DiagnosticError7, addTemplate as addTemplate4, diagnostic as diagnostic3, useLogger as useLogger4 } from "hamur/kit";
1155
+
1156
+ // packages/seo/src/sitemap/alternates.ts
1157
+ var SEPARATOR = "___";
1158
+ function readLocales(input) {
1159
+ if (typeof input !== "object" || input === null)
1160
+ return;
1161
+ const { locales, defaultLocale } = input;
1162
+ if (!Array.isArray(locales) || typeof defaultLocale !== "string")
1163
+ return;
1164
+ const found = locales.flatMap((locale) => {
1165
+ const entry = typeof locale === "string" ? { code: locale } : locale;
1166
+ if (typeof entry?.code !== "string")
1167
+ return [];
1168
+ return [
1169
+ {
1170
+ code: entry.code,
1171
+ language: typeof entry.language === "string" ? entry.language : entry.code
1172
+ }
1173
+ ];
1174
+ });
1175
+ return found.length ? { locales: found, defaultLocale } : undefined;
1176
+ }
1177
+ function pageAlternates(pages, i18n, listed, clean) {
1178
+ const byName = new Map;
1179
+ for (const { name, path } of pages) {
1180
+ const index = name.indexOf(SEPARATOR);
1181
+ const base = index === -1 ? name : name.slice(0, index);
1182
+ const code = index === -1 ? i18n.defaultLocale : name.slice(index + SEPARATOR.length);
1183
+ const cleaned = clean(path);
1184
+ if (cleaned === undefined || /[:*]/.test(path))
1185
+ continue;
1186
+ const copies = byName.get(base) ?? new Map;
1187
+ copies.set(code, cleaned);
1188
+ byName.set(base, copies);
1189
+ }
1190
+ const result = {};
1191
+ for (const copies of byName.values()) {
1192
+ const pairs = [];
1193
+ for (const { code, language } of i18n.locales) {
1194
+ const path = copies.get(code);
1195
+ if (path !== undefined && listed.has(path))
1196
+ pairs.push([language, path]);
1197
+ }
1198
+ const fallback = copies.get(i18n.defaultLocale);
1199
+ if (fallback !== undefined && listed.has(fallback))
1200
+ pairs.push(["x-default", fallback]);
1201
+ if (pairs.length === 0)
1202
+ continue;
1203
+ for (const path of copies.values())
1204
+ if (listed.has(path))
1205
+ result[path] = pairs;
1206
+ }
1207
+ return result;
1208
+ }
1209
+
1210
+ // packages/seo/src/sitemap/paths.ts
1211
+ import { createRouteRules as createRouteRules3 } from "hamur/kit";
1212
+ var ORIGIN2 = "http://localhost";
1213
+ var isDynamic = (path) => /[:*]/.test(path);
1214
+ function clean(path) {
1215
+ if (!path.startsWith("/") || path.startsWith("//"))
1216
+ return;
1217
+ try {
1218
+ return new URL(path, ORIGIN2).pathname.replace(/(.)\/+$/, "$1");
1219
+ } catch {
1220
+ return;
1221
+ }
1222
+ }
1223
+ function sitemapPaths({ pages, listed, rules, exclude }) {
1224
+ const matcher = createRouteRules3({ ...rules });
1225
+ const excluded = createRouteRules3(Object.fromEntries(exclude.map((pattern) => [pattern, {}])));
1226
+ const found = new Set;
1227
+ for (const path of [...pages.filter((page) => !isDynamic(page)), ...listed, ...matcher.prerenderPaths()]) {
1228
+ const clear = clean(path);
1229
+ if (clear !== undefined)
1230
+ found.add(clear);
1231
+ }
1232
+ return [...found].filter((path) => {
1233
+ if (excluded.match(path).matches.length)
1234
+ return false;
1235
+ const { rule } = matcher.match(path);
1236
+ return rule.noindex !== true && rule.redirect === undefined;
1237
+ });
1238
+ }
1239
+
1240
+ // packages/seo/src/sitemap/options.ts
1241
+ import { DiagnosticError as DiagnosticError6 } from "hamur/kit";
1242
+ var MAX_CHUNK_SIZE = 50000;
1243
+ var KEYS4 = ["sources", "exclude", "chunkSize"];
1244
+ var show5 = (value) => JSON.stringify(value) ?? String(value);
1245
+ function fail4(message) {
1246
+ throw new DiagnosticError6("HAMUR_E6402", message);
1247
+ }
1248
+ function resolveSitemap(input) {
1249
+ if (input === undefined || input === true)
1250
+ return { sources: [], exclude: [], chunkSize: MAX_CHUNK_SIZE };
1251
+ if (input === false)
1252
+ return;
1253
+ if (typeof input !== "object" || input === null || Array.isArray(input))
1254
+ fail4(`seo.sitemap must be a boolean or an object (got ${show5(input)})`);
1255
+ for (const key of Object.keys(input))
1256
+ if (!KEYS4.includes(key))
1257
+ fail4(`seo.sitemap.${key} is not an option`);
1258
+ const { sources = [], exclude = [], chunkSize = MAX_CHUNK_SIZE } = input;
1259
+ if (!Array.isArray(sources))
1260
+ fail4(`seo.sitemap.sources must be an array of handler routes (got ${show5(sources)})`);
1261
+ sources.forEach((source, index) => {
1262
+ if (typeof source !== "string" || !source.startsWith("/"))
1263
+ fail4(`seo.sitemap.sources[${index}] ${show5(source)} must be a path starting with "/"`);
1264
+ if (source === "/sitemap.xml" || /^\/sitemap-[^/]*\.xml$/.test(source))
1265
+ fail4(`seo.sitemap.sources[${index}] ${show5(source)} is a route of the sitemap itself`);
1266
+ if (/[:*]/.test(source))
1267
+ fail4(`seo.sitemap.sources[${index}] ${show5(source)} must be the literal route of a handler, without params or wildcards`);
1268
+ });
1269
+ if (!Array.isArray(exclude))
1270
+ fail4(`seo.sitemap.exclude must be an array of route rule patterns (got ${show5(exclude)})`);
1271
+ exclude.forEach((pattern, index) => {
1272
+ if (typeof pattern !== "string" || !pattern.startsWith("/"))
1273
+ fail4(`seo.sitemap.exclude[${index}] must be a route rule pattern starting with "/"`);
1274
+ });
1275
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > MAX_CHUNK_SIZE)
1276
+ fail4(`seo.sitemap.chunkSize must be an integer from 1 to ${MAX_CHUNK_SIZE} (got ${show5(chunkSize)})`);
1277
+ return { sources: [...sources], exclude: [...exclude], chunkSize };
1278
+ }
1279
+
1280
+ // packages/seo/src/build/sitemap.ts
1281
+ import { slashForm as slashForm2 } from "hamur/server/internal";
1282
+ var PATH3 = "/sitemap.xml";
1283
+ var PART_ROUTE = "/sitemap-:n.xml";
1284
+ var flatten = (routes) => routes.flatMap((route) => [...route.pathless ? [] : [route], ...flatten(route.children)]);
1285
+ var slashed = (path) => slashForm2(path, "/") ?? path;
1286
+ var hash = (text) => {
1287
+ let value = 5381;
1288
+ for (let index = 0;index < text.length; index++)
1289
+ value = (value * 33 ^ text.charCodeAt(index)) >>> 0;
1290
+ return value.toString(36);
1291
+ };
1292
+ var moduleSource = (values) => Object.entries(values).map(([name, value]) => `export const ${name} = ${JSON.stringify(value)};
1293
+ `).join("");
1294
+ function setupSitemap(served, hamur, listed = false) {
1295
+ const own = yieldToApp(hamur, PATH3, served !== undefined, [PART_ROUTE]);
1296
+ const sitemap = served ?? (listed ? resolveSitemap(true) : undefined);
1297
+ if (!sitemap) {
1298
+ addTemplate4({
1299
+ filename: "seo/sitemap",
1300
+ getContents: () => moduleSource({ paths: [], alternates: {}, sources: [], chunkSize: 50000, baseURL: "/", signature: "" })
1301
+ });
1302
+ return;
1303
+ }
1304
+ const { baseURL } = hamur.options.app;
1305
+ if (served && hamur.options.site.url === undefined && !process.env.HAMUR_SITE_URL)
1306
+ useLogger4("seo").warn(diagnostic3("HAMUR_W6411", `site.url is not set; ${PATH3} needs HAMUR_SITE_URL at run time`));
1307
+ hamur.hooks.hook("server:extend", (records) => {
1308
+ if (!own.served())
1309
+ return;
1310
+ sitemap.sources.forEach((source, index) => {
1311
+ if (!records.some((record) => record.path === source && (record.method === undefined || record.method === "GET"))) {
1312
+ throw new DiagnosticError7("HAMUR_E6408", `seo.sitemap.sources[${index}] ${JSON.stringify(source)} is not the route of a GET handler`);
1313
+ }
1314
+ });
1315
+ });
1316
+ addTemplate4({
1317
+ filename: "seo/sitemap",
1318
+ getContents: (ctx) => {
1319
+ const pages = flatten(ctx.routes);
1320
+ const paths = sitemapPaths({
1321
+ pages: pages.map((route) => route.path),
1322
+ listed: Array.isArray(ctx.options.prerender.routes) ? ctx.options.prerender.routes : [],
1323
+ rules: ctx.routeRules,
1324
+ exclude: sitemap.exclude
1325
+ });
1326
+ const locales = readLocales(ctx.options.i18n);
1327
+ const alternates = locales ? pageAlternates(pages, locales, new Set(paths), clean) : {};
1328
+ if (hamur.options.app.trailingSlash === "always") {
1329
+ return moduleSource({
1330
+ paths: paths.map(slashed),
1331
+ alternates: Object.fromEntries(Object.entries(alternates).map(([path, list]) => [
1332
+ slashed(path),
1333
+ list.map(([hreflang, other]) => [hreflang, slashed(other)])
1334
+ ])),
1335
+ sources: sitemap.sources,
1336
+ chunkSize: sitemap.chunkSize,
1337
+ baseURL,
1338
+ signature: hash(JSON.stringify([paths, alternates, sitemap.sources, "always"]))
1339
+ });
1340
+ }
1341
+ return moduleSource({
1342
+ paths,
1343
+ alternates,
1344
+ sources: sitemap.sources,
1345
+ chunkSize: sitemap.chunkSize,
1346
+ baseURL,
1347
+ signature: hash(JSON.stringify([paths, alternates, sitemap.sources]))
1348
+ });
1349
+ }
1350
+ });
1351
+ if (served && hamur.options.preset === "static") {
1352
+ hamur.hooks.hook("prerender:routes", (routes) => {
1353
+ if (own.served())
1354
+ routes.add(PATH3);
1355
+ });
1356
+ }
1357
+ }
1358
+
1359
+ // packages/seo/src/module.ts
1360
+ var module_default = defineModule({
1361
+ meta: { name: "seo", configKey: "seo" },
1362
+ setup(input, hamur) {
1363
+ const sitemap = resolveSitemap(input.sitemap);
1364
+ setupRobots(input.robots, hamur, sitemap !== undefined);
1365
+ const llms = readLlms(input.llms, hamur);
1366
+ setupSitemap(sitemap, hamur, llms !== undefined);
1367
+ setupSchemaOrg(input.schemaOrg, hamur);
1368
+ setupLinkChecker(input.linkChecker, hamur);
1369
+ setupLlms(llms, hamur);
1370
+ addServer(createResolver2(new URL("../../src/module.ts", import.meta.url).href).resolve("./server/door.ts"));
1371
+ }
1372
+ });
1373
+ export {
1374
+ module_default as default
1375
+ };