| 1 | /** `null` unsets something, `undefined` falls back to what the template says. */ |
| 2 | export interface Meta { |
| 3 | /** recommended for all pages. `<title>{content}</title>` */ |
| 4 | title?: string | null; |
| 5 | /** recommended for all pages. `<meta name="description" content="{...}" />` */ |
| 6 | description?: string | null; |
| 7 | /** automatically added for static renders from the 'pages' folders. */ |
| 8 | canonical?: string | null; |
| 9 | /** add `<link rel="alternate" ... />`. Object keys are interpreted as |
| 10 | * mime types if they contain a slash, otherwise seen as an alternative language. */ |
| 11 | alternates?: Alternate[] | Record<string, string> | null; |
| 12 | |
| 13 | /** automatically generate both OpenGraph and Twitter meta tags */ |
| 14 | embed?: AutoEmbed | null; |
| 15 | /** add a robots tag for `noindex` and `nofollow` */ |
| 16 | denyRobots?: boolean | null; |
| 17 | /** add 'og:*' meta tags */ |
| 18 | openGraph?: OpenGraph | null; |
| 19 | /** add 'twitter:*' meta tags */ |
| 20 | twitter?: Twitter | null; |
| 21 | /** refer to an oEmbed file. See https://oembed.com */ |
| 22 | oEmbed?: string | null; |
| 23 | /** |
| 24 | * replace Discord's link preview with a layout of components, in a `container`. |
| 25 | * A string is the url of a JSON file holding it, for what does not fit the inline limit. |
| 26 | * Discord falls back to the Open Graph tags, so set `embed` too. |
| 27 | */ |
| 28 | discord?: DiscordComponent | string | null; |
| 29 | /** add arbitrary scripts to the document head */ |
| 30 | scripts?: Array<{ content: string } | ExternalScript> | null; |
| 31 | /** add arbitrary styles to the document head */ |
| 32 | styles?: Array<{ content: string } | ExternalStylesheet> | null; |
| 33 | /** |
| 34 | * '@clo/lib/meta' intentionally excludes a lot of exotic tags. |
| 35 | * Use `{ tag, ...attrs }` to add arbitrary head elements: |
| 36 | * |
| 37 | * ```ts |
| 38 | * extra: [ |
| 39 | * { tag: "meta", name: "site-verification", content: "waffles" }, |
| 40 | * { tag: "link", rel: "icon", href: "/favicon.ico" }, |
| 41 | * ], |
| 42 | * ``` |
| 43 | */ |
| 44 | extra?: Array<ExtraItem> | null; |
| 45 | |
| 46 | /** adds `<meta name="author" content="{...}" />` */ |
| 47 | authors?: string[] | null; |
| 48 | /** credit your framework or toolchain */ |
| 49 | generator?: string | null; |
| 50 | /** adds `<meta name="keywords" content="{keywords.join(', ')}" />` */ |
| 51 | keywords?: string[] | null; |
| 52 | /** URL to a manifest; https://developer.mozilla.org/en-US/docs/Web/Manifest */ |
| 53 | manifest?: string | null; |
| 54 | /** adds `<meta name="publisher" content="{...}" />` */ |
| 55 | publisher?: string | null; |
| 56 | /** https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta/name/referrer */ |
| 57 | referrer?: Referrer | null; |
| 58 | /** adds `<meta name="theme-color" content="{...}" />` */ |
| 59 | themeColor?: string | { dark: string; light: string } | null; |
| 60 | /** defaults to `width=device-width, initial-scale=1` for mobile compatibility. */ |
| 61 | viewport?: string | null; |
| 62 | } |
| 63 | export interface ExternalStylesheet { |
| 64 | rel?: "stylesheet"; |
| 65 | href: string; |
| 66 | media?: string; |
| 67 | [attr: string]: string | boolean | null | undefined; |
| 68 | // TODO: add the rest of the important attributes for autocomplete |
| 69 | } |
| 70 | export interface ExternalScript { |
| 71 | src: string; |
| 72 | async?: boolean; |
| 73 | defer?: boolean; |
| 74 | crossorigin?: "anonymous" | "use-credentials" | false; |
| 75 | [attr: string]: string | boolean | null | undefined; |
| 76 | // TODO: add the rest of the attributes for autocomplete |
| 77 | } |
| 78 | export type Alternate = { type: string; url: string } | { |
| 79 | lang: string; |
| 80 | url: string; |
| 81 | }; |
| 82 | export interface AutoEmbed { |
| 83 | /* defaults to the top level page title. */ |
| 84 | title?: string | null; |
| 85 | /* defaults to the top level page description. */ |
| 86 | description?: string | null; |
| 87 | /* add an image url to the embed card. */ |
| 88 | thumbnail?: string | null; |
| 89 | /** describe the embed image. */ |
| 90 | thumbnailAlt?: string | null; |
| 91 | /** @default "banner", which applies twitter:card = "summary_large_image" */ |
| 92 | thumbnailSize?: "banner" | "icon" | null; |
| 93 | /** @default null - no site title */ |
| 94 | siteTitle?: string | null; |
| 95 | } |
| 96 | /** See https://ogp.me for extra rules. */ |
| 97 | export interface OpenGraph { |
| 98 | /** the title of your object as it should appear within the graph */ |
| 99 | title?: string; |
| 100 | /** a one to two sentence description of your object. */ |
| 101 | description?: string | null; |
| 102 | /** the type of your object, e.g., "video.movie". Depending on the type you specify, other properties may also be required */ |
| 103 | type?: string; |
| 104 | /** an image URL which should represent your object within the graph */ |
| 105 | image?: OpenGraphField; |
| 106 | /** the canonical URL of your object that will be used as its permanent ID in the graph, e.g., "https://www.imdb.com/title/tt0117500/" */ |
| 107 | url?: string; |
| 108 | /** a URL to an audio file to accompany this object */ |
| 109 | audio?: OpenGraphField; |
| 110 | /** the word that appears before this object's title in a sentence. An enum of (a, an, the, "", auto). if auto is chosen, the consumer of your data should choose between "a" or "an". Default is "" (blank) */ |
| 111 | determiner?: string; |
| 112 | /** the locale these tags are marked up in. Of the format language_TERRITORY. Default is en_US */ |
| 113 | locale?: string; |
| 114 | /** an array of other locales this page is available in */ |
| 115 | "locale:alternate"?: string[]; |
| 116 | /** if your object is part of a larger web site, the name which should be displayed for the overall site. e.g., "IMDb" */ |
| 117 | site_name?: string; |
| 118 | /** a URL to a video file that complements this object */ |
| 119 | video?: OpenGraphField; |
| 120 | [field: string]: OpenGraphField; |
| 121 | } |
| 122 | /** |
| 123 | * when passing an array, the property is duplicated. |
| 124 | * when passing an object, the fields are emitted as namespaced with ':'. |
| 125 | */ |
| 126 | type OpenGraphField = |
| 127 | | string |
| 128 | | { [field: string]: OpenGraphField } |
| 129 | | Array<OpenGraphField> |
| 130 | | (null | undefined); |
| 131 | /** |
| 132 | * A component of a Discord embed, as in |
| 133 | * https://docs.discord.com/developers/link-previews/component-embeds. Fields |
| 134 | * are Discord's own, and only `type` has names: a number is the component |
| 135 | * as Discord has it, for those that are not named here. Relative `url`s are |
| 136 | * resolved against `Template.base`. |
| 137 | */ |
| 138 | export type DiscordComponent = |
| 139 | /** the top level component, and at most 40 components in all */ |
| 140 | | { type: "container"; components: DiscordComponent[]; accent_color?: number; spoiler?: boolean } |
| 141 | /** one to three `text`, and a `thumbnail` or `button` beside them */ |
| 142 | | { type: "section"; components: DiscordComponent[]; accessory: DiscordComponent } |
| 143 | /** Discord markdown */ |
| 144 | | { type: "text"; content: string } |
| 145 | | ({ type: "thumbnail" } & DiscordMedia) |
| 146 | /** one to ten items, and at most ten across the whole embed */ |
| 147 | | { type: "gallery"; items: DiscordMedia[] } |
| 148 | | { type: "separator"; divider?: boolean; spacing?: 1 | 2 } |
| 149 | /** up to five buttons */ |
| 150 | | { type: "row"; components: DiscordComponent[] } |
| 151 | /** an embed only has link buttons */ |
| 152 | | { |
| 153 | type: "button"; |
| 154 | url: string; |
| 155 | label?: string; |
| 156 | emoji?: { id?: string; name?: string; animated?: boolean }; |
| 157 | disabled?: boolean; |
| 158 | } |
| 159 | | { type: number; [field: string]: unknown }; |
| 160 | export interface DiscordMedia { |
| 161 | media: { url: string }; |
| 162 | description?: string | null; |
| 163 | spoiler?: boolean; |
| 164 | } |
| 165 | /** what Discord reads: the container of a `DiscordComponent`, with numbers for types */ |
| 166 | export interface DiscordPayload { |
| 167 | component: { type: 17; components: Array<{ type: number; [field: string]: unknown }>; [field: string]: unknown }; |
| 168 | } |
| 169 | |
| 170 | /** Twitter uses various OpenGraph fields if these are not specified. */ |
| 171 | export interface Twitter { |
| 172 | card: string; |
| 173 | title?: string; |
| 174 | description?: string | null; |
| 175 | url?: string; |
| 176 | image?: string; |
| 177 | player?: string; |
| 178 | /** Same logic as Open Graph */ |
| 179 | [field: string]: OpenGraphField; |
| 180 | } |
| 181 | export interface Template extends Omit<Meta, "title" | "description" | "canonical"> { |
| 182 | base: URL; |
| 183 | titleTemplate?: (title: string) => string; |
| 184 | } |
| 185 | export type Referrer = |
| 186 | | "no-referrer" |
| 187 | | "origin" |
| 188 | | "no-referrer-when-downgrade" |
| 189 | | "origin-when-cross-origin" |
| 190 | | "same-origin" |
| 191 | | "strict-origin" |
| 192 | | "strict-origin-when-cross-origin"; |
| 193 | export type ExtraItem = { |
| 194 | tag: "meta" | "link" | "script" | "style"; |
| 195 | [attr: string]: string | boolean | null | undefined; |
| 196 | }; |
| 197 | export interface Tags { |
| 198 | meta: Array<Record<string, string>>; |
| 199 | links: Array<Record<string, string>>; |
| 200 | scripts: Array<Record<string, string | boolean>>; |
| 201 | styles: Array<Record<string, string>>; |
| 202 | } |
| 203 | |
| 204 | /** convert a metadata definition into a structured list of tags, compatible with TanStack start */ |
| 205 | export function toTags(template: Template, meta: Meta): Tags { |
| 206 | const { titleTemplate, base } = template; |
| 207 | const resolve = (str: string) => new URL(str, base).href; |
| 208 | |
| 209 | const title = meta.title == null ? null : titleTemplate ? titleTemplate(meta.title) : meta.title; |
| 210 | const description = meta.description ?? null; |
| 211 | const canonical = meta.canonical ? resolve(meta.canonical) : null; |
| 212 | const denyRobots = Boolean(pick(meta.denyRobots, template.denyRobots)); |
| 213 | const authors = pick(meta.authors, template.authors); |
| 214 | const generator = pick(meta.generator, template.generator); |
| 215 | const keywords = pick(meta.keywords, template.keywords); |
| 216 | const manifest = pick(meta.manifest, template.manifest); |
| 217 | const publisher = pick(meta.publisher, template.publisher); |
| 218 | const referrer = pick(meta.referrer, template.referrer); |
| 219 | const themeColor = pick(meta.themeColor, template.themeColor); |
| 220 | const viewport = pick( |
| 221 | meta.viewport, |
| 222 | template.viewport, |
| 223 | "width=device-width, initial-scale=1, maximum-scale=1", |
| 224 | ); |
| 225 | |
| 226 | const alternates = pick(meta.alternates, template.alternates); |
| 227 | const oEmbed = pick(meta.oEmbed, template.oEmbed); |
| 228 | const discord = pick(meta.discord, template.discord); |
| 229 | const embed = pick(meta.embed, template.embed); |
| 230 | let openGraph = pick(meta.openGraph, template.openGraph); |
| 231 | let twitter = pick(meta.twitter, template.twitter); |
| 232 | if (embed) { |
| 233 | const { thumbnail, thumbnailSize, thumbnailAlt, siteTitle } = embed; |
| 234 | openGraph = { |
| 235 | type: "website", |
| 236 | title: embed.title ?? title ?? undefined, |
| 237 | description: embed.description ?? description, |
| 238 | ...openGraph, |
| 239 | }; |
| 240 | twitter = { |
| 241 | title: embed.title ?? title ?? undefined, |
| 242 | description: embed.description ?? description ?? undefined, |
| 243 | card: (thumbnailSize ?? (thumbnail ? "banner" : "icon")) === "banner" |
| 244 | ? "summary_large_image" |
| 245 | : "summary", |
| 246 | url: canonical ?? undefined, |
| 247 | ...twitter, |
| 248 | }; |
| 249 | if (thumbnail) { |
| 250 | const resolved = new URL(thumbnail, template.base).href; |
| 251 | openGraph.image = resolved; |
| 252 | twitter.image = resolved; |
| 253 | if (thumbnailAlt) { |
| 254 | openGraph["image:alt"] = thumbnailAlt; |
| 255 | twitter["image:alt"] = thumbnailAlt; |
| 256 | } |
| 257 | } |
| 258 | if (siteTitle) { |
| 259 | openGraph.site_name = siteTitle; |
| 260 | } |
| 261 | if (canonical) { |
| 262 | openGraph.url = canonical; |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | const metaTags: Array<Record<string, string>> = title == null ? [] : [{ title }]; |
| 267 | const links: Array<Record<string, string>> = []; |
| 268 | |
| 269 | if (description) metaTags.push({ name: "description", content: description }); |
| 270 | for (const author of authors ?? []) metaTags.push({ name: "author", content: author }); |
| 271 | if (keywords) metaTags.push({ name: "keywords", content: keywords.join(", ") }); |
| 272 | if (generator) { |
| 273 | metaTags.push({ name: "generator", content: generator }); |
| 274 | } |
| 275 | if (publisher) metaTags.push({ name: "publisher", content: publisher }); |
| 276 | if (referrer) metaTags.push({ name: "referrer", content: referrer }); |
| 277 | if (themeColor) { |
| 278 | if (typeof themeColor === "string") { |
| 279 | metaTags.push({ name: "theme-color", content: themeColor }); |
| 280 | } else { |
| 281 | metaTags.push({ name: "theme-color", media: "(prefers-color-scheme:light)", content: themeColor.light }); |
| 282 | metaTags.push({ name: "theme-color", media: "(prefers-color-scheme:dark)", content: themeColor.dark }); |
| 283 | } |
| 284 | } |
| 285 | if (denyRobots) metaTags.push({ name: "robots", content: "noindex,nofollow" }); |
| 286 | if (viewport) metaTags.push({ name: "viewport", content: viewport }); |
| 287 | if (canonical) links.push({ rel: "canonical", href: canonical }); |
| 288 | if (manifest) links.push({ rel: "manifest", href: manifest }); |
| 289 | if (oEmbed) links.push({ rel: "alternate", type: "application/json+oembed", href: resolve(oEmbed) }); |
| 290 | if (typeof discord === "string") { |
| 291 | links.push({ rel: discordRel, type: "application/json", href: resolve(discord) }); |
| 292 | } |
| 293 | if (alternates) { |
| 294 | const items = Array.isArray(alternates) |
| 295 | ? alternates |
| 296 | : Object.entries(alternates).map(([key, url]) => key.includes("/") ? { type: key, url } : { lang: key, url }); |
| 297 | for (const alt of items) { |
| 298 | const href = resolve(alt.url); |
| 299 | links.push( |
| 300 | "lang" in alt ? { rel: "alternate", hreflang: alt.lang, href } : { rel: "alternate", type: alt.type, href }, |
| 301 | ); |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | if (openGraph) metaTags.push(...collectOpenGraph("og", openGraph)); |
| 306 | if (twitter) metaTags.push(...collectOpenGraph("twitter", twitter)); |
| 307 | |
| 308 | const scriptTags: Array<Record<string, string | boolean>> = []; |
| 309 | const styleTags: Array<Record<string, string>> = []; |
| 310 | |
| 311 | if (discord && typeof discord === "object") { |
| 312 | const component = discordWire(discord, resolve) as DiscordPayload["component"]; |
| 313 | if (component.type !== 17) throw new Error("discord needs a container as its top level component"); |
| 314 | // `<` is escaped so that the payload cannot close its own script, and still counts toward the limit in full |
| 315 | const children = JSON.stringify({ component }).replaceAll("<", "\\u003c"); |
| 316 | const bytes = new TextEncoder().encode(children).length; |
| 317 | if (bytes > discordLimit) { |
| 318 | throw new Error(`discord component embed is ${bytes} bytes, over the ${discordLimit} limit`); |
| 319 | } |
| 320 | scriptTags.push({ id: discordRel, type: "application/json", children }); |
| 321 | } |
| 322 | |
| 323 | for (const entry of pick(meta.scripts, template.scripts) ?? []) { |
| 324 | if ("content" in entry) { |
| 325 | scriptTags.push({ children: String(entry.content) }); |
| 326 | } else { |
| 327 | const { src, ...rest } = entry; |
| 328 | const tag: Record<string, string | boolean> = { src }; |
| 329 | for (const [k, v] of Object.entries(rest)) { |
| 330 | if (v != null && v !== false) tag[k] = v; |
| 331 | } |
| 332 | scriptTags.push(tag); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | for (const entry of pick(meta.styles, template.styles) ?? []) { |
| 337 | if ("content" in entry) { |
| 338 | const tag: Record<string, string> = { children: String(entry.content) }; |
| 339 | if ("media" in entry && entry.media) tag.media = entry.media; |
| 340 | styleTags.push(tag); |
| 341 | } else { |
| 342 | const { href, ...rest } = entry; |
| 343 | const tag: Record<string, string> = { rel: "stylesheet", href }; |
| 344 | for (const [k, v] of Object.entries(rest)) { |
| 345 | if (v != null && v !== false && k !== "rel") tag[k] = v as string; |
| 346 | } |
| 347 | links.push(tag); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | for (const { tag, ...attrs } of pick(meta.extra, template.extra) ?? []) { |
| 352 | const clean: Record<string, string | boolean> = {}; |
| 353 | for (const [k, v] of Object.entries(attrs)) { |
| 354 | if (v != null && v !== false) clean[k] = v; |
| 355 | } |
| 356 | if (tag === "meta") metaTags.push(clean as Record<string, string>); |
| 357 | else if (tag === "link") links.push(clean as Record<string, string>); |
| 358 | else if (tag === "script") scriptTags.push(clean); |
| 359 | else if (tag === "style") styleTags.push(clean as Record<string, string>); |
| 360 | } |
| 361 | |
| 362 | return { meta: metaTags, links, scripts: scriptTags, styles: styleTags }; |
| 363 | } |
| 364 | |
| 365 | /* convert a metadata definition into HTML text. */ |
| 366 | export function toHtml(template: Template, meta: Meta): string { |
| 367 | const tags = toTags(template, meta); |
| 368 | let out = ""; |
| 369 | for (const attrs of tags.meta) { |
| 370 | if (isTitle(attrs)) { |
| 371 | out += `<title>${esc(attrs.title!)}</title>`; |
| 372 | } else { |
| 373 | out += `<meta` + Object.entries(attrs).map(([k, v]) => ` ${k}=${attr(v)}`).join("") + `>`; |
| 374 | } |
| 375 | } |
| 376 | for (const attrs of tags.links) { |
| 377 | out += `<link` + Object.entries(attrs).map(([k, v]) => ` ${k}=${attr(v)}`).join("") + `>`; |
| 378 | } |
| 379 | for (const { children = "", ...rest } of tags.scripts) { |
| 380 | out += `<script` + serializeAttrs(rest) + `>${children}</script>`; |
| 381 | } |
| 382 | for (const entry of tags.styles) { |
| 383 | if ("children" in entry) { |
| 384 | const { children, ...rest } = entry; |
| 385 | out += `<style` + serializeAttrs(rest) + `>${children}</style>`; |
| 386 | } |
| 387 | } |
| 388 | return out; |
| 389 | } |
| 390 | |
| 391 | /** |
| 392 | * the inverse of `toTags`: the tags of a parsed document. Give it a document |
| 393 | * from `DOMParser` to see the page as a crawler does, since none of them run |
| 394 | * scripts. Only the bodies of inline json scripts and styles are read. |
| 395 | */ |
| 396 | export function readTags(root: ParentNode): Tags { |
| 397 | const attrs = (element: Element) => Object.fromEntries(Array.from(element.attributes, (a) => [a.name, a.value])); |
| 398 | const withText = (element: Element) => ({ ...attrs(element), children: element.textContent ?? "" }); |
| 399 | const meta = Array.from(root.querySelectorAll("meta"), attrs); |
| 400 | const title = root.querySelector("title"); |
| 401 | if (title) meta.unshift({ title: title.textContent ?? "" }); |
| 402 | return { |
| 403 | meta, |
| 404 | links: Array.from(root.querySelectorAll("link"), attrs), |
| 405 | scripts: Array.from(root.querySelectorAll("script"), (element) => { |
| 406 | return element.src === "" && /json/.test(element.type) ? withText(element) : attrs(element); |
| 407 | }), |
| 408 | styles: Array.from(root.querySelectorAll("style"), withText), |
| 409 | }; |
| 410 | } |
| 411 | |
| 412 | /** what the tags of a document say, by the names that crawlers look for them under */ |
| 413 | export interface Scraped { |
| 414 | title: string | null; |
| 415 | description: string | null; |
| 416 | canonical: string | null; |
| 417 | /** the last one, as Discord reads it */ |
| 418 | themeColor: string | null; |
| 419 | /** the url of the oEmbed json */ |
| 420 | oEmbed: string | null; |
| 421 | /** the payload of a component embed, as inline text or the url that holds it */ |
| 422 | discord: { text: string } | { href: string } | null; |
| 423 | /** the values of `og:*` tags, by the rest of the name, in document order */ |
| 424 | openGraph: Record<string, string[]>; |
| 425 | /** the values of `twitter:*` tags, the same way */ |
| 426 | twitter: Record<string, string[]>; |
| 427 | } |
| 428 | |
| 429 | /** the inverse of toTags */ |
| 430 | export function scrape(tags: Tags): Scraped { |
| 431 | const scraped: Scraped = { |
| 432 | title: null, |
| 433 | description: null, |
| 434 | canonical: null, |
| 435 | themeColor: null, |
| 436 | oEmbed: null, |
| 437 | discord: null, |
| 438 | openGraph: {}, |
| 439 | twitter: {}, |
| 440 | }; |
| 441 | for (const attrs of tags.meta) { |
| 442 | if (isTitle(attrs)) { |
| 443 | scraped.title ??= attrs.title!; |
| 444 | continue; |
| 445 | } |
| 446 | const key = attrs.name ?? attrs.property; |
| 447 | const value = attrs.content ?? attrs.value; |
| 448 | if (!key || !value) continue; |
| 449 | if (key === "description") scraped.description ??= value; |
| 450 | else if (key === "theme-color") scraped.themeColor = value; |
| 451 | else if (key.startsWith("og:")) (scraped.openGraph[key.slice(3)] ??= []).push(value); |
| 452 | else if (key.startsWith("twitter:")) (scraped.twitter[key.slice(8)] ??= []).push(value); |
| 453 | } |
| 454 | for (const link of tags.links) { |
| 455 | if (link.rel === "canonical") scraped.canonical = link.href ?? null; |
| 456 | else if (link.type === "application/json+oembed") scraped.oEmbed ??= link.href ?? null; |
| 457 | else if (link.rel === discordRel && link.href) scraped.discord = { href: link.href }; |
| 458 | } |
| 459 | for (const script of tags.scripts) { |
| 460 | if (script.id === discordRel && typeof script.children === "string") scraped.discord = { text: script.children }; |
| 461 | } |
| 462 | return scraped; |
| 463 | } |
| 464 | |
| 465 | /** `toTags` puts the title among the meta tags as an entry of nothing else */ |
| 466 | function isTitle(attrs: Record<string, string>): boolean { |
| 467 | return Object.keys(attrs).length === 1 && "title" in attrs; |
| 468 | } |
| 469 | |
| 470 | const discordRel = "discord:component-embed"; |
| 471 | /** bytes of an inline payload, which Discord drops the embed over */ |
| 472 | const discordLimit = 3000; |
| 473 | |
| 474 | const discordTypes = { |
| 475 | row: 1, |
| 476 | button: 2, |
| 477 | section: 9, |
| 478 | text: 10, |
| 479 | thumbnail: 11, |
| 480 | gallery: 12, |
| 481 | separator: 14, |
| 482 | container: 17, |
| 483 | }; |
| 484 | |
| 485 | /** a component as Discord reads it: type names are numbers, a button is a link, and every `url` is resolved */ |
| 486 | function discordWire(value: unknown, resolve: (url: string) => string): unknown { |
| 487 | if (Array.isArray(value)) return value.map((item) => discordWire(item, resolve)); |
| 488 | if (value === null || typeof value !== "object") return value; |
| 489 | const { type, ...fields } = value as Record<string, unknown>; |
| 490 | const wire = Object.fromEntries( |
| 491 | Object.entries(fields).map(( |
| 492 | [k, v], |
| 493 | ) => [k, k === "url" && typeof v === "string" ? resolve(v) : discordWire(v, resolve)]), |
| 494 | ); |
| 495 | if (typeof type !== "string") return type === undefined ? wire : { type, ...wire }; |
| 496 | if (!Object.hasOwn(discordTypes, type)) throw new Error(`discord has no component type "${type}"`); |
| 497 | return { type: discordTypes[type as keyof typeof discordTypes], ...(type === "button" && { style: 5 }), ...wire }; |
| 498 | } |
| 499 | |
| 500 | const buttonKeys = new Set(["id", "type", "url", "style", "label", "emoji", "disabled"]); |
| 501 | /** what a component of each kind may hold, by where it is */ |
| 502 | const discordChildren = { top: [17], container: [1, 9, 10, 12, 14], section: [10], accessory: [2, 11], row: [2] }; |
| 503 | |
| 504 | /** |
| 505 | * how a payload breaks the rules of component embeds, which make Discord |
| 506 | * leave the embed out. It reads what a page holds, so it trusts nothing about |
| 507 | * its shape. |
| 508 | */ |
| 509 | export function discordProblems({ component }: DiscordPayload): string[] { |
| 510 | const problems: string[] = []; |
| 511 | let components = 0; |
| 512 | let items = 0; |
| 513 | const name = (type: number) => Object.entries(discordTypes).find(([, n]) => n === type)?.[0] ?? `type ${type}`; |
| 514 | |
| 515 | const media = (m: any, at: string) => { |
| 516 | const url = m?.media?.url; |
| 517 | if (typeof url !== "string" || !/^https?:\/\//.test(url) || url.length > 2048) { |
| 518 | problems.push(`${at}.media.url must be an http(s) url of at most 2048 characters`); |
| 519 | } |
| 520 | if (typeof m?.description === "string" && m.description.length > 1024) { |
| 521 | problems.push(`${at}.description is over 1024 characters`); |
| 522 | } |
| 523 | }; |
| 524 | |
| 525 | const visit = (c: any, at: string, within: keyof typeof discordChildren) => { |
| 526 | if (typeof c?.type !== "number") return void problems.push(`${at} is not a component`); |
| 527 | components++; |
| 528 | if (!discordChildren[within].includes(c.type)) { |
| 529 | problems.push(`${at}: a ${name(c.type)} cannot go ${within === "top" ? "at the top" : `in a ${within}`}`); |
| 530 | } |
| 531 | const list = (key: string, min: number, max: number, child: keyof typeof discordChildren) => { |
| 532 | const children = c[key]; |
| 533 | if (!Array.isArray(children) || children.length < min || children.length > max) { |
| 534 | return void problems.push(`${at}.${key} needs ${min} to ${max} components`); |
| 535 | } |
| 536 | children.forEach((item, i) => visit(item, `${at}.${key}[${i}]`, child)); |
| 537 | }; |
| 538 | switch (c.type) { |
| 539 | case 17: |
| 540 | list("components", 1, 40, "container"); |
| 541 | if ( |
| 542 | c.accent_color != null |
| 543 | && !(c.accent_color >= 0 && c.accent_color <= 0xffffff && Number.isInteger(c.accent_color)) |
| 544 | ) { |
| 545 | problems.push(`${at}.accent_color must be an integer from 0 to 16777215`); |
| 546 | } |
| 547 | break; |
| 548 | case 9: |
| 549 | list("components", 1, 3, "section"); |
| 550 | visit(c.accessory, `${at}.accessory`, "accessory"); |
| 551 | break; |
| 552 | case 1: |
| 553 | list("components", 1, 5, "row"); |
| 554 | break; |
| 555 | case 2: { |
| 556 | const extra = Object.keys(c).filter((key) => !buttonKeys.has(key)); |
| 557 | if (extra.length > 0) { |
| 558 | problems.push(`${at} has ${extra.join(", ")}, and any key but ${[...buttonKeys].join(", ")} voids the embed`); |
| 559 | } |
| 560 | if (c.style !== 5) problems.push(`${at}.style must be 5, a link`); |
| 561 | if (typeof c.url !== "string" || !/^https?:\/\//.test(c.url) || c.url.length > 512) { |
| 562 | problems.push(`${at}.url must be an http(s) url of at most 512 characters`); |
| 563 | } |
| 564 | if (!c.label && !c.emoji) problems.push(`${at} needs a label or an emoji`); |
| 565 | if (typeof c.label === "string" && c.label.length > 80) problems.push(`${at}.label is over 80 characters`); |
| 566 | break; |
| 567 | } |
| 568 | case 10: |
| 569 | if (typeof c.content !== "string") problems.push(`${at}.content must be a string`); |
| 570 | break; |
| 571 | case 11: |
| 572 | media(c, at); |
| 573 | break; |
| 574 | case 12: |
| 575 | if (!Array.isArray(c.items) || c.items.length < 1 || c.items.length > 10) { |
| 576 | problems.push(`${at}.items needs 1 to 10 items`); |
| 577 | } else { |
| 578 | items += c.items.length; |
| 579 | c.items.forEach((item: unknown, i: number) => media(item, `${at}.items[${i}]`)); |
| 580 | } |
| 581 | break; |
| 582 | case 14: |
| 583 | if (c.spacing != null && c.spacing !== 1 && c.spacing !== 2) problems.push(`${at}.spacing must be 1 or 2`); |
| 584 | if (c.divider != null && typeof c.divider !== "boolean") problems.push(`${at}.divider must be a boolean`); |
| 585 | break; |
| 586 | } |
| 587 | }; |
| 588 | |
| 589 | visit(component, "component", "top"); |
| 590 | if (components > 40) problems.push(`${components} components, at most 40`); |
| 591 | if (items > 10) problems.push(`${items} gallery items, at most 10 across the embed`); |
| 592 | return problems; |
| 593 | } |
| 594 | |
| 595 | function serializeAttrs(attrs: Record<string, string | boolean>): string { |
| 596 | let out = ""; |
| 597 | for (const [k, v] of Object.entries(attrs)) { |
| 598 | if (v === true) out += ` ${k}`; |
| 599 | else if (v != null && v !== false) out += ` ${k}=${attr(v as string)}`; |
| 600 | } |
| 601 | return out; |
| 602 | } |
| 603 | |
| 604 | function pick<T>(value: T | null | undefined, template: T | null | undefined, fallback: T | null = null): T | null { |
| 605 | if (value !== undefined) return value; |
| 606 | if (template !== undefined) return template; |
| 607 | return fallback; |
| 608 | } |
| 609 | |
| 610 | function collectOpenGraph(prefix: string, value: OpenGraphField): Array<Record<string, string>> { |
| 611 | if (!value) return []; |
| 612 | if (typeof value === "string") { |
| 613 | // OG keys on `property`, twitter keys on `name`. |
| 614 | const key = prefix.startsWith("og:") ? "property" : "name"; |
| 615 | return [{ [key]: prefix, content: value }]; |
| 616 | } |
| 617 | if (Array.isArray(value)) return value.flatMap((item) => collectOpenGraph(prefix, item)); |
| 618 | return Object.entries(value).flatMap(([key, item]) => collectOpenGraph(`${prefix}:${key}`, item)); |
| 619 | } |
| 620 | |
| 621 | function attr(value: string) { |
| 622 | value = string.escapeHtmlAttr(value); |
| 623 | if (value.match(/["/> ]/)) return "\"" + value + "\""; |
| 624 | return value; |
| 625 | } |
| 626 | |
| 627 | import * as string from "./string.ts"; |
| 628 | import { escapeHtmlContent as esc } from "./string.ts"; |