@hamur/seo 0.0.0-stage → 0.0.2

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 +136 -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,372 @@
1
+ import type { SchemaNode } from "../schema.ts"
2
+
3
+ export type DateLike = string | Date
4
+ export type NodeRef = SchemaNode | { "@id": string }
5
+ type Many<T> = T | T[]
6
+ type Link = Many<string | NodeRef>
7
+ type Price = number | `${number}`
8
+ type Typed<Type extends string, Input> = Omit<Input, "@type"> & { "@type": Type }
9
+
10
+ type Base = {
11
+ "@id"?: string
12
+ name?: string
13
+ alternateName?: string
14
+ description?: string
15
+ url?: string
16
+ image?: Link
17
+ sameAs?: Many<string>
18
+ identifier?: string
19
+ }
20
+
21
+ const withType = <Type extends string>(type: Type, value: unknown): unknown => {
22
+ if (Array.isArray(value)) return value.map((item) => withType(type, item))
23
+ if (typeof value !== "object" || value === null || value instanceof Date || "@type" in value) return value
24
+ return { "@type": type, ...value }
25
+ }
26
+
27
+ const define = <Type extends string, Input extends object>(
28
+ type: Type,
29
+ input: Input,
30
+ nested: Record<string, string> = {},
31
+ ): Typed<Type, Input> => {
32
+ const node: Record<string, unknown> = { "@type": type, ...input }
33
+ for (const [key, nestedType] of Object.entries(nested)) if (key in node) node[key] = withType(nestedType, node[key])
34
+ return node as Typed<Type, Input>
35
+ }
36
+
37
+ export type WebPageType =
38
+ | "WebPage"
39
+ | "AboutPage"
40
+ | "CheckoutPage"
41
+ | "CollectionPage"
42
+ | "ContactPage"
43
+ | "FAQPage"
44
+ | "ItemPage"
45
+ | "MedicalWebPage"
46
+ | "ProfilePage"
47
+ | "QAPage"
48
+ | "RealEstateListing"
49
+ | "SearchResultsPage"
50
+
51
+ export type WebSiteInput = Base & { publisher?: Link; inLanguage?: string; potentialAction?: Link }
52
+ export type WebPageInput = Base & {
53
+ "@type"?: WebPageType
54
+ isPartOf?: Link
55
+ breadcrumb?: Link
56
+ datePublished?: DateLike
57
+ dateModified?: DateLike
58
+ inLanguage?: string
59
+ primaryImageOfPage?: Link
60
+ mainEntity?: Link
61
+ about?: Link
62
+ lastReviewed?: DateLike
63
+ }
64
+
65
+ export type PostalAddressInput = {
66
+ "@id"?: string
67
+ streetAddress?: string
68
+ addressLocality?: string
69
+ addressRegion?: string
70
+ postalCode?: string
71
+ addressCountry?: string
72
+ }
73
+ export type ContactPointInput = {
74
+ "@id"?: string
75
+ contactType?: string
76
+ telephone?: string
77
+ email?: string
78
+ areaServed?: Many<string>
79
+ availableLanguage?: Many<string>
80
+ }
81
+ type Address = string | PostalAddressInput | NodeRef
82
+
83
+ export type OrganizationInput = Base & {
84
+ name: string
85
+ legalName?: string
86
+ logo?: string | NodeRef
87
+ email?: string
88
+ telephone?: string
89
+ address?: Address
90
+ contactPoint?: Many<ContactPointInput | NodeRef>
91
+ foundingDate?: DateLike
92
+ founder?: Link
93
+ parentOrganization?: Link
94
+ taxID?: string
95
+ vatID?: string
96
+ }
97
+ export type PersonInput = Base & {
98
+ name: string
99
+ givenName?: string
100
+ familyName?: string
101
+ email?: string
102
+ telephone?: string
103
+ jobTitle?: string
104
+ worksFor?: Link
105
+ birthDate?: DateLike
106
+ address?: Address
107
+ nationality?: string
108
+ }
109
+ export type LocalBusinessInput = Base & {
110
+ name: string
111
+ address: Address
112
+ telephone?: string
113
+ email?: string
114
+ priceRange?: string
115
+ logo?: string | NodeRef
116
+ geo?: NodeRef | { "@type": "GeoCoordinates"; latitude: number; longitude: number }
117
+ openingHours?: Many<string>
118
+ openingHoursSpecification?: Many<NodeRef>
119
+ servesCuisine?: Many<string>
120
+ areaServed?: Many<string | NodeRef>
121
+ aggregateRating?: AggregateRatingInput | NodeRef
122
+ review?: Many<ReviewInput | NodeRef>
123
+ }
124
+
125
+ type ArticleFields = Base & {
126
+ headline: string
127
+ author?: Link
128
+ publisher?: Link
129
+ datePublished?: DateLike
130
+ dateModified?: DateLike
131
+ articleSection?: string
132
+ articleBody?: string
133
+ wordCount?: number
134
+ inLanguage?: string
135
+ keywords?: Many<string>
136
+ mainEntityOfPage?: string | NodeRef
137
+ isAccessibleForFree?: boolean
138
+ }
139
+ export type ArticleInput = ArticleFields
140
+ export type BlogPostingInput = ArticleFields
141
+
142
+ export type OfferInput = {
143
+ "@id"?: string
144
+ price: Price
145
+ priceCurrency: string
146
+ availability?: string
147
+ itemCondition?: string
148
+ priceValidUntil?: DateLike
149
+ validFrom?: DateLike
150
+ url?: string
151
+ seller?: Link
152
+ name?: string
153
+ sku?: string
154
+ }
155
+ export type AggregateRatingInput = {
156
+ "@id"?: string
157
+ ratingValue: number | `${number}`
158
+ bestRating?: number | `${number}`
159
+ worstRating?: number | `${number}`
160
+ itemReviewed?: Link
161
+ } & ({ ratingCount: number; reviewCount?: number } | { reviewCount: number; ratingCount?: number })
162
+ export type RatingInput = {
163
+ "@id"?: string
164
+ ratingValue: number | `${number}`
165
+ bestRating?: number | `${number}`
166
+ worstRating?: number | `${number}`
167
+ }
168
+ export type ReviewInput = Base & {
169
+ reviewRating: RatingInput | NodeRef
170
+ author: string | NodeRef
171
+ reviewBody?: string
172
+ datePublished?: DateLike
173
+ itemReviewed?: Link
174
+ publisher?: Link
175
+ }
176
+ export type ProductInput = Base & {
177
+ name: string
178
+ offers?: Many<OfferInput | NodeRef>
179
+ aggregateRating?: AggregateRatingInput | NodeRef
180
+ review?: Many<ReviewInput | NodeRef>
181
+ brand?: string | NodeRef
182
+ sku?: string
183
+ gtin?: string
184
+ gtin13?: string
185
+ mpn?: string
186
+ color?: string
187
+ category?: string
188
+ }
189
+
190
+ export type ListItemInput = {
191
+ "@type"?: "ListItem"
192
+ "@id"?: string
193
+ position?: number
194
+ name?: string
195
+ item?: string | NodeRef
196
+ }
197
+ export type BreadcrumbListInput = { "@id"?: string; itemListElement: (ListItemInput | NodeRef)[] }
198
+ export type AnswerInput = { "@id"?: string; text: string; url?: string; author?: Link; datePublished?: DateLike }
199
+ export type QuestionInput = {
200
+ "@id"?: string
201
+ name: string
202
+ acceptedAnswer: AnswerInput | NodeRef
203
+ text?: string
204
+ answerCount?: number
205
+ author?: Link
206
+ datePublished?: DateLike
207
+ }
208
+ export type FaqPageInput = Base & {
209
+ mainEntity: Many<QuestionInput | NodeRef>
210
+ datePublished?: DateLike
211
+ dateModified?: DateLike
212
+ inLanguage?: string
213
+ }
214
+
215
+ export type HowToStepInput = { "@id"?: string; name?: string; text?: string; url?: string; image?: Link }
216
+ export type HowToInput = Base & {
217
+ name: string
218
+ step: Many<HowToStepInput | NodeRef | string>
219
+ totalTime?: string
220
+ estimatedCost?: string | NodeRef
221
+ supply?: Many<string | NodeRef>
222
+ tool?: Many<string | NodeRef>
223
+ }
224
+ export type EventInput = Base & {
225
+ name: string
226
+ startDate: DateLike
227
+ location: string | NodeRef | { "@type"?: "Place" | "VirtualLocation"; name?: string; address?: Address; url?: string }
228
+ endDate?: DateLike
229
+ eventStatus?: string
230
+ eventAttendanceMode?: string
231
+ organizer?: Link
232
+ performer?: Link
233
+ offers?: Many<OfferInput | NodeRef>
234
+ previousStartDate?: DateLike
235
+ }
236
+ export type RecipeInput = Base & {
237
+ name: string
238
+ image: Link
239
+ author?: Link
240
+ datePublished?: DateLike
241
+ prepTime?: string
242
+ cookTime?: string
243
+ totalTime?: string
244
+ recipeYield?: Many<string | number>
245
+ recipeCategory?: string
246
+ recipeCuisine?: string
247
+ recipeIngredient?: string[]
248
+ recipeInstructions?: Many<string | NodeRef>
249
+ keywords?: Many<string>
250
+ aggregateRating?: AggregateRatingInput | NodeRef
251
+ }
252
+ export type VideoObjectInput = Base & {
253
+ name: string
254
+ thumbnailUrl: Many<string>
255
+ uploadDate: DateLike
256
+ contentUrl?: string
257
+ embedUrl?: string
258
+ duration?: string
259
+ expires?: DateLike
260
+ interactionStatistic?: Many<NodeRef>
261
+ }
262
+ export type ImageObjectInput = Base & {
263
+ contentUrl: string
264
+ width?: number | string
265
+ height?: number | string
266
+ caption?: string
267
+ creator?: Link
268
+ creditText?: string
269
+ copyrightNotice?: string
270
+ license?: string
271
+ acquireLicensePage?: string
272
+ }
273
+ export type SoftwareAppInput = Base & {
274
+ name: string
275
+ applicationCategory?: string
276
+ operatingSystem?: string
277
+ offers?: Many<OfferInput | NodeRef>
278
+ aggregateRating?: AggregateRatingInput | NodeRef
279
+ review?: Many<ReviewInput | NodeRef>
280
+ softwareVersion?: string
281
+ downloadUrl?: string
282
+ }
283
+ export type BookInput = Base & {
284
+ name: string
285
+ author: string | NodeRef | (string | NodeRef)[]
286
+ isbn?: string
287
+ numberOfPages?: number
288
+ bookFormat?: string
289
+ datePublished?: DateLike
290
+ publisher?: Link
291
+ inLanguage?: string
292
+ workExample?: Many<NodeRef>
293
+ aggregateRating?: AggregateRatingInput | NodeRef
294
+ review?: Many<ReviewInput | NodeRef>
295
+ }
296
+ export type CourseInput = Base & {
297
+ name: string
298
+ description: string
299
+ provider?: Link
300
+ courseCode?: string
301
+ hasCourseInstance?: Many<NodeRef>
302
+ inLanguage?: string
303
+ offers?: Many<OfferInput | NodeRef>
304
+ }
305
+ export type JobPostingInput = Base & {
306
+ title: string
307
+ description: string
308
+ datePosted: DateLike
309
+ hiringOrganization: string | NodeRef
310
+ validThrough?: DateLike
311
+ employmentType?: Many<string>
312
+ jobLocation?: Many<NodeRef | { "@type": "Place"; address: Address }>
313
+ jobLocationType?: string
314
+ baseSalary?: NodeRef
315
+ directApply?: boolean
316
+ applicantLocationRequirements?: Many<NodeRef>
317
+ identifier?: string | NodeRef
318
+ }
319
+
320
+ const nestedTypes = {
321
+ reviewRating: "Rating",
322
+ aggregateRating: "AggregateRating",
323
+ review: "Review",
324
+ offers: "Offer",
325
+ address: "PostalAddress",
326
+ contactPoint: "ContactPoint",
327
+ }
328
+
329
+ export const defineWebSite = (input: WebSiteInput = {}): Typed<"WebSite", WebSiteInput> => define("WebSite", input)
330
+ export const defineWebPage = <Input extends WebPageInput>(
331
+ input: Input = {} as Input,
332
+ ): Typed<Input["@type"] extends string ? Input["@type"] : "WebPage", Input> => define("WebPage", input) as never
333
+ export const defineOrganization = (input: OrganizationInput) => define("Organization", input, nestedTypes)
334
+ export const definePerson = (input: PersonInput) => define("Person", input, nestedTypes)
335
+ export const defineLocalBusiness = (input: LocalBusinessInput) => define("LocalBusiness", input, nestedTypes)
336
+ export const defineArticle = (input: ArticleInput) => define("Article", input)
337
+ export const defineBlogPosting = (input: BlogPostingInput) => define("BlogPosting", input)
338
+ export const defineProduct = (input: ProductInput) => define("Product", input, nestedTypes)
339
+ export const defineOffer = (input: OfferInput) => define("Offer", input)
340
+ export const defineAggregateRating = (input: AggregateRatingInput) => define("AggregateRating", input)
341
+ export const defineReview = (input: ReviewInput) => define("Review", input, nestedTypes)
342
+ export const defineQuestion = (input: QuestionInput) => define("Question", input, { acceptedAnswer: "Answer" })
343
+ const questions = (value: unknown): unknown => {
344
+ if (Array.isArray(value)) return value.map(questions)
345
+ if (typeof value !== "object" || value === null || "@type" in value || !("acceptedAnswer" in value)) return value
346
+ return defineQuestion(value as QuestionInput)
347
+ }
348
+ export const defineFaqPage = (input: FaqPageInput) =>
349
+ define(
350
+ "FAQPage",
351
+ { ...input, mainEntity: questions(input.mainEntity) as FaqPageInput["mainEntity"] },
352
+ { mainEntity: "Question" },
353
+ )
354
+ export const defineHowTo = (input: HowToInput) => define("HowTo", input, { step: "HowToStep" })
355
+ export const defineEvent = (input: EventInput) => define("Event", input, { offers: "Offer", location: "Place" })
356
+ export const defineRecipe = (input: RecipeInput) => define("Recipe", input, nestedTypes)
357
+ export const defineVideoObject = (input: VideoObjectInput) => define("VideoObject", input)
358
+ export const defineImageObject = (input: ImageObjectInput) => define("ImageObject", input)
359
+ export const defineSoftwareApp = (input: SoftwareAppInput) => define("SoftwareApplication", input, nestedTypes)
360
+ export const defineBook = (input: BookInput) => define("Book", input, nestedTypes)
361
+ export const defineCourse = (input: CourseInput) => define("Course", input, { offers: "Offer" })
362
+ export const defineJobPosting = (input: JobPostingInput) => define("JobPosting", input)
363
+
364
+ export const defineBreadcrumbList = (input: BreadcrumbListInput): Typed<"BreadcrumbList", BreadcrumbListInput> => {
365
+ const items = input.itemListElement.map((item, index) => {
366
+ const entry = item as Record<string, unknown>
367
+ return "@type" in entry || !("name" in entry || "item" in entry || "position" in entry)
368
+ ? item
369
+ : { "@type": "ListItem", position: index + 1, ...entry }
370
+ })
371
+ return { "@type": "BreadcrumbList", ...input, itemListElement: items as BreadcrumbListInput["itemListElement"] }
372
+ }
@@ -0,0 +1,39 @@
1
+ import type { IdentityNode } from "../schema.ts"
2
+ import { DiagnosticError } from "hamur/kit"
3
+
4
+ export interface ResolvedSchemaOrg {
5
+ enabled: boolean
6
+ identity?: IdentityNode
7
+ }
8
+
9
+ const show = (value: unknown): string => JSON.stringify(value) ?? String(value)
10
+ const isObject = (value: unknown): value is Record<string, unknown> =>
11
+ typeof value === "object" && value !== null && !Array.isArray(value)
12
+ const IDENTITY_TYPES = ["Organization", "Person", "LocalBusiness"]
13
+
14
+ /** `seo.schemaOrg`, `true` when unset. */
15
+ export function resolveSchemaOrg(value: unknown): ResolvedSchemaOrg {
16
+ if (value === undefined || value === true) return { enabled: true }
17
+ if (value === false) return { enabled: false }
18
+ if (!isObject(value))
19
+ throw new DiagnosticError("HAMUR_E6405", `seo.schemaOrg must be a boolean or an object (got ${show(value)})`)
20
+ for (const key of Object.keys(value))
21
+ if (key !== "identity") throw new DiagnosticError("HAMUR_E6405", `seo.schemaOrg.${key} is not an option`)
22
+ const identity = value.identity
23
+ if (identity === undefined) return { enabled: true }
24
+ const type = isObject(identity) ? identity["@type"] : undefined
25
+ if (!isObject(identity) || typeof type !== "string" || !IDENTITY_TYPES.includes(type)) {
26
+ throw new DiagnosticError(
27
+ "HAMUR_E6405",
28
+ `seo.schemaOrg.identity must be an object whose @type is Organization, Person or LocalBusiness (got ${show(isObject(identity) ? type : identity)})`,
29
+ )
30
+ }
31
+ if (typeof identity.name !== "string" || identity.name === "")
32
+ throw new DiagnosticError(
33
+ "HAMUR_E6405",
34
+ `seo.schemaOrg.identity.name must be a non-empty string (got ${show(identity.name)})`,
35
+ )
36
+ if ("@id" in identity)
37
+ throw new DiagnosticError("HAMUR_E6406", "seo.schemaOrg.identity.@id is set by @hamur/seo; remove it")
38
+ return { enabled: true, identity: identity as IdentityNode }
39
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type SchemaNode = { "@type": string | string[]; "@id"?: string; [key: string]: unknown }
2
+
3
+ export type IdentityNode = SchemaNode & { "@type": "Organization" | "Person" | "LocalBusiness"; name: string }
4
+
5
+ export * from "./schema/helpers.ts"
@@ -0,0 +1,45 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { baseURL, enabled, rootId, trailingSlash } from "#hamur/seo/llms"
3
+ import { defineMiddleware, definePlugin, useSiteConfig } from "hamur/server"
4
+ import { absoluteUrl, slashForm } from "hamur/server/internal"
5
+ import { pageOfMarkdown, pathBelow, prefersMarkdown } from "../llms/paths.ts"
6
+ import { htmlToMarkdown } from "../runtime/markdown.ts"
7
+ import { render } from "./render.ts"
8
+
9
+ const isFile = (path: string): boolean => path.lastIndexOf(".") > path.lastIndexOf("/")
10
+
11
+ /** `<path>.md` and a page asked with `Accept: text/markdown` answer the Markdown of the page's rendered HTML. */
12
+ export const agentMarkdown = defineMiddleware(async ({ event }) => {
13
+ if (!enabled || (event.method !== "GET" && event.method !== "HEAD")) return undefined
14
+ const path = pathBelow(event.url.pathname, baseURL)
15
+ if (path === undefined || path.startsWith("//") || path.startsWith("/_hamur/")) return undefined
16
+ const asked = pageOfMarkdown(path)
17
+ const page = asked ?? (!isFile(path) && prefersMarkdown(event.request.headers.get("accept")) ? path : undefined)
18
+ if (page === undefined) return undefined
19
+ const target = trailingSlash === "always" ? (slashForm(page, "/") ?? page) : page
20
+ const answer = await render(target, "text/html")
21
+ if (!answer) return undefined
22
+ if (answer.status >= 300 && answer.status < 400) {
23
+ const location = answer.headers.get("location")
24
+ return new Response(null, { status: answer.status, headers: location ? { location } : {} })
25
+ }
26
+ if (asked === undefined && !(answer.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html"))
27
+ return undefined
28
+ const origin = useSiteConfig(event).url ?? event.url.origin
29
+ const markdown = htmlToMarkdown(answer.body, { base: absoluteUrl(origin, baseURL, target), rootId })
30
+ return new Response(event.method === "HEAD" ? null : markdown, {
31
+ status: answer.status,
32
+ headers: { "content-type": "text/markdown; charset=utf-8", vary: "Accept" },
33
+ })
34
+ })
35
+
36
+ /** Every HTML answer of a page names `Accept` in `Vary`, since the same URL answers Markdown to an agent. */
37
+ export const varyAccept = definePlugin((server) => {
38
+ server.hooks.hook("beforeResponse", (_event, response) => {
39
+ if (!enabled) return
40
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html")) return
41
+ const vary = response.headers.get("vary")
42
+ if (vary?.split(",").some((name) => ["accept", "*"].includes(name.trim().toLowerCase()))) return
43
+ response.headers.set("vary", vary ? `${vary}, Accept` : "Accept")
44
+ })
45
+ })
@@ -0,0 +1,8 @@
1
+ import { defineServer } from "hamur/server"
2
+ import { agentMarkdown, varyAccept } from "./agent.ts"
3
+
4
+ export { llmsFullTxt, llmsTxt } from "./llms.ts"
5
+ export { robotsTxt } from "./robots.ts"
6
+ export { sitemapPart, sitemapXml } from "./sitemap.ts"
7
+
8
+ export default defineServer({ plugins: [varyAccept], middleware: [agentMarkdown] })
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,139 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { baseURL, description, exclude, title, trailingSlash } from "#hamur/seo/llms"
3
+ import { signature } from "#hamur/seo/sitemap"
4
+ import {
5
+ defineCachedFunction,
6
+ defineHandler,
7
+ matchRouteRules,
8
+ useLogger,
9
+ useSiteConfig,
10
+ type HamurEvent,
11
+ } from "hamur/server"
12
+ import { markdownPath, pathBelow } from "../llms/paths.ts"
13
+ import { llmsFullText, llmsText, type LlmsPage } from "../llms/text.ts"
14
+ import { pageInfo } from "../runtime/markdown.ts"
15
+ import type { SitemapUrl } from "../sitemap/xml.ts"
16
+ import { render } from "./render.ts"
17
+ import { sitemapUrls } from "./sitemap.ts"
18
+ import { diagnostic } from "hamur/server/internal"
19
+
20
+ const NEEDS_URL = "@hamur/seo: /llms.txt needs site.url (set site.url or HAMUR_SITE_URL)"
21
+ const CONCURRENCY = 8
22
+ const MANY = 500
23
+ const MARKDOWN = { "content-type": "text/markdown; charset=utf-8" }
24
+ const rules = Object.fromEntries(exclude.map((pattern) => [pattern, {}]))
25
+ const warned = new Set<string>()
26
+
27
+ interface Files {
28
+ txt: string
29
+ full: string
30
+ }
31
+
32
+ const failed = (event: HamurEvent, message: string, status = 500): Response => {
33
+ useLogger(event).child({ name: "seo" }).error(message)
34
+ return new Response(message, { status, headers: { "content-type": "text/plain; charset=utf-8" } })
35
+ }
36
+
37
+ const noindex = (headers: Headers): boolean =>
38
+ /(^|[\s,])(noindex|none)([\s,]|$)/i.test(headers.get("x-robots-tag") ?? "")
39
+
40
+ async function each<T, R>(items: readonly T[], work: (item: T) => Promise<R>): Promise<R[]> {
41
+ const results = new Array<R>(items.length)
42
+ let next = 0
43
+ const lane = async () => {
44
+ while (next < items.length) {
45
+ const at = next++
46
+ results[at] = await work(items[at]!)
47
+ }
48
+ }
49
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, lane))
50
+ return results
51
+ }
52
+
53
+ /** The app paths of the sitemap's URLs on the site's origin that `exclude` does not match. */
54
+ function listed(urls: readonly SitemapUrl[], origin: string): Array<{ path: string; url: string }> {
55
+ const site = new URL(origin).origin
56
+ return urls.flatMap(({ loc }) => {
57
+ const url = new URL(loc)
58
+ const path = url.origin === site ? pathBelow(url.pathname, baseURL) : undefined
59
+ if (path === undefined || (exclude.length && matchRouteRules(rules, { path }).patterns.length)) return []
60
+ return [{ path, url: loc }]
61
+ })
62
+ }
63
+
64
+ const cachedFiles = defineCachedFunction(
65
+ async (event: HamurEvent, origin: string, urls: SitemapUrl[]): Promise<Files> => {
66
+ const site = useSiteConfig(event)
67
+ const pages = listed(urls, origin)
68
+ if (pages.length > MANY && !warned.has(origin)) {
69
+ warned.add(origin)
70
+ useLogger(event)
71
+ .child({ name: "seo" })
72
+ .warn(
73
+ diagnostic(
74
+ "HAMUR_W6412",
75
+ `/llms.txt renders ${pages.length} pages per refresh; seo.llms.exclude narrows the list`,
76
+ ),
77
+ )
78
+ }
79
+ const found = await each(pages, async ({ path, url }) => {
80
+ const html = await render(path, "text/html")
81
+ if (!html || html.status < 200 || html.status > 299 || noindex(html.headers)) return undefined
82
+ const info = pageInfo(html.body)
83
+ if (info.noindex) return undefined
84
+ const markdown = await render(markdownPath(path), "text/markdown")
85
+ const page: LlmsPage = {
86
+ title: info.title ?? path,
87
+ url,
88
+ ...(info.description ? { description: info.description } : {}),
89
+ }
90
+ return { page, markdown: markdown && markdown.status >= 200 && markdown.status <= 299 ? markdown.body : "" }
91
+ })
92
+ const kept = found.filter((entry) => entry !== undefined)
93
+ return {
94
+ txt: llmsText(
95
+ { title: title ?? site.name ?? new URL(origin).hostname, description: description ?? site.description },
96
+ kept.map((entry) => entry.page),
97
+ ),
98
+ full: llmsFullText(kept.map((entry) => entry.markdown).filter((markdown) => markdown.trim() !== "")),
99
+ }
100
+ },
101
+ {
102
+ maxAge: 600,
103
+ swr: false,
104
+ getKey: (event, origin) =>
105
+ `llms:${signature}:${origin}:${useSiteConfig(event).name}:${trailingSlash}:${title}:${description}:${exclude.join(",")}`,
106
+ },
107
+ )
108
+
109
+ async function files(event: HamurEvent): Promise<Files | Response> {
110
+ const { url: origin } = useSiteConfig(event)
111
+ if (origin === undefined) return failed(event, NEEDS_URL)
112
+ const urls = await sitemapUrls(event)
113
+ if (urls instanceof Response) return urls
114
+ try {
115
+ return await cachedFiles(event, origin, urls)
116
+ } catch (error) {
117
+ return failed(event, `@hamur/seo: /llms.txt failed: ${error instanceof Error ? error.message : String(error)}`)
118
+ }
119
+ }
120
+
121
+ export const llmsTxt = defineHandler({
122
+ route: "/llms.txt",
123
+ method: "GET",
124
+ raw: true,
125
+ async handler(_, { event }) {
126
+ const result = await files(event)
127
+ return result instanceof Response ? result : new Response(result.txt, { headers: MARKDOWN })
128
+ },
129
+ })
130
+
131
+ export const llmsFullTxt = defineHandler({
132
+ route: "/llms-full.txt",
133
+ method: "GET",
134
+ raw: true,
135
+ async handler(_, { event }) {
136
+ const result = await files(event)
137
+ return result instanceof Response ? result : new Response(result.full, { headers: MARKDOWN })
138
+ },
139
+ })
@@ -0,0 +1,33 @@
1
+ import { $fetch } from "hamur/server"
2
+
3
+ /** One leading `/`, no backslash or control character, and the same origin once resolved: the call never leaves the app. */
4
+ export function isAppPath(path: string): boolean {
5
+ if (!path.startsWith("/") || path.startsWith("//") || /[\\\u0000-\u001f]/.test(path)) return false
6
+ try {
7
+ return new URL(path, "http://x").origin === "http://x"
8
+ } catch {
9
+ return false
10
+ }
11
+ }
12
+
13
+ export interface Rendered {
14
+ status: number
15
+ headers: Headers
16
+ body: string
17
+ }
18
+
19
+ /** A page answered in process by the bare `$fetch`; `undefined` when the call itself failed. */
20
+ export async function render(path: string, accept: string): Promise<Rendered | undefined> {
21
+ if (!isAppPath(path)) return undefined
22
+ try {
23
+ const { response, data } = await $fetch.raw<string>(path, {
24
+ headers: { accept },
25
+ responseType: "text",
26
+ ignoreResponseError: true,
27
+ retry: 0,
28
+ })
29
+ return { status: response.status, headers: response.headers, body: typeof data === "string" ? data : "" }
30
+ } catch {
31
+ return undefined
32
+ }
33
+ }
@@ -0,0 +1,19 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import { body, sitemap } from "#hamur/seo/robots"
3
+ import { defineHandler, useSiteConfig } from "hamur/server"
4
+ import { NOINDEX_BODY } from "../robots/body.ts"
5
+
6
+ export const robotsTxt = defineHandler({
7
+ route: "/robots.txt",
8
+ method: "GET",
9
+ raw: true,
10
+ handler(_, { event }) {
11
+ const site = useSiteConfig(event)
12
+ const text = !site.indexable
13
+ ? NOINDEX_BODY
14
+ : site.url !== undefined && sitemap !== null
15
+ ? `${body}\nSitemap: ${site.url}${sitemap}\n`
16
+ : body
17
+ return new Response(text, { headers: { "content-type": "text/plain; charset=utf-8" } })
18
+ },
19
+ })