{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "embed",
  "title": "Embed",
  "description": "Turns a URL into what it points to: a YouTube facade, a lazy Spotify player, an image, a video, or a plain link card, decided from the URL alone.",
  "registryDependencies": [
    "https://www.deltacomponents.dev/r/utils.json",
    "https://www.deltacomponents.dev/r/image.json",
    "skeleton"
  ],
  "files": [
    {
      "path": "registry/ui/embed.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { classifyUrl, type EmbedSource } from \"@/lib/embed\"\nimport { Image, type ImageProps } from \"@/components/ui/image\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport type { LinkPreviewData } from \"@/lib/link-preview\"\n\n// iPadOS reports itself as a Mac, distinguishable only by the touch points a\n// real Mac doesn't have.\nfunction isIOS(nav: Pick<Navigator, \"userAgent\" | \"platform\" | \"maxTouchPoints\">): boolean {\n  return (\n    /iP(hone|ad|od)/.test(nav.userAgent) ||\n    (nav.platform === \"MacIntel\" && nav.maxTouchPoints > 1)\n  )\n}\n\n// loading=\"lazy\" does defer the request, but the browser starts it thousands\n// of pixels before the viewport, so a player far down a page still loads with\n// it. Holding the src back until the element is about to be seen is tighter.\nfunction useNearViewport<T extends Element>(\n  ref: React.RefObject<T | null>,\n  rootMargin = \"200px\"\n): boolean {\n  const [near, setNear] = React.useState(false)\n\n  React.useEffect(() => {\n    if (near) return\n    const el = ref.current\n    if (!el) return\n    const observer = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((entry) => entry.isIntersecting)) return\n        setNear(true)\n        observer.disconnect()\n      },\n      { rootMargin }\n    )\n    observer.observe(el)\n    return () => observer.disconnect()\n  }, [ref, near, rootMargin])\n\n  return near\n}\n\ninterface EmbedProps {\n  url: string\n  className?: string\n  /** Where `LinkPreview` fetches a plain link's title, description and image\n   *  from. `null` turns the fetch off. */\n  endpoint?: string | null\n}\n\n/** Turns an arbitrary URL into whichever embed fits it, or nothing at all.\n *  Trusts `classifyUrl` completely — a `link` classification renders as a\n *  card, not an iframe, and anything it refuses renders nothing. */\nfunction Embed({ url, className, endpoint }: EmbedProps) {\n  const source = classifyUrl(url)\n  if (!source) return null\n  return <EmbedFromSource source={source} className={className} endpoint={endpoint} />\n}\n\nfunction EmbedFromSource({\n  source,\n  className,\n  endpoint,\n}: {\n  source: EmbedSource\n  className?: string\n  endpoint?: string | null\n}) {\n  switch (source.kind) {\n    case \"youtube\":\n      return <YouTubeEmbed videoId={source.videoId} className={className} />\n    case \"spotify\":\n      return <SpotifyEmbed type={source.type} id={source.id} className={className} />\n    case \"image\":\n      return <ImageEmbed src={source.url} className={className} />\n    case \"video\":\n      return <VideoEmbed src={source.url} className={className} />\n    case \"link\":\n      return <LinkPreview url={source.url} className={className} endpoint={endpoint} />\n  }\n}\n\ninterface YouTubeEmbedProps {\n  videoId: string\n  title?: string\n  className?: string\n}\n\n// YouTube answers a missing maxresdefault with a 4:3 grey 120x90, where the\n// real one is 16:9.\nfunction isPlaceholderThumbnail(image: HTMLImageElement): boolean {\n  return image.currentSrc.includes(\"maxresdefault\") && image.naturalWidth / image.naturalHeight < 1.5\n}\n\n// A facade: the real player is close to a megabyte of third-party script, and\n// a page shouldn't pay for it until someone actually presses play. Until\n// then this is a thumbnail and a button.\nfunction YouTubeEmbed({ videoId, title = \"YouTube video\", className }: YouTubeEmbedProps) {\n  // A cross-origin iframe doesn't inherit the tap that landed on our facade,\n  // so on iOS `autoplay=1` with sound just shows YouTube's own play button —\n  // muted autoplay used to be the workaround. Android Chrome and desktop DO\n  // honour that tap through `allow=\"autoplay\"`, so they play with sound on\n  // one tap. On iOS the player is mounted up front instead, once the block\n  // nears the viewport, so the one tap lands inside YouTube's player and\n  // plays with sound; the cost is the player script loading for every video\n  // on iOS, which is the trade the site chose.\n  const [playing, setPlaying] = React.useState(false)\n  const [eager, setEager] = React.useState(false)\n  React.useEffect(() => setEager(isIOS(navigator)), [])\n  const ref = React.useRef<HTMLDivElement>(null)\n  const near = useNearViewport(ref)\n  const showIframe = playing || (eager && near)\n\n  const [thumbnailLoaded, setThumbnailLoaded] = React.useState(false)\n  const [playerLoaded, setPlayerLoaded] = React.useState(false)\n  const thumbRef = React.useRef<HTMLImageElement>(null)\n  const iframeRef = React.useRef<HTMLIFrameElement>(null)\n\n  // Once the video is going, a tap on the player is a tap on YouTube's own\n  // chrome, and on a phone-height embed the title bar across the top — a link\n  // into the YouTube app — takes a good share of it, so trying to pause opens\n  // the app instead. On a coarse pointer a layer of ours takes the tap and\n  // toggles playback over the player's message API; YouTube's control bar\n  // along the bottom stays uncovered for scrubbing, volume and fullscreen.\n  // The layer only exists once playback has been seen (state 1), because\n  // before that the first tap has to reach the player itself on iOS.\n  const [playerState, setPlayerState] = React.useState<number | null>(null)\n  const [origin, setOrigin] = React.useState(\"\")\n  React.useEffect(() => setOrigin(window.location.origin), [])\n  React.useEffect(() => {\n    const onMessage = (event: MessageEvent) => {\n      if (event.source !== iframeRef.current?.contentWindow || typeof event.data !== \"string\") return\n      let data: { event?: string; info?: number | { playerState?: number } }\n      try {\n        data = JSON.parse(event.data)\n      } catch {\n        return\n      }\n      if (data.event === \"onStateChange\" && typeof data.info === \"number\") setPlayerState(data.info)\n      else if (data.event === \"infoDelivery\" && typeof data.info === \"object\" && typeof data.info?.playerState === \"number\")\n        setPlayerState(data.info.playerState)\n    }\n    window.addEventListener(\"message\", onMessage)\n    return () => window.removeEventListener(\"message\", onMessage)\n  }, [])\n  const sendToPlayer = (func: \"playVideo\" | \"pauseVideo\" | \"listening\") => {\n    const target = iframeRef.current?.contentWindow\n    if (!target) return\n    const message = func === \"listening\" ? { event: \"listening\", id: videoId } : { event: \"command\", func, args: [] }\n    target.postMessage(JSON.stringify(message), \"https://www.youtube-nocookie.com\")\n  }\n  const [started, setStarted] = React.useState(false)\n  React.useEffect(() => {\n    if (playerState === 1) setStarted(true)\n  }, [playerState])\n  // A cached thumbnail can finish loading before hydration, which means\n  // React's onLoad below never fires for it.\n  React.useEffect(() => {\n    const image = thumbRef.current\n    if (!image?.complete || !image.naturalWidth) return\n    if (isPlaceholderThumbnail(image)) setWithoutLargeThumbnail(videoId)\n    else setThumbnailLoaded(true)\n  }, [videoId])\n\n  // 1280x720 is the largest thumbnail YouTube publishes, and it only exists\n  // for some videos. A missing one is not an error: YouTube answers 404 with\n  // a valid grey placeholder, which loads fine — `isPlaceholderThumbnail`\n  // above is how both the mount check and `onLoad` tell it apart from the\n  // real thing. Keyed on the id so a new video gets a fresh try.\n  const [withoutLargeThumbnail, setWithoutLargeThumbnail] = React.useState<string | null>(null)\n  const thumbnailSrc =\n    withoutLargeThumbnail === videoId\n      ? `https://i.ytimg.com/vi/${encodeURIComponent(videoId)}/hqdefault.jpg`\n      : `https://i.ytimg.com/vi_webp/${encodeURIComponent(videoId)}/maxresdefault.webp`\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"youtube-embed\"\n      // No radius by default — a consumer rounds it with `className`.\n      className={cn(\"group relative aspect-video w-full overflow-hidden bg-muted\", className)}\n    >\n      {showIframe && (\n        <iframe\n          ref={iframeRef}\n          // `enablejsapi` with our origin is what lets the player report its\n          // state and accept play/pause over postMessage — see the tap layer.\n          src={`https://www.youtube-nocookie.com/embed/${encodeURIComponent(videoId)}?playsinline=1&enablejsapi=1&origin=${encodeURIComponent(origin)}${\n            playing ? \"&autoplay=1\" : \"\"\n          }`}\n          title={title}\n          className=\"absolute inset-0 h-full w-full border-0\"\n          allow=\"autoplay; encrypted-media; picture-in-picture; fullscreen\"\n          allowFullScreen\n          referrerPolicy=\"strict-origin-when-cross-origin\"\n          onLoad={() => {\n            setPlayerLoaded(true)\n            // The player only posts state changes to a page that asked.\n            sendToPlayer(\"listening\")\n          }}\n        />\n      )}\n      {/* The facade sits over the player until the player has painted, then\n          fades: the iframe is transparent while YouTube loads, then black\n          before its poster, and on iOS its chrome replaces ours. It never\n          takes a tap, so on iOS the one tap lands inside the player. */}\n      <div\n        aria-hidden=\"true\"\n        className={cn(\n          \"pointer-events-none absolute inset-0 transition-opacity duration-(--motion-slow) ease-spring\",\n          playerLoaded && \"opacity-0\"\n        )}\n      >\n        {!thumbnailLoaded && <Skeleton className=\"absolute inset-0 rounded-none\" />}\n        {/* hqdefault is 4:3 with black bars top and bottom; cover crops them\n            out instead of letterboxing the thumbnail. */}\n        {/* eslint-disable-next-line @next/next/no-img-element -- a registry\n            component installs into any React project, so it must not depend\n            on next/image; the consumer swaps this for their framework's\n            loader. */}\n        <img\n          ref={thumbRef}\n          src={thumbnailSrc}\n          onLoad={(event) => {\n            const image = event.currentTarget\n            if (isPlaceholderThumbnail(image)) setWithoutLargeThumbnail(videoId)\n            else setThumbnailLoaded(true)\n          }}\n          onError={() => setWithoutLargeThumbnail(videoId)}\n          alt=\"\"\n          loading=\"lazy\"\n          decoding=\"async\"\n          referrerPolicy=\"no-referrer\"\n          className=\"absolute inset-0 h-full w-full object-cover\"\n        />\n        {/* The glyph goes the moment the reader presses play — where\n            autoplay is honoured the video is about to start under it. */}\n        {!playing && (\n          <span className=\"absolute inset-0 flex items-center justify-center\">\n            {/* Our own drawing, not YouTube's mark: a plain rounded rectangle\n                in their red, which is how their player shows its button. The\n                red is a literal because it is a brand colour, not one of the\n                theme's. */}\n            <svg viewBox=\"0 0 68 48\" className=\"h-12 w-[68px]\">\n              <rect\n                width=\"68\"\n                height=\"48\"\n                rx=\"12\"\n                className={cn(\n                  \"fill-[#f00] transition-colors duration-(--motion-fast) ease-spring\",\n                  \"group-hover:fill-[#c00]\"\n                )}\n              />\n              <path d=\"M27 14v20l18-10z\" className=\"fill-white\" />\n            </svg>\n          </span>\n        )}\n      </div>\n      {started && (\n        <button\n          type=\"button\"\n          onClick={() => sendToPlayer(playerState === 1 ? \"pauseVideo\" : \"playVideo\")}\n          aria-label={playerState === 1 ? \"Pause\" : \"Play\"}\n          // Touch only, and never over the bottom strip where YouTube's own\n          // controls live; a mouse can aim, and desktop clicks already toggle.\n          className=\"absolute inset-x-0 top-0 bottom-12 hidden cursor-pointer pointer-coarse:block\"\n        />\n      )}\n      {!showIframe && (\n        <button\n          type=\"button\"\n          onClick={() => setPlaying(true)}\n          aria-label={`Play: ${title}`}\n          className={cn(\n            \"absolute inset-0 h-full w-full cursor-pointer\",\n            // `rounded-none` beats the base-layer `:focus-visible` radius,\n            // which would round the ring's corners off the square container.\n            \"rounded-none outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-[color:var(--focus-ring,#6B97FF)]\"\n          )}\n        />\n      )}\n    </div>\n  )\n}\n\ninterface SpotifyEmbedProps {\n  type: \"track\" | \"playlist\" | \"album\" | \"episode\" | \"show\"\n  id: string\n  className?: string\n}\n\nfunction SpotifyEmbed({ type, id, className }: SpotifyEmbedProps) {\n  const ref = React.useRef<HTMLDivElement>(null)\n  const near = useNearViewport(ref)\n  const [loaded, setLoaded] = React.useState(false)\n  const height = type === \"track\" || type === \"episode\" ? 152 : 352\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"spotify-embed\"\n      className={cn(\"relative w-full\", className)}\n      style={{ height }}\n    >\n      {/* The iframe is transparent until Spotify paints, so the skeleton\n          behind it reads through until then. */}\n      {(!near || !loaded) && (\n        <Skeleton aria-hidden className=\"absolute inset-0 rounded-[12px]\" />\n      )}\n      {near && (\n        <iframe\n          src={`https://open.spotify.com/embed/${type}/${encodeURIComponent(id)}`}\n          title=\"Spotify player\"\n          allow=\"encrypted-media; clipboard-write; fullscreen; picture-in-picture\"\n          className=\"block h-full w-full border-0\"\n          // Spotify's own card already has 12px corners; any other radius\n          // shows the iframe's background in them, and `normal` keeps a dark\n          // page from painting an opaque canvas behind the transparent ones.\n          // Literal 12px on purpose — the site's radius tokens are\n          // user-adjustable and would fight Spotify's fixed corners.\n          style={{ borderRadius: 12, colorScheme: \"normal\" }}\n          onLoad={() => setLoaded(true)}\n        />\n      )}\n    </div>\n  )\n}\n\ninterface VideoEmbedProps extends Omit<React.ComponentProps<\"video\">, \"src\" | \"className\"> {\n  src: string\n  className?: string\n}\n\nfunction VideoEmbed({ src, className, ...videoProps }: VideoEmbedProps) {\n  const ref = React.useRef<HTMLVideoElement>(null)\n  const near = useNearViewport(ref)\n  // Safari, on a phone above all, fetches the metadata and then paints\n  // nothing until play. Asking for a moment just past zero makes it decode\n  // and show the opening frame. The fragment never reaches the server.\n  const framed = src.includes(\"#\") ? src : `${src}#t=0.001`\n\n  return (\n    <video\n      ref={ref}\n      data-slot=\"video-embed\"\n      controls\n      // Without this, iOS takes the video fullscreen the moment it plays.\n      playsInline\n      preload=\"metadata\"\n      src={near ? framed : undefined}\n      className={cn(\"aspect-video w-full\", className)}\n      {...videoProps}\n    />\n  )\n}\n\ntype ImageEmbedProps = Omit<ImageProps, \"alt\"> & {\n  /** Optional here, unlike on Image: a pasted URL never came with any. */\n  alt?: string\n}\n\n// The registry's Image, so an embedded picture enlarges on a click like any\n// other. No referrer by default: the URL is usually someone else's server.\nfunction ImageEmbed({ alt = \"\", ...props }: ImageEmbedProps) {\n  return <Image alt={alt} referrerPolicy=\"no-referrer\" {...props} />\n}\n\ninterface LinkPreviewProps {\n  url: string\n  /** The page's title. Passing it turns the plain card into a full preview\n   *  and skips the fetch entirely. */\n  title?: string\n  /** One or two lines under the title. Passing it skips the fetch. */\n  description?: string\n  /** A thumbnail. Passing it skips the fetch. */\n  image?: string\n  className?: string\n  /** Where the title, description and image are fetched from when none of\n   *  them are passed. `null` turns the fetch off. */\n  endpoint?: string | null\n}\n\n// A remount (the editor remounts widgets) shouldn't refetch a URL it already\n// has an answer for.\n// ponytail: unbounded, lives as long as the page. Cap it if a page can show\n// thousands of distinct links.\nconst previewCache = new Map<string, Promise<LinkPreviewData | null>>()\n\n// The card draws what it is given, and fetches the rest itself. A page's\n// title and thumbnail have to come from a server — a browser can't read\n// another site's HTML — so with no `title`/`description`/`image` prop and an\n// `endpoint`, it asks the route for them; a bare URL and no endpoint stays a\n// plain card.\nfunction LinkPreview({ url, title, description, image, className, endpoint = \"/api/link-preview\" }: LinkPreviewProps) {\n  // The part is exported, so it can be handed a URL `Embed` would have\n  // refused. Anything but http(s) — `javascript:` above all — is not a link\n  // this renders.\n  const allowed = isHttpUrl(url)\n  const [fetched, setFetched] = React.useState<LinkPreviewData | null>(null)\n\n  React.useEffect(() => {\n    if (!allowed || title || !endpoint) return\n    const key = `${endpoint}\\n${url}`\n    let request = previewCache.get(key)\n    if (!request) {\n      // Shared by every card showing this URL, so no one card's unmount may\n      // abort it — and a failure is dropped, so a later card can try again.\n      request = fetch(`${endpoint}?url=${encodeURIComponent(url)}`)\n        .then((response) => (response.ok ? (response.json() as Promise<LinkPreviewData>) : null))\n        .catch(() => null)\n        .then((data) => {\n          if (!data) previewCache.delete(key)\n          return data\n        })\n      previewCache.set(key, request)\n    }\n    let cancelled = false\n    request.then((data) => {\n      if (!cancelled) setFetched(data)\n    })\n    return () => {\n      cancelled = true\n    }\n  }, [allowed, title, endpoint, url])\n\n  if (!allowed) return null\n  const hostname = new URL(url).hostname.replace(/^www\\./, \"\")\n\n  const resolvedTitle = title ?? fetched?.title ?? undefined\n  const resolvedDescription = description ?? fetched?.description ?? undefined\n  const rawImage = image ?? fetched?.image ?? undefined\n  // Taken from an untrusted page. The route already limits it to http(s),\n  // but this component can't assume its own copy is what's deployed.\n  const resolvedImage = rawImage && isHttpUrl(rawImage) ? rawImage : undefined\n\n  return (\n    <a\n      data-slot=\"link-preview\"\n      href={url}\n      target=\"_blank\"\n      rel=\"noopener noreferrer\"\n      className={cn(\n        \"border-border/60 bg-card relative flex w-full flex-col overflow-hidden border sm:flex-row\",\n        \"rounded-[var(--radius-bg,var(--radius,0.5rem))]\",\n        // A wash laid over the card rather than a second fill: `--hover` is\n        // translucent, so as the background itself it would replace the\n        // card's colour, and in dark mode it lands on exactly that colour.\n        \"after:pointer-events-none after:absolute after:inset-0 after:bg-[var(--hover)] after:opacity-0\",\n        \"after:transition-opacity after:duration-(--motion-fast) after:ease-spring\",\n        \"hover:after:opacity-100 active:after:bg-[var(--active)]\",\n        \"outline-none focus-visible:ring-1 focus-visible:ring-[color:var(--focus-ring,#6B97FF)]\",\n        className\n      )}\n    >\n      {resolvedImage && (\n        /* eslint-disable-next-line @next/next/no-img-element -- a registry\n           component installs into any React project, so it must not depend on\n           next/image; the consumer swaps this for their framework's loader. */\n        <img\n          src={resolvedImage}\n          alt=\"\"\n          loading=\"lazy\"\n          decoding=\"async\"\n          referrerPolicy=\"no-referrer\"\n          className=\"aspect-[1.91/1] w-full shrink-0 object-cover sm:w-48\"\n        />\n      )}\n      <span className=\"flex min-w-0 flex-col justify-center gap-0.5 p-3\">\n        <span className=\"text-foreground truncate font-medium\">{resolvedTitle ?? hostname}</span>\n        {resolvedDescription && (\n          <span className=\"text-muted-foreground line-clamp-2 text-sm\">{resolvedDescription}</span>\n        )}\n        <span className=\"text-muted-foreground truncate text-sm\">\n          {resolvedTitle ? hostname : url}\n        </span>\n      </span>\n    </a>\n  )\n}\n\nfunction isHttpUrl(value: string): boolean {\n  try {\n    const protocol = new URL(value).protocol\n    return protocol === \"http:\" || protocol === \"https:\"\n  } catch {\n    return false\n  }\n}\n\nexport { Embed, YouTubeEmbed, SpotifyEmbed, VideoEmbed, ImageEmbed, LinkPreview, isIOS }\nexport type {\n  EmbedProps,\n  YouTubeEmbedProps,\n  SpotifyEmbedProps,\n  VideoEmbedProps,\n  ImageEmbedProps,\n  LinkPreviewProps,\n}\n",
      "type": "registry:ui",
      "target": "components/ui/embed.tsx"
    },
    {
      "path": "registry/lib/embed.ts",
      "content": "export type EmbedSource =\n  | { kind: \"youtube\"; videoId: string }\n  | { kind: \"spotify\"; type: \"track\" | \"playlist\" | \"album\" | \"episode\" | \"show\"; id: string }\n  | { kind: \"image\"; url: string }\n  | { kind: \"video\"; url: string }\n  | { kind: \"link\"; url: string };\n\nconst ABSOLUTE_URL = /^https?:\\/\\/\\S+$/;\nconst YOUTUBE_ID = /^[\\w-]{11}$/;\n\nfunction matchYouTube(parsed: URL): EmbedSource | null {\n  const host = parsed.hostname.replace(/^(www\\.|m\\.)/, \"\");\n  if (host === \"youtu.be\") {\n    const id = parsed.pathname.slice(1);\n    return YOUTUBE_ID.test(id) ? { kind: \"youtube\", videoId: id } : null;\n  }\n  if (host !== \"youtube.com\") return null;\n  if (parsed.pathname === \"/watch\") {\n    const id = parsed.searchParams.get(\"v\");\n    return id && YOUTUBE_ID.test(id) ? { kind: \"youtube\", videoId: id } : null;\n  }\n  const path = parsed.pathname.match(/^\\/(?:shorts|embed)\\/([\\w-]{11})$/);\n  return path ? { kind: \"youtube\", videoId: path[1] } : null;\n}\n\ntype SpotifyType = \"track\" | \"playlist\" | \"album\" | \"episode\" | \"show\";\n\nfunction matchSpotify(parsed: URL): EmbedSource | null {\n  if (parsed.hostname !== \"open.spotify.com\") return null;\n  const match = parsed.pathname.match(\n    /^\\/(track|playlist|album|episode|show)\\/([A-Za-z0-9]+)$/,\n  );\n  if (!match) return null;\n  return { kind: \"spotify\", type: match[1] as SpotifyType, id: match[2] };\n}\n\n/** For UNTRUSTED text (a pasted line, a comment body). Null means \"not a URL we\n *  will touch\". */\nexport function classifyUrl(text: string): EmbedSource | null {\n  const trimmed = text.trim();\n  // Root- and protocol-relative paths (\"/x.png\", \"//host/x.png\") resolve\n  // against the reader's own origin, so following one sends their cookies\n  // wherever the pasted text points. Only an absolute http(s) URL qualifies.\n  if (!ABSOLUTE_URL.test(trimmed)) return null;\n\n  let parsed: URL;\n  try {\n    parsed = new URL(trimmed);\n  } catch {\n    return null;\n  }\n\n  const youtube = matchYouTube(parsed);\n  if (youtube) return youtube;\n\n  const spotify = matchSpotify(parsed);\n  if (spotify) return spotify;\n\n  // Path only, never the full string — a query string could otherwise pass\n  // an endpoint off as an image (e.g. \"/api/logout?next=.png\"), and an <img>\n  // fires that GET with whatever cookies the reader has.\n  const path = parsed.pathname;\n  if (/\\.(jpe?g|png|gif|webp|avif|svg)$/i.test(path)) return { kind: \"image\", url: trimmed };\n  if (/\\.(mp4|webm|mov)$/i.test(path)) return { kind: \"video\", url: trimmed };\n\n  return { kind: \"link\", url: trimmed };\n}\n",
      "type": "registry:lib",
      "target": "lib/embed.ts"
    },
    {
      "path": "registry/lib/link-preview.ts",
      "content": "import * as dns from \"node:dns\";\nimport * as http from \"node:http\";\nimport * as https from \"node:https\";\nimport { BlockList, isIP } from \"node:net\";\n\nexport interface LinkPreviewData {\n  title: string | null;\n  description: string | null;\n  image: string | null;\n  siteName: string | null;\n}\n\nexport class LinkPreviewError extends Error {\n  constructor(\n    message: string,\n    readonly status: 400 | 502,\n  ) {\n    super(message);\n    this.name = \"LinkPreviewError\";\n  }\n}\n\n// RFC 6890 special-use ranges, plus the ranges that matter for SSRF: loopback,\n// the RFC 1918 private blocks, and 169.254.0.0/16 — where AWS, GCP and Azure\n// all serve their instance-metadata endpoint.\nconst privateAddresses = new BlockList();\nprivateAddresses.addSubnet(\"0.0.0.0\", 8, \"ipv4\");\nprivateAddresses.addSubnet(\"10.0.0.0\", 8, \"ipv4\");\nprivateAddresses.addSubnet(\"100.64.0.0\", 10, \"ipv4\");\nprivateAddresses.addSubnet(\"127.0.0.0\", 8, \"ipv4\");\nprivateAddresses.addSubnet(\"169.254.0.0\", 16, \"ipv4\");\nprivateAddresses.addSubnet(\"172.16.0.0\", 12, \"ipv4\");\nprivateAddresses.addSubnet(\"192.0.0.0\", 24, \"ipv4\");\nprivateAddresses.addSubnet(\"192.0.2.0\", 24, \"ipv4\");\nprivateAddresses.addSubnet(\"192.168.0.0\", 16, \"ipv4\");\nprivateAddresses.addSubnet(\"198.18.0.0\", 15, \"ipv4\");\nprivateAddresses.addSubnet(\"198.51.100.0\", 24, \"ipv4\");\nprivateAddresses.addSubnet(\"203.0.113.0\", 24, \"ipv4\");\nprivateAddresses.addSubnet(\"224.0.0.0\", 4, \"ipv4\"); // multicast\nprivateAddresses.addSubnet(\"240.0.0.0\", 4, \"ipv4\"); // reserved, incl. broadcast\nprivateAddresses.addAddress(\"::\", \"ipv6\");\nprivateAddresses.addAddress(\"::1\", \"ipv6\");\nprivateAddresses.addSubnet(\"fc00::\", 7, \"ipv6\"); // unique local\nprivateAddresses.addSubnet(\"fe80::\", 10, \"ipv6\"); // link local\nprivateAddresses.addSubnet(\"ff00::\", 8, \"ipv6\"); // multicast\nprivateAddresses.addSubnet(\"2001:db8::\", 32, \"ipv6\"); // documentation\n// These prefixes each carry an arbitrary IPv4 address inside an IPv6 one\n// (NAT64, 6to4, Teredo, IPv4-compatible). Rather than unwrapping and\n// re-checking what they carry, the whole prefix is refused.\nprivateAddresses.addSubnet(\"64:ff9b::\", 96, \"ipv6\");\nprivateAddresses.addSubnet(\"2002::\", 16, \"ipv6\");\nprivateAddresses.addSubnet(\"2001::\", 32, \"ipv6\");\nprivateAddresses.addSubnet(\"::\", 96, \"ipv6\");\n\n/** True only for addresses on the public internet. */\nexport function isPublicAddress(address: string, family: 4 | 6): boolean {\n  if (isIP(address) === 0) return false;\n  // check() unwraps an IPv4-mapped IPv6 address (::ffff:a.b.c.d, dotted or\n  // hex) against the ipv4 subnets above before comparing.\n  return !privateAddresses.check(address, family === 4 ? \"ipv4\" : \"ipv6\");\n}\n\nconst MAX_URL_LENGTH = 2048;\n\n/** Throws LinkPreviewError(400) unless this is a URL the server may fetch. */\nexport function assertFetchableUrl(input: string): URL {\n  if (typeof input !== \"string\" || input.length === 0 || input.length > MAX_URL_LENGTH) {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n\n  let url: URL;\n  try {\n    url = new URL(input);\n  } catch {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n\n  if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n  if (url.username || url.password) {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n  // A non-default port would let this route be pointed at whatever else is\n  // listening on the target host.\n  if (url.port !== \"\") {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n  if (url.hostname.length === 0) {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n\n  // This is the ONLY check a literal IP gets: Node connects straight to an\n  // IP hostname without calling `lookup`, so guardedLookup below never sees\n  // it. The URL parser has already turned forms like \"2130706433\" or \"0x7f.1\"\n  // into dotted form by this point.\n  const literalIp = url.hostname.replace(/^\\[|\\]$/g, \"\");\n  const ipFamily = isIP(literalIp);\n  if (ipFamily !== 0 && !isPublicAddress(literalIp, ipFamily === 6 ? 6 : 4)) {\n    throw new LinkPreviewError(\"URL not allowed\", 400);\n  }\n\n  return url;\n}\n\n// Validating inside the socket's own lookup means the address that was\n// checked is the address that is connected to, so a hostname cannot pass the\n// check and then re-resolve to an internal one (DNS rebinding). Hostnames\n// only: Node skips `lookup` for a literal IP, which assertFetchableUrl covers.\nexport function guardedLookup(\n  hostname: string,\n  options: dns.LookupOptions,\n  callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void,\n): void {\n  dns.lookup(hostname, { ...options, all: true }, (err, addresses) => {\n    if (err) {\n      callback(err, \"\");\n      return;\n    }\n    const blocked = addresses.find(\n      (candidate) => !isPublicAddress(candidate.address, candidate.family === 6 ? 6 : 4),\n    );\n    if (blocked || addresses.length === 0) {\n      callback(new LinkPreviewError(\"URL not allowed\", 400), \"\");\n      return;\n    }\n    if (options.all) {\n      callback(null, addresses);\n    } else {\n      callback(null, addresses[0].address, addresses[0].family);\n    }\n  });\n}\n\nexport type RequestPage = (\n  url: URL,\n) => Promise<{ status: number; headers: Record<string, string | string[] | undefined>; body: string }>;\n\nconst TIMEOUT_MS = 5000;\nconst MAX_BODY_BYTES = 512 * 1024;\n\nconst defaultRequest: RequestPage = (url) =>\n  new Promise((resolve, reject) => {\n    let settled = false;\n    const settle = (run: () => void) => {\n      if (settled) return;\n      settled = true;\n      clearTimeout(deadline);\n      run();\n    };\n\n    const transport = url.protocol === \"https:\" ? https : http;\n    const req = transport.request(\n      url,\n      {\n        method: \"GET\",\n        headers: {\n          accept: \"text/html,application/xhtml+xml\",\n          \"user-agent\": \"link-preview/1.0\",\n          \"accept-encoding\": \"identity\",\n        },\n        lookup: guardedLookup,\n        timeout: TIMEOUT_MS,\n      },\n      (res) => {\n        const status = res.statusCode ?? 0;\n        const headers = res.headers as Record<string, string | string[] | undefined>;\n        let received = 0;\n        let body = \"\";\n        res.setEncoding(\"utf8\");\n        res.on(\"data\", (chunk: string) => {\n          received += Buffer.byteLength(chunk, \"utf8\");\n          // A preview's tags are in the head, so the rest of the body is\n          // never needed — and an unbounded read is a free download on\n          // someone else's bill.\n          if (received > MAX_BODY_BYTES) {\n            res.destroy();\n            settle(() => resolve({ status, headers, body }));\n            return;\n          }\n          body += chunk;\n        });\n        res.on(\"end\", () => settle(() => resolve({ status, headers, body })));\n        res.on(\"error\", () => settle(() => reject(new LinkPreviewError(\"Could not fetch the page\", 502))));\n      },\n    );\n\n    req.on(\"timeout\", () => req.destroy(new LinkPreviewError(\"Could not fetch the page\", 502)));\n    // The `timeout` option only measures idle time, so a server dripping a\n    // byte every few seconds would never trip it. This one is the whole budget.\n    const deadline = setTimeout(\n      () => req.destroy(new LinkPreviewError(\"Could not fetch the page\", 502)),\n      TIMEOUT_MS,\n    );\n    req.on(\"error\", (err) =>\n      settle(() => reject(err instanceof LinkPreviewError ? err : new LinkPreviewError(\"Could not fetch the page\", 502))),\n    );\n    req.end();\n  });\n\nconst ENTITIES: Record<string, string> = {\n  amp: \"&\",\n  lt: \"<\",\n  gt: \">\",\n  quot: '\"',\n  apos: \"'\",\n  nbsp: \" \",\n};\n\nfunction decodeEntities(text: string): string {\n  return text.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, entity: string) => {\n    if (entity[0] === \"#\") {\n      const codePoint =\n        entity[1]?.toLowerCase() === \"x\" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);\n      return Number.isNaN(codePoint) ? whole : String.fromCodePoint(codePoint);\n    }\n    return ENTITIES[entity.toLowerCase()] ?? whole;\n  });\n}\n\nfunction normalize(raw: string | undefined, max = Infinity): string | null {\n  if (raw === undefined) return null;\n  const text = decodeEntities(raw).replace(/\\s+/g, \" \").trim();\n  if (text === \"\") return null;\n  return text.length > max ? text.slice(0, max) : text;\n}\n\nfunction resolveImage(raw: string | undefined, pageUrl: URL): string | null {\n  if (!raw) return null;\n  try {\n    const resolved = new URL(raw, pageUrl);\n    return resolved.protocol === \"http:\" || resolved.protocol === \"https:\" ? resolved.href : null;\n  } catch {\n    return null;\n  }\n}\n\nconst MAX_META_TAG_LENGTH = 8192;\n\n// The page is hostile input, so nothing here may backtrack: an attribute name\n// has to follow whitespace (one way in per name, not one per letter), a tag\n// longer than any real one is skipped, and the title is found with indexOf.\nfunction collectMetaTags(html: string): Record<string, string>[] {\n  const tags: Record<string, string>[] = [];\n  const tagPattern = /<meta\\b[^>]*>/gi;\n  const attrPattern = /\\s([a-zA-Z-]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/g;\n\n  let tagMatch: RegExpExecArray | null;\n  while ((tagMatch = tagPattern.exec(html))) {\n    if (tagMatch[0].length > MAX_META_TAG_LENGTH) continue;\n    const attrs: Record<string, string> = {};\n    let attrMatch: RegExpExecArray | null;\n    attrPattern.lastIndex = 0;\n    while ((attrMatch = attrPattern.exec(tagMatch[0]))) {\n      attrs[attrMatch[1].toLowerCase()] = attrMatch[2] ?? attrMatch[3];\n    }\n    tags.push(attrs);\n  }\n  return tags;\n}\n\nfunction findTitle(html: string): string | undefined {\n  const open = html.search(/<title[\\s>]/i);\n  if (open === -1) return undefined;\n  const start = html.indexOf(\">\", open);\n  if (start === -1) return undefined;\n  const lower = html.slice(start + 1, start + 1 + 2048).toLowerCase();\n  const end = lower.indexOf(\"</title\");\n  return end === -1 ? undefined : html.slice(start + 1, start + 1 + end);\n}\n\nexport function extractMetadata(html: string, pageUrl: URL): LinkPreviewData {\n  const tags = collectMetaTags(html);\n  const metaContent = (name: string): string | undefined =>\n    tags.find((tag) => tag.property === name || tag.name === name)?.content;\n\n  const rawTitle = metaContent(\"og:title\") ?? findTitle(html);\n  const rawDescription = metaContent(\"og:description\") ?? metaContent(\"description\");\n  const rawImage = metaContent(\"og:image\") ?? metaContent(\"twitter:image\");\n  const rawSiteName = metaContent(\"og:site_name\");\n\n  return {\n    title: normalize(rawTitle, 300),\n    description: normalize(rawDescription, 500),\n    image: resolveImage(rawImage, pageUrl),\n    siteName: normalize(rawSiteName),\n  };\n}\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\nconst MAX_REDIRECTS = 3;\n\nexport async function fetchLinkPreview(\n  input: string,\n  options?: { request?: RequestPage },\n): Promise<LinkPreviewData> {\n  const request = options?.request ?? defaultRequest;\n  let url = assertFetchableUrl(input);\n  let redirects = 0;\n  let response: Awaited<ReturnType<RequestPage>>;\n\n  for (;;) {\n    try {\n      response = await request(url);\n    } catch (error) {\n      throw error instanceof LinkPreviewError ? error : new LinkPreviewError(\"Could not fetch the page\", 502);\n    }\n\n    if (!REDIRECT_STATUSES.has(response.status)) break;\n\n    redirects += 1;\n    if (redirects > MAX_REDIRECTS) throw new LinkPreviewError(\"Too many redirects\", 502);\n\n    const location = response.headers.location;\n    const target = Array.isArray(location) ? location[0] : location;\n    if (!target) throw new LinkPreviewError(\"Could not fetch the page\", 502);\n\n    // Every hop is a new URL from an untrusted server, so every hop is\n    // checked like the first.\n    url = assertFetchableUrl(new URL(target, url).href);\n  }\n\n  if (response.status < 200 || response.status >= 300) {\n    throw new LinkPreviewError(\"Could not fetch the page\", 502);\n  }\n\n  const contentType = response.headers[\"content-type\"];\n  const contentTypeValue = Array.isArray(contentType) ? contentType[0] : contentType;\n  const isHtml =\n    !!contentTypeValue &&\n    (contentTypeValue.includes(\"text/html\") || contentTypeValue.includes(\"application/xhtml+xml\"));\n  if (!isHtml) {\n    return { title: null, description: null, image: null, siteName: null };\n  }\n\n  return extractMetadata(response.body, url);\n}\n",
      "type": "registry:lib",
      "target": "lib/link-preview.ts"
    },
    {
      "path": "registry/api/link-preview/route.ts",
      "content": "import { fetchLinkPreview, LinkPreviewError } from \"@/lib/link-preview\";\n\nexport const runtime = \"nodejs\";\n\nexport async function GET(request: Request) {\n  const url = new URL(request.url).searchParams.get(\"url\");\n  if (!url) {\n    return Response.json({ error: \"Missing url\" }, { status: 400 });\n  }\n\n  try {\n    const data = await fetchLinkPreview(url);\n    // Only the extracted fields ever leave this route, never the page body —\n    // so it can't be used as a general-purpose proxy.\n    return Response.json(data, {\n      headers: { \"cache-control\": \"public, max-age=86400, s-maxage=86400\" },\n    });\n  } catch (error) {\n    if (error instanceof LinkPreviewError) {\n      return Response.json({ error: error.message }, { status: error.status });\n    }\n    return Response.json({ error: \"Could not fetch the page\" }, { status: 502 });\n  }\n}\n\n// Rate limiting is deployment-specific (a CDN, middleware, an API gateway)\n// and is left to the consumer.\n",
      "type": "registry:file",
      "target": "app/api/link-preview/route.ts"
    }
  ],
  "docs": "Docs & live playground: https://www.deltacomponents.dev/docs/embed.",
  "categories": [
    "components"
  ],
  "type": "registry:ui"
}
