getRegistryIndex() function in shadcn-ui/ui source code.

May 21, 2024 (7mo ago)

This article explains how getRegistryIndex() function in shadcn-ui/ui source code works. You will find this function in shadcn-ui/ui source code related to CLI package.

getRegistryIndex:

getRegistryIndex function is called at Line number #68 in add.ts and this is imported at the top of add.ts from registry/index.ts

getRegistryIndex calls another function named fetchRegistry located in the same file registry/index.ts

fetchRegistry:

async function fetchRegistry(paths: string\[\]) {
  try {
    const results = await Promise.all(
    paths.map(async (path) => {
        const response = await fetch(\`${baseUrl}/registry/${path}\`, {
          agent,
        })
        return await response.json()
      })
    )
    return results
  } catch (error) {
    console.log(error)
    throw new Error(\`Failed to fetch registry from ${baseUrl}.\`)
  }
}

This function accepts a parameter named paths which is an array and wraps paths.map in a Promise.all and makes a fetch call inside the map definition for each path.

You might be wondering what the baseUrl contains.

At the top of the file, you will find the below code snippet at this line

const baseUrl = process.env.COMPONENTS_REGISTRY_URL ?? "https://ui.shadcn.com"

Since getRegistryIndex calls fetchRegistry with [“index.json”], the fetch is made to an endpoint that looks like https://ui.shadcn.com/registry/index.json

References:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts#L68
  2. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L139
  3. https://ui.shadcn.com/registry/index.json