Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

9.4 KB
Raw Blame
import { exec } from "child_process"
import { promises as fs } from "fs"
import path from "path"
import { rimraf } from "rimraf"
import { Registry } from "shadcn/schema"

import { siteConfig } from "../config/site"
import {
  assertNoMissingExampleFiles,
  syncExampleRegistryDependencies,
} from "./sync-example-registry-dependencies.mts"

async function loadRegistry(): Promise<Registry> {
  const { registry } = await import("../registry/index.ts")
  return registry
}

async function buildRegistryIndex(registry: Registry) {
  let index = `/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-explicit-any */
// @ts-nocheck
// This file is autogenerated by scripts/build-registry.ts
// Do not edit this file directly.
import * as React from "react"

export const Index: Record<string, any> = {`
  for (const item of registry.items) {
    const resolveFiles = item.files?.map((file) => `registry/${file.path}`)
    if (!resolveFiles) {
      continue
    }

    const componentPath = item.files?.[0]?.path
      ? `@/registry/${item.files[0].path}`
      : ""

    index += `
  "${item.name}": {
    name: "${item.name}",
    description: "${item.description ?? ""}",
    type: "${item.type}",
    registryDependencies: ${JSON.stringify(item.registryDependencies)},
    files: [${item.files?.map((file) => {
      const filePath = `registry/${typeof file === "string" ? file : file.path}`
      const resolvedFilePath = path.resolve(filePath)
      return typeof file === "string"
        ? `"${resolvedFilePath}"`
        : `{
      path: "${filePath}",
      type: "${file.type}",
      target: "${file.target ?? ""}"
    }`
    })}],
    component: ${
      componentPath
        ? `React.lazy(async () => {
      const mod = await import("${componentPath}")
      const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') ?? item.name
      return { default: mod.default ?? mod[exportName] }
    })`
        : "null"
    },
    meta: ${JSON.stringify(item.meta)},
  },`
  }

  index += `
  }`

  // Write style index.
  rimraf.sync(path.join(process.cwd(), "registry/__index__.tsx"))
  await fs.writeFile(path.join(process.cwd(), "registry/__index__.tsx"), index)
}

async function buildRegistryJsonFile(registry: Registry) {
  // 1. Fix the path for registry items.
  const fixedRegistry = {
    ...registry,
    items: registry.items.map((item) => {
      const files = item.files?.map((file) => {
        return {
          ...file,
          path: `registry/${file.path}`,
        }
      })

      return {
        ...item,
        files,
      }
    }),
  }

  // 2. Write the content of the registry to `registry.json`
  rimraf.sync(path.join(process.cwd(), `registry.json`))
  await fs.writeFile(
    path.join(process.cwd(), `registry.json`),
    JSON.stringify(fixedRegistry, null, 2)
  )

  // 3. Copy the registry.json to the www/public/r directory.
  await fs.cp(
    path.join(process.cwd(), "registry.json"),
    path.join(process.cwd(), "../www/public/r/registry.json"),
    { recursive: true }
  )

  // 3. Copy the registry.json to the www/public/r directory.
  await fs.cp(
    path.join(process.cwd(), "registry.json"),
    path.join(process.cwd(), "../www/public/registry.json"),
    { recursive: true }
  )
}

type RegistryItem = Registry["items"][number]

type FileEntry = string | { path: string; type?: string; target?: string }

async function readRegistryFilesContents(item: RegistryItem): Promise<string> {
  if (!item.files?.length) return ""

  const paths = item.files
    .map((f: FileEntry) => (typeof f === "string" ? f : f?.path))
    .filter(Boolean)
    .sort() as string[]

  // Read all files in parallel
  const contents = await Promise.all(
    paths.map(async (filePath) => {
      try {
        const content = await fs.readFile(
          path.join(process.cwd(), "registry", filePath),
          "utf8"
        )
        return `--- file: ${filePath} ---\n${content.endsWith("\n") ? content : content + "\n"}`
      } catch {
        return null // Skip missing files
      }
    })
  )

  // Join non-null contents with blank lines between them
  return contents.filter(Boolean).join("\n")
}

function getComponentExamples(registry: Registry) {
  const examplesByComponent = new Map<string, string[]>()

  registry.items
    .filter((item) => item.type === "registry:example")
    .forEach((example) => {
      example.registryDependencies?.forEach((dep) => {
        const componentName = dep.split("/").pop()
        if (componentName) {
          if (!examplesByComponent.has(componentName)) {
            examplesByComponent.set(componentName, [])
          }
          examplesByComponent.get(componentName)!.push(example.name)
        }
      })
    })

  return examplesByComponent
}

async function generateLlmsContent(registry: Registry) {
  const components = registry.items
    .filter((item) => item.type === "registry:ui")
    .sort((a, b) => a.name.localeCompare(b.name))
    .map((component) => {
      const title = component.title || component.name
      const description = component.description || `The ${title} component.`
      return `- [${title}](${siteConfig.url}/docs/components/${component.name}): ${description}`
    })

  const exampleSet = new Set<string>()
  const examplesList = registry.items
    .filter((item) => item.type === "registry:example")
    .filter((example) => {
      if (exampleSet.has(example.name)) return false
      exampleSet.add(example.name)
      return true
    })
    .map((example) => {
      const title = example.title || example.name
      const firstFile = example.files?.[0]?.path || ""
      const url = firstFile
        ? `${siteConfig.links.github}/blob/main/${firstFile}`
        : siteConfig.links.github
      return `- [${title}](${url}): Example usage`
    })

  return [
    `# ${siteConfig.name}`,
    "",
    `> ${siteConfig.description}`,
    "",
    "This file provides LLM-friendly entry points to documentation and examples.",
    "",
    "## Components",
    "",
    ...components,
    "",
    "## Examples",
    "",
    ...examplesList,
    "",
    "## Optional",
    "",
    `- [Repository](${siteConfig.links.github}): Source code and issues`,
    `- [Sitemap](${siteConfig.url}/sitemap.xml): Indexable pages`,
  ].join("\n")
}

async function generateLlmsFullContent(
  registry: Registry,
  examplesByComponent: Map<string, string[]>
) {
  const components = registry.items
    .filter((item) => item.type === "registry:ui")
    .sort((a, b) => a.name.localeCompare(b.name))

  const componentContents = await Promise.all(
    components.map(async (component) => {
      const title = component.title || component.name
      const description = component.description || `The ${title} component.`

      let content = [
        `===== COMPONENT: ${component.name} =====`,
        `Title: ${title}`,
        `Description: ${description}`,
        "",
        await readRegistryFilesContents(component),
      ].join("\n")

      // Add examples for this component
      const relatedExamples = examplesByComponent.get(component.name) || []
      for (const exampleName of relatedExamples) {
        const example = registry.items.find((e) => e.name === exampleName)
        if (example) {
          const exTitle = example.title || example.name
          content += [
            "",
            "",
            `===== EXAMPLE: ${exampleName} =====`,
            `Title: ${exTitle}`,
            "",
            await readRegistryFilesContents(example),
          ].join("\n")
        }
      }

      return content
    })
  )

  return componentContents.join("\n\n\n")
}

async function buildLlmsFiles(registry: Registry) {
  const examplesByComponent = getComponentExamples(registry)

  const [minContent, fullContent] = await Promise.all([
    generateLlmsContent(registry),
    generateLlmsFullContent(registry, examplesByComponent),
  ])

  const publicDir = path.join(process.cwd(), "public")
  await fs.mkdir(publicDir, { recursive: true })

  await Promise.all([
    fs.writeFile(path.join(publicDir, "llms.txt"), minContent, "utf8"),
    fs.writeFile(path.join(publicDir, "llms-full.txt"), fullContent, "utf8"),
  ])
}

async function buildRegistry() {
  return new Promise((resolve, reject) => {
    const process = exec(`pnpm shadcn:build`)

    process.on("exit", (code) => {
      if (code === 0) {
        resolve(undefined)
      } else {
        reject(new Error(`Process exited with code ${code}`))
      }
    })
  })
}

try {
  console.log("πŸ”Ž Syncing registry example dependencies...")
  const syncIssues = await syncExampleRegistryDependencies({ mode: "fix" })
  assertNoMissingExampleFiles(syncIssues)
  console.log("βœ… Registry example dependencies synced")

  const registry = await loadRegistry()

  console.log("��️ Building registry/__index__.tsx...")
  await buildRegistryIndex(registry)
  console.log("βœ… Registry index built successfully")

  console.log("πŸ’… Building registry.json...")
  await buildRegistryJsonFile(registry)
  console.log("βœ… Registry JSON file built successfully")

  console.log("🧠 Building llms files...")
  await buildLlmsFiles(registry)
  console.log("βœ… llms-min.txt and llms.txt built successfully")

  console.log("πŸ—οΈ Building registry...")
  await buildRegistry()
  console.log("βœ… Registry build completed")
} catch (error) {
  console.error("❌ Build failed with error:")
  console.error(error)
  if (error instanceof Error) {
    console.error("Error stack:", error.stack)
  }
  process.exit(1)
}