@sinnstack/ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +373 -0
  3. package/README.md +186 -2
  4. package/docs/blocks.md +364 -0
  5. package/docs/data.md +128 -0
  6. package/docs/motion.md +166 -0
  7. package/docs/primitives.md +510 -0
  8. package/docs/seo.md +187 -0
  9. package/docs/tokens.md +122 -0
  10. package/package.json +141 -3
  11. package/scripts/check-contrast.mjs +180 -0
  12. package/src/blocks/BlockRenderer.astro +54 -0
  13. package/src/blocks/CTABanner.astro +121 -0
  14. package/src/blocks/CTAPair.astro +110 -0
  15. package/src/blocks/CardGrid.astro +167 -0
  16. package/src/blocks/ConsentEmbed.astro +125 -0
  17. package/src/blocks/ConsentManager.astro +147 -0
  18. package/src/blocks/ConsentScript.astro +47 -0
  19. package/src/blocks/ContactCard.astro +164 -0
  20. package/src/blocks/ContactForm.astro +224 -0
  21. package/src/blocks/ErrorPage.astro +242 -0
  22. package/src/blocks/FAQ.astro +135 -0
  23. package/src/blocks/FeatureGrid.astro +148 -0
  24. package/src/blocks/Hero.astro +171 -0
  25. package/src/blocks/HeroCarousel.astro +220 -0
  26. package/src/blocks/HighlightCards.astro +107 -0
  27. package/src/blocks/LocationHours.astro +311 -0
  28. package/src/blocks/LogoCloud.astro +135 -0
  29. package/src/blocks/MaintenancePage.astro +168 -0
  30. package/src/blocks/MediaText.astro +177 -0
  31. package/src/blocks/PageHeader.astro +126 -0
  32. package/src/blocks/ProseSection.astro +98 -0
  33. package/src/blocks/Reviews.astro +194 -0
  34. package/src/blocks/RichText.astro +57 -0
  35. package/src/blocks/StatsBand.astro +117 -0
  36. package/src/blocks/Steps.astro +141 -0
  37. package/src/blocks/Testimonials.astro +144 -0
  38. package/src/blocks/Topbar.astro +158 -0
  39. package/src/blocks/cms/card-grid.ts +80 -0
  40. package/src/blocks/cms/consent.ts +45 -0
  41. package/src/blocks/cms/contact-card.ts +88 -0
  42. package/src/blocks/cms/contact-form.ts +55 -0
  43. package/src/blocks/cms/cta-banner.ts +48 -0
  44. package/src/blocks/cms/cta-pair.ts +63 -0
  45. package/src/blocks/cms/data-base.ts +7 -0
  46. package/src/blocks/cms/data.ts +257 -0
  47. package/src/blocks/cms/faq.ts +70 -0
  48. package/src/blocks/cms/feature-grid.ts +80 -0
  49. package/src/blocks/cms/fixtures.ts +599 -0
  50. package/src/blocks/cms/hero-carousel.ts +80 -0
  51. package/src/blocks/cms/hero.ts +77 -0
  52. package/src/blocks/cms/highlight-cards.ts +76 -0
  53. package/src/blocks/cms/images.ts +38 -0
  54. package/src/blocks/cms/index.ts +87 -0
  55. package/src/blocks/cms/location-hours.ts +149 -0
  56. package/src/blocks/cms/logo-cloud.ts +62 -0
  57. package/src/blocks/cms/media-text.ts +44 -0
  58. package/src/blocks/cms/page-header.ts +49 -0
  59. package/src/blocks/cms/pages.ts +81 -0
  60. package/src/blocks/cms/prose-section.ts +45 -0
  61. package/src/blocks/cms/reviews.ts +101 -0
  62. package/src/blocks/cms/shared.ts +115 -0
  63. package/src/blocks/cms/stats-band.ts +61 -0
  64. package/src/blocks/cms/steps.ts +67 -0
  65. package/src/blocks/cms/testimonials.ts +80 -0
  66. package/src/blocks/cms/topbar.ts +64 -0
  67. package/src/blocks/cms/types.ts +63 -0
  68. package/src/blocks/consent.ts +14 -0
  69. package/src/blocks/icons.ts +47 -0
  70. package/src/blocks/index.ts +42 -0
  71. package/src/blocks/internal/Actions.astro +29 -0
  72. package/src/blocks/internal/BlockHeader.astro +45 -0
  73. package/src/blocks/internal/BlockShell.astro +58 -0
  74. package/src/blocks/internal/CarouselScript.astro +7 -0
  75. package/src/blocks/internal/ConsentEmbedScript.astro +7 -0
  76. package/src/blocks/internal/ConsentManagerScript.astro +7 -0
  77. package/src/blocks/internal/HoursScript.astro +7 -0
  78. package/src/blocks/internal/Placeholder.astro +13 -0
  79. package/src/blocks/internal/RichTextNode.astro +133 -0
  80. package/src/blocks/internal/StandaloneDocument.astro +53 -0
  81. package/src/blocks/internal/tina.ts +19 -0
  82. package/src/blocks/internal/util.ts +23 -0
  83. package/src/blocks/lib/consent.ts +96 -0
  84. package/src/blocks/lib/contact.ts +86 -0
  85. package/src/blocks/lib/error-pages.ts +119 -0
  86. package/src/blocks/lib/faq.ts +37 -0
  87. package/src/blocks/lib/hours.ts +201 -0
  88. package/src/blocks/lib/maintenance.ts +129 -0
  89. package/src/blocks/lib/reviews.ts +22 -0
  90. package/src/blocks/lib/rich-text.ts +143 -0
  91. package/src/blocks/lib/slug.ts +12 -0
  92. package/src/blocks/registry.ts +79 -0
  93. package/src/blocks/scripts/carousel.ts +218 -0
  94. package/src/blocks/scripts/consent-embed.ts +105 -0
  95. package/src/blocks/scripts/consent-manager.ts +112 -0
  96. package/src/blocks/scripts/consent-store.ts +86 -0
  97. package/src/blocks/scripts/error-page.ts +71 -0
  98. package/src/blocks/scripts/hours.ts +106 -0
  99. package/src/blocks/scripts/maintenance.ts +109 -0
  100. package/src/blocks/styles/blocks.css +1320 -0
  101. package/src/blocks/styles/consent.css +102 -0
  102. package/src/blocks/styles/faq.css +28 -0
  103. package/src/blocks/styles/location.css +92 -0
  104. package/src/blocks/styles/prose-section.css +13 -0
  105. package/src/blocks/styles/quotes.css +123 -0
  106. package/src/blocks/styles/rich-text.css +14 -0
  107. package/src/blocks/types.ts +283 -0
  108. package/src/data/ChartAxis.astro +19 -0
  109. package/src/data/ChartContainer.astro +151 -0
  110. package/src/data/ChartLegend.astro +25 -0
  111. package/src/data/ChartSeries.astro +14 -0
  112. package/src/data/ChartTable.astro +17 -0
  113. package/src/data/ChartTooltip.astro +20 -0
  114. package/src/data/Sparkline.astro +55 -0
  115. package/src/data/cms.ts +190 -0
  116. package/src/data/index.ts +10 -0
  117. package/src/data/lib/chart.ts +450 -0
  118. package/src/data/lib/render.ts +219 -0
  119. package/src/data/lib/scale.ts +107 -0
  120. package/src/data/lib/sparkline.ts +117 -0
  121. package/src/data/scripts/chart.ts +324 -0
  122. package/src/data/styles/chart.css +392 -0
  123. package/src/motion/Marquee.astro +90 -0
  124. package/src/motion/MotionProvider.astro +50 -0
  125. package/src/motion/PageTransitions.astro +61 -0
  126. package/src/motion/Parallax.astro +44 -0
  127. package/src/motion/ParallaxLayer.astro +31 -0
  128. package/src/motion/RevealOnScroll.astro +59 -0
  129. package/src/motion/SceneRegistry.astro +38 -0
  130. package/src/motion/ScrollScene.astro +81 -0
  131. package/src/motion/index.ts +12 -0
  132. package/src/motion/integration.ts +48 -0
  133. package/src/motion/runtime/page-transitions.ts +68 -0
  134. package/src/motion/runtime/runtime.ts +180 -0
  135. package/src/motion/runtime/scenes.ts +248 -0
  136. package/src/motion/runtime/types.ts +103 -0
  137. package/src/motion/styles/motion.css +332 -0
  138. package/src/motion/transitions.ts +74 -0
  139. package/src/motion/virtual.d.ts +4 -0
  140. package/src/primitives/Accordion.astro +129 -0
  141. package/src/primitives/Breadcrumbs.astro +50 -0
  142. package/src/primitives/BulletList.astro +69 -0
  143. package/src/primitives/Button.astro +73 -0
  144. package/src/primitives/ButtonGroup.astro +54 -0
  145. package/src/primitives/Callout.astro +137 -0
  146. package/src/primitives/Caption.astro +35 -0
  147. package/src/primitives/Card.astro +72 -0
  148. package/src/primitives/CardContent.astro +24 -0
  149. package/src/primitives/CardFooter.astro +36 -0
  150. package/src/primitives/CardHeader.astro +86 -0
  151. package/src/primitives/Checkbox.astro +38 -0
  152. package/src/primitives/ChoiceGroup.astro +23 -0
  153. package/src/primitives/Cluster.astro +49 -0
  154. package/src/primitives/Container.astro +44 -0
  155. package/src/primitives/DescriptionList.astro +83 -0
  156. package/src/primitives/Dialog.astro +38 -0
  157. package/src/primitives/Disclosure.astro +67 -0
  158. package/src/primitives/Divider.astro +93 -0
  159. package/src/primitives/Drawer.astro +33 -0
  160. package/src/primitives/Fieldset.astro +80 -0
  161. package/src/primitives/Flex.astro +64 -0
  162. package/src/primitives/FocusRing.astro +63 -0
  163. package/src/primitives/FocusTrap.astro +64 -0
  164. package/src/primitives/Footer.astro +155 -0
  165. package/src/primitives/Form.astro +68 -0
  166. package/src/primitives/FormDescription.astro +26 -0
  167. package/src/primitives/FormError.astro +106 -0
  168. package/src/primitives/FormField.astro +72 -0
  169. package/src/primitives/Grid.astro +64 -0
  170. package/src/primitives/Heading.astro +45 -0
  171. package/src/primitives/IconButton.astro +48 -0
  172. package/src/primitives/Image.astro +125 -0
  173. package/src/primitives/Input.astro +84 -0
  174. package/src/primitives/Label.astro +50 -0
  175. package/src/primitives/Link.astro +81 -0
  176. package/src/primitives/LinkButton.astro +66 -0
  177. package/src/primitives/List.astro +39 -0
  178. package/src/primitives/ListItem.astro +178 -0
  179. package/src/primitives/MediaObject.astro +66 -0
  180. package/src/primitives/MetricCard.astro +276 -0
  181. package/src/primitives/NavLink.astro +81 -0
  182. package/src/primitives/NavMenu.astro +109 -0
  183. package/src/primitives/Navbar.astro +197 -0
  184. package/src/primitives/Panel.astro +153 -0
  185. package/src/primitives/Picture.astro +167 -0
  186. package/src/primitives/Popover.astro +95 -0
  187. package/src/primitives/Prose.astro +45 -0
  188. package/src/primitives/Radio.astro +21 -0
  189. package/src/primitives/Rating.astro +135 -0
  190. package/src/primitives/ReducedMotion.astro +90 -0
  191. package/src/primitives/SegmentedControl.astro +132 -0
  192. package/src/primitives/Select.astro +107 -0
  193. package/src/primitives/Sheet.astro +45 -0
  194. package/src/primitives/SkipLink.astro +31 -0
  195. package/src/primitives/Slider.astro +186 -0
  196. package/src/primitives/Spacer.astro +35 -0
  197. package/src/primitives/Stack.astro +51 -0
  198. package/src/primitives/Surface.astro +70 -0
  199. package/src/primitives/Switch.astro +22 -0
  200. package/src/primitives/Table.astro +382 -0
  201. package/src/primitives/Tabs.astro +126 -0
  202. package/src/primitives/Text.astro +56 -0
  203. package/src/primitives/Textarea.astro +73 -0
  204. package/src/primitives/Thumbnail.astro +154 -0
  205. package/src/primitives/Toggle.astro +99 -0
  206. package/src/primitives/Tooltip.astro +50 -0
  207. package/src/primitives/VisuallyHidden.astro +29 -0
  208. package/src/primitives/index.ts +103 -0
  209. package/src/primitives/internal/AccordionScript.astro +7 -0
  210. package/src/primitives/internal/ChoiceField.astro +89 -0
  211. package/src/primitives/internal/FocusTrapScript.astro +8 -0
  212. package/src/primitives/internal/FormValidationScript.astro +10 -0
  213. package/src/primitives/internal/IndeterminateScript.astro +13 -0
  214. package/src/primitives/internal/ModalPanel.astro +114 -0
  215. package/src/primitives/internal/OverlayScript.astro +7 -0
  216. package/src/primitives/internal/ReducedMotionScript.astro +7 -0
  217. package/src/primitives/internal/SliderScript.astro +7 -0
  218. package/src/primitives/internal/SparklineScript.astro +7 -0
  219. package/src/primitives/internal/TableSortScript.astro +7 -0
  220. package/src/primitives/internal/TabsScript.astro +7 -0
  221. package/src/primitives/internal/TooltipScript.astro +7 -0
  222. package/src/primitives/lib/deprecate.ts +47 -0
  223. package/src/primitives/lib/focus-trap.ts +197 -0
  224. package/src/primitives/lib/focus.ts +60 -0
  225. package/src/primitives/lib/image-plan.ts +82 -0
  226. package/src/primitives/lib/image.ts +129 -0
  227. package/src/primitives/lib/motion.ts +68 -0
  228. package/src/primitives/lib/slider.ts +170 -0
  229. package/src/primitives/scripts/accordion.ts +123 -0
  230. package/src/primitives/scripts/form-validation.ts +225 -0
  231. package/src/primitives/scripts/overlay.ts +71 -0
  232. package/src/primitives/scripts/reduced-motion.ts +59 -0
  233. package/src/primitives/scripts/slider.ts +150 -0
  234. package/src/primitives/scripts/sparkline.ts +131 -0
  235. package/src/primitives/scripts/table-sort.ts +68 -0
  236. package/src/primitives/scripts/tabs.ts +151 -0
  237. package/src/primitives/scripts/tooltip.ts +28 -0
  238. package/src/primitives/styles/a11y.css +104 -0
  239. package/src/primitives/styles/accordion.css +53 -0
  240. package/src/primitives/styles/breadcrumbs.css +59 -0
  241. package/src/primitives/styles/bullet-list.css +89 -0
  242. package/src/primitives/styles/button.css +237 -0
  243. package/src/primitives/styles/choice.css +164 -0
  244. package/src/primitives/styles/cluster.css +24 -0
  245. package/src/primitives/styles/container.css +19 -0
  246. package/src/primitives/styles/data.css +849 -0
  247. package/src/primitives/styles/disclosure.css +140 -0
  248. package/src/primitives/styles/divider.css +50 -0
  249. package/src/primitives/styles/flex.css +42 -0
  250. package/src/primitives/styles/form.css +241 -0
  251. package/src/primitives/styles/grid.css +36 -0
  252. package/src/primitives/styles/media.css +247 -0
  253. package/src/primitives/styles/nav.css +792 -0
  254. package/src/primitives/styles/overlay.css +362 -0
  255. package/src/primitives/styles/prose.css +146 -0
  256. package/src/primitives/styles/scale.css +175 -0
  257. package/src/primitives/styles/segmented.css +165 -0
  258. package/src/primitives/styles/slider.css +170 -0
  259. package/src/primitives/styles/spacer.css +17 -0
  260. package/src/primitives/styles/stack.css +25 -0
  261. package/src/primitives/styles/surface.css +403 -0
  262. package/src/primitives/styles/tabs.css +223 -0
  263. package/src/primitives/styles/typography.css +144 -0
  264. package/src/primitives/styles/utilities.css +24 -0
  265. package/src/primitives/types.ts +385 -0
  266. package/src/primitives/utils.ts +254 -0
  267. package/src/seo/JSONLD.astro +35 -0
  268. package/src/seo/SEOHead.astro +47 -0
  269. package/src/seo/cms.ts +80 -0
  270. package/src/seo/index.ts +10 -0
  271. package/src/seo/integration.ts +231 -0
  272. package/src/seo/lib/jsonld.ts +334 -0
  273. package/src/seo/lib/meta.ts +205 -0
  274. package/src/seo/lib/redirects.ts +283 -0
  275. package/src/seo/lib/robots.ts +33 -0
  276. package/src/seo/lib/rss.ts +98 -0
  277. package/src/seo/lib/sitemap.ts +105 -0
  278. package/src/seo/lib/url.ts +68 -0
  279. package/src/tokens/base.css +71 -0
  280. package/src/tokens/tokens.css +210 -0
@@ -0,0 +1,334 @@
1
+ /**
2
+ * JSON-LD: typed builders for the schema.org types sites here use most, a @graph helper that
3
+ * links them by @id, safe serialization for <script type="application/ld+json">, and checks
4
+ * against Google's rich-result requirements (warnings, not errors).
5
+ */
6
+ import { absolute, isoDate } from './url';
7
+
8
+ export type Thing = { '@type': string | string[]; '@id'?: string; [key: string]: unknown };
9
+ export type Ref = { '@id': string };
10
+
11
+ const clean = <T extends Record<string, unknown>>(o: T): T =>
12
+ Object.fromEntries(
13
+ Object.entries(o)
14
+ .filter(([, v]) => v !== undefined && v !== null && v !== '' && !(Array.isArray(v) && v.length === 0))
15
+ .map(([k, v]) => [k, v]),
16
+ ) as T;
17
+ const ref = (id?: string): Ref | undefined => (id ? { '@id': id } : undefined);
18
+
19
+ // ---------------- Organizations & places ----------------
20
+
21
+ export interface PostalAddressInput {
22
+ street: string;
23
+ city: string;
24
+ region: string;
25
+ postalCode: string;
26
+ country?: string;
27
+ }
28
+ export const postalAddress = (a: PostalAddressInput): Thing =>
29
+ clean({ '@type': 'PostalAddress', streetAddress: a.street, addressLocality: a.city, addressRegion: a.region, postalCode: a.postalCode, addressCountry: a.country ?? 'US' });
30
+
31
+ export type DayCode = 'Mo' | 'Tu' | 'We' | 'Th' | 'Fr' | 'Sa' | 'Su';
32
+ const DAYS: Record<DayCode, string> = { Mo: 'Monday', Tu: 'Tuesday', We: 'Wednesday', Th: 'Thursday', Fr: 'Friday', Sa: 'Saturday', Su: 'Sunday' };
33
+ /** [{ days: ['Mo','Tu','We','Th','Fr'], opens: '08:00', closes: '17:00' }] → OpeningHoursSpecification[]. */
34
+ export const openingHours = (rows: Array<{ days: DayCode[]; opens: string; closes: string }>): Thing[] =>
35
+ rows.map((r) => ({ '@type': 'OpeningHoursSpecification', dayOfWeek: r.days.map((d) => DAYS[d]), opens: r.opens, closes: r.closes }));
36
+
37
+ export interface OrganizationInput {
38
+ name: string;
39
+ url: string;
40
+ logo?: string;
41
+ /** Social profiles and directory listings (Facebook, LinkedIn, Google Business Profile…). */
42
+ sameAs?: string[];
43
+ telephone?: string;
44
+ email?: string;
45
+ contactPoints?: Array<{ telephone: string; contactType: string; areaServed?: string; availableLanguage?: string[] }>;
46
+ /** schema.org type: Organization, MedicalOrganization, NGO, Corporation… */
47
+ type?: string;
48
+ id?: string;
49
+ }
50
+ export function organization(o: OrganizationInput): Thing {
51
+ return clean({
52
+ '@type': o.type ?? 'Organization',
53
+ '@id': o.id ?? `${new URL(o.url).origin}/#organization`,
54
+ name: o.name,
55
+ url: o.url,
56
+ logo: o.logo ? { '@type': 'ImageObject', url: o.logo } : undefined,
57
+ sameAs: o.sameAs,
58
+ telephone: o.telephone,
59
+ email: o.email,
60
+ contactPoint: o.contactPoints?.map((c) => clean({ '@type': 'ContactPoint', ...c })),
61
+ });
62
+ }
63
+
64
+ export interface LocalBusinessInput extends Omit<OrganizationInput, 'type'> {
65
+ /**
66
+ * LocalBusiness or a more specific type: MedicalBusiness, MedicalClinic, Physician, Dentist,
67
+ * Pharmacy, Optician, LegalService, Restaurant, HomeAndConstructionBusiness…
68
+ */
69
+ type?: string;
70
+ address: PostalAddressInput;
71
+ geo?: { lat: number; lng: number };
72
+ hours?: Array<{ days: DayCode[]; opens: string; closes: string }>;
73
+ priceRange?: string;
74
+ image?: string | string[];
75
+ areaServed?: string[];
76
+ /** MedicalBusiness & co: e.g. ["Nursing", "PhysicalTherapy"] (schema.org MedicalSpecialty). */
77
+ medicalSpecialty?: string[];
78
+ /** The parent organization's @id, for multi-location brands. */
79
+ parentOrganization?: string;
80
+ hasMap?: string;
81
+ }
82
+ export function localBusiness(b: LocalBusinessInput): Thing {
83
+ const base = organization({ ...b, type: b.type ?? 'LocalBusiness', id: b.id ?? `${b.url.replace(/#.*$/, '')}#business` });
84
+ return clean({
85
+ ...base,
86
+ address: postalAddress(b.address),
87
+ geo: b.geo ? { '@type': 'GeoCoordinates', latitude: b.geo.lat, longitude: b.geo.lng } : undefined,
88
+ openingHoursSpecification: b.hours ? openingHours(b.hours) : undefined,
89
+ priceRange: b.priceRange,
90
+ image: b.image,
91
+ areaServed: b.areaServed?.map((name) => ({ '@type': 'City', name })),
92
+ medicalSpecialty: b.medicalSpecialty,
93
+ parentOrganization: ref(b.parentOrganization),
94
+ hasMap: b.hasMap,
95
+ });
96
+ }
97
+
98
+ // ---------------- Site & pages ----------------
99
+
100
+ export function website(w: { name: string; url: string; publisher?: string; searchUrlTemplate?: string; inLanguage?: string }): Thing {
101
+ const origin = new URL(w.url).origin;
102
+ return clean({
103
+ '@type': 'WebSite',
104
+ '@id': `${origin}/#website`,
105
+ name: w.name,
106
+ url: w.url,
107
+ inLanguage: w.inLanguage,
108
+ publisher: ref(w.publisher ?? `${origin}/#organization`),
109
+ // "{search_term_string}" in the URL template, e.g. https://example.com/search?q={search_term_string}
110
+ potentialAction: w.searchUrlTemplate
111
+ ? { '@type': 'SearchAction', target: { '@type': 'EntryPoint', urlTemplate: w.searchUrlTemplate }, 'query-input': 'required name=search_term_string' }
112
+ : undefined,
113
+ });
114
+ }
115
+
116
+ export function webPage(p: { url: string; name: string; description?: string; type?: string; breadcrumb?: string; primaryImage?: string; datePublished?: string | Date; dateModified?: string | Date }): Thing {
117
+ return clean({
118
+ '@type': p.type ?? 'WebPage',
119
+ '@id': `${p.url.replace(/#.*$/, '')}#webpage`,
120
+ url: p.url,
121
+ name: p.name,
122
+ description: p.description,
123
+ isPartOf: { '@id': `${new URL(p.url).origin}/#website` },
124
+ breadcrumb: ref(p.breadcrumb),
125
+ primaryImageOfPage: p.primaryImage ? { '@type': 'ImageObject', url: p.primaryImage } : undefined,
126
+ datePublished: isoDate(p.datePublished),
127
+ dateModified: isoDate(p.dateModified),
128
+ });
129
+ }
130
+
131
+ /** Breadcrumbs: positions are added; relative URLs resolved against `site`. The last item may omit `url`. */
132
+ export function breadcrumbList(items: Array<{ name: string; url?: string }>, options: { site?: string; id?: string } = {}): Thing {
133
+ return clean({
134
+ '@type': 'BreadcrumbList',
135
+ '@id': options.id,
136
+ itemListElement: items.map((it, i) => clean({ '@type': 'ListItem', position: i + 1, name: it.name, item: it.url ? absolute(it.url, options.site) : undefined })),
137
+ });
138
+ }
139
+
140
+ // ---------------- Content ----------------
141
+
142
+ export interface ArticleInput {
143
+ type?: 'Article' | 'BlogPosting' | 'NewsArticle';
144
+ url: string;
145
+ headline: string;
146
+ description?: string;
147
+ /** 1–3 images, ideally 16:9, 4:3 and 1:1, at least 1200px wide. */
148
+ images?: string[];
149
+ datePublished: string | Date;
150
+ dateModified?: string | Date;
151
+ authors: Array<{ name: string; url?: string; type?: 'Person' | 'Organization' }>;
152
+ publisher?: string;
153
+ section?: string;
154
+ keywords?: string[];
155
+ }
156
+ export function article(a: ArticleInput): Thing {
157
+ return clean({
158
+ '@type': a.type ?? 'Article',
159
+ '@id': `${a.url.replace(/#.*$/, '')}#article`,
160
+ mainEntityOfPage: { '@id': `${a.url.replace(/#.*$/, '')}#webpage` },
161
+ headline: a.headline,
162
+ description: a.description,
163
+ image: a.images,
164
+ datePublished: isoDate(a.datePublished),
165
+ dateModified: isoDate(a.dateModified ?? a.datePublished),
166
+ author: a.authors.map((p) => clean({ '@type': p.type ?? 'Person', name: p.name, url: p.url })),
167
+ publisher: ref(a.publisher ?? `${new URL(a.url).origin}/#organization`),
168
+ articleSection: a.section,
169
+ keywords: a.keywords?.join(', '),
170
+ });
171
+ }
172
+
173
+ /**
174
+ * FAQPage. Answers are plain text (or simple HTML: <p>, <a>, <ul>, <ol>, <li>, <b>, <strong>,
175
+ * <i>, <em>, <br>, <h1>–<h6>). Google currently shows FAQ rich results mainly for authoritative
176
+ * government and health sites; the markup is valid for everyone.
177
+ */
178
+ export function faqPage(questions: Array<{ question: string; answer: string }>, options: { url?: string } = {}): Thing {
179
+ return clean({
180
+ '@type': 'FAQPage',
181
+ '@id': options.url ? `${options.url.replace(/#.*$/, '')}#faq` : undefined,
182
+ mainEntity: questions.map((q) => ({ '@type': 'Question', name: q.question, acceptedAnswer: { '@type': 'Answer', text: q.answer } })),
183
+ });
184
+ }
185
+
186
+ export interface EventInput {
187
+ name: string;
188
+ url: string;
189
+ startDate: string | Date;
190
+ endDate?: string | Date;
191
+ description?: string;
192
+ images?: string[];
193
+ /** A place, or `online: true` for a virtual event (url = join link page). */
194
+ location?: { name: string; address: PostalAddressInput } | { online: true; url: string };
195
+ status?: 'EventScheduled' | 'EventCancelled' | 'EventPostponed' | 'EventRescheduled' | 'EventMovedOnline';
196
+ organizer?: { name: string; url?: string };
197
+ offers?: { price: number | string; currency?: string; url?: string; availability?: 'InStock' | 'SoldOut' | 'PreOrder'; validFrom?: string | Date };
198
+ }
199
+ export function event(e: EventInput): Thing {
200
+ const online = e.location && 'online' in e.location;
201
+ return clean({
202
+ '@type': 'Event',
203
+ '@id': `${e.url.replace(/#.*$/, '')}#event`,
204
+ name: e.name,
205
+ url: e.url,
206
+ description: e.description,
207
+ image: e.images,
208
+ startDate: isoDate(e.startDate) ?? String(e.startDate),
209
+ endDate: e.endDate ? isoDate(e.endDate) ?? String(e.endDate) : undefined,
210
+ eventStatus: `https://schema.org/${e.status ?? 'EventScheduled'}`,
211
+ eventAttendanceMode: e.location ? `https://schema.org/${online ? 'OnlineEventAttendanceMode' : 'OfflineEventAttendanceMode'}` : undefined,
212
+ location: !e.location
213
+ ? undefined
214
+ : 'online' in e.location
215
+ ? { '@type': 'VirtualLocation', url: e.location.url }
216
+ : { '@type': 'Place', name: e.location.name, address: postalAddress(e.location.address) },
217
+ organizer: e.organizer ? clean({ '@type': 'Organization', ...e.organizer }) : undefined,
218
+ offers: e.offers
219
+ ? clean({ '@type': 'Offer', price: String(e.offers.price), priceCurrency: e.offers.currency ?? 'USD', url: e.offers.url, availability: `https://schema.org/${e.offers.availability ?? 'InStock'}`, validFrom: isoDate(e.offers.validFrom) })
220
+ : undefined,
221
+ });
222
+ }
223
+
224
+ export function person(p: { name: string; url?: string; image?: string; jobTitle?: string; sameAs?: string[]; worksFor?: string; type?: string; medicalSpecialty?: string[] }): Thing {
225
+ return clean({ '@type': p.type ?? 'Person', name: p.name, url: p.url, image: p.image, jobTitle: p.jobTitle, sameAs: p.sameAs, worksFor: ref(p.worksFor), medicalSpecialty: p.medicalSpecialty });
226
+ }
227
+
228
+ /** A service the business offers ("Website design"). Use MedicalTherapy/MedicalProcedure only when accurate. */
229
+ export function service(s: { name: string; url: string; description?: string; provider?: string; areaServed?: string[]; serviceType?: string; type?: string }): Thing {
230
+ return clean({
231
+ '@type': s.type ?? 'Service',
232
+ '@id': `${s.url.replace(/#.*$/, '')}#service`,
233
+ name: s.name,
234
+ url: s.url,
235
+ description: s.description,
236
+ serviceType: s.serviceType,
237
+ provider: ref(s.provider ?? `${new URL(s.url).origin}/#organization`),
238
+ areaServed: s.areaServed?.map((name) => ({ '@type': 'City', name })),
239
+ });
240
+ }
241
+
242
+ /** Wraps nodes in one document with a shared @context, linked by @id. */
243
+ export function graph(nodes: Array<Thing | undefined | false>): Record<string, unknown> {
244
+ return { '@context': 'https://schema.org', '@graph': nodes.filter(Boolean) };
245
+ }
246
+ /** A single node as a document. */
247
+ export function withContext(node: Thing): Record<string, unknown> {
248
+ return { '@context': 'https://schema.org', ...node };
249
+ }
250
+
251
+ /**
252
+ * JSON for a <script type="application/ld+json"> body. Escapes `<`, `>` and `&` (so a value like
253
+ * "</script>" can't end the element) and U+2028/2029. Undefined values are dropped.
254
+ */
255
+ export function serializeJsonLd(data: unknown, pretty = false): string {
256
+ return JSON.stringify(data, null, pretty ? 2 : undefined)
257
+ .replace(/</g, '\\u003c')
258
+ .replace(/>/g, '\\u003e')
259
+ .replace(/&/g, '\\u0026')
260
+ .replace(/\u2028/g, '\\u2028')
261
+ .replace(/\u2029/g, '\\u2029');
262
+ }
263
+
264
+ // ---------------- Validation ----------------
265
+
266
+ type Rule = { required?: string[]; recommended?: string[] };
267
+ const RULES: Record<string, Rule> = {
268
+ Article: { required: ['headline'], recommended: ['image', 'datePublished', 'author'] },
269
+ BlogPosting: { required: ['headline'], recommended: ['image', 'datePublished', 'author'] },
270
+ NewsArticle: { required: ['headline'], recommended: ['image', 'datePublished', 'author'] },
271
+ BreadcrumbList: { required: ['itemListElement'] },
272
+ Event: { required: ['name', 'startDate', 'location'], recommended: ['description', 'image', 'endDate', 'eventStatus', 'organizer', 'offers'] },
273
+ FAQPage: { required: ['mainEntity'] },
274
+ LocalBusiness: { required: ['name', 'address'], recommended: ['telephone', 'url', 'openingHoursSpecification', 'geo', 'image'] },
275
+ Organization: { recommended: ['name', 'url', 'logo'] },
276
+ WebSite: { required: ['name', 'url'] },
277
+ Person: { required: ['name'] },
278
+ Service: { required: ['name'], recommended: ['provider', 'description'] },
279
+ };
280
+ const LOCAL = new Set(['LocalBusiness', 'MedicalBusiness', 'MedicalClinic', 'Physician', 'Dentist', 'Pharmacy', 'Optician', 'LegalService', 'Restaurant', 'HomeAndConstructionBusiness', 'ProfessionalService', 'Store', 'AutomotiveBusiness', 'HealthAndBeautyBusiness']);
281
+ const DATE_KEYS = ['datePublished', 'dateModified', 'startDate', 'endDate', 'validFrom'];
282
+
283
+ /** Checks a JSON-LD document (single node or @graph). Returns human-readable warnings. */
284
+ export function validateJsonLd(doc: unknown): string[] {
285
+ const warnings: string[] = [];
286
+ const root = doc as Record<string, unknown>;
287
+ if (!root || typeof root !== 'object') return ['JSON-LD must be an object.'];
288
+ if (root['@context'] !== 'https://schema.org' && root['@context'] !== 'http://schema.org') warnings.push('Missing "@context": "https://schema.org".');
289
+ const nodes = (Array.isArray(root['@graph']) ? root['@graph'] : [root]) as Thing[];
290
+ const ids = new Set(nodes.map((n) => n['@id']).filter(Boolean));
291
+ const refs: string[] = [];
292
+ const walk = (v: unknown) => {
293
+ if (Array.isArray(v)) v.forEach(walk);
294
+ else if (v && typeof v === 'object') {
295
+ const o = v as Record<string, unknown>;
296
+ if (Object.keys(o).length === 1 && typeof o['@id'] === 'string') refs.push(o['@id']);
297
+ Object.values(o).forEach(walk);
298
+ }
299
+ };
300
+ for (const node of nodes) {
301
+ const types = ([] as string[]).concat(node['@type'] ?? []);
302
+ if (!types.length) warnings.push('A node has no "@type".');
303
+ const label = `${types.join('/') || 'Node'}${node.name ? ` "${node.name}"` : node.headline ? ` "${node.headline}"` : ''}`;
304
+ for (const t of types) {
305
+ const rule = RULES[LOCAL.has(t) ? 'LocalBusiness' : t];
306
+ if (!rule) continue;
307
+ for (const k of rule.required ?? []) if (node[k] === undefined) warnings.push(`${label}: missing required "${k}".`);
308
+ for (const k of rule.recommended ?? []) if (node[k] === undefined) warnings.push(`${label}: missing recommended "${k}".`);
309
+ }
310
+ for (const k of DATE_KEYS) {
311
+ const v = node[k];
312
+ if (typeof v === 'string' && !/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/.test(v)) warnings.push(`${label}: "${k}" isn't an ISO 8601 date ("${v}").`);
313
+ if (typeof v === 'string' && /T\d{2}:\d{2}/.test(v) && !/(Z|[+-]\d{2}:\d{2})$/.test(v)) warnings.push(`${label}: "${k}" has a time but no time zone.`);
314
+ }
315
+ for (const k of ['url', 'logo', 'item']) {
316
+ const v = node[k];
317
+ if (typeof v === 'string' && !/^https?:\/\//.test(v)) warnings.push(`${label}: "${k}" should be an absolute URL ("${v}").`);
318
+ }
319
+ if (types.includes('BreadcrumbList')) {
320
+ const items = (node.itemListElement as Array<Record<string, unknown>>) ?? [];
321
+ items.forEach((it, i) => {
322
+ if (it.position !== i + 1) warnings.push(`BreadcrumbList: item ${i + 1} has position ${it.position}.`);
323
+ if (!it.name) warnings.push(`BreadcrumbList: item ${i + 1} has no name.`);
324
+ if (!it.item && i < items.length - 1) warnings.push(`BreadcrumbList: item ${i + 1} needs a URL (only the last item may omit it).`);
325
+ });
326
+ }
327
+ if (types.includes('FAQPage')) {
328
+ for (const q of (node.mainEntity as Array<Record<string, any>>) ?? []) if (!q?.acceptedAnswer?.text) warnings.push(`FAQPage: "${q?.name}" has no answer text.`);
329
+ }
330
+ walk(Object.fromEntries(Object.entries(node).filter(([k]) => k !== '@id')));
331
+ }
332
+ for (const r of refs) if (!ids.has(r) && Array.isArray(root['@graph'])) warnings.push(`Reference to "${r}" isn't defined in this @graph (fine if another block on the page defines it).`);
333
+ return warnings;
334
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Builds every <head> tag SEOHead renders, as data, plus warnings about likely SEO mistakes.
3
+ * Pure: SEOHead calls it with Astro.url / Astro.site; tests call it directly.
4
+ */
5
+ import { absolute, canonicalize, escapeXml, isAbsolute, isoDate, type TrailingSlash } from './url';
6
+
7
+ export interface SeoImage {
8
+ /** Absolute URL or a path on the site. */
9
+ url: string;
10
+ /** Describe the image; it's read out when the share card is shown to screen-reader users. */
11
+ alt: string;
12
+ width?: number;
13
+ height?: number;
14
+ type?: string;
15
+ }
16
+
17
+ export interface SeoInput {
18
+ /** The page's own title ("Web design services"). */
19
+ title?: string;
20
+ /** "%s | Sinnstack". Not applied when `title` already contains the site name. */
21
+ titleTemplate?: string;
22
+ /** Title when the page has none (usually the site name, for the home page). */
23
+ defaultTitle?: string;
24
+ description?: string;
25
+ /** The current request URL (Astro.url). */
26
+ url: string | URL;
27
+ /** Production origin (Astro.site). Canonical and social URLs always use it. */
28
+ site?: string | URL;
29
+ /** `false` omits the canonical link (rare). Otherwise defaults to the current URL, canonicalized. */
30
+ canonical?: string | URL | false;
31
+ trailingSlash?: TrailingSlash;
32
+ /** Query params that change content and belong in the canonical URL (e.g. "page"). */
33
+ keepQuery?: string[];
34
+ noindex?: boolean;
35
+ nofollow?: boolean;
36
+ /** Extra robots directives. Defaults to max-image-preview:large for indexable pages. */
37
+ robots?: string[];
38
+ siteName?: string;
39
+ /** Open Graph locale, e.g. "en_US". */
40
+ locale?: string;
41
+ alternateLocales?: string[];
42
+ /** hreflang alternates (include this page). `xDefault` adds hreflang="x-default". */
43
+ alternates?: Array<{ hreflang: string; href: string }>;
44
+ xDefault?: string;
45
+ type?: 'website' | 'article' | 'profile' | 'book' | 'video.other' | 'music.song';
46
+ image?: SeoImage;
47
+ twitter?: { card?: 'summary' | 'summary_large_image'; site?: string; creator?: string };
48
+ article?: { publishedTime?: string | Date; modifiedTime?: string | Date; authors?: string[]; section?: string; tags?: string[] };
49
+ /** RSS/Atom feeds to advertise (rel="alternate"). */
50
+ feeds?: Array<{ title: string; href: string; type?: 'rss' | 'atom' | 'json' }>;
51
+ pagination?: { prev?: string; next?: string };
52
+ verification?: { google?: string; bing?: string; yandex?: string; pinterest?: string };
53
+ /** Facebook App ID (only if you use Facebook Insights). */
54
+ fbAppId?: string;
55
+ }
56
+
57
+ export type HeadTag =
58
+ | { tag: 'title'; text: string }
59
+ | { tag: 'meta'; attrs: Record<string, string> }
60
+ | { tag: 'link'; attrs: Record<string, string> };
61
+
62
+ export interface HeadResult {
63
+ tags: HeadTag[];
64
+ title: string;
65
+ canonical?: string;
66
+ warnings: string[];
67
+ }
68
+
69
+ const LIMITS = { title: 60, descriptionMin: 70, descriptionMax: 160 };
70
+
71
+ function applyTemplate(title: string | undefined, input: SeoInput): string {
72
+ const t = title?.trim();
73
+ if (!t) return input.defaultTitle ?? input.siteName ?? '';
74
+ const tpl = input.titleTemplate;
75
+ if (!tpl || !tpl.includes('%s')) return t;
76
+ if (input.siteName && t.toLowerCase().includes(input.siteName.toLowerCase())) return t;
77
+ return tpl.replace('%s', t);
78
+ }
79
+
80
+ export function buildHead(input: SeoInput): HeadResult {
81
+ const warnings: string[] = [];
82
+ const tags: HeadTag[] = [];
83
+ const meta = (attrs: Record<string, string | undefined>) => {
84
+ if (Object.values(attrs).some((v) => v === undefined || v === '')) return;
85
+ tags.push({ tag: 'meta', attrs: attrs as Record<string, string> });
86
+ };
87
+ const link = (attrs: Record<string, string | undefined>) => {
88
+ if (Object.values(attrs).some((v) => v === undefined || v === '')) return;
89
+ tags.push({ tag: 'link', attrs: attrs as Record<string, string> });
90
+ };
91
+ const site = input.site ? String(input.site) : undefined;
92
+ if (!site) warnings.push('No `site` set in astro.config: canonical and social URLs use the request host, which may be a preview domain.');
93
+ const abs = (v?: string) => (v ? absolute(v, site ?? input.url) : undefined);
94
+
95
+ // Title & description
96
+ const title = applyTemplate(input.title, input);
97
+ tags.push({ tag: 'title', text: title });
98
+ if (!input.title?.trim() && !input.defaultTitle) warnings.push('Missing page title.');
99
+ if (title.length > LIMITS.title) warnings.push(`Title is ${title.length} characters; search results usually cut off around ${LIMITS.title}.`);
100
+ const description = input.description?.replace(/\s+/g, ' ').trim();
101
+ if (!description) warnings.push('Missing meta description.');
102
+ else if (description.length < LIMITS.descriptionMin) warnings.push(`Description is short (${description.length} characters); aim for ${LIMITS.descriptionMin}–${LIMITS.descriptionMax}.`);
103
+ else if (description.length > LIMITS.descriptionMax) warnings.push(`Description is ${description.length} characters; search results usually cut off around ${LIMITS.descriptionMax}.`);
104
+ meta({ name: 'description', content: description });
105
+
106
+ // Canonical
107
+ let canonical: string | undefined;
108
+ if (input.canonical !== false) {
109
+ const raw = input.canonical ? String(input.canonical) : String(input.url);
110
+ canonical = canonicalize(raw, { site: input.canonical && isAbsolute(String(input.canonical)) ? undefined : site, trailingSlash: input.trailingSlash, keepQuery: input.keepQuery });
111
+ link({ rel: 'canonical', href: canonical });
112
+ const self = canonicalize(String(input.url), { site, trailingSlash: input.trailingSlash, keepQuery: input.keepQuery });
113
+ if (input.noindex && canonical !== self) warnings.push('Page is noindex but its canonical points to another URL; pick one signal.');
114
+ }
115
+
116
+ // Robots
117
+ const directives = [input.noindex ? 'noindex' : '', input.nofollow ? 'nofollow' : '', ...(input.robots ?? (input.noindex ? [] : ['max-image-preview:large']))].filter(Boolean);
118
+ if (directives.length) meta({ name: 'robots', content: directives.join(', ') });
119
+
120
+ // Alternates
121
+ const seen = new Set<string>();
122
+ for (const alt of input.alternates ?? []) {
123
+ const key = alt.hreflang.toLowerCase();
124
+ if (seen.has(key)) warnings.push(`Duplicate hreflang "${alt.hreflang}".`);
125
+ seen.add(key);
126
+ link({ rel: 'alternate', hreflang: alt.hreflang, href: abs(alt.href) });
127
+ }
128
+ if (input.xDefault) link({ rel: 'alternate', hreflang: 'x-default', href: abs(input.xDefault) });
129
+ if (input.alternates?.length && canonical && !input.alternates.some((a) => abs(a.href) === canonical)) warnings.push('hreflang alternates should include this page itself.');
130
+
131
+ for (const f of input.feeds ?? []) {
132
+ const type = f.type === 'atom' ? 'application/atom+xml' : f.type === 'json' ? 'application/feed+json' : 'application/rss+xml';
133
+ link({ rel: 'alternate', type, title: f.title, href: abs(f.href) });
134
+ }
135
+ if (input.pagination?.prev) link({ rel: 'prev', href: abs(input.pagination.prev) });
136
+ if (input.pagination?.next) link({ rel: 'next', href: abs(input.pagination.next) });
137
+
138
+ // Open Graph
139
+ const type = input.type ?? (input.article ? 'article' : 'website');
140
+ const ogTitle = input.title?.trim() || title;
141
+ meta({ property: 'og:type', content: type });
142
+ meta({ property: 'og:title', content: ogTitle });
143
+ meta({ property: 'og:description', content: description });
144
+ meta({ property: 'og:url', content: canonical ?? abs(String(input.url)) });
145
+ meta({ property: 'og:site_name', content: input.siteName });
146
+ meta({ property: 'og:locale', content: input.locale });
147
+ for (const l of input.alternateLocales ?? []) meta({ property: 'og:locale:alternate', content: l });
148
+
149
+ const img = input.image;
150
+ const imageUrl = img ? abs(img.url) : undefined;
151
+ if (img && imageUrl) {
152
+ meta({ property: 'og:image', content: imageUrl });
153
+ if (imageUrl.startsWith('https:')) meta({ property: 'og:image:secure_url', content: imageUrl });
154
+ meta({ property: 'og:image:type', content: img.type });
155
+ if (img.width && img.height) {
156
+ meta({ property: 'og:image:width', content: String(img.width) });
157
+ meta({ property: 'og:image:height', content: String(img.height) });
158
+ if (img.width < 1200 || img.height < 630) warnings.push(`Share image is ${img.width}×${img.height}; large previews need at least 1200×630.`);
159
+ }
160
+ meta({ property: 'og:image:alt', content: img.alt?.trim() });
161
+ if (!img.alt?.trim()) warnings.push('Share image has no alt text.');
162
+ } else if (type !== 'profile') {
163
+ warnings.push('No share image: links shared on social sites will show a small or empty preview.');
164
+ }
165
+ if (input.fbAppId) meta({ property: 'fb:app_id', content: input.fbAppId });
166
+
167
+ if (input.article && type === 'article') {
168
+ const a = input.article;
169
+ meta({ property: 'article:published_time', content: isoDate(a.publishedTime) });
170
+ meta({ property: 'article:modified_time', content: isoDate(a.modifiedTime) });
171
+ for (const author of a.authors ?? []) meta({ property: 'article:author', content: author });
172
+ meta({ property: 'article:section', content: a.section });
173
+ for (const t of a.tags ?? []) meta({ property: 'article:tag', content: t });
174
+ if (a.publishedTime && !isoDate(a.publishedTime)) warnings.push('article.publishedTime is not a valid date.');
175
+ }
176
+
177
+ // Twitter / X (falls back to Open Graph for title, description and image)
178
+ const card = input.twitter?.card ?? (imageUrl ? 'summary_large_image' : 'summary');
179
+ meta({ name: 'twitter:card', content: card });
180
+ meta({ name: 'twitter:site', content: input.twitter?.site });
181
+ meta({ name: 'twitter:creator', content: input.twitter?.creator });
182
+ if (imageUrl) meta({ name: 'twitter:image:alt', content: img?.alt?.trim() });
183
+
184
+ // Verification
185
+ const v = input.verification ?? {};
186
+ meta({ name: 'google-site-verification', content: v.google });
187
+ meta({ name: 'msvalidate.01', content: v.bing });
188
+ meta({ name: 'yandex-verification', content: v.yandex });
189
+ meta({ name: 'p:domain_verify', content: v.pinterest });
190
+
191
+ return { tags, title, canonical, warnings };
192
+ }
193
+
194
+ /** Serializes tags to HTML (attribute values and text escaped). */
195
+ export function renderHead(tags: HeadTag[]): string {
196
+ return tags
197
+ .map((t) => {
198
+ if (t.tag === 'title') return `<title>${escapeXml(t.text)}</title>`;
199
+ const attrs = Object.entries(t.attrs)
200
+ .map(([k, v]) => `${k}="${escapeXml(v)}"`)
201
+ .join(' ');
202
+ return `<${t.tag} ${attrs}>`;
203
+ })
204
+ .join('\n');
205
+ }