bejamas 0.2.2 → 0.2.3

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["errors: Record<string, boolean>","fs","ERRORS.MISSING_DIR_OR_EMPTY_PROJECT","context: RegistryContext","template: keyof typeof TEMPLATES","projectName: string","fs","TEMPLATE_TAR_SUBPATH: Record<keyof typeof TEMPLATES, string>","headers: Record<string, string>","DEFAULT_REGISTRY_URL","ERRORS.MISSING_DIR_OR_EMPTY_PROJECT","baseUrl: string","paths: Record<string, string[] | string>","probe: string | null","mapped: string","uiAbs: string | null","cssAbs: string | null","outResolved: string | null","relative","err: any","FIELD_LABELS: Record<string, string>","missingRequired: string[]","missingRecommended: string[]","status: \"complete\" | \"incomplete\" | \"missing\"","probe: string | null","mapped: string","uiAbs: string | null","cssAbs: string | null","uiRoot: string","join","extname","results: ComponentDocStatus[]","checkResult: CheckResult","err: any","path","dirname","path","result: ReorganizeResult","forwarded: string[]","addIndex","rest","forwarded","files: string[]","path","currentSubfolder: string | null","result: ParsedOutput","allPaths: string[]","autoFlags: string[]","args: string[]"],"sources":["../src/utils/errors.ts","../src/preflights/preflight-init.ts","../src/registry/context.ts","../src/utils/get-package-manager.ts","../src/registry/errors.ts","../src/utils/handle-error.ts","../src/utils/create-project.ts","../src/commands/init.ts","../src/utils/tsconfig-utils.ts","../src/commands/docs.ts","../src/commands/docs-check.ts","../src/utils/astro-imports.ts","../src/utils/reorganize-components.ts","../src/commands/add.ts","../src/index.ts"],"sourcesContent":["export const MISSING_DIR_OR_EMPTY_PROJECT = \"1\";\nexport const EXISTING_CONFIG = \"2\";\nexport const MISSING_CONFIG = \"3\";\nexport const FAILED_CONFIG_READ = \"4\";\nexport const TAILWIND_NOT_CONFIGURED = \"5\";\nexport const IMPORT_ALIAS_MISSING = \"6\";\nexport const UNSUPPORTED_FRAMEWORK = \"7\";\nexport const COMPONENT_URL_NOT_FOUND = \"8\";\nexport const COMPONENT_URL_UNAUTHORIZED = \"9\";\nexport const COMPONENT_URL_FORBIDDEN = \"10\";\nexport const COMPONENT_URL_BAD_REQUEST = \"11\";\nexport const COMPONENT_URL_INTERNAL_SERVER_ERROR = \"12\";\nexport const BUILD_MISSING_REGISTRY_FILE = \"13\";\n","import path from \"path\";\nimport { initOptionsSchema } from \"@/src/commands/init\";\nimport * as ERRORS from \"@/src/utils/errors\";\nimport fs from \"fs-extra\";\nimport { z } from \"zod\";\n\nexport async function preFlightInit(\n options: z.infer<typeof initOptionsSchema>,\n) {\n const errors: Record<string, boolean> = {};\n\n // Ensure target directory exists.\n // Check for empty project. We assume if no package.json exists, the project is empty.\n if (\n !fs.existsSync(options.cwd) ||\n !fs.existsSync(path.resolve(options.cwd, \"package.json\"))\n ) {\n errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true;\n return {\n errors,\n projectInfo: null,\n };\n }\n\n return {\n errors,\n projectInfo: null,\n };\n}\n","interface RegistryContext {\n headers: Record<string, Record<string, string>>;\n}\n\nlet context: RegistryContext = {\n headers: {},\n};\n\nexport function setRegistryHeaders(\n headers: Record<string, Record<string, string>>,\n) {\n // Merge new headers with existing ones to preserve headers for nested dependencies\n context.headers = { ...context.headers, ...headers };\n}\n\nexport function getRegistryHeadersFromContext(\n url: string,\n): Record<string, string> {\n return context.headers[url] || {};\n}\n\nexport function clearRegistryContext() {\n context.headers = {};\n}\n","import { detect } from \"@antfu/ni\";\n\nexport async function getPackageManager(\n targetDir: string,\n { withFallback }: { withFallback?: boolean } = {\n withFallback: false,\n },\n): Promise<\"yarn\" | \"pnpm\" | \"bun\" | \"npm\" | \"deno\"> {\n const packageManager = await detect({ programmatic: true, cwd: targetDir });\n\n if (packageManager === \"yarn@berry\") return \"yarn\";\n if (packageManager === \"pnpm@6\") return \"pnpm\";\n if (packageManager === \"bun\") return \"bun\";\n if (packageManager === \"deno\") return \"deno\";\n if (!withFallback) {\n return packageManager ?? \"npm\";\n }\n\n // Fallback to user agent if not detected.\n const userAgent = process.env.npm_config_user_agent || \"\";\n\n if (userAgent.startsWith(\"yarn\")) {\n return \"yarn\";\n }\n\n if (userAgent.startsWith(\"pnpm\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"bun\")) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport async function getPackageRunner(cwd: string) {\n const packageManager = await getPackageManager(cwd);\n\n if (packageManager === \"pnpm\") return \"pnpm dlx\";\n\n if (packageManager === \"bun\") return \"bunx\";\n\n return \"npx\";\n}\n","import { z } from \"zod\";\n\n// Error codes for programmatic error handling\nexport const RegistryErrorCode = {\n // Network errors\n NETWORK_ERROR: \"NETWORK_ERROR\",\n NOT_FOUND: \"NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n FETCH_ERROR: \"FETCH_ERROR\",\n\n // Configuration errors\n NOT_CONFIGURED: \"NOT_CONFIGURED\",\n INVALID_CONFIG: \"INVALID_CONFIG\",\n MISSING_ENV_VARS: \"MISSING_ENV_VARS\",\n\n // File system errors\n LOCAL_FILE_ERROR: \"LOCAL_FILE_ERROR\",\n\n // Parsing errors\n PARSE_ERROR: \"PARSE_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n\n // Generic errors\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\nexport type RegistryErrorCode =\n (typeof RegistryErrorCode)[keyof typeof RegistryErrorCode];\n\nexport class RegistryError extends Error {\n public readonly code: RegistryErrorCode;\n public readonly statusCode?: number;\n public readonly context?: Record<string, unknown>;\n public readonly suggestion?: string;\n public readonly timestamp: Date;\n public readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n code?: RegistryErrorCode;\n statusCode?: number;\n cause?: unknown;\n context?: Record<string, unknown>;\n suggestion?: string;\n } = {},\n ) {\n super(message);\n this.name = \"RegistryError\";\n this.code = options.code || RegistryErrorCode.UNKNOWN_ERROR;\n this.statusCode = options.statusCode;\n this.cause = options.cause;\n this.context = options.context;\n this.suggestion = options.suggestion;\n this.timestamp = new Date();\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n context: this.context,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n stack: this.stack,\n };\n }\n}\n\nexport class RegistryNotFoundError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `The item at ${url} was not found. It may not exist at the registry.`;\n\n super(message, {\n code: RegistryErrorCode.NOT_FOUND,\n statusCode: 404,\n cause,\n context: { url },\n suggestion:\n \"Check if the item name is correct and the registry URL is accessible.\",\n });\n this.name = \"RegistryNotFoundError\";\n }\n}\n\nexport class RegistryUnauthorizedError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`;\n\n super(message, {\n code: RegistryErrorCode.UNAUTHORIZED,\n statusCode: 401,\n cause,\n context: { url },\n suggestion:\n \"Check your authentication credentials and environment variables.\",\n });\n this.name = \"RegistryUnauthorizedError\";\n }\n}\n\nexport class RegistryForbiddenError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`;\n\n super(message, {\n code: RegistryErrorCode.FORBIDDEN,\n statusCode: 403,\n cause,\n context: { url },\n suggestion:\n \"Check your authentication credentials and environment variables.\",\n });\n this.name = \"RegistryForbiddenError\";\n }\n}\n\nexport class RegistryFetchError extends RegistryError {\n constructor(\n public readonly url: string,\n statusCode?: number,\n public readonly responseBody?: string,\n cause?: unknown,\n ) {\n // Use the error detail from the server if available\n const baseMessage = statusCode\n ? `Failed to fetch from registry (${statusCode}): ${url}`\n : `Failed to fetch from registry: ${url}`;\n\n const message =\n typeof cause === \"string\" && cause\n ? `${baseMessage} - ${cause}`\n : baseMessage;\n\n let suggestion = \"Check your network connection and try again.\";\n if (statusCode === 404) {\n suggestion =\n \"The requested resource was not found. Check the URL or item name.\";\n } else if (statusCode === 500) {\n suggestion = \"The registry server encountered an error. Try again later.\";\n } else if (statusCode && statusCode >= 400 && statusCode < 500) {\n suggestion = \"There was a client error. Check your request parameters.\";\n }\n\n super(message, {\n code: RegistryErrorCode.FETCH_ERROR,\n statusCode,\n cause,\n context: { url, responseBody },\n suggestion,\n });\n this.name = \"RegistryFetchError\";\n }\n}\n\nexport class RegistryNotConfiguredError extends RegistryError {\n constructor(public readonly registryName: string | null) {\n const message = registryName\n ? `Unknown registry \"${registryName}\". Make sure it is defined in components.json as follows:\n{\n \"registries\": {\n \"${registryName}\": \"[URL_TO_REGISTRY]\"\n }\n}`\n : `Unknown registry. Make sure it is defined in components.json under \"registries\".`;\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { registryName },\n suggestion:\n \"Add the registry configuration to your components.json file. Consult the registry documentation for the correct format.\",\n });\n this.name = \"RegistryNotConfiguredError\";\n }\n}\n\nexport class RegistryLocalFileError extends RegistryError {\n constructor(\n public readonly filePath: string,\n cause?: unknown,\n ) {\n super(`Failed to read local registry file: ${filePath}`, {\n code: RegistryErrorCode.LOCAL_FILE_ERROR,\n cause,\n context: { filePath },\n suggestion: \"Check if the file exists and you have read permissions.\",\n });\n this.name = \"RegistryLocalFileError\";\n }\n}\n\nexport class RegistryParseError extends RegistryError {\n public readonly parseError: unknown;\n\n constructor(\n public readonly item: string,\n parseError: unknown,\n ) {\n let message = `Failed to parse registry item: ${item}`;\n\n if (parseError instanceof z.ZodError) {\n message = `Failed to parse registry item: ${item}\\n${parseError.errors\n .map((e) => ` - ${e.path.join(\".\")}: ${e.message}`)\n .join(\"\\n\")}`;\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { item },\n suggestion:\n \"The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object. See https://ui.shadcn.com/schema/registry-item.json.\",\n });\n\n this.parseError = parseError;\n this.name = \"RegistryParseError\";\n }\n}\n\nexport class RegistryMissingEnvironmentVariablesError extends RegistryError {\n constructor(\n public readonly registryName: string,\n public readonly missingVars: string[],\n ) {\n const message =\n `Registry \"${registryName}\" requires the following environment variables:\\n\\n` +\n missingVars.map((v) => ` • ${v}`).join(\"\\n\");\n\n super(message, {\n code: RegistryErrorCode.MISSING_ENV_VARS,\n context: { registryName, missingVars },\n suggestion:\n \"Set the required environment variables to your .env or .env.local file.\",\n });\n this.name = \"RegistryMissingEnvironmentVariablesError\";\n }\n}\n\nexport class RegistryInvalidNamespaceError extends RegistryError {\n constructor(public readonly name: string) {\n const message = `Invalid registry namespace: \"${name}\". Registry names must start with @ (e.g., @shadcn, @v0).`;\n\n super(message, {\n code: RegistryErrorCode.VALIDATION_ERROR,\n context: { name },\n suggestion:\n \"Use a valid registry name starting with @ or provide a direct URL to the registry.\",\n });\n this.name = \"RegistryInvalidNamespaceError\";\n }\n}\n\nexport class ConfigMissingError extends RegistryError {\n constructor(public readonly cwd: string) {\n const message = `No components.json found in ${cwd} or parent directories.`;\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { cwd },\n suggestion:\n \"Run 'npx shadcn@latest init' to create a components.json file, or check that you're in the correct directory.\",\n });\n this.name = \"ConfigMissingError\";\n }\n}\n\nexport class ConfigParseError extends RegistryError {\n constructor(\n public readonly cwd: string,\n parseError: unknown,\n ) {\n let message = `Invalid components.json configuration in ${cwd}.`;\n\n if (parseError instanceof z.ZodError) {\n message = `Invalid components.json configuration in ${cwd}:\\n${parseError.errors\n .map((e) => ` - ${e.path.join(\".\")}: ${e.message}`)\n .join(\"\\n\")}`;\n }\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n cause: parseError,\n context: { cwd },\n suggestion:\n \"Check your components.json file for syntax errors or invalid configuration. Run 'npx shadcn@latest init' to regenerate a valid configuration.\",\n });\n this.name = \"ConfigParseError\";\n }\n}\n","import { RegistryError } from \"@/src/registry/errors\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { z } from \"zod\";\n\nexport function handleError(error: unknown) {\n logger.break();\n logger.error(\n `Something went wrong. Please check the error below for more details.`,\n );\n logger.error(\n `If the problem persists, please open an issue on GitHub: https://github.com/bejamas/ui/issues`,\n );\n logger.error(\"\");\n if (typeof error === \"string\") {\n logger.error(error);\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof RegistryError) {\n if (error.message) {\n logger.error(error.cause ? \"Error:\" : \"Message:\");\n logger.error(error.message);\n }\n\n if (error.cause) {\n logger.error(\"\\nMessage:\");\n logger.error(error.cause);\n }\n\n if (error.suggestion) {\n logger.error(\"\\nSuggestion:\");\n logger.error(error.suggestion);\n }\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof z.ZodError) {\n logger.error(\"Validation failed:\");\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${highlighter.info(key)}: ${value}`);\n }\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof Error) {\n logger.error(error.message);\n logger.break();\n process.exit(1);\n }\n\n logger.break();\n process.exit(1);\n}\n","import os from \"os\";\nimport path from \"path\";\nimport dotenv from \"dotenv\";\nimport { initOptionsSchema } from \"@/src/commands/init\";\nimport { getPackageManager } from \"@/src/utils/get-package-manager\";\nimport { handleError } from \"@/src/utils/handle-error\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { spinner } from \"@/src/utils/spinner\";\nimport { execa } from \"execa\";\nimport fs from \"fs-extra\";\nimport prompts from \"prompts\";\nimport { z } from \"zod\";\n\nexport const TEMPLATES = {\n astro: \"astro\",\n \"astro-monorepo\": \"astro-monorepo\",\n \"astro-with-component-docs-monorepo\": \"astro-with-component-docs-monorepo\",\n} as const;\n\nconst MONOREPO_TEMPLATE_URL =\n \"https://codeload.github.com/bejamas/ui/tar.gz/main\";\n\nexport async function createProject(\n options: Pick<\n z.infer<typeof initOptionsSchema>,\n \"cwd\" | \"force\" | \"srcDir\" | \"components\" | \"template\"\n >,\n) {\n options = {\n srcDir: false,\n ...options,\n };\n\n let template: keyof typeof TEMPLATES =\n options.template && TEMPLATES[options.template as keyof typeof TEMPLATES]\n ? (options.template as keyof typeof TEMPLATES)\n : \"astro\";\n\n let projectName: string = \"my-app\";\n\n const isRemoteComponent =\n options.components?.length === 1 &&\n !!options.components[0].match(/\\/chat\\/b\\//);\n\n if (!options.force) {\n const { type, name } = await prompts([\n {\n type: options.template || isRemoteComponent ? null : \"select\",\n name: \"type\",\n message: `The path ${highlighter.info(\n options.cwd,\n )} does not contain a package.json file.\\n Would you like to start a new project?`,\n choices: [\n { title: \"Astro\", value: \"astro\" },\n { title: \"Astro (Monorepo)\", value: \"astro-monorepo\" },\n {\n title: \"Astro with Component Docs (Monorepo)\",\n value: \"astro-with-component-docs-monorepo\",\n },\n ],\n initial: 0,\n },\n {\n type: \"text\",\n name: \"name\",\n message: \"What is your project named?\",\n initial: (_prev: any, values: any) => {\n const selectedTemplate: string =\n (options.template &&\n TEMPLATES[options.template as keyof typeof TEMPLATES] &&\n options.template) ||\n values.type ||\n template;\n return selectedTemplate?.endsWith(\"monorepo\")\n ? \"my-monorepo\"\n : \"my-app\";\n },\n format: (value: string) => value.trim(),\n validate: (value: string) =>\n value.length > 128\n ? `Name should be less than 128 characters.`\n : true,\n },\n ]);\n\n template = type ?? template;\n projectName = name;\n }\n\n const packageManager = await getPackageManager(options.cwd, {\n withFallback: true,\n });\n\n const projectPath = `${options.cwd}/${projectName}`;\n\n // Check if path is writable.\n try {\n await fs.access(options.cwd, fs.constants.W_OK);\n } catch (error) {\n logger.break();\n logger.error(`The path ${highlighter.info(options.cwd)} is not writable.`);\n logger.error(\n `It is likely you do not have write permissions for this folder or the path ${highlighter.info(\n options.cwd,\n )} does not exist.`,\n );\n logger.break();\n process.exit(1);\n }\n\n if (fs.existsSync(path.resolve(options.cwd, projectName, \"package.json\"))) {\n logger.break();\n logger.error(\n `A project with the name ${highlighter.info(projectName)} already exists.`,\n );\n logger.error(`Please choose a different name and try again.`);\n logger.break();\n process.exit(1);\n }\n\n await createProjectFromTemplate(projectPath, {\n templateKey: template,\n packageManager,\n cwd: options.cwd,\n });\n\n return {\n projectPath,\n projectName,\n template,\n };\n}\n\nasync function createProjectFromTemplate(\n projectPath: string,\n options: {\n templateKey: keyof typeof TEMPLATES;\n packageManager: string;\n cwd: string;\n },\n) {\n const createSpinner = spinner(\n `Creating a new project from template. This may take a few minutes.`,\n ).start();\n\n const TEMPLATE_TAR_SUBPATH: Record<keyof typeof TEMPLATES, string> = {\n astro: \"ui-main/templates/astro\",\n \"astro-monorepo\": \"ui-main/templates/monorepo-astro\",\n \"astro-with-component-docs-monorepo\":\n \"ui-main/templates/monorepo-astro-with-docs\",\n };\n\n try {\n // Load local .env if present to allow GITHUB_TOKEN/GH_TOKEN\n dotenv.config({ quiet: true });\n const templatePath = path.join(\n os.tmpdir(),\n `bejamas-template-${Date.now()}`,\n );\n await fs.ensureDir(templatePath);\n\n // Auth via environment variables (.env supported)\n const authToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n const usedAuth = Boolean(authToken);\n const headers: Record<string, string> = {\n \"User-Agent\": \"bejamas-cli\",\n };\n if (authToken) {\n headers[\"Authorization\"] = `Bearer ${authToken}`;\n }\n\n const response = await fetch(MONOREPO_TEMPLATE_URL, { headers });\n if (!response.ok) {\n if (\n response.status === 401 ||\n response.status === 403 ||\n (!usedAuth && response.status === 404)\n ) {\n throw new Error(\n \"Unauthorized to access private template. Set GITHUB_TOKEN or GH_TOKEN (in .env or env) with repo access and try again.\",\n );\n }\n if (response.status === 404) {\n throw new Error(\"Failed to download template: not found.\");\n }\n throw new Error(\n `Failed to download template: ${response.status} ${response.statusText}`,\n );\n }\n\n const tarPath = path.resolve(templatePath, \"template.tar.gz\");\n await fs.writeFile(tarPath, Buffer.from(await response.arrayBuffer()));\n\n const tarSubpath = TEMPLATE_TAR_SUBPATH[options.templateKey];\n const leafName = tarSubpath.split(\"/\").pop() as string;\n\n await execa(\"tar\", [\n \"-xzf\",\n tarPath,\n \"-C\",\n templatePath,\n \"--strip-components=2\",\n tarSubpath,\n ]);\n\n const extractedPath = path.resolve(templatePath, leafName);\n await fs.move(extractedPath, projectPath);\n await fs.remove(templatePath);\n\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n });\n\n try {\n // Detect if we're inside an existing git repo; if yes, skip initializing a nested repo\n const { stdout } = await execa(\n \"git\",\n [\"rev-parse\", \"--is-inside-work-tree\"],\n { cwd: projectPath },\n );\n const insideExistingRepo = stdout.trim() === \"true\";\n\n if (!insideExistingRepo) {\n await execa(\"git\", [\"init\"], { cwd: projectPath });\n await execa(\"git\", [\"add\", \"-A\"], { cwd: projectPath });\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit\"], {\n cwd: projectPath,\n });\n }\n } catch (_) {\n // ignore git detection/initialization failures\n }\n\n createSpinner?.succeed(\"Creating a new project from template.\");\n } catch (error) {\n createSpinner?.fail(\n \"Something went wrong creating a new project from template.\",\n );\n handleError(error);\n }\n}\n","import { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { preFlightInit } from \"@/src/preflights/preflight-init\";\n\nimport { BASE_COLORS, BUILTIN_REGISTRIES } from \"@/src/registry/constants\";\nimport { clearRegistryContext } from \"@/src/registry/context\";\n\nimport { TEMPLATES, createProject } from \"@/src/utils/create-project\";\nimport * as ERRORS from \"@/src/utils/errors\";\nimport { getConfig, createConfig, type Config } from \"@/src/utils/get-config\";\nimport { getProjectConfig, getProjectInfo } from \"@/src/utils/get-project-info\";\nimport { getPackageRunner } from \"@/src/utils/get-package-manager\";\nimport { handleError } from \"@/src/utils/handle-error\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { Command } from \"commander\";\nimport { execa } from \"execa\";\nimport fsExtra from \"fs-extra\";\nimport { z } from \"zod\";\n\n// process.on(\"exit\", (code) => {\n// const filePath = path.resolve(process.cwd(), \"components.json\")\n\n// // Delete backup if successful.\n// if (code === 0) {\n// return deleteFileBackup(filePath)\n// }\n\n// // Restore backup if error.\n// return restoreFileBackup(filePath)\n// })\n\n// Default fallback registry endpoint for shadcn (expects /r)\nconst DEFAULT_REGISTRY_URL = \"https://ui.bejamas.com/r\";\n\nexport const initOptionsSchema = z.object({\n cwd: z.string(),\n components: z.array(z.string()).optional(),\n yes: z.boolean(),\n defaults: z.boolean(),\n force: z.boolean(),\n silent: z.boolean(),\n isNewProject: z.boolean(),\n srcDir: z.boolean().optional(),\n cssVariables: z.boolean(),\n template: z\n .string()\n .optional()\n .refine(\n (val) => {\n if (val) {\n return TEMPLATES[val as keyof typeof TEMPLATES];\n }\n return true;\n },\n {\n message: \"Invalid template. Please use 'next' or 'next-monorepo'.\",\n },\n ),\n baseColor: z\n .string()\n .optional()\n .refine(\n (val) => {\n if (val) {\n return BASE_COLORS.find((color) => color.name === val);\n }\n\n return true;\n },\n {\n message: `Invalid base color. Please use '${BASE_COLORS.map(\n (color) => color.name,\n ).join(\"', '\")}'`,\n },\n ),\n baseStyle: z.boolean(),\n});\n\nexport const init = new Command()\n .name(\"init\")\n .description(\"initialize your project and install dependencies\")\n .argument(\"[components...]\", \"names, url or local path to component\")\n .option(\n \"-t, --template <template>\",\n \"the template to use. (next, next-monorepo)\",\n )\n .option(\n \"-b, --base-color <base-color>\",\n \"the base color to use. (neutral, gray, zinc, stone, slate)\",\n undefined,\n )\n .option(\"-y, --yes\", \"skip confirmation prompt.\", true)\n .option(\"-d, --defaults,\", \"use default configuration.\", false)\n .option(\"-f, --force\", \"force overwrite of existing configuration.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd(),\n )\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project.\",\n false,\n )\n .option(\n \"--no-src-dir\",\n \"do not use the src directory when creating a new project.\",\n )\n .option(\"--css-variables\", \"use css variables for theming.\", true)\n .option(\"--no-css-variables\", \"do not use css variables for theming.\")\n .option(\"--no-base-style\", \"do not install the base shadcn style.\")\n .action(async (_components, opts) => {\n try {\n await runInit(opts);\n } catch (error) {\n logger.break();\n handleError(error);\n } finally {\n clearRegistryContext();\n }\n });\n\nexport async function runInit(\n options: z.infer<typeof initOptionsSchema> & {\n skipPreflight?: boolean;\n },\n) {\n let projectInfo;\n let newProjectTemplate;\n if (!options.skipPreflight) {\n const preflight = await preFlightInit(options);\n\n if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {\n const { projectPath, template } = await createProject(options);\n if (!projectPath) {\n process.exit(1);\n }\n options.cwd = projectPath;\n options.isNewProject = true;\n newProjectTemplate = template;\n }\n projectInfo = preflight.projectInfo;\n } else {\n projectInfo = await getProjectInfo(options.cwd);\n }\n\n if (newProjectTemplate) {\n const projectPath = {\n \"astro-monorepo\": \"apps/web\",\n \"astro-with-component-docs-monorepo\": \"apps/web\",\n astro: \"\",\n } as const;\n options.cwd = path.resolve(options.cwd, projectPath[newProjectTemplate]);\n\n logger.log(\n `${highlighter.success(\n \"Success!\",\n )} Project initialization completed.\\nYou may now add components.`,\n );\n\n return await getConfig(options.cwd);\n }\n\n // const projectConfig = await getProjectConfig(options.cwd, projectInfo);\n\n const shadcnBin = process.platform === \"win32\" ? \"shadcn.cmd\" : \"shadcn\";\n const localShadcnPath = path.resolve(\n options.cwd,\n \"node_modules\",\n \".bin\",\n shadcnBin,\n );\n\n try {\n const env = {\n ...process.env,\n REGISTRY_URL: process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL,\n };\n if (await fsExtra.pathExists(localShadcnPath)) {\n await execa(localShadcnPath, [\"init\", \"--base-color\", \"neutral\"], {\n stdio: \"inherit\",\n cwd: options.cwd,\n env,\n });\n } else {\n // Follow user's runner preference (npx, bunx, pnpm dlx)\n await execa(\n \"npx\",\n [\"-y\", \"shadcn@latest\", \"init\", \"--base-color\", \"neutral\"],\n {\n stdio: \"inherit\",\n cwd: options.cwd,\n env,\n },\n );\n }\n } catch (err) {\n // shadcn already printed the detailed error to stdio, avoid double-reporting\n process.exit(1);\n }\n}\n","import { resolve } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\n\n/**\n * Read and parse tsconfig.json from the project root\n */\nexport function readTsConfig(projectRoot: string): any | null {\n try {\n const tsconfigPath = resolve(projectRoot, \"tsconfig.json\");\n if (!existsSync(tsconfigPath)) return null;\n const raw = readFileSync(tsconfigPath, \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve an alias path (like @/components) using tsconfig.json paths\n */\nexport function resolveAliasPathUsingTsConfig(\n inputPath: string,\n projectRoot: string,\n): string | null {\n const cfg = readTsConfig(projectRoot);\n if (!cfg || !cfg.compilerOptions) return null;\n const baseUrl: string = cfg.compilerOptions.baseUrl || \".\";\n const paths: Record<string, string[] | string> =\n cfg.compilerOptions.paths || {};\n for (const [key, values] of Object.entries(paths)) {\n const pattern = key.replace(/\\*/g, \"(.*)\");\n const re = new RegExp(`^${pattern}$`);\n const match = inputPath.match(re);\n if (!match) continue;\n const wildcard = match[1] || \"\";\n const first = Array.isArray(values) ? values[0] : values;\n if (!first) continue;\n const target = String(first).replace(/\\*/g, wildcard);\n return resolve(projectRoot, baseUrl, target);\n }\n return null;\n}\n","import { Command } from \"commander\";\nimport { resolve, isAbsolute, relative } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { logger } from \"@/src/utils/logger\";\nimport { resolveAliasPathUsingTsConfig } from \"@/src/utils/tsconfig-utils\";\nimport prompts from \"prompts\";\n\nasync function generateDocs({\n cwd,\n outDir,\n verbose,\n}: {\n cwd?: string;\n outDir?: string;\n verbose?: boolean;\n}) {\n const DEBUG =\n process.env.BEJAMAS_DEBUG === \"1\" ||\n process.env.BEJAMAS_DEBUG === \"true\" ||\n verbose;\n\n try {\n const shellCwd = process.cwd();\n\n // Probe for components.json up the directory tree starting from shell CWD\n let projectRoot = shellCwd;\n let probe: string | null = shellCwd;\n for (let i = 0; i < 6 && probe; i += 1) {\n const candidate = resolve(probe, \"components.json\");\n if (existsSync(candidate)) {\n projectRoot = probe;\n try {\n const raw = readFileSync(candidate, \"utf-8\");\n const config = JSON.parse(raw);\n // If UI root not provided via CLI, try to infer from aliases.ui first\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.aliases?.ui) {\n const mapped: string = String(config.aliases.ui);\n let uiAbs: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n uiAbs = resolve(projectRoot, mapped);\n } else {\n uiAbs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n }\n if (!uiAbs && mapped.startsWith(\"@/\")) {\n uiAbs = resolve(projectRoot, \"src\", mapped.slice(2));\n }\n if (uiAbs) {\n process.env.BEJAMAS_UI_ROOT = uiAbs;\n }\n }\n // Fallback: infer UI root from tailwind.css\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.tailwind?.css) {\n const cssRaw = String(config.tailwind.css);\n let cssAbs: string | null = null;\n if (\n cssRaw.startsWith(\"./\") ||\n cssRaw.startsWith(\"../\") ||\n isAbsolute(cssRaw)\n ) {\n cssAbs = resolve(projectRoot, cssRaw);\n } else {\n cssAbs = resolveAliasPathUsingTsConfig(cssRaw, projectRoot);\n }\n if (!cssAbs && cssRaw.startsWith(\"@/\")) {\n cssAbs = resolve(projectRoot, \"src\", cssRaw.slice(2));\n }\n if (cssAbs) {\n const uiRootFromCss = resolve(cssAbs, \"..\", \"..\", \"..\");\n process.env.BEJAMAS_UI_ROOT = uiRootFromCss;\n }\n }\n // If out dir not provided via CLI, try to infer from aliases.docs\n if (!outDir && config?.aliases?.docs) {\n const mapped: string = String(config.aliases.docs);\n let outResolved: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n outResolved = mapped;\n } else {\n const abs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n if (abs) outResolved = relative(projectRoot, abs);\n }\n if (!outResolved && mapped.startsWith(\"@/\")) {\n outResolved = mapped.replace(/^@\\//, \"src/\");\n }\n // As a last resort, use the mapped value as-is so we do not prompt for output\n const finalOut = outResolved ?? mapped;\n if (finalOut && !process.env.BEJAMAS_DOCS_OUT_DIR) {\n process.env.BEJAMAS_DOCS_OUT_DIR = finalOut;\n process.env.BEJAMAS_DOCS_CWD = projectRoot;\n }\n }\n } catch {}\n break;\n }\n const parent = resolve(probe, \"..\");\n probe = parent === probe ? null : parent;\n }\n\n // Defaults if not already set from components.json\n if (!process.env.BEJAMAS_DOCS_CWD) {\n process.env.BEJAMAS_DOCS_CWD = shellCwd;\n }\n if (!process.env.BEJAMAS_UI_ROOT) {\n // Ask user for @bejamas/ui root when not inferred\n const defaultGuess = (() => {\n // Try local monorepo style packages/ui\n let current = shellCwd;\n for (let i = 0; i < 6; i += 1) {\n const cand = resolve(current, \"packages/ui/package.json\");\n if (existsSync(cand)) {\n const abs = resolve(current, \"packages/ui\");\n const rel = relative(shellCwd, abs);\n return rel || abs;\n }\n const parent = resolve(current, \"..\");\n if (parent === current) break;\n current = parent;\n }\n // Try installed node_modules fallback\n const nm = resolve(shellCwd, \"node_modules/@bejamas/ui/package.json\");\n if (existsSync(nm)) {\n const abs = resolve(shellCwd, \"node_modules/@bejamas/ui\");\n const rel = relative(shellCwd, abs);\n return rel || abs;\n }\n // Last resort: suggest a common local path\n return \"packages/ui\";\n })();\n const { uiRoot } = await prompts({\n type: \"text\",\n name: \"uiRoot\",\n message: \"Path to @bejamas/ui package root:\",\n initial: defaultGuess,\n validate: (val: string) => {\n const p = resolve(shellCwd, val);\n return existsSync(resolve(p, \"package.json\"))\n ? true\n : `No package.json found in ${p}`;\n },\n });\n if (!uiRoot) {\n logger.error(\"@bejamas/ui root is required to generate docs.\");\n process.exit(1);\n }\n process.env.BEJAMAS_UI_ROOT = resolve(shellCwd, uiRoot);\n }\n\n // CLI overrides take precedence\n if (cwd && cwd.length) {\n process.env.BEJAMAS_UI_ROOT = resolve(cwd);\n }\n if (outDir && outDir.length) {\n // Pass through exactly as provided; the generator will resolve against BEJAMAS_DOCS_CWD if needed.\n process.env.BEJAMAS_DOCS_OUT_DIR = outDir;\n }\n\n // If output dir still not defined, prompt the user\n if (!process.env.BEJAMAS_DOCS_OUT_DIR) {\n const { out } = await prompts({\n type: \"text\",\n name: \"out\",\n message: \"Where should we output docs (relative to project root)?\",\n initial: \"src/content/docs/components\",\n });\n if (!out) {\n logger.error(\"An output directory is required to generate docs.\");\n process.exit(1);\n }\n process.env.BEJAMAS_DOCS_OUT_DIR = out;\n process.env.BEJAMAS_DOCS_CWD = process.env.BEJAMAS_DOCS_CWD || shellCwd;\n }\n // Ensure the generator does not auto-run upon import; we'll invoke it explicitly\n process.env.BEJAMAS_SKIP_AUTO_RUN = \"1\";\n logger.info(`Generating docs...`);\n if (DEBUG) {\n logger.info(`Generator entry: @/src/docs/generate-mdx/index`);\n if (process.env.BEJAMAS_UI_ROOT)\n logger.info(`UI root: ${process.env.BEJAMAS_UI_ROOT}`);\n if (process.env.BEJAMAS_DOCS_CWD)\n logger.info(`Docs CWD: ${process.env.BEJAMAS_DOCS_CWD}`);\n if (process.env.BEJAMAS_DOCS_OUT_DIR)\n logger.info(`Docs out: ${process.env.BEJAMAS_DOCS_OUT_DIR}`);\n }\n const mod = await import(\"@/src/docs/generate-mdx/index\");\n if (typeof mod.runDocsGenerator === \"function\") {\n await mod.runDocsGenerator();\n } else {\n throw new Error(\n \"Failed to load docs generator. Export 'runDocsGenerator' not found.\",\n );\n }\n } catch (err: any) {\n logger.error(err?.message || String(err));\n process.exit(1);\n }\n}\n\nexport const docs = new Command()\n .name(\"docs:build\")\n .alias(\"docs\")\n .description(\"generate docs from @bejamas/ui components\")\n .option(\"-c, --cwd <cwd>\", \"path to UI working directory\")\n .option(\"-o, --out <outDir>\", \"output directory for generated MDX files\")\n .action(async (opts) => {\n await generateDocs({\n cwd: opts.cwd,\n outDir: opts.out,\n verbose: Boolean(opts.verbose),\n });\n });\n","import { Command } from \"commander\";\nimport { resolve, isAbsolute, join, extname } from \"node:path\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport {\n cyan,\n green,\n red,\n yellow,\n dim,\n bold,\n magenta,\n white,\n} from \"kleur/colors\";\nimport { logger } from \"@/src/utils/logger\";\nimport { resolveAliasPathUsingTsConfig } from \"@/src/utils/tsconfig-utils\";\nimport {\n extractFrontmatter,\n parseJsDocMetadata,\n resolveUiRoot,\n} from \"@/src/docs/generate-mdx/utils\";\n\ninterface ComponentDocStatus {\n name: string;\n file: string;\n status: \"complete\" | \"incomplete\" | \"missing\";\n missingRequired: string[];\n missingRecommended: string[];\n}\n\ninterface CheckResult {\n total: number;\n complete: ComponentDocStatus[];\n incomplete: ComponentDocStatus[];\n missing: ComponentDocStatus[];\n}\n\nconst REQUIRED_FIELDS = [\"name\", \"title\", \"description\"] as const;\nconst RECOMMENDED_FIELDS = [\n \"primaryExampleMDX\",\n \"usageMDX\",\n \"figmaUrl\",\n] as const;\n\nconst FIELD_LABELS: Record<string, string> = {\n name: \"@component\",\n title: \"@title\",\n description: \"@description\",\n primaryExampleMDX: \"@preview\",\n usageMDX: \"@usage\",\n figmaUrl: \"@figmaUrl\",\n};\n\nfunction checkComponentDocs(\n filePath: string,\n fileName: string,\n): ComponentDocStatus {\n const content = readFileSync(filePath, \"utf-8\");\n const frontmatter = extractFrontmatter(content);\n const meta = parseJsDocMetadata(frontmatter);\n\n const componentName = fileName.replace(/\\.astro$/i, \"\");\n const missingRequired: string[] = [];\n const missingRecommended: string[] = [];\n\n for (const field of REQUIRED_FIELDS) {\n const value = meta[field];\n if (!value || (typeof value === \"string\" && !value.trim())) {\n missingRequired.push(FIELD_LABELS[field] || field);\n }\n }\n\n for (const field of RECOMMENDED_FIELDS) {\n const value = meta[field];\n if (!value || (typeof value === \"string\" && !value.trim())) {\n missingRecommended.push(FIELD_LABELS[field] || field);\n }\n }\n\n let status: \"complete\" | \"incomplete\" | \"missing\";\n if (missingRequired.length > 0) {\n status = \"missing\";\n } else if (missingRecommended.length > 0) {\n status = \"incomplete\";\n } else {\n status = \"complete\";\n }\n\n return {\n name: componentName,\n file: fileName,\n status,\n missingRequired,\n missingRecommended,\n };\n}\n\nasync function checkDocs({\n cwd,\n json,\n}: {\n cwd?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n const shellCwd = process.cwd();\n\n // Probe for components.json up the directory tree starting from shell CWD\n let projectRoot = shellCwd;\n let probe: string | null = shellCwd;\n for (let i = 0; i < 6 && probe; i += 1) {\n const candidate = resolve(probe, \"components.json\");\n if (existsSync(candidate)) {\n projectRoot = probe;\n try {\n const raw = readFileSync(candidate, \"utf-8\");\n const config = JSON.parse(raw);\n // If UI root not provided via CLI, try to infer from aliases.ui first\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.aliases?.ui) {\n const mapped: string = String(config.aliases.ui);\n let uiAbs: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n uiAbs = resolve(projectRoot, mapped);\n } else {\n uiAbs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n }\n if (!uiAbs && mapped.startsWith(\"@/\")) {\n uiAbs = resolve(projectRoot, \"src\", mapped.slice(2));\n }\n if (uiAbs) {\n process.env.BEJAMAS_UI_ROOT = uiAbs;\n }\n }\n // Fallback: infer UI root from tailwind.css\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.tailwind?.css) {\n const cssRaw = String(config.tailwind.css);\n let cssAbs: string | null = null;\n if (\n cssRaw.startsWith(\"./\") ||\n cssRaw.startsWith(\"../\") ||\n isAbsolute(cssRaw)\n ) {\n cssAbs = resolve(projectRoot, cssRaw);\n } else {\n cssAbs = resolveAliasPathUsingTsConfig(cssRaw, projectRoot);\n }\n if (!cssAbs && cssRaw.startsWith(\"@/\")) {\n cssAbs = resolve(projectRoot, \"src\", cssRaw.slice(2));\n }\n if (cssAbs) {\n const uiRootFromCss = resolve(cssAbs, \"..\", \"..\", \"..\");\n process.env.BEJAMAS_UI_ROOT = uiRootFromCss;\n }\n }\n } catch {}\n break;\n }\n const parent = resolve(probe, \"..\");\n probe = parent === probe ? null : parent;\n }\n\n // CLI override takes precedence\n if (cwd && cwd.length) {\n process.env.BEJAMAS_UI_ROOT = resolve(cwd);\n }\n\n let uiRoot: string;\n try {\n uiRoot = resolveUiRoot(shellCwd);\n } catch {\n logger.error(\n \"Unable to locate @bejamas/ui. Use --cwd to specify the UI package path.\",\n );\n process.exit(1);\n }\n\n const componentsDir = join(uiRoot, \"src\", \"components\");\n if (!existsSync(componentsDir)) {\n logger.error(\n `Components directory not found: ${componentsDir}\\n\\n` +\n `Expected structure: <uiRoot>/src/components/*.astro\\n` +\n `Use --cwd to specify a different UI package root.`,\n );\n process.exit(1);\n }\n\n const files = readdirSync(componentsDir, { withFileTypes: true })\n .filter((e) => e.isFile() && extname(e.name).toLowerCase() === \".astro\")\n .map((e) => e.name)\n .sort();\n\n if (files.length === 0) {\n logger.warn(\"No .astro component files found.\");\n process.exit(0);\n }\n\n const results: ComponentDocStatus[] = [];\n for (const file of files) {\n const filePath = join(componentsDir, file);\n const status = checkComponentDocs(filePath, file);\n results.push(status);\n }\n\n const complete = results.filter((r) => r.status === \"complete\");\n const incomplete = results.filter((r) => r.status === \"incomplete\");\n const missing = results.filter((r) => r.status === \"missing\");\n\n const checkResult: CheckResult = {\n total: results.length,\n complete,\n incomplete,\n missing,\n };\n\n if (json) {\n console.log(JSON.stringify(checkResult, null, 2));\n // Exit with error code if there are components missing required docs\n if (missing.length > 0) {\n process.exit(1);\n }\n return;\n }\n\n // Print formatted report\n const termWidth = Math.min(80, process.stdout.columns || 80);\n const headerLine = \"━\".repeat(termWidth);\n\n logger.break();\n console.log(dim(\"┌\" + \"─\".repeat(termWidth - 2) + \"┐\"));\n console.log(\n dim(\"│\") +\n bold(cyan(\" docs:check\")) +\n dim(\" — Component Documentation Status\") +\n \" \".repeat(Math.max(0, termWidth - 47)) +\n dim(\"│\"),\n );\n console.log(dim(\"└\" + \"─\".repeat(termWidth - 2) + \"┘\"));\n logger.break();\n\n // Helper to format tags with color\n const formatTag = (tag: string) => magenta(tag);\n const formatComponentName = (name: string) => bold(white(name));\n\n // Complete components\n if (complete.length > 0) {\n console.log(\n green(\n `✓ Complete (${complete.length} component${complete.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n const names = complete\n .map((c) => formatComponentName(c.name))\n .join(dim(\", \"));\n console.log(` ${names}`);\n logger.break();\n }\n\n // Incomplete components (missing recommended fields)\n if (incomplete.length > 0) {\n console.log(\n yellow(\n `⚠ Incomplete (${incomplete.length} component${incomplete.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n for (const comp of incomplete) {\n const missingFields = comp.missingRecommended\n .map(formatTag)\n .join(dim(\", \"));\n console.log(\n ` ${formatComponentName(comp.name)} ${dim(\"-\")} ${dim(\"missing:\")} ${missingFields}`,\n );\n }\n logger.break();\n }\n\n // Missing docs (missing required fields)\n if (missing.length > 0) {\n console.log(\n red(\n `✗ Missing Docs (${missing.length} component${missing.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n for (const comp of missing) {\n const missingFields = comp.missingRequired\n .map(formatTag)\n .join(dim(\", \"));\n console.log(\n ` ${formatComponentName(comp.name)} ${dim(\"-\")} ${dim(\"missing:\")} ${missingFields}`,\n );\n }\n logger.break();\n }\n\n // Summary\n console.log(dim(headerLine));\n const completeText = green(`${complete.length}/${results.length} complete`);\n const incompleteText =\n incomplete.length > 0\n ? yellow(`${incomplete.length} incomplete`)\n : dim(`${incomplete.length} incomplete`);\n const missingText =\n missing.length > 0\n ? red(`${missing.length} missing docs`)\n : dim(`${missing.length} missing docs`);\n console.log(\n `${bold(\"Summary:\")} ${completeText} ${dim(\"|\")} ${incompleteText} ${dim(\"|\")} ${missingText}`,\n );\n logger.break();\n\n // Exit with error code if there are components missing required docs\n if (missing.length > 0) {\n process.exit(1);\n }\n } catch (err: any) {\n logger.error(err?.message || String(err));\n process.exit(1);\n }\n}\n\nexport const docsCheck = new Command()\n .name(\"docs:check\")\n .description(\"check documentation status for all components\")\n .option(\"-c, --cwd <cwd>\", \"path to UI working directory\")\n .option(\"--json\", \"output results as JSON\")\n .action(async (opts) => {\n await checkDocs({\n cwd: opts.cwd,\n json: Boolean(opts.json),\n });\n });\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport { logger } from \"@/src/utils/logger\";\nimport { Config, getConfig } from \"@/src/utils/get-config\";\n\nexport function updateImportAliases(\n moduleSpecifier: string,\n config: Config,\n isRemote: boolean = false,\n) {\n // Not a local import.\n if (!moduleSpecifier.startsWith(\"@/\") && !isRemote) {\n return moduleSpecifier;\n }\n\n // This treats the remote as coming from a faux registry.\n let specifier = moduleSpecifier;\n if (isRemote && specifier.startsWith(\"@/\")) {\n specifier = specifier.replace(/^@\\//, \"@/registry/new-york/\");\n }\n\n // Not a registry import.\n if (!specifier.startsWith(\"@/registry/\")) {\n // We fix the alias and return.\n const alias = config.aliases.components.split(\"/\")[0];\n return specifier.replace(/^@\\//, `${alias}/`);\n }\n\n if (specifier.match(/^@\\/registry\\/(.+)\\/ui/)) {\n return specifier.replace(\n /^@\\/registry\\/(.+)\\/ui/,\n config.aliases.ui ?? `${config.aliases.components}/ui`,\n );\n }\n\n if (\n config.aliases.components &&\n specifier.match(/^@\\/registry\\/(.+)\\/components/)\n ) {\n return specifier.replace(\n /^@\\/registry\\/(.+)\\/components/,\n config.aliases.components,\n );\n }\n\n if (config.aliases.lib && specifier.match(/^@\\/registry\\/(.+)\\/lib/)) {\n return specifier.replace(/^@\\/registry\\/(.+)\\/lib/, config.aliases.lib);\n }\n\n if (config.aliases.hooks && specifier.match(/^@\\/registry\\/(.+)\\/hooks/)) {\n return specifier.replace(/^@\\/registry\\/(.+)\\/hooks/, config.aliases.hooks);\n }\n\n return specifier.replace(/^@\\/registry\\/[^/]+/, config.aliases.components);\n}\n\nexport function rewriteAstroImports(content: string, config: Config) {\n let updated = content;\n\n const utilsAlias = config.aliases?.utils;\n const workspaceAlias =\n typeof utilsAlias === \"string\" && utilsAlias.includes(\"/\")\n ? utilsAlias.split(\"/\")[0]\n : \"@\";\n const utilsImport = `${workspaceAlias}/lib/utils`;\n\n // Handle standard imports with specifiers, e.g. `import { x } from \"path\"`\n updated = updated.replace(\n /import\\s+([\\s\\S]*?)\\s+from\\s+[\"']([^\"']+)[\"']/g,\n (full, importsPart, specifier) => {\n const next = updateImportAliases(specifier, config, false);\n\n let finalSpec = next;\n const includesCn =\n typeof importsPart === \"string\" &&\n importsPart.split(/[{},\\s]/).some((part: string) => part === \"cn\");\n\n if (\n includesCn &&\n config.aliases.utils &&\n (next === utilsImport || next === \"@/lib/utils\")\n ) {\n finalSpec =\n utilsImport === next\n ? next.replace(utilsImport, config.aliases.utils)\n : config.aliases.utils;\n }\n\n if (finalSpec === specifier) return full;\n return full.replace(specifier, finalSpec);\n },\n );\n\n // Handle bare imports, e.g. `import \"path\"`\n updated = updated.replace(/import\\s+[\"']([^\"']+)[\"']/g, (full, specifier) => {\n const next = updateImportAliases(specifier, config, false);\n if (next === specifier) return full;\n return full.replace(specifier, next);\n });\n\n return updated;\n}\n\nexport async function fixAstroImports(cwd: string, isVerbose: boolean) {\n const config = await getConfig(cwd);\n if (!config) return;\n\n const searchRoots = new Set<string>([\n config.resolvedPaths.components,\n config.resolvedPaths.ui,\n ]);\n\n for (const root of Array.from(searchRoots)) {\n if (!root) continue;\n const astroFiles = await fg(\"**/*.astro\", {\n cwd: root,\n absolute: true,\n dot: false,\n });\n\n for (const filePath of astroFiles) {\n const original = await fs.readFile(filePath, \"utf8\");\n const rewritten = rewriteAstroImports(original, config);\n if (rewritten === original) continue;\n await fs.writeFile(filePath, rewritten, \"utf8\");\n if (isVerbose) {\n logger.info(\n `[bejamas-ui] fixed imports in ${path.relative(cwd, filePath)}`,\n );\n }\n }\n }\n}\n\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { logger } from \"@/src/utils/logger\";\n\nexport interface RegistryFile {\n path: string;\n content: string;\n type: string;\n target?: string;\n}\n\nexport interface RegistryItem {\n name: string;\n type: string;\n files: RegistryFile[];\n dependencies?: string[];\n devDependencies?: string[];\n registryDependencies?: string[];\n}\n\n/** Maps filename to subfolder/filename for path rewriting */\nexport type PathRewriteMap = Map<string, string>;\n\n/**\n * Fetches a registry item JSON from the registry URL.\n */\nexport async function fetchRegistryItem(\n componentName: string,\n registryUrl: string,\n): Promise<RegistryItem | null> {\n // Handle style-prefixed URLs (e.g., styles/new-york-v4/avatar.json)\n const url = `${registryUrl}/styles/new-york-v4/${componentName}.json`;\n\n try {\n const response = await fetch(url);\n if (!response.ok) {\n // Try without styles prefix as fallback\n const fallbackUrl = `${registryUrl}/${componentName}.json`;\n const fallbackResponse = await fetch(fallbackUrl);\n if (!fallbackResponse.ok) {\n return null;\n }\n return (await fallbackResponse.json()) as RegistryItem;\n }\n return (await response.json()) as RegistryItem;\n } catch {\n return null;\n }\n}\n\n/**\n * Extracts the subfolder name from registry file paths.\n * E.g., \"components/ui/avatar/Avatar.astro\" → \"avatar\"\n */\nexport function getSubfolderFromPaths(files: RegistryFile[]): string | null {\n // Only consider registry:ui files\n const uiFiles = files.filter((f) => f.type === \"registry:ui\");\n if (uiFiles.length < 2) {\n // Single file components don't need subfolders\n return null;\n }\n\n const subfolders = new Set<string>();\n\n for (const file of uiFiles) {\n const parts = file.path.split(\"/\");\n // Look for pattern: .../ui/<subfolder>/<filename>\n const uiIndex = parts.indexOf(\"ui\");\n if (uiIndex !== -1 && parts.length > uiIndex + 2) {\n // There's at least one folder after \"ui\" before the filename\n subfolders.add(parts[uiIndex + 1]);\n }\n }\n\n // If all files share the same subfolder, use it\n if (subfolders.size === 1) {\n return Array.from(subfolders)[0];\n }\n\n // Fallback: use the component name from the first file's parent directory\n if (uiFiles.length > 0) {\n const firstPath = uiFiles[0].path;\n const dirname = path.dirname(firstPath);\n const folderName = path.basename(dirname);\n // Only use if it's not \"ui\" itself\n if (folderName && folderName !== \"ui\") {\n return folderName;\n }\n }\n\n return null;\n}\n\n/**\n * Checks if a path exists.\n */\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Builds a map of path rewrites for components that will be reorganized.\n * Call this BEFORE shadcn runs to know how to rewrite output paths.\n */\nexport async function buildPathRewriteMap(\n components: string[],\n uiDir: string,\n registryUrl: string,\n): Promise<PathRewriteMap> {\n const rewrites: PathRewriteMap = new Map();\n\n if (!uiDir || components.length === 0) {\n return rewrites;\n }\n\n for (const componentName of components) {\n try {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) continue;\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) continue;\n\n // Get the UI files that will be reorganized\n const uiFiles = registryItem.files.filter(\n (f) => f.type === \"registry:ui\",\n );\n\n for (const file of uiFiles) {\n const filename = path.basename(file.path);\n // Map: \"Avatar.astro\" → \"avatar/Avatar.astro\"\n rewrites.set(filename, `${subfolder}/${filename}`);\n }\n } catch {\n // Ignore errors, just skip this component\n }\n }\n\n return rewrites;\n}\n\n/**\n * Rewrites file paths in shadcn output to reflect reorganized structure.\n * Replaces flat paths like \"/ui/Avatar.astro\" with \"/ui/avatar/Avatar.astro\"\n */\nexport function rewriteOutputPaths(\n output: string,\n rewrites: PathRewriteMap,\n): string {\n let result = output;\n\n for (const [filename, newPath] of rewrites) {\n // Match paths ending with the filename (handles various path formats)\n // e.g., \"packages/ui/src/components/Avatar.astro\" → \"packages/ui/src/components/avatar/Avatar.astro\"\n const escapedFilename = filename.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`(/[^/\\\\s]+)/${escapedFilename}(?=\\\\s|$|\\\\n)`, \"g\");\n result = result.replace(pattern, `$1/${newPath}`);\n }\n\n return result;\n}\n\nexport interface ReorganizeResult {\n totalMoved: number;\n movedFiles: string[]; // e.g., [\"avatar/Avatar.astro\", \"avatar/index.ts\"]\n skippedFiles: string[]; // Files that already existed in subfolder (flat duplicate removed)\n}\n\n/**\n * Reorganizes multi-file components into correct subfolders.\n * Only moves files from FLAT location to subfolder.\n * Does NOT touch files already in subfolders.\n * E.g., moves `uiDir/Avatar.astro` to `uiDir/avatar/Avatar.astro`.\n * Returns info about moved files for display purposes.\n */\nexport async function reorganizeComponents(\n components: string[],\n uiDir: string,\n registryUrl: string,\n verbose: boolean,\n): Promise<ReorganizeResult> {\n const result: ReorganizeResult = { totalMoved: 0, movedFiles: [], skippedFiles: [] };\n\n if (!uiDir || components.length === 0) {\n return result;\n }\n\n for (const componentName of components) {\n try {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) {\n if (verbose) {\n logger.info(\n `[bejamas-ui] Could not fetch registry for ${componentName}, skipping reorganization`,\n );\n }\n continue;\n }\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) {\n // Single-file component or no subfolder detected, skip\n if (verbose) {\n logger.info(\n `[bejamas-ui] ${componentName} is single-file or has no subfolder, skipping`,\n );\n }\n continue;\n }\n\n // Get the UI files that need to be moved\n const uiFiles = registryItem.files.filter(\n (f) => f.type === \"registry:ui\",\n );\n\n const targetDir = path.join(uiDir, subfolder);\n let movedCount = 0;\n\n for (const file of uiFiles) {\n const filename = path.basename(file.path);\n // Only look for files in FLAT location (directly in uiDir)\n const flatPath = path.join(uiDir, filename);\n const targetPath = path.join(targetDir, filename);\n\n // Check if file exists in flat location\n if (!(await pathExists(flatPath))) {\n // Not in flat location, skip (may already be in subfolder)\n continue;\n }\n\n // Check if target already exists (don't overwrite, but clean up flat duplicate)\n if (await pathExists(targetPath)) {\n // Target exists in subfolder - delete the flat duplicate shadcn just created\n try {\n await fs.unlink(flatPath);\n result.skippedFiles.push(`${subfolder}/${filename}`);\n if (verbose) {\n logger.info(\n `[bejamas-ui] Removed flat duplicate: ${filename} (${subfolder}/${filename} exists)`,\n );\n }\n } catch {\n // Flat file might not exist or already deleted, but still counts as skipped\n result.skippedFiles.push(`${subfolder}/${filename}`);\n }\n continue;\n }\n\n // Create target directory if needed\n await fs.mkdir(targetDir, { recursive: true });\n\n // Move file from flat to subfolder\n await fs.rename(flatPath, targetPath);\n movedCount++;\n result.totalMoved++;\n result.movedFiles.push(`${subfolder}/${filename}`);\n\n if (verbose) {\n logger.info(`[bejamas-ui] Moved ${filename} → ${subfolder}/${filename}`);\n }\n }\n\n if (movedCount > 0 && verbose) {\n logger.info(\n `[bejamas-ui] Reorganized ${componentName} into ${subfolder}/`,\n );\n }\n } catch (err) {\n // Non-fatal: log and continue with other components\n if (verbose) {\n logger.warn(\n `[bejamas-ui] Failed to reorganize ${componentName}: ${err}`,\n );\n }\n }\n }\n\n return result;\n}\n\n","import path from \"node:path\";\nimport { Command } from \"commander\";\nimport { execa } from \"execa\";\nimport { logger } from \"@/src/utils/logger\";\nimport { spinner } from \"@/src/utils/spinner\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { getPackageRunner } from \"@/src/utils/get-package-manager\";\nimport { fixAstroImports } from \"@/src/utils/astro-imports\";\nimport { getConfig, getWorkspaceConfig } from \"@/src/utils/get-config\";\nimport {\n reorganizeComponents,\n fetchRegistryItem,\n getSubfolderFromPaths,\n} from \"@/src/utils/reorganize-components\";\n\ninterface ParsedOutput {\n created: string[];\n updated: string[];\n skipped: string[];\n}\n\n// Default fallback registry endpoint for shadcn (expects /r)\nconst DEFAULT_REGISTRY_URL = \"https://ui.bejamas.com/r\";\n\n// Derive only the user-provided flags for shadcn to avoid losing options\nfunction extractOptionsForShadcn(rawArgv: string[], cmd: Command): string[] {\n // Prefer commander metadata when available so we only forward options that\n // were explicitly set (avoids defaults and keeps aliases consistent).\n if (typeof cmd.getOptionValueSource === \"function\") {\n const opts = cmd.optsWithGlobals() as Record<string, unknown>;\n const forwarded: string[] = [];\n const getSource = (key: string) => cmd.getOptionValueSource(key);\n\n const addBoolean = (key: string, flag: string, negateFlag?: string) => {\n if (getSource(key) !== \"cli\") return;\n const value = opts[key];\n if (typeof value !== \"boolean\") return;\n if (value) {\n forwarded.push(flag);\n } else if (negateFlag) {\n forwarded.push(negateFlag);\n }\n };\n\n const addString = (key: string, flag: string) => {\n if (getSource(key) !== \"cli\") return;\n const value = opts[key];\n if (typeof value === \"string\") {\n forwarded.push(flag, value);\n }\n };\n\n addBoolean(\"yes\", \"--yes\");\n addBoolean(\"overwrite\", \"--overwrite\");\n addString(\"cwd\", \"--cwd\");\n addBoolean(\"all\", \"--all\");\n addString(\"path\", \"--path\");\n addBoolean(\"silent\", \"--silent\");\n addBoolean(\"srcDir\", \"--src-dir\", \"--no-src-dir\");\n\n // Preserve any explicit passthrough after \"--\" for shadcn.\n const addIndex = rawArgv.findIndex((arg) => arg === \"add\");\n if (addIndex !== -1) {\n const rest = rawArgv.slice(addIndex + 1);\n const doubleDashIndex = rest.indexOf(\"--\");\n if (doubleDashIndex !== -1) {\n forwarded.push(...rest.slice(doubleDashIndex));\n }\n }\n\n return forwarded;\n }\n\n // Fallback: lightweight parser that only forwards known options.\n const addIndex = rawArgv.findIndex((arg) => arg === \"add\");\n if (addIndex === -1) return [];\n const rest = rawArgv.slice(addIndex + 1);\n const forwarded: string[] = [];\n const optionsWithValues = new Set([\"-c\", \"--cwd\", \"-p\", \"--path\"]);\n const filteredFlags = new Set([\"-v\", \"--verbose\"]);\n\n for (let i = 0; i < rest.length; i += 1) {\n const token = rest[i];\n if (token === \"--\") {\n forwarded.push(\"--\", ...rest.slice(i + 1));\n break;\n }\n if (!token.startsWith(\"-\")) continue;\n if (filteredFlags.has(token)) continue;\n\n forwarded.push(token);\n if (token.includes(\"=\")) continue;\n\n if (optionsWithValues.has(token)) {\n const next = rest[i + 1];\n if (next) {\n forwarded.push(next);\n i += 1;\n }\n }\n }\n return forwarded;\n}\n\ninterface ComponentFileInfo {\n subfolder: string;\n files: string[]; // All filenames for this component\n}\n\ninterface SubfolderMapResult {\n // Maps unique filename -> subfolder/filename\n uniqueMap: Map<string, string>;\n // Maps component subfolder -> all its files (for grouping)\n componentInfo: Map<string, ComponentFileInfo>;\n // Set of shared filenames (like index.ts) that appear in multiple components\n sharedFilenames: Set<string>;\n}\n\n/** Build maps for path rewriting, handling filename collisions */\nasync function buildSubfolderMap(\n components: string[],\n registryUrl: string,\n): Promise<SubfolderMapResult> {\n const filenameToSubfolders = new Map<string, string[]>();\n const componentInfo = new Map<string, ComponentFileInfo>();\n\n // First pass: collect all filename -> subfolder mappings\n for (const componentName of components) {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) continue;\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) continue;\n\n const files: string[] = [];\n for (const file of registryItem.files) {\n if (file.type === \"registry:ui\") {\n const filename = path.basename(file.path);\n files.push(filename);\n\n // Track which subfolders each filename appears in\n const subfolders = filenameToSubfolders.get(filename) || [];\n subfolders.push(subfolder);\n filenameToSubfolders.set(filename, subfolders);\n }\n }\n\n componentInfo.set(subfolder, { subfolder, files });\n }\n\n // Build the unique map (only filenames that appear once)\n const uniqueMap = new Map<string, string>();\n const sharedFilenames = new Set<string>();\n\n filenameToSubfolders.forEach((subfolders, filename) => {\n if (subfolders.length === 1) {\n // Unique filename - safe to map directly\n uniqueMap.set(filename, `${subfolders[0]}/${filename}`);\n } else {\n // Shared filename (like index.ts) - track for context-based rewriting\n sharedFilenames.add(filename);\n }\n });\n\n return { uniqueMap, componentInfo, sharedFilenames };\n}\n\n/**\n * Rewrite file paths to include correct subfolders.\n * Handles shared filenames (like index.ts) by tracking current component context.\n */\nfunction rewritePaths(\n paths: string[],\n mapResult: SubfolderMapResult,\n): string[] {\n const { uniqueMap, componentInfo, sharedFilenames } = mapResult;\n let currentSubfolder: string | null = null;\n\n return paths.map((filePath) => {\n const filename = path.basename(filePath);\n const parentDir = path.basename(path.dirname(filePath));\n\n // Check if this is a unique filename (can map directly)\n const uniqueMapping = uniqueMap.get(filename);\n if (uniqueMapping) {\n const expectedSubfolder = path.dirname(uniqueMapping);\n\n // Update current context for subsequent shared files\n currentSubfolder = expectedSubfolder;\n\n // Only rewrite if not already in the correct subfolder\n if (parentDir !== expectedSubfolder) {\n const dir = path.dirname(filePath);\n return `${dir}/${uniqueMapping}`;\n }\n return filePath;\n }\n\n // Check if this is a shared filename (like index.ts)\n if (sharedFilenames.has(filename) && currentSubfolder) {\n // Use the current component context\n const expectedSubfolder = currentSubfolder;\n\n // Only rewrite if not already in the correct subfolder\n if (parentDir !== expectedSubfolder) {\n const dir = path.dirname(filePath);\n return `${dir}/${expectedSubfolder}/${filename}`;\n }\n }\n\n return filePath;\n });\n}\n\n/** Parse shadcn output to extract file lists (stdout has paths, stderr has headers) */\nfunction parseShadcnOutput(stdout: string, stderr: string): ParsedOutput {\n const result: ParsedOutput = { created: [], updated: [], skipped: [] };\n\n // Remove ANSI escape codes for parsing\n const cleanStderr = stderr.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n const cleanStdout = stdout.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\n // Extract counts from stderr headers\n // Matches patterns like \"✔ Created 4 files:\" or \"ℹ Skipped 2 files:\"\n const createdMatch = cleanStderr.match(/Created\\s+(\\d+)\\s+file/i);\n const updatedMatch = cleanStderr.match(/Updated\\s+(\\d+)\\s+file/i);\n const skippedMatch = cleanStderr.match(/Skipped\\s+(\\d+)\\s+file/i);\n\n const createdCount = createdMatch ? parseInt(createdMatch[1], 10) : 0;\n const updatedCount = updatedMatch ? parseInt(updatedMatch[1], 10) : 0;\n const skippedCount = skippedMatch ? parseInt(skippedMatch[1], 10) : 0;\n\n // Extract file paths from stdout (lines starting with \" - \")\n const allPaths: string[] = [];\n for (const line of cleanStdout.split(\"\\n\")) {\n const match = line.match(/^\\s+-\\s+(.+)$/);\n if (match) {\n allPaths.push(match[1].trim());\n }\n }\n\n // Also check stderr for file paths (some shadcn versions output there)\n for (const line of cleanStderr.split(\"\\n\")) {\n const match = line.match(/^\\s+-\\s+(.+)$/);\n if (match) {\n const filePath = match[1].trim();\n // Avoid duplicates\n if (!allPaths.includes(filePath)) {\n allPaths.push(filePath);\n }\n }\n }\n\n // Assign paths to sections based on counts (order: created, updated, skipped)\n let idx = 0;\n for (let i = 0; i < createdCount && idx < allPaths.length; i++) {\n result.created.push(allPaths[idx++]);\n }\n for (let i = 0; i < updatedCount && idx < allPaths.length; i++) {\n result.updated.push(allPaths[idx++]);\n }\n for (let i = 0; i < skippedCount && idx < allPaths.length; i++) {\n result.skipped.push(allPaths[idx++]);\n }\n\n return result;\n}\n\nasync function addComponents(\n packages: string[],\n forwardedOptions: string[],\n isVerbose: boolean,\n isSilent: boolean,\n subfolderMapResult: SubfolderMapResult,\n): Promise<ParsedOutput> {\n const runner = await getPackageRunner(process.cwd());\n const env = {\n ...process.env,\n REGISTRY_URL: process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL,\n };\n // Always pass --yes for non-interactive mode (skips \"Add components?\" confirmation)\n // Note: we don't pass --overwrite by default to respect user customizations\n const autoFlags: string[] = [];\n if (!forwardedOptions.includes(\"--yes\")) {\n autoFlags.push(\"--yes\");\n }\n const baseArgs = [\n \"shadcn@latest\",\n \"add\",\n ...packages,\n ...autoFlags,\n ...forwardedOptions,\n ];\n\n let cmd = \"npx\";\n let args: string[] = [\"-y\", ...baseArgs];\n if (runner === \"bunx\") {\n cmd = \"bunx\";\n args = baseArgs;\n } else if (runner === \"pnpm dlx\") {\n cmd = \"pnpm\";\n args = [\"dlx\", ...baseArgs];\n } else if (runner === \"npx\") {\n cmd = \"npx\";\n args = [\"-y\", ...baseArgs];\n }\n\n if (isVerbose) {\n logger.info(`[bejamas-ui] ${cmd} ${args.join(\" \")}`);\n }\n\n // Show our own spinner for checking registry\n const registrySpinner = spinner(\"Checking registry.\", { silent: isSilent });\n registrySpinner.start();\n\n try {\n // Run shadcn and capture output\n // Pipe \"n\" to stdin to answer \"no\" to any overwrite prompts (respects user customizations)\n const result = await execa(cmd, args, {\n env,\n input: \"n\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\n\", // Answer \"no\" to up to 10 overwrite prompts\n stdout: \"pipe\",\n stderr: \"pipe\",\n reject: false,\n });\n\n registrySpinner.succeed();\n\n // Show installing spinner (already done at this point)\n const installSpinner = spinner(\"Installing components.\", {\n silent: isSilent,\n });\n installSpinner.succeed();\n\n // Parse the output to get file lists (stdout has paths, stderr has headers)\n const stdout = result.stdout || \"\";\n const stderr = result.stderr || \"\";\n\n if (isVerbose) {\n logger.info(`[bejamas-ui] Raw stdout: ${stdout}`);\n logger.info(`[bejamas-ui] Raw stderr: ${stderr}`);\n }\n\n const parsed = parseShadcnOutput(stdout, stderr);\n\n // Return parsed data - display is handled by caller after reorganization\n // This allows accurate reporting (shadcn says \"created\" but we may skip)\n\n if (result.exitCode !== 0) {\n // Show any error output\n if (result.stderr) {\n logger.error(result.stderr);\n }\n process.exit(result.exitCode);\n }\n\n return parsed;\n } catch (err) {\n registrySpinner.fail();\n logger.error(\"Failed to add components\");\n process.exit(1);\n }\n}\n\nexport const add = new Command()\n .name(\"add\")\n .description(\"Add components via shadcn@latest using registry URLs\")\n .argument(\"[components...]\", \"Component package names to add\")\n .option(\"-y, --yes\", \"skip confirmation prompt.\", false)\n .option(\"-o, --overwrite\", \"overwrite existing files.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd(),\n )\n .option(\"-a, --all\", \"add all available components\", false)\n .option(\"-p, --path <path>\", \"the path to add the component to.\")\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project.\",\n false,\n )\n .option(\n \"--no-src-dir\",\n \"do not use the src directory when creating a new project.\",\n )\n // .option(\"--css-variables\", \"use css variables for theming.\", true)\n // .option(\"--no-css-variables\", \"do not use css variables for theming.\")\n .action(async function action(packages: string[], _opts, cmd) {\n const root = cmd?.parent;\n const verbose = Boolean(root?.opts?.().verbose);\n const rawArgv = process.argv.slice(2);\n const forwardedOptions = extractOptionsForShadcn(rawArgv, cmd);\n const opts =\n typeof cmd.optsWithGlobals === \"function\"\n ? cmd.optsWithGlobals()\n : (cmd.opts?.() ?? {});\n const cwd = opts.cwd || process.cwd();\n\n // Get config for resolved paths (needed for reorganization)\n // In monorepos, we need to follow the alias chain to find the actual UI package config\n const config = await getConfig(cwd);\n const registryUrl = process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL;\n\n // Try to get workspace config (follows aliases to find package-specific configs)\n let uiDir = config?.resolvedPaths?.ui || \"\";\n let uiConfig = config;\n\n if (config) {\n const workspaceConfig = await getWorkspaceConfig(config);\n if (workspaceConfig?.ui) {\n // Use the UI package's own config (e.g., packages/ui/components.json)\n uiConfig = workspaceConfig.ui;\n uiDir = uiConfig.resolvedPaths?.ui || uiDir;\n }\n }\n\n if (verbose) {\n logger.info(`[bejamas-ui] cwd: ${cwd}`);\n logger.info(`[bejamas-ui] uiDir: ${uiDir}`);\n logger.info(\n `[bejamas-ui] aliases.ui: ${uiConfig?.aliases?.ui || \"not set\"}`,\n );\n }\n\n // Process components ONE AT A TIME to avoid index.ts conflicts\n // When shadcn runs with multiple components, files with same name overwrite each other\n const isSilent = opts.silent || false;\n const componentsToAdd = packages || [];\n const totalComponents = componentsToAdd.length;\n\n for (let i = 0; i < componentsToAdd.length; i++) {\n const component = componentsToAdd[i];\n\n // Show component header when adding multiple\n if (totalComponents > 1 && !isSilent) {\n logger.break();\n logger.info(\n highlighter.info(`[${i + 1}/${totalComponents}]`) +\n ` Adding ${highlighter.success(component)}...`,\n );\n }\n\n // Build subfolder map for this single component\n const subfolderMapResult = await buildSubfolderMap(\n [component],\n registryUrl,\n );\n\n // Run shadcn for just this component\n const parsed = await addComponents(\n [component],\n forwardedOptions,\n verbose,\n isSilent,\n subfolderMapResult,\n );\n\n // Immediately reorganize this component's files before the next one\n let skippedCount = 0;\n if (uiDir) {\n const reorgResult = await reorganizeComponents(\n [component],\n uiDir,\n registryUrl,\n verbose,\n );\n skippedCount = reorgResult.skippedFiles.length;\n }\n\n // Display accurate results (accounting for files we skipped after shadcn \"created\" them)\n if (!isSilent) {\n const relativeUiDir = uiDir ? path.relative(cwd, uiDir) : \"\";\n\n // Files that were actually created (shadcn created minus our skipped)\n const actuallyCreated = Math.max(\n 0,\n parsed.created.length - skippedCount,\n );\n\n if (actuallyCreated > 0) {\n const createdPaths = rewritePaths(\n parsed.created.slice(0, actuallyCreated),\n subfolderMapResult,\n );\n logger.success(\n `Created ${createdPaths.length} file${createdPaths.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const file of createdPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Updated files (globals.css etc)\n if (parsed.updated.length > 0) {\n const uniqueUpdated = Array.from(new Set(parsed.updated));\n const updatedPaths = rewritePaths(uniqueUpdated, subfolderMapResult);\n logger.info(\n `Updated ${updatedPaths.length} file${updatedPaths.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const file of updatedPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Files skipped because they already exist in subfolder\n if (skippedCount > 0) {\n logger.info(\n `Skipped ${skippedCount} file${skippedCount > 1 ? \"s\" : \"\"}: (already exists)`,\n );\n }\n\n // Files shadcn skipped (different from our reorganization skip)\n if (parsed.skipped.length > 0) {\n const skippedPaths = rewritePaths(parsed.skipped, subfolderMapResult);\n logger.info(\n `Skipped ${skippedPaths.length} file${skippedPaths.length > 1 ? \"s\" : \"\"}: (use --overwrite)`,\n );\n for (const file of skippedPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Nothing happened\n if (\n actuallyCreated === 0 &&\n parsed.updated.length === 0 &&\n skippedCount === 0 &&\n parsed.skipped.length === 0\n ) {\n logger.info(\"Already up to date.\");\n }\n }\n }\n\n // Fix aliases inside Astro files until upstream adds .astro support.\n await fixAstroImports(cwd, verbose);\n });\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"module\";\nimport { init } from \"@/src/commands/init\";\nimport { docs } from \"@/src/commands/docs\";\nimport { docsCheck } from \"@/src/commands/docs-check\";\nimport { add } from \"@/src/commands/add\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\");\n\nconst program = new Command()\n .name(\"bejamas\")\n .description(\"bejamas/ui cli\")\n .configureHelp({\n helpWidth: Math.min(100, process.stdout.columns || 100),\n })\n .version(pkg.version, \"-v, --version\", \"output the version number\");\n\nprogram.addCommand(init);\nprogram.addCommand(add);\nprogram.addCommand(docs);\nprogram.addCommand(docsCheck);\n\nprogram.parse(process.argv);\n\nexport default program;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,MAAa,+BAA+B;;;;ACM5C,eAAsB,cACpB,SACA;CACA,MAAMA,SAAkC,EAAE;AAI1C,KACE,CAACC,QAAG,WAAW,QAAQ,IAAI,IAC3B,CAACA,QAAG,WAAW,KAAK,QAAQ,QAAQ,KAAK,eAAe,CAAC,EACzD;AACA,SAAOC,gCAAuC;AAC9C,SAAO;GACL;GACA,aAAa;GACd;;AAGH,QAAO;EACL;EACA,aAAa;EACd;;;;;ACvBH,IAAIC,UAA2B,EAC7B,SAAS,EAAE,EACZ;AAeD,SAAgB,uBAAuB;AACrC,SAAQ,UAAU,EAAE;;;;;ACpBtB,eAAsB,kBACpB,WACA,EAAE,iBAA6C,EAC7C,cAAc,OACf,EACkD;CACnD,MAAM,iBAAiB,MAAM,OAAO;EAAE,cAAc;EAAM,KAAK;EAAW,CAAC;AAE3E,KAAI,mBAAmB,aAAc,QAAO;AAC5C,KAAI,mBAAmB,SAAU,QAAO;AACxC,KAAI,mBAAmB,MAAO,QAA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ERRORS.MISSING_DIR_OR_EMPTY_PROJECT","context: RegistryContext","template: keyof typeof TEMPLATES","projectName: string","fs","TEMPLATE_TAR_SUBPATH: Record<keyof typeof TEMPLATES, string>","headers: Record<string, string>","DEFAULT_REGISTRY_URL","ERRORS.MISSING_DIR_OR_EMPTY_PROJECT","baseUrl: string","paths: Record<string, string[] | string>","probe: string | null","mapped: string","uiAbs: string | null","cssAbs: string | null","outResolved: string | null","relative","err: any","FIELD_LABELS: Record<string, string>","missingRequired: string[]","missingRecommended: string[]","status: \"complete\" | \"incomplete\" | \"missing\"","probe: string | null","mapped: string","uiAbs: string | null","cssAbs: string | null","uiRoot: string","join","extname","results: ComponentDocStatus[]","checkResult: CheckResult","err: any","path","dirname","path","result: ReorganizeResult","forwarded: string[]","addIndex","rest","forwarded","files: string[]","path","currentSubfolder: string | null","result: ParsedOutput","allPaths: string[]","autoFlags: string[]","args: string[]"],"sources":["../src/utils/errors.ts","../src/preflights/preflight-init.ts","../src/registry/context.ts","../src/utils/get-package-manager.ts","../src/registry/errors.ts","../src/utils/handle-error.ts","../src/utils/create-project.ts","../src/commands/init.ts","../src/utils/tsconfig-utils.ts","../src/commands/docs.ts","../src/commands/docs-check.ts","../src/utils/astro-imports.ts","../src/utils/reorganize-components.ts","../src/commands/add.ts","../src/index.ts"],"sourcesContent":["export const MISSING_DIR_OR_EMPTY_PROJECT = \"1\";\nexport const EXISTING_CONFIG = \"2\";\nexport const MISSING_CONFIG = \"3\";\nexport const FAILED_CONFIG_READ = \"4\";\nexport const TAILWIND_NOT_CONFIGURED = \"5\";\nexport const IMPORT_ALIAS_MISSING = \"6\";\nexport const UNSUPPORTED_FRAMEWORK = \"7\";\nexport const COMPONENT_URL_NOT_FOUND = \"8\";\nexport const COMPONENT_URL_UNAUTHORIZED = \"9\";\nexport const COMPONENT_URL_FORBIDDEN = \"10\";\nexport const COMPONENT_URL_BAD_REQUEST = \"11\";\nexport const COMPONENT_URL_INTERNAL_SERVER_ERROR = \"12\";\nexport const BUILD_MISSING_REGISTRY_FILE = \"13\";\n","import path from \"path\";\nimport { initOptionsSchema } from \"@/src/commands/init\";\nimport * as ERRORS from \"@/src/utils/errors\";\nimport fs from \"fs-extra\";\nimport { z } from \"zod\";\n\nexport async function preFlightInit(\n options: z.infer<typeof initOptionsSchema>,\n) {\n const errors: Record<string, boolean> = {};\n\n // Ensure target directory exists.\n // Check for empty project. We assume if no package.json exists, the project is empty.\n if (\n !fs.existsSync(options.cwd) ||\n !fs.existsSync(path.resolve(options.cwd, \"package.json\"))\n ) {\n errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true;\n return {\n errors,\n projectInfo: null,\n };\n }\n\n return {\n errors,\n projectInfo: null,\n };\n}\n","interface RegistryContext {\n headers: Record<string, Record<string, string>>;\n}\n\nlet context: RegistryContext = {\n headers: {},\n};\n\nexport function setRegistryHeaders(\n headers: Record<string, Record<string, string>>,\n) {\n // Merge new headers with existing ones to preserve headers for nested dependencies\n context.headers = { ...context.headers, ...headers };\n}\n\nexport function getRegistryHeadersFromContext(\n url: string,\n): Record<string, string> {\n return context.headers[url] || {};\n}\n\nexport function clearRegistryContext() {\n context.headers = {};\n}\n","import { detect } from \"@antfu/ni\";\n\nexport async function getPackageManager(\n targetDir: string,\n { withFallback }: { withFallback?: boolean } = {\n withFallback: false,\n },\n): Promise<\"yarn\" | \"pnpm\" | \"bun\" | \"npm\" | \"deno\"> {\n const packageManager = await detect({ programmatic: true, cwd: targetDir });\n\n if (packageManager === \"yarn@berry\") return \"yarn\";\n if (packageManager === \"pnpm@6\") return \"pnpm\";\n if (packageManager === \"bun\") return \"bun\";\n if (packageManager === \"deno\") return \"deno\";\n if (!withFallback) {\n return packageManager ?? \"npm\";\n }\n\n // Fallback to user agent if not detected.\n const userAgent = process.env.npm_config_user_agent || \"\";\n\n if (userAgent.startsWith(\"yarn\")) {\n return \"yarn\";\n }\n\n if (userAgent.startsWith(\"pnpm\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"bun\")) {\n return \"bun\";\n }\n\n return \"npm\";\n}\n\nexport async function getPackageRunner(cwd: string) {\n const packageManager = await getPackageManager(cwd);\n\n if (packageManager === \"pnpm\") return \"pnpm dlx\";\n\n if (packageManager === \"bun\") return \"bunx\";\n\n return \"npx\";\n}\n","import { z } from \"zod\";\n\n// Error codes for programmatic error handling\nexport const RegistryErrorCode = {\n // Network errors\n NETWORK_ERROR: \"NETWORK_ERROR\",\n NOT_FOUND: \"NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n FETCH_ERROR: \"FETCH_ERROR\",\n\n // Configuration errors\n NOT_CONFIGURED: \"NOT_CONFIGURED\",\n INVALID_CONFIG: \"INVALID_CONFIG\",\n MISSING_ENV_VARS: \"MISSING_ENV_VARS\",\n\n // File system errors\n LOCAL_FILE_ERROR: \"LOCAL_FILE_ERROR\",\n\n // Parsing errors\n PARSE_ERROR: \"PARSE_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n\n // Generic errors\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\nexport type RegistryErrorCode =\n (typeof RegistryErrorCode)[keyof typeof RegistryErrorCode];\n\nexport class RegistryError extends Error {\n public readonly code: RegistryErrorCode;\n public readonly statusCode?: number;\n public readonly context?: Record<string, unknown>;\n public readonly suggestion?: string;\n public readonly timestamp: Date;\n public readonly cause?: unknown;\n\n constructor(\n message: string,\n options: {\n code?: RegistryErrorCode;\n statusCode?: number;\n cause?: unknown;\n context?: Record<string, unknown>;\n suggestion?: string;\n } = {},\n ) {\n super(message);\n this.name = \"RegistryError\";\n this.code = options.code || RegistryErrorCode.UNKNOWN_ERROR;\n this.statusCode = options.statusCode;\n this.cause = options.cause;\n this.context = options.context;\n this.suggestion = options.suggestion;\n this.timestamp = new Date();\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n context: this.context,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n stack: this.stack,\n };\n }\n}\n\nexport class RegistryNotFoundError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `The item at ${url} was not found. It may not exist at the registry.`;\n\n super(message, {\n code: RegistryErrorCode.NOT_FOUND,\n statusCode: 404,\n cause,\n context: { url },\n suggestion:\n \"Check if the item name is correct and the registry URL is accessible.\",\n });\n this.name = \"RegistryNotFoundError\";\n }\n}\n\nexport class RegistryUnauthorizedError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`;\n\n super(message, {\n code: RegistryErrorCode.UNAUTHORIZED,\n statusCode: 401,\n cause,\n context: { url },\n suggestion:\n \"Check your authentication credentials and environment variables.\",\n });\n this.name = \"RegistryUnauthorizedError\";\n }\n}\n\nexport class RegistryForbiddenError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`;\n\n super(message, {\n code: RegistryErrorCode.FORBIDDEN,\n statusCode: 403,\n cause,\n context: { url },\n suggestion:\n \"Check your authentication credentials and environment variables.\",\n });\n this.name = \"RegistryForbiddenError\";\n }\n}\n\nexport class RegistryFetchError extends RegistryError {\n constructor(\n public readonly url: string,\n statusCode?: number,\n public readonly responseBody?: string,\n cause?: unknown,\n ) {\n // Use the error detail from the server if available\n const baseMessage = statusCode\n ? `Failed to fetch from registry (${statusCode}): ${url}`\n : `Failed to fetch from registry: ${url}`;\n\n const message =\n typeof cause === \"string\" && cause\n ? `${baseMessage} - ${cause}`\n : baseMessage;\n\n let suggestion = \"Check your network connection and try again.\";\n if (statusCode === 404) {\n suggestion =\n \"The requested resource was not found. Check the URL or item name.\";\n } else if (statusCode === 500) {\n suggestion = \"The registry server encountered an error. Try again later.\";\n } else if (statusCode && statusCode >= 400 && statusCode < 500) {\n suggestion = \"There was a client error. Check your request parameters.\";\n }\n\n super(message, {\n code: RegistryErrorCode.FETCH_ERROR,\n statusCode,\n cause,\n context: { url, responseBody },\n suggestion,\n });\n this.name = \"RegistryFetchError\";\n }\n}\n\nexport class RegistryNotConfiguredError extends RegistryError {\n constructor(public readonly registryName: string | null) {\n const message = registryName\n ? `Unknown registry \"${registryName}\". Make sure it is defined in components.json as follows:\n{\n \"registries\": {\n \"${registryName}\": \"[URL_TO_REGISTRY]\"\n }\n}`\n : `Unknown registry. Make sure it is defined in components.json under \"registries\".`;\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { registryName },\n suggestion:\n \"Add the registry configuration to your components.json file. Consult the registry documentation for the correct format.\",\n });\n this.name = \"RegistryNotConfiguredError\";\n }\n}\n\nexport class RegistryLocalFileError extends RegistryError {\n constructor(\n public readonly filePath: string,\n cause?: unknown,\n ) {\n super(`Failed to read local registry file: ${filePath}`, {\n code: RegistryErrorCode.LOCAL_FILE_ERROR,\n cause,\n context: { filePath },\n suggestion: \"Check if the file exists and you have read permissions.\",\n });\n this.name = \"RegistryLocalFileError\";\n }\n}\n\nexport class RegistryParseError extends RegistryError {\n public readonly parseError: unknown;\n\n constructor(\n public readonly item: string,\n parseError: unknown,\n ) {\n let message = `Failed to parse registry item: ${item}`;\n\n if (parseError instanceof z.ZodError) {\n message = `Failed to parse registry item: ${item}\\n${parseError.errors\n .map((e) => ` - ${e.path.join(\".\")}: ${e.message}`)\n .join(\"\\n\")}`;\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { item },\n suggestion:\n \"The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object. See https://ui.shadcn.com/schema/registry-item.json.\",\n });\n\n this.parseError = parseError;\n this.name = \"RegistryParseError\";\n }\n}\n\nexport class RegistryMissingEnvironmentVariablesError extends RegistryError {\n constructor(\n public readonly registryName: string,\n public readonly missingVars: string[],\n ) {\n const message =\n `Registry \"${registryName}\" requires the following environment variables:\\n\\n` +\n missingVars.map((v) => ` • ${v}`).join(\"\\n\");\n\n super(message, {\n code: RegistryErrorCode.MISSING_ENV_VARS,\n context: { registryName, missingVars },\n suggestion:\n \"Set the required environment variables to your .env or .env.local file.\",\n });\n this.name = \"RegistryMissingEnvironmentVariablesError\";\n }\n}\n\nexport class RegistryInvalidNamespaceError extends RegistryError {\n constructor(public readonly name: string) {\n const message = `Invalid registry namespace: \"${name}\". Registry names must start with @ (e.g., @shadcn, @v0).`;\n\n super(message, {\n code: RegistryErrorCode.VALIDATION_ERROR,\n context: { name },\n suggestion:\n \"Use a valid registry name starting with @ or provide a direct URL to the registry.\",\n });\n this.name = \"RegistryInvalidNamespaceError\";\n }\n}\n\nexport class ConfigMissingError extends RegistryError {\n constructor(public readonly cwd: string) {\n const message = `No components.json found in ${cwd} or parent directories.`;\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { cwd },\n suggestion:\n \"Run 'npx shadcn@latest init' to create a components.json file, or check that you're in the correct directory.\",\n });\n this.name = \"ConfigMissingError\";\n }\n}\n\nexport class ConfigParseError extends RegistryError {\n constructor(\n public readonly cwd: string,\n parseError: unknown,\n ) {\n let message = `Invalid components.json configuration in ${cwd}.`;\n\n if (parseError instanceof z.ZodError) {\n message = `Invalid components.json configuration in ${cwd}:\\n${parseError.errors\n .map((e) => ` - ${e.path.join(\".\")}: ${e.message}`)\n .join(\"\\n\")}`;\n }\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n cause: parseError,\n context: { cwd },\n suggestion:\n \"Check your components.json file for syntax errors or invalid configuration. Run 'npx shadcn@latest init' to regenerate a valid configuration.\",\n });\n this.name = \"ConfigParseError\";\n }\n}\n","import { RegistryError } from \"@/src/registry/errors\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { z } from \"zod\";\n\nexport function handleError(error: unknown) {\n logger.break();\n logger.error(\n `Something went wrong. Please check the error below for more details.`,\n );\n logger.error(\n `If the problem persists, please open an issue on GitHub: https://github.com/bejamas/ui/issues`,\n );\n logger.error(\"\");\n if (typeof error === \"string\") {\n logger.error(error);\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof RegistryError) {\n if (error.message) {\n logger.error(error.cause ? \"Error:\" : \"Message:\");\n logger.error(error.message);\n }\n\n if (error.cause) {\n logger.error(\"\\nMessage:\");\n logger.error(error.cause);\n }\n\n if (error.suggestion) {\n logger.error(\"\\nSuggestion:\");\n logger.error(error.suggestion);\n }\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof z.ZodError) {\n logger.error(\"Validation failed:\");\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${highlighter.info(key)}: ${value}`);\n }\n logger.break();\n process.exit(1);\n }\n\n if (error instanceof Error) {\n logger.error(error.message);\n logger.break();\n process.exit(1);\n }\n\n logger.break();\n process.exit(1);\n}\n","import os from \"os\";\nimport path from \"path\";\nimport dotenv from \"dotenv\";\nimport { initOptionsSchema } from \"@/src/commands/init\";\nimport { getPackageManager } from \"@/src/utils/get-package-manager\";\nimport { handleError } from \"@/src/utils/handle-error\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { spinner } from \"@/src/utils/spinner\";\nimport { execa } from \"execa\";\nimport fs from \"fs-extra\";\nimport prompts from \"prompts\";\nimport { z } from \"zod\";\n\nexport const TEMPLATES = {\n astro: \"astro\",\n \"astro-monorepo\": \"astro-monorepo\",\n \"astro-with-component-docs-monorepo\": \"astro-with-component-docs-monorepo\",\n} as const;\n\nconst MONOREPO_TEMPLATE_URL =\n \"https://codeload.github.com/bejamas/ui/tar.gz/main\";\n\nexport async function createProject(\n options: Pick<\n z.infer<typeof initOptionsSchema>,\n \"cwd\" | \"force\" | \"srcDir\" | \"components\" | \"template\"\n >,\n) {\n options = {\n srcDir: false,\n ...options,\n };\n\n let template: keyof typeof TEMPLATES =\n options.template && TEMPLATES[options.template as keyof typeof TEMPLATES]\n ? (options.template as keyof typeof TEMPLATES)\n : \"astro\";\n\n let projectName: string = \"my-app\";\n\n const isRemoteComponent =\n options.components?.length === 1 &&\n !!options.components[0].match(/\\/chat\\/b\\//);\n\n if (!options.force) {\n const { type, name } = await prompts([\n {\n type: options.template || isRemoteComponent ? null : \"select\",\n name: \"type\",\n message: `The path ${highlighter.info(\n options.cwd,\n )} does not contain a package.json file.\\n Would you like to start a new project?`,\n choices: [\n { title: \"Astro\", value: \"astro\" },\n { title: \"Astro (Monorepo)\", value: \"astro-monorepo\" },\n {\n title: \"Astro with Component Docs (Monorepo)\",\n value: \"astro-with-component-docs-monorepo\",\n },\n ],\n initial: 0,\n },\n {\n type: \"text\",\n name: \"name\",\n message: \"What is your project named?\",\n initial: (_prev: any, values: any) => {\n const selectedTemplate: string =\n (options.template &&\n TEMPLATES[options.template as keyof typeof TEMPLATES] &&\n options.template) ||\n values.type ||\n template;\n return selectedTemplate?.endsWith(\"monorepo\")\n ? \"my-monorepo\"\n : \"my-app\";\n },\n format: (value: string) => value.trim(),\n validate: (value: string) =>\n value.length > 128\n ? `Name should be less than 128 characters.`\n : true,\n },\n ]);\n\n template = type ?? template;\n projectName = name;\n }\n\n const packageManager = await getPackageManager(options.cwd, {\n withFallback: true,\n });\n\n const projectPath = `${options.cwd}/${projectName}`;\n\n // Check if path is writable.\n try {\n await fs.access(options.cwd, fs.constants.W_OK);\n } catch (error) {\n logger.break();\n logger.error(`The path ${highlighter.info(options.cwd)} is not writable.`);\n logger.error(\n `It is likely you do not have write permissions for this folder or the path ${highlighter.info(\n options.cwd,\n )} does not exist.`,\n );\n logger.break();\n process.exit(1);\n }\n\n if (fs.existsSync(path.resolve(options.cwd, projectName, \"package.json\"))) {\n logger.break();\n logger.error(\n `A project with the name ${highlighter.info(projectName)} already exists.`,\n );\n logger.error(`Please choose a different name and try again.`);\n logger.break();\n process.exit(1);\n }\n\n await createProjectFromTemplate(projectPath, {\n templateKey: template,\n packageManager,\n cwd: options.cwd,\n });\n\n return {\n projectPath,\n projectName,\n template,\n };\n}\n\nasync function createProjectFromTemplate(\n projectPath: string,\n options: {\n templateKey: keyof typeof TEMPLATES;\n packageManager: string;\n cwd: string;\n },\n) {\n const createSpinner = spinner(\n `Creating a new project from template. This may take a few minutes.`,\n ).start();\n\n const TEMPLATE_TAR_SUBPATH: Record<keyof typeof TEMPLATES, string> = {\n astro: \"ui-main/templates/astro\",\n \"astro-monorepo\": \"ui-main/templates/monorepo-astro\",\n \"astro-with-component-docs-monorepo\":\n \"ui-main/templates/monorepo-astro-with-docs\",\n };\n\n try {\n // Load local .env if present to allow GITHUB_TOKEN/GH_TOKEN\n dotenv.config({ quiet: true });\n const templatePath = path.join(\n os.tmpdir(),\n `bejamas-template-${Date.now()}`,\n );\n await fs.ensureDir(templatePath);\n\n // Auth via environment variables (.env supported)\n const authToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;\n const usedAuth = Boolean(authToken);\n const headers: Record<string, string> = {\n \"User-Agent\": \"bejamas-cli\",\n };\n if (authToken) {\n headers[\"Authorization\"] = `Bearer ${authToken}`;\n }\n\n const response = await fetch(MONOREPO_TEMPLATE_URL, { headers });\n if (!response.ok) {\n if (\n response.status === 401 ||\n response.status === 403 ||\n (!usedAuth && response.status === 404)\n ) {\n throw new Error(\n \"Unauthorized to access private template. Set GITHUB_TOKEN or GH_TOKEN (in .env or env) with repo access and try again.\",\n );\n }\n if (response.status === 404) {\n throw new Error(\"Failed to download template: not found.\");\n }\n throw new Error(\n `Failed to download template: ${response.status} ${response.statusText}`,\n );\n }\n\n const tarPath = path.resolve(templatePath, \"template.tar.gz\");\n await fs.writeFile(tarPath, Buffer.from(await response.arrayBuffer()));\n\n const tarSubpath = TEMPLATE_TAR_SUBPATH[options.templateKey];\n const leafName = tarSubpath.split(\"/\").pop() as string;\n\n await execa(\"tar\", [\n \"-xzf\",\n tarPath,\n \"-C\",\n templatePath,\n \"--strip-components=2\",\n tarSubpath,\n ]);\n\n const extractedPath = path.resolve(templatePath, leafName);\n await fs.move(extractedPath, projectPath);\n await fs.remove(templatePath);\n\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n });\n\n try {\n // Detect if we're inside an existing git repo; if yes, skip initializing a nested repo\n const { stdout } = await execa(\n \"git\",\n [\"rev-parse\", \"--is-inside-work-tree\"],\n { cwd: projectPath },\n );\n const insideExistingRepo = stdout.trim() === \"true\";\n\n if (!insideExistingRepo) {\n await execa(\"git\", [\"init\"], { cwd: projectPath });\n await execa(\"git\", [\"add\", \"-A\"], { cwd: projectPath });\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit\"], {\n cwd: projectPath,\n });\n }\n } catch (_) {\n // ignore git detection/initialization failures\n }\n\n createSpinner?.succeed(\"Creating a new project from template.\");\n } catch (error) {\n createSpinner?.fail(\n \"Something went wrong creating a new project from template.\",\n );\n handleError(error);\n }\n}\n","import { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { preFlightInit } from \"@/src/preflights/preflight-init\";\n\nimport { BASE_COLORS, BUILTIN_REGISTRIES } from \"@/src/registry/constants\";\nimport { clearRegistryContext } from \"@/src/registry/context\";\n\nimport { TEMPLATES, createProject } from \"@/src/utils/create-project\";\nimport * as ERRORS from \"@/src/utils/errors\";\nimport { getConfig, createConfig, type Config } from \"@/src/utils/get-config\";\nimport { getProjectConfig, getProjectInfo } from \"@/src/utils/get-project-info\";\nimport { getPackageRunner } from \"@/src/utils/get-package-manager\";\nimport { handleError } from \"@/src/utils/handle-error\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { logger } from \"@/src/utils/logger\";\nimport { Command } from \"commander\";\nimport { execa } from \"execa\";\nimport fsExtra from \"fs-extra\";\nimport { z } from \"zod\";\n\n// process.on(\"exit\", (code) => {\n// const filePath = path.resolve(process.cwd(), \"components.json\")\n\n// // Delete backup if successful.\n// if (code === 0) {\n// return deleteFileBackup(filePath)\n// }\n\n// // Restore backup if error.\n// return restoreFileBackup(filePath)\n// })\n\n// Default fallback registry endpoint for shadcn (expects /r)\nconst DEFAULT_REGISTRY_URL = \"https://ui.bejamas.com/r\";\n\nexport const initOptionsSchema = z.object({\n cwd: z.string(),\n components: z.array(z.string()).optional(),\n yes: z.boolean(),\n defaults: z.boolean(),\n force: z.boolean(),\n silent: z.boolean(),\n isNewProject: z.boolean(),\n srcDir: z.boolean().optional(),\n cssVariables: z.boolean(),\n template: z\n .string()\n .optional()\n .refine(\n (val) => {\n if (val) {\n return TEMPLATES[val as keyof typeof TEMPLATES];\n }\n return true;\n },\n {\n message: \"Invalid template. Please use 'next' or 'next-monorepo'.\",\n },\n ),\n baseColor: z\n .string()\n .optional()\n .refine(\n (val) => {\n if (val) {\n return BASE_COLORS.find((color) => color.name === val);\n }\n\n return true;\n },\n {\n message: `Invalid base color. Please use '${BASE_COLORS.map(\n (color) => color.name,\n ).join(\"', '\")}'`,\n },\n ),\n baseStyle: z.boolean(),\n});\n\nexport const init = new Command()\n .name(\"init\")\n .description(\"initialize your project and install dependencies\")\n .argument(\"[components...]\", \"names, url or local path to component\")\n .option(\n \"-t, --template <template>\",\n \"the template to use. (next, next-monorepo)\",\n )\n .option(\n \"-b, --base-color <base-color>\",\n \"the base color to use. (neutral, gray, zinc, stone, slate)\",\n undefined,\n )\n .option(\"-y, --yes\", \"skip confirmation prompt.\", true)\n .option(\"-d, --defaults,\", \"use default configuration.\", false)\n .option(\"-f, --force\", \"force overwrite of existing configuration.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd(),\n )\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project.\",\n false,\n )\n .option(\n \"--no-src-dir\",\n \"do not use the src directory when creating a new project.\",\n )\n .option(\"--css-variables\", \"use css variables for theming.\", true)\n .option(\"--no-css-variables\", \"do not use css variables for theming.\")\n .option(\"--no-base-style\", \"do not install the base shadcn style.\")\n .action(async (_components, opts) => {\n try {\n await runInit(opts);\n } catch (error) {\n logger.break();\n handleError(error);\n } finally {\n clearRegistryContext();\n }\n });\n\nexport async function runInit(\n options: z.infer<typeof initOptionsSchema> & {\n skipPreflight?: boolean;\n },\n) {\n let projectInfo;\n let newProjectTemplate;\n if (!options.skipPreflight) {\n const preflight = await preFlightInit(options);\n\n if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {\n const { projectPath, template } = await createProject(options);\n if (!projectPath) {\n process.exit(1);\n }\n options.cwd = projectPath;\n options.isNewProject = true;\n newProjectTemplate = template;\n }\n projectInfo = preflight.projectInfo;\n } else {\n projectInfo = await getProjectInfo(options.cwd);\n }\n\n if (newProjectTemplate) {\n const projectPath = {\n \"astro-monorepo\": \"apps/web\",\n \"astro-with-component-docs-monorepo\": \"apps/web\",\n astro: \"\",\n } as const;\n options.cwd = path.resolve(options.cwd, projectPath[newProjectTemplate]);\n\n logger.log(\n `${highlighter.success(\n \"Success!\",\n )} Project initialization completed.\\nYou may now add components.`,\n );\n\n return await getConfig(options.cwd);\n }\n\n // const projectConfig = await getProjectConfig(options.cwd, projectInfo);\n\n const shadcnBin = process.platform === \"win32\" ? \"shadcn.cmd\" : \"shadcn\";\n const localShadcnPath = path.resolve(\n options.cwd,\n \"node_modules\",\n \".bin\",\n shadcnBin,\n );\n\n try {\n const env = {\n ...process.env,\n REGISTRY_URL: process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL,\n };\n if (await fsExtra.pathExists(localShadcnPath)) {\n await execa(localShadcnPath, [\"init\", \"--base-color\", \"neutral\"], {\n stdio: \"inherit\",\n cwd: options.cwd,\n env,\n });\n } else {\n // Follow user's runner preference (npx, bunx, pnpm dlx)\n await execa(\n \"npx\",\n [\"-y\", \"shadcn@latest\", \"init\", \"--base-color\", \"neutral\"],\n {\n stdio: \"inherit\",\n cwd: options.cwd,\n env,\n },\n );\n }\n } catch (err) {\n // shadcn already printed the detailed error to stdio, avoid double-reporting\n process.exit(1);\n }\n}\n","import { resolve } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\n\n/**\n * Read and parse tsconfig.json from the project root\n */\nexport function readTsConfig(projectRoot: string): any | null {\n try {\n const tsconfigPath = resolve(projectRoot, \"tsconfig.json\");\n if (!existsSync(tsconfigPath)) return null;\n const raw = readFileSync(tsconfigPath, \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve an alias path (like @/components) using tsconfig.json paths\n */\nexport function resolveAliasPathUsingTsConfig(\n inputPath: string,\n projectRoot: string,\n): string | null {\n const cfg = readTsConfig(projectRoot);\n if (!cfg || !cfg.compilerOptions) return null;\n const baseUrl: string = cfg.compilerOptions.baseUrl || \".\";\n const paths: Record<string, string[] | string> =\n cfg.compilerOptions.paths || {};\n for (const [key, values] of Object.entries(paths)) {\n const pattern = key.replace(/\\*/g, \"(.*)\");\n const re = new RegExp(`^${pattern}$`);\n const match = inputPath.match(re);\n if (!match) continue;\n const wildcard = match[1] || \"\";\n const first = Array.isArray(values) ? values[0] : values;\n if (!first) continue;\n const target = String(first).replace(/\\*/g, wildcard);\n return resolve(projectRoot, baseUrl, target);\n }\n return null;\n}\n","import { Command } from \"commander\";\nimport { resolve, isAbsolute, relative } from \"node:path\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { logger } from \"@/src/utils/logger\";\nimport { resolveAliasPathUsingTsConfig } from \"@/src/utils/tsconfig-utils\";\nimport prompts from \"prompts\";\n\nasync function generateDocs({\n cwd,\n outDir,\n verbose,\n}: {\n cwd?: string;\n outDir?: string;\n verbose?: boolean;\n}) {\n const DEBUG =\n process.env.BEJAMAS_DEBUG === \"1\" ||\n process.env.BEJAMAS_DEBUG === \"true\" ||\n verbose;\n\n try {\n const shellCwd = process.cwd();\n\n // Probe for components.json up the directory tree starting from shell CWD\n let projectRoot = shellCwd;\n let probe: string | null = shellCwd;\n for (let i = 0; i < 6 && probe; i += 1) {\n const candidate = resolve(probe, \"components.json\");\n if (existsSync(candidate)) {\n projectRoot = probe;\n try {\n const raw = readFileSync(candidate, \"utf-8\");\n const config = JSON.parse(raw);\n // If UI root not provided via CLI, try to infer from aliases.ui first\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.aliases?.ui) {\n const mapped: string = String(config.aliases.ui);\n let uiAbs: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n uiAbs = resolve(projectRoot, mapped);\n } else {\n uiAbs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n }\n if (!uiAbs && mapped.startsWith(\"@/\")) {\n uiAbs = resolve(projectRoot, \"src\", mapped.slice(2));\n }\n if (uiAbs) {\n process.env.BEJAMAS_UI_ROOT = uiAbs;\n }\n }\n // Fallback: infer UI root from tailwind.css\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.tailwind?.css) {\n const cssRaw = String(config.tailwind.css);\n let cssAbs: string | null = null;\n if (\n cssRaw.startsWith(\"./\") ||\n cssRaw.startsWith(\"../\") ||\n isAbsolute(cssRaw)\n ) {\n cssAbs = resolve(projectRoot, cssRaw);\n } else {\n cssAbs = resolveAliasPathUsingTsConfig(cssRaw, projectRoot);\n }\n if (!cssAbs && cssRaw.startsWith(\"@/\")) {\n cssAbs = resolve(projectRoot, \"src\", cssRaw.slice(2));\n }\n if (cssAbs) {\n const uiRootFromCss = resolve(cssAbs, \"..\", \"..\", \"..\");\n process.env.BEJAMAS_UI_ROOT = uiRootFromCss;\n }\n }\n // If out dir not provided via CLI, try to infer from aliases.docs\n if (!outDir && config?.aliases?.docs) {\n const mapped: string = String(config.aliases.docs);\n let outResolved: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n outResolved = mapped;\n } else {\n const abs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n if (abs) outResolved = relative(projectRoot, abs);\n }\n if (!outResolved && mapped.startsWith(\"@/\")) {\n outResolved = mapped.replace(/^@\\//, \"src/\");\n }\n // As a last resort, use the mapped value as-is so we do not prompt for output\n const finalOut = outResolved ?? mapped;\n if (finalOut && !process.env.BEJAMAS_DOCS_OUT_DIR) {\n process.env.BEJAMAS_DOCS_OUT_DIR = finalOut;\n process.env.BEJAMAS_DOCS_CWD = projectRoot;\n }\n }\n } catch {}\n break;\n }\n const parent = resolve(probe, \"..\");\n probe = parent === probe ? null : parent;\n }\n\n // Defaults if not already set from components.json\n if (!process.env.BEJAMAS_DOCS_CWD) {\n process.env.BEJAMAS_DOCS_CWD = shellCwd;\n }\n if (!process.env.BEJAMAS_UI_ROOT) {\n // Ask user for @bejamas/ui root when not inferred\n const defaultGuess = (() => {\n // Try local monorepo style packages/ui\n let current = shellCwd;\n for (let i = 0; i < 6; i += 1) {\n const cand = resolve(current, \"packages/ui/package.json\");\n if (existsSync(cand)) {\n const abs = resolve(current, \"packages/ui\");\n const rel = relative(shellCwd, abs);\n return rel || abs;\n }\n const parent = resolve(current, \"..\");\n if (parent === current) break;\n current = parent;\n }\n // Try installed node_modules fallback\n const nm = resolve(shellCwd, \"node_modules/@bejamas/ui/package.json\");\n if (existsSync(nm)) {\n const abs = resolve(shellCwd, \"node_modules/@bejamas/ui\");\n const rel = relative(shellCwd, abs);\n return rel || abs;\n }\n // Last resort: suggest a common local path\n return \"packages/ui\";\n })();\n const { uiRoot } = await prompts({\n type: \"text\",\n name: \"uiRoot\",\n message: \"Path to @bejamas/ui package root:\",\n initial: defaultGuess,\n validate: (val: string) => {\n const p = resolve(shellCwd, val);\n return existsSync(resolve(p, \"package.json\"))\n ? true\n : `No package.json found in ${p}`;\n },\n });\n if (!uiRoot) {\n logger.error(\"@bejamas/ui root is required to generate docs.\");\n process.exit(1);\n }\n process.env.BEJAMAS_UI_ROOT = resolve(shellCwd, uiRoot);\n }\n\n // CLI overrides take precedence\n if (cwd && cwd.length) {\n process.env.BEJAMAS_UI_ROOT = resolve(cwd);\n }\n if (outDir && outDir.length) {\n // Pass through exactly as provided; the generator will resolve against BEJAMAS_DOCS_CWD if needed.\n process.env.BEJAMAS_DOCS_OUT_DIR = outDir;\n }\n\n // If output dir still not defined, prompt the user\n if (!process.env.BEJAMAS_DOCS_OUT_DIR) {\n const { out } = await prompts({\n type: \"text\",\n name: \"out\",\n message: \"Where should we output docs (relative to project root)?\",\n initial: \"src/content/docs/components\",\n });\n if (!out) {\n logger.error(\"An output directory is required to generate docs.\");\n process.exit(1);\n }\n process.env.BEJAMAS_DOCS_OUT_DIR = out;\n process.env.BEJAMAS_DOCS_CWD = process.env.BEJAMAS_DOCS_CWD || shellCwd;\n }\n // Ensure the generator does not auto-run upon import; we'll invoke it explicitly\n process.env.BEJAMAS_SKIP_AUTO_RUN = \"1\";\n logger.info(`Generating docs...`);\n if (DEBUG) {\n logger.info(`Generator entry: @/src/docs/generate-mdx/index`);\n if (process.env.BEJAMAS_UI_ROOT)\n logger.info(`UI root: ${process.env.BEJAMAS_UI_ROOT}`);\n if (process.env.BEJAMAS_DOCS_CWD)\n logger.info(`Docs CWD: ${process.env.BEJAMAS_DOCS_CWD}`);\n if (process.env.BEJAMAS_DOCS_OUT_DIR)\n logger.info(`Docs out: ${process.env.BEJAMAS_DOCS_OUT_DIR}`);\n }\n const mod = await import(\"@/src/docs/generate-mdx/index\");\n if (typeof mod.runDocsGenerator === \"function\") {\n await mod.runDocsGenerator();\n } else {\n throw new Error(\n \"Failed to load docs generator. Export 'runDocsGenerator' not found.\",\n );\n }\n } catch (err: any) {\n logger.error(err?.message || String(err));\n process.exit(1);\n }\n}\n\nexport const docs = new Command()\n .name(\"docs:build\")\n .alias(\"docs\")\n .description(\"generate docs from @bejamas/ui components\")\n .option(\"-c, --cwd <cwd>\", \"path to UI working directory\")\n .option(\"-o, --out <outDir>\", \"output directory for generated MDX files\")\n .action(async (opts) => {\n await generateDocs({\n cwd: opts.cwd,\n outDir: opts.out,\n verbose: Boolean(opts.verbose),\n });\n });\n","import { Command } from \"commander\";\nimport { resolve, isAbsolute, join, extname } from \"node:path\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport {\n cyan,\n green,\n red,\n yellow,\n dim,\n bold,\n magenta,\n white,\n} from \"kleur/colors\";\nimport { logger } from \"@/src/utils/logger\";\nimport { resolveAliasPathUsingTsConfig } from \"@/src/utils/tsconfig-utils\";\nimport {\n extractFrontmatter,\n parseJsDocMetadata,\n resolveUiRoot,\n} from \"@/src/docs/generate-mdx/utils\";\n\ninterface ComponentDocStatus {\n name: string;\n file: string;\n status: \"complete\" | \"incomplete\" | \"missing\";\n missingRequired: string[];\n missingRecommended: string[];\n}\n\ninterface CheckResult {\n total: number;\n complete: ComponentDocStatus[];\n incomplete: ComponentDocStatus[];\n missing: ComponentDocStatus[];\n}\n\nconst REQUIRED_FIELDS = [\"name\", \"title\", \"description\"] as const;\nconst RECOMMENDED_FIELDS = [\n \"primaryExampleMDX\",\n \"usageMDX\",\n \"figmaUrl\",\n] as const;\n\nconst FIELD_LABELS: Record<string, string> = {\n name: \"@component\",\n title: \"@title\",\n description: \"@description\",\n primaryExampleMDX: \"@preview\",\n usageMDX: \"@usage\",\n figmaUrl: \"@figmaUrl\",\n};\n\nfunction checkComponentDocs(\n filePath: string,\n fileName: string,\n): ComponentDocStatus {\n const content = readFileSync(filePath, \"utf-8\");\n const frontmatter = extractFrontmatter(content);\n const meta = parseJsDocMetadata(frontmatter);\n\n const componentName = fileName.replace(/\\.astro$/i, \"\");\n const missingRequired: string[] = [];\n const missingRecommended: string[] = [];\n\n for (const field of REQUIRED_FIELDS) {\n const value = meta[field];\n if (!value || (typeof value === \"string\" && !value.trim())) {\n missingRequired.push(FIELD_LABELS[field] || field);\n }\n }\n\n for (const field of RECOMMENDED_FIELDS) {\n const value = meta[field];\n if (!value || (typeof value === \"string\" && !value.trim())) {\n missingRecommended.push(FIELD_LABELS[field] || field);\n }\n }\n\n let status: \"complete\" | \"incomplete\" | \"missing\";\n if (missingRequired.length > 0) {\n status = \"missing\";\n } else if (missingRecommended.length > 0) {\n status = \"incomplete\";\n } else {\n status = \"complete\";\n }\n\n return {\n name: componentName,\n file: fileName,\n status,\n missingRequired,\n missingRecommended,\n };\n}\n\nasync function checkDocs({\n cwd,\n json,\n}: {\n cwd?: string;\n json?: boolean;\n}): Promise<void> {\n try {\n const shellCwd = process.cwd();\n\n // Probe for components.json up the directory tree starting from shell CWD\n let projectRoot = shellCwd;\n let probe: string | null = shellCwd;\n for (let i = 0; i < 6 && probe; i += 1) {\n const candidate = resolve(probe, \"components.json\");\n if (existsSync(candidate)) {\n projectRoot = probe;\n try {\n const raw = readFileSync(candidate, \"utf-8\");\n const config = JSON.parse(raw);\n // If UI root not provided via CLI, try to infer from aliases.ui first\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.aliases?.ui) {\n const mapped: string = String(config.aliases.ui);\n let uiAbs: string | null = null;\n if (\n mapped.startsWith(\"./\") ||\n mapped.startsWith(\"../\") ||\n isAbsolute(mapped)\n ) {\n uiAbs = resolve(projectRoot, mapped);\n } else {\n uiAbs = resolveAliasPathUsingTsConfig(mapped, projectRoot);\n }\n if (!uiAbs && mapped.startsWith(\"@/\")) {\n uiAbs = resolve(projectRoot, \"src\", mapped.slice(2));\n }\n if (uiAbs) {\n process.env.BEJAMAS_UI_ROOT = uiAbs;\n }\n }\n // Fallback: infer UI root from tailwind.css\n if (!cwd && !process.env.BEJAMAS_UI_ROOT && config?.tailwind?.css) {\n const cssRaw = String(config.tailwind.css);\n let cssAbs: string | null = null;\n if (\n cssRaw.startsWith(\"./\") ||\n cssRaw.startsWith(\"../\") ||\n isAbsolute(cssRaw)\n ) {\n cssAbs = resolve(projectRoot, cssRaw);\n } else {\n cssAbs = resolveAliasPathUsingTsConfig(cssRaw, projectRoot);\n }\n if (!cssAbs && cssRaw.startsWith(\"@/\")) {\n cssAbs = resolve(projectRoot, \"src\", cssRaw.slice(2));\n }\n if (cssAbs) {\n const uiRootFromCss = resolve(cssAbs, \"..\", \"..\", \"..\");\n process.env.BEJAMAS_UI_ROOT = uiRootFromCss;\n }\n }\n } catch {}\n break;\n }\n const parent = resolve(probe, \"..\");\n probe = parent === probe ? null : parent;\n }\n\n // CLI override takes precedence\n if (cwd && cwd.length) {\n process.env.BEJAMAS_UI_ROOT = resolve(cwd);\n }\n\n let uiRoot: string;\n try {\n uiRoot = resolveUiRoot(shellCwd);\n } catch {\n logger.error(\n \"Unable to locate @bejamas/ui. Use --cwd to specify the UI package path.\",\n );\n process.exit(1);\n }\n\n const componentsDir = join(uiRoot, \"src\", \"components\");\n if (!existsSync(componentsDir)) {\n logger.error(\n `Components directory not found: ${componentsDir}\\n\\n` +\n `Expected structure: <uiRoot>/src/components/*.astro\\n` +\n `Use --cwd to specify a different UI package root.`,\n );\n process.exit(1);\n }\n\n const files = readdirSync(componentsDir, { withFileTypes: true })\n .filter((e) => e.isFile() && extname(e.name).toLowerCase() === \".astro\")\n .map((e) => e.name)\n .sort();\n\n if (files.length === 0) {\n logger.warn(\"No .astro component files found.\");\n process.exit(0);\n }\n\n const results: ComponentDocStatus[] = [];\n for (const file of files) {\n const filePath = join(componentsDir, file);\n const status = checkComponentDocs(filePath, file);\n results.push(status);\n }\n\n const complete = results.filter((r) => r.status === \"complete\");\n const incomplete = results.filter((r) => r.status === \"incomplete\");\n const missing = results.filter((r) => r.status === \"missing\");\n\n const checkResult: CheckResult = {\n total: results.length,\n complete,\n incomplete,\n missing,\n };\n\n if (json) {\n console.log(JSON.stringify(checkResult, null, 2));\n // Exit with error code if there are components missing required docs\n if (missing.length > 0) {\n process.exit(1);\n }\n return;\n }\n\n // Print formatted report\n const termWidth = Math.min(80, process.stdout.columns || 80);\n const headerLine = \"━\".repeat(termWidth);\n\n logger.break();\n console.log(dim(\"┌\" + \"─\".repeat(termWidth - 2) + \"┐\"));\n console.log(\n dim(\"│\") +\n bold(cyan(\" docs:check\")) +\n dim(\" — Component Documentation Status\") +\n \" \".repeat(Math.max(0, termWidth - 47)) +\n dim(\"│\"),\n );\n console.log(dim(\"└\" + \"─\".repeat(termWidth - 2) + \"┘\"));\n logger.break();\n\n // Helper to format tags with color\n const formatTag = (tag: string) => magenta(tag);\n const formatComponentName = (name: string) => bold(white(name));\n\n // Complete components\n if (complete.length > 0) {\n console.log(\n green(\n `✓ Complete (${complete.length} component${complete.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n const names = complete\n .map((c) => formatComponentName(c.name))\n .join(dim(\", \"));\n console.log(` ${names}`);\n logger.break();\n }\n\n // Incomplete components (missing recommended fields)\n if (incomplete.length > 0) {\n console.log(\n yellow(\n `⚠ Incomplete (${incomplete.length} component${incomplete.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n for (const comp of incomplete) {\n const missingFields = comp.missingRecommended\n .map(formatTag)\n .join(dim(\", \"));\n console.log(\n ` ${formatComponentName(comp.name)} ${dim(\"-\")} ${dim(\"missing:\")} ${missingFields}`,\n );\n }\n logger.break();\n }\n\n // Missing docs (missing required fields)\n if (missing.length > 0) {\n console.log(\n red(\n `✗ Missing Docs (${missing.length} component${missing.length === 1 ? \"\" : \"s\"}):`,\n ),\n );\n for (const comp of missing) {\n const missingFields = comp.missingRequired\n .map(formatTag)\n .join(dim(\", \"));\n console.log(\n ` ${formatComponentName(comp.name)} ${dim(\"-\")} ${dim(\"missing:\")} ${missingFields}`,\n );\n }\n logger.break();\n }\n\n // Summary\n console.log(dim(headerLine));\n const completeText = green(`${complete.length}/${results.length} complete`);\n const incompleteText =\n incomplete.length > 0\n ? yellow(`${incomplete.length} incomplete`)\n : dim(`${incomplete.length} incomplete`);\n const missingText =\n missing.length > 0\n ? red(`${missing.length} missing docs`)\n : dim(`${missing.length} missing docs`);\n console.log(\n `${bold(\"Summary:\")} ${completeText} ${dim(\"|\")} ${incompleteText} ${dim(\"|\")} ${missingText}`,\n );\n logger.break();\n\n // Exit with error code if there are components missing required docs\n if (missing.length > 0) {\n process.exit(1);\n }\n } catch (err: any) {\n logger.error(err?.message || String(err));\n process.exit(1);\n }\n}\n\nexport const docsCheck = new Command()\n .name(\"docs:check\")\n .description(\"check documentation status for all components\")\n .option(\"-c, --cwd <cwd>\", \"path to UI working directory\")\n .option(\"--json\", \"output results as JSON\")\n .action(async (opts) => {\n await checkDocs({\n cwd: opts.cwd,\n json: Boolean(opts.json),\n });\n });\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport fg from \"fast-glob\";\nimport { logger } from \"@/src/utils/logger\";\nimport { Config, getConfig } from \"@/src/utils/get-config\";\n\nexport function updateImportAliases(\n moduleSpecifier: string,\n config: Config,\n isRemote: boolean = false,\n) {\n // Not a local import.\n if (!moduleSpecifier.startsWith(\"@/\") && !isRemote) {\n return moduleSpecifier;\n }\n\n // This treats the remote as coming from a faux registry.\n let specifier = moduleSpecifier;\n if (isRemote && specifier.startsWith(\"@/\")) {\n specifier = specifier.replace(/^@\\//, \"@/registry/new-york/\");\n }\n\n // Not a registry import.\n if (!specifier.startsWith(\"@/registry/\")) {\n // We fix the alias and return.\n const alias = config.aliases.components.split(\"/\")[0];\n return specifier.replace(/^@\\//, `${alias}/`);\n }\n\n if (specifier.match(/^@\\/registry\\/(.+)\\/ui/)) {\n return specifier.replace(\n /^@\\/registry\\/(.+)\\/ui/,\n config.aliases.ui ?? `${config.aliases.components}/ui`,\n );\n }\n\n if (\n config.aliases.components &&\n specifier.match(/^@\\/registry\\/(.+)\\/components/)\n ) {\n return specifier.replace(\n /^@\\/registry\\/(.+)\\/components/,\n config.aliases.components,\n );\n }\n\n if (config.aliases.lib && specifier.match(/^@\\/registry\\/(.+)\\/lib/)) {\n return specifier.replace(/^@\\/registry\\/(.+)\\/lib/, config.aliases.lib);\n }\n\n if (config.aliases.hooks && specifier.match(/^@\\/registry\\/(.+)\\/hooks/)) {\n return specifier.replace(/^@\\/registry\\/(.+)\\/hooks/, config.aliases.hooks);\n }\n\n return specifier.replace(/^@\\/registry\\/[^/]+/, config.aliases.components);\n}\n\nexport function rewriteAstroImports(content: string, config: Config) {\n let updated = content;\n\n const utilsAlias = config.aliases?.utils;\n const workspaceAlias =\n typeof utilsAlias === \"string\" && utilsAlias.includes(\"/\")\n ? utilsAlias.split(\"/\")[0]\n : \"@\";\n const utilsImport = `${workspaceAlias}/lib/utils`;\n\n // Handle standard imports with specifiers, e.g. `import { x } from \"path\"`\n updated = updated.replace(\n /import\\s+([\\s\\S]*?)\\s+from\\s+[\"']([^\"']+)[\"']/g,\n (full, importsPart, specifier) => {\n const next = updateImportAliases(specifier, config, false);\n\n let finalSpec = next;\n const includesCn =\n typeof importsPart === \"string\" &&\n importsPart.split(/[{},\\s]/).some((part: string) => part === \"cn\");\n\n if (\n includesCn &&\n config.aliases.utils &&\n (next === utilsImport || next === \"@/lib/utils\")\n ) {\n finalSpec =\n utilsImport === next\n ? next.replace(utilsImport, config.aliases.utils)\n : config.aliases.utils;\n }\n\n if (finalSpec === specifier) return full;\n return full.replace(specifier, finalSpec);\n },\n );\n\n // Handle bare imports, e.g. `import \"path\"`\n updated = updated.replace(/import\\s+[\"']([^\"']+)[\"']/g, (full, specifier) => {\n const next = updateImportAliases(specifier, config, false);\n if (next === specifier) return full;\n return full.replace(specifier, next);\n });\n\n return updated;\n}\n\nexport async function fixAstroImports(cwd: string, isVerbose: boolean) {\n const config = await getConfig(cwd);\n if (!config) return;\n\n const searchRoots = new Set<string>([\n config.resolvedPaths.components,\n config.resolvedPaths.ui,\n ]);\n\n for (const root of Array.from(searchRoots)) {\n if (!root) continue;\n const astroFiles = await fg(\"**/*.astro\", {\n cwd: root,\n absolute: true,\n dot: false,\n });\n\n for (const filePath of astroFiles) {\n const original = await fs.readFile(filePath, \"utf8\");\n const rewritten = rewriteAstroImports(original, config);\n if (rewritten === original) continue;\n await fs.writeFile(filePath, rewritten, \"utf8\");\n if (isVerbose) {\n logger.info(\n `[bejamas-ui] fixed imports in ${path.relative(cwd, filePath)}`,\n );\n }\n }\n }\n}\n\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { logger } from \"@/src/utils/logger\";\n\nexport interface RegistryFile {\n path: string;\n content: string;\n type: string;\n target?: string;\n}\n\nexport interface RegistryItem {\n name: string;\n type: string;\n files: RegistryFile[];\n dependencies?: string[];\n devDependencies?: string[];\n registryDependencies?: string[];\n}\n\n/** Maps filename to subfolder/filename for path rewriting */\nexport type PathRewriteMap = Map<string, string>;\n\n/**\n * Fetches a registry item JSON from the registry URL.\n */\nexport async function fetchRegistryItem(\n componentName: string,\n registryUrl: string,\n): Promise<RegistryItem | null> {\n // Handle style-prefixed URLs (e.g., styles/new-york-v4/avatar.json)\n const url = `${registryUrl}/styles/new-york-v4/${componentName}.json`;\n\n try {\n const response = await fetch(url);\n if (!response.ok) {\n // Try without styles prefix as fallback\n const fallbackUrl = `${registryUrl}/${componentName}.json`;\n const fallbackResponse = await fetch(fallbackUrl);\n if (!fallbackResponse.ok) {\n return null;\n }\n return (await fallbackResponse.json()) as RegistryItem;\n }\n return (await response.json()) as RegistryItem;\n } catch {\n return null;\n }\n}\n\n/**\n * Extracts the subfolder name from registry file paths.\n * E.g., \"components/ui/avatar/Avatar.astro\" → \"avatar\"\n */\nexport function getSubfolderFromPaths(files: RegistryFile[]): string | null {\n // Only consider registry:ui files\n const uiFiles = files.filter((f) => f.type === \"registry:ui\");\n if (uiFiles.length < 2) {\n // Single file components don't need subfolders\n return null;\n }\n\n const subfolders = new Set<string>();\n\n for (const file of uiFiles) {\n const parts = file.path.split(\"/\");\n // Look for pattern: .../ui/<subfolder>/<filename>\n const uiIndex = parts.indexOf(\"ui\");\n if (uiIndex !== -1 && parts.length > uiIndex + 2) {\n // There's at least one folder after \"ui\" before the filename\n subfolders.add(parts[uiIndex + 1]);\n }\n }\n\n // If all files share the same subfolder, use it\n if (subfolders.size === 1) {\n return Array.from(subfolders)[0];\n }\n\n // Fallback: use the component name from the first file's parent directory\n if (uiFiles.length > 0) {\n const firstPath = uiFiles[0].path;\n const dirname = path.dirname(firstPath);\n const folderName = path.basename(dirname);\n // Only use if it's not \"ui\" itself\n if (folderName && folderName !== \"ui\") {\n return folderName;\n }\n }\n\n return null;\n}\n\n/**\n * Checks if a path exists.\n */\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Builds a map of path rewrites for components that will be reorganized.\n * Call this BEFORE shadcn runs to know how to rewrite output paths.\n */\nexport async function buildPathRewriteMap(\n components: string[],\n uiDir: string,\n registryUrl: string,\n): Promise<PathRewriteMap> {\n const rewrites: PathRewriteMap = new Map();\n\n if (!uiDir || components.length === 0) {\n return rewrites;\n }\n\n for (const componentName of components) {\n try {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) continue;\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) continue;\n\n // Get the UI files that will be reorganized\n const uiFiles = registryItem.files.filter(\n (f) => f.type === \"registry:ui\",\n );\n\n for (const file of uiFiles) {\n const filename = path.basename(file.path);\n // Map: \"Avatar.astro\" → \"avatar/Avatar.astro\"\n rewrites.set(filename, `${subfolder}/${filename}`);\n }\n } catch {\n // Ignore errors, just skip this component\n }\n }\n\n return rewrites;\n}\n\n/**\n * Rewrites file paths in shadcn output to reflect reorganized structure.\n * Replaces flat paths like \"/ui/Avatar.astro\" with \"/ui/avatar/Avatar.astro\"\n */\nexport function rewriteOutputPaths(\n output: string,\n rewrites: PathRewriteMap,\n): string {\n let result = output;\n\n for (const [filename, newPath] of rewrites) {\n // Match paths ending with the filename (handles various path formats)\n // e.g., \"packages/ui/src/components/Avatar.astro\" → \"packages/ui/src/components/avatar/Avatar.astro\"\n const escapedFilename = filename.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`(/[^/\\\\s]+)/${escapedFilename}(?=\\\\s|$|\\\\n)`, \"g\");\n result = result.replace(pattern, `$1/${newPath}`);\n }\n\n return result;\n}\n\nexport interface ReorganizeResult {\n totalMoved: number;\n movedFiles: string[]; // e.g., [\"avatar/Avatar.astro\", \"avatar/index.ts\"]\n skippedFiles: string[]; // Files that already existed in subfolder (flat duplicate removed)\n}\n\n/**\n * Reorganizes multi-file components into correct subfolders.\n * Only moves files from FLAT location to subfolder.\n * Does NOT touch files already in subfolders.\n * E.g., moves `uiDir/Avatar.astro` to `uiDir/avatar/Avatar.astro`.\n * Returns info about moved files for display purposes.\n */\nexport async function reorganizeComponents(\n components: string[],\n uiDir: string,\n registryUrl: string,\n verbose: boolean,\n): Promise<ReorganizeResult> {\n const result: ReorganizeResult = { totalMoved: 0, movedFiles: [], skippedFiles: [] };\n\n if (!uiDir || components.length === 0) {\n return result;\n }\n\n for (const componentName of components) {\n try {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) {\n if (verbose) {\n logger.info(\n `[bejamas-ui] Could not fetch registry for ${componentName}, skipping reorganization`,\n );\n }\n continue;\n }\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) {\n // Single-file component or no subfolder detected, skip\n if (verbose) {\n logger.info(\n `[bejamas-ui] ${componentName} is single-file or has no subfolder, skipping`,\n );\n }\n continue;\n }\n\n // Get the UI files that need to be moved\n const uiFiles = registryItem.files.filter(\n (f) => f.type === \"registry:ui\",\n );\n\n const targetDir = path.join(uiDir, subfolder);\n let movedCount = 0;\n\n for (const file of uiFiles) {\n const filename = path.basename(file.path);\n // Only look for files in FLAT location (directly in uiDir)\n const flatPath = path.join(uiDir, filename);\n const targetPath = path.join(targetDir, filename);\n\n // Check if file exists in flat location\n if (!(await pathExists(flatPath))) {\n // Not in flat location, skip (may already be in subfolder)\n continue;\n }\n\n // Check if target already exists (don't overwrite, but clean up flat duplicate)\n if (await pathExists(targetPath)) {\n // Target exists in subfolder - delete the flat duplicate shadcn just created\n try {\n await fs.unlink(flatPath);\n result.skippedFiles.push(`${subfolder}/${filename}`);\n if (verbose) {\n logger.info(\n `[bejamas-ui] Removed flat duplicate: ${filename} (${subfolder}/${filename} exists)`,\n );\n }\n } catch {\n // Flat file might not exist or already deleted, but still counts as skipped\n result.skippedFiles.push(`${subfolder}/${filename}`);\n }\n continue;\n }\n\n // Create target directory if needed\n await fs.mkdir(targetDir, { recursive: true });\n\n // Move file from flat to subfolder\n await fs.rename(flatPath, targetPath);\n movedCount++;\n result.totalMoved++;\n result.movedFiles.push(`${subfolder}/${filename}`);\n\n if (verbose) {\n logger.info(`[bejamas-ui] Moved ${filename} → ${subfolder}/${filename}`);\n }\n }\n\n if (movedCount > 0 && verbose) {\n logger.info(\n `[bejamas-ui] Reorganized ${componentName} into ${subfolder}/`,\n );\n }\n } catch (err) {\n // Non-fatal: log and continue with other components\n if (verbose) {\n logger.warn(\n `[bejamas-ui] Failed to reorganize ${componentName}: ${err}`,\n );\n }\n }\n }\n\n return result;\n}\n\n","import path from \"node:path\";\nimport { Command } from \"commander\";\nimport { execa } from \"execa\";\nimport { logger } from \"@/src/utils/logger\";\nimport { spinner } from \"@/src/utils/spinner\";\nimport { highlighter } from \"@/src/utils/highlighter\";\nimport { getPackageRunner } from \"@/src/utils/get-package-manager\";\nimport { fixAstroImports } from \"@/src/utils/astro-imports\";\nimport { getConfig, getWorkspaceConfig } from \"@/src/utils/get-config\";\nimport {\n reorganizeComponents,\n fetchRegistryItem,\n getSubfolderFromPaths,\n} from \"@/src/utils/reorganize-components\";\n\ninterface ParsedOutput {\n created: string[];\n updated: string[];\n skipped: string[];\n}\n\n// Default fallback registry endpoint for shadcn (expects /r)\nconst DEFAULT_REGISTRY_URL = \"https://ui.bejamas.com/r\";\n\n// Derive only the user-provided flags for shadcn to avoid losing options\nfunction extractOptionsForShadcn(rawArgv: string[], cmd: Command): string[] {\n // Prefer commander metadata when available so we only forward options that\n // were explicitly set (avoids defaults and keeps aliases consistent).\n if (typeof cmd.getOptionValueSource === \"function\") {\n const opts = cmd.optsWithGlobals() as Record<string, unknown>;\n const forwarded: string[] = [];\n const getSource = (key: string) => cmd.getOptionValueSource(key);\n\n const addBoolean = (key: string, flag: string, negateFlag?: string) => {\n if (getSource(key) !== \"cli\") return;\n const value = opts[key];\n if (typeof value !== \"boolean\") return;\n if (value) {\n forwarded.push(flag);\n } else if (negateFlag) {\n forwarded.push(negateFlag);\n }\n };\n\n const addString = (key: string, flag: string) => {\n if (getSource(key) !== \"cli\") return;\n const value = opts[key];\n if (typeof value === \"string\") {\n forwarded.push(flag, value);\n }\n };\n\n addBoolean(\"yes\", \"--yes\");\n addBoolean(\"overwrite\", \"--overwrite\");\n addString(\"cwd\", \"--cwd\");\n addBoolean(\"all\", \"--all\");\n addString(\"path\", \"--path\");\n addBoolean(\"silent\", \"--silent\");\n addBoolean(\"srcDir\", \"--src-dir\", \"--no-src-dir\");\n\n // Preserve any explicit passthrough after \"--\" for shadcn.\n const addIndex = rawArgv.findIndex((arg) => arg === \"add\");\n if (addIndex !== -1) {\n const rest = rawArgv.slice(addIndex + 1);\n const doubleDashIndex = rest.indexOf(\"--\");\n if (doubleDashIndex !== -1) {\n forwarded.push(...rest.slice(doubleDashIndex));\n }\n }\n\n return forwarded;\n }\n\n // Fallback: lightweight parser that only forwards known options.\n const addIndex = rawArgv.findIndex((arg) => arg === \"add\");\n if (addIndex === -1) return [];\n const rest = rawArgv.slice(addIndex + 1);\n const forwarded: string[] = [];\n const optionsWithValues = new Set([\"-c\", \"--cwd\", \"-p\", \"--path\"]);\n const filteredFlags = new Set([\"-v\", \"--verbose\"]);\n\n for (let i = 0; i < rest.length; i += 1) {\n const token = rest[i];\n if (token === \"--\") {\n forwarded.push(\"--\", ...rest.slice(i + 1));\n break;\n }\n if (!token.startsWith(\"-\")) continue;\n if (filteredFlags.has(token)) continue;\n\n forwarded.push(token);\n if (token.includes(\"=\")) continue;\n\n if (optionsWithValues.has(token)) {\n const next = rest[i + 1];\n if (next) {\n forwarded.push(next);\n i += 1;\n }\n }\n }\n return forwarded;\n}\n\ninterface ComponentFileInfo {\n subfolder: string;\n files: string[]; // All filenames for this component\n}\n\ninterface SubfolderMapResult {\n // Maps unique filename -> subfolder/filename\n uniqueMap: Map<string, string>;\n // Maps component subfolder -> all its files (for grouping)\n componentInfo: Map<string, ComponentFileInfo>;\n // Set of shared filenames (like index.ts) that appear in multiple components\n sharedFilenames: Set<string>;\n}\n\n/** Build maps for path rewriting, handling filename collisions */\nasync function buildSubfolderMap(\n components: string[],\n registryUrl: string,\n): Promise<SubfolderMapResult> {\n const filenameToSubfolders = new Map<string, string[]>();\n const componentInfo = new Map<string, ComponentFileInfo>();\n\n // First pass: collect all filename -> subfolder mappings\n for (const componentName of components) {\n const registryItem = await fetchRegistryItem(componentName, registryUrl);\n if (!registryItem) continue;\n\n const subfolder = getSubfolderFromPaths(registryItem.files);\n if (!subfolder) continue;\n\n const files: string[] = [];\n for (const file of registryItem.files) {\n if (file.type === \"registry:ui\") {\n const filename = path.basename(file.path);\n files.push(filename);\n\n // Track which subfolders each filename appears in\n const subfolders = filenameToSubfolders.get(filename) || [];\n subfolders.push(subfolder);\n filenameToSubfolders.set(filename, subfolders);\n }\n }\n\n componentInfo.set(subfolder, { subfolder, files });\n }\n\n // Build the unique map (only filenames that appear once)\n const uniqueMap = new Map<string, string>();\n const sharedFilenames = new Set<string>();\n\n filenameToSubfolders.forEach((subfolders, filename) => {\n if (subfolders.length === 1) {\n // Unique filename - safe to map directly\n uniqueMap.set(filename, `${subfolders[0]}/${filename}`);\n } else {\n // Shared filename (like index.ts) - track for context-based rewriting\n sharedFilenames.add(filename);\n }\n });\n\n return { uniqueMap, componentInfo, sharedFilenames };\n}\n\n/**\n * Rewrite file paths to include correct subfolders.\n * Handles shared filenames (like index.ts) by tracking current component context.\n */\nfunction rewritePaths(\n paths: string[],\n mapResult: SubfolderMapResult,\n): string[] {\n const { uniqueMap, componentInfo, sharedFilenames } = mapResult;\n let currentSubfolder: string | null = null;\n\n return paths.map((filePath) => {\n const filename = path.basename(filePath);\n const parentDir = path.basename(path.dirname(filePath));\n\n // Check if this is a unique filename (can map directly)\n const uniqueMapping = uniqueMap.get(filename);\n if (uniqueMapping) {\n const expectedSubfolder = path.dirname(uniqueMapping);\n\n // Update current context for subsequent shared files\n currentSubfolder = expectedSubfolder;\n\n // Only rewrite if not already in the correct subfolder\n if (parentDir !== expectedSubfolder) {\n const dir = path.dirname(filePath);\n return `${dir}/${uniqueMapping}`;\n }\n return filePath;\n }\n\n // Check if this is a shared filename (like index.ts)\n if (sharedFilenames.has(filename) && currentSubfolder) {\n // Use the current component context\n const expectedSubfolder = currentSubfolder;\n\n // Only rewrite if not already in the correct subfolder\n if (parentDir !== expectedSubfolder) {\n const dir = path.dirname(filePath);\n return `${dir}/${expectedSubfolder}/${filename}`;\n }\n }\n\n return filePath;\n });\n}\n\n/** Parse shadcn output to extract file lists (stdout has paths, stderr has headers) */\nfunction parseShadcnOutput(stdout: string, stderr: string): ParsedOutput {\n const result: ParsedOutput = { created: [], updated: [], skipped: [] };\n\n // Remove ANSI escape codes for parsing\n const cleanStderr = stderr.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n const cleanStdout = stdout.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n\n // Extract counts from stderr headers\n // Matches patterns like \"✔ Created 4 files:\" or \"ℹ Skipped 2 files:\"\n const createdMatch = cleanStderr.match(/Created\\s+(\\d+)\\s+file/i);\n const updatedMatch = cleanStderr.match(/Updated\\s+(\\d+)\\s+file/i);\n const skippedMatch = cleanStderr.match(/Skipped\\s+(\\d+)\\s+file/i);\n\n const createdCount = createdMatch ? parseInt(createdMatch[1], 10) : 0;\n const updatedCount = updatedMatch ? parseInt(updatedMatch[1], 10) : 0;\n const skippedCount = skippedMatch ? parseInt(skippedMatch[1], 10) : 0;\n\n // Extract file paths from stdout (lines starting with \" - \")\n const allPaths: string[] = [];\n for (const line of cleanStdout.split(\"\\n\")) {\n const match = line.match(/^\\s+-\\s+(.+)$/);\n if (match) {\n allPaths.push(match[1].trim());\n }\n }\n\n // Also check stderr for file paths (some shadcn versions output there)\n for (const line of cleanStderr.split(\"\\n\")) {\n const match = line.match(/^\\s+-\\s+(.+)$/);\n if (match) {\n const filePath = match[1].trim();\n // Avoid duplicates\n if (!allPaths.includes(filePath)) {\n allPaths.push(filePath);\n }\n }\n }\n\n // Assign paths to sections based on counts (order: created, updated, skipped)\n let idx = 0;\n for (let i = 0; i < createdCount && idx < allPaths.length; i++) {\n result.created.push(allPaths[idx++]);\n }\n for (let i = 0; i < updatedCount && idx < allPaths.length; i++) {\n result.updated.push(allPaths[idx++]);\n }\n for (let i = 0; i < skippedCount && idx < allPaths.length; i++) {\n result.skipped.push(allPaths[idx++]);\n }\n\n return result;\n}\n\nasync function addComponents(\n packages: string[],\n forwardedOptions: string[],\n isVerbose: boolean,\n isSilent: boolean,\n subfolderMapResult: SubfolderMapResult,\n): Promise<ParsedOutput> {\n const runner = await getPackageRunner(process.cwd());\n const env = {\n ...process.env,\n REGISTRY_URL: process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL,\n };\n // Always pass --yes for non-interactive mode (skips \"Add components?\" confirmation)\n // Note: we don't pass --overwrite by default to respect user customizations\n const autoFlags: string[] = [];\n if (!forwardedOptions.includes(\"--yes\")) {\n autoFlags.push(\"--yes\");\n }\n const baseArgs = [\n \"shadcn@latest\",\n \"add\",\n ...packages,\n ...autoFlags,\n ...forwardedOptions,\n ];\n\n let cmd = \"npx\";\n let args: string[] = [\"-y\", ...baseArgs];\n if (runner === \"bunx\") {\n cmd = \"bunx\";\n args = baseArgs;\n } else if (runner === \"pnpm dlx\") {\n cmd = \"pnpm\";\n args = [\"dlx\", ...baseArgs];\n } else if (runner === \"npx\") {\n cmd = \"npx\";\n args = [\"-y\", ...baseArgs];\n }\n\n if (isVerbose) {\n logger.info(`[bejamas-ui] ${cmd} ${args.join(\" \")}`);\n }\n\n // Show our own spinner for checking registry\n const registrySpinner = spinner(\"Checking registry.\", { silent: isSilent });\n registrySpinner.start();\n\n try {\n // Run shadcn and capture output\n // Pipe \"n\" to stdin to answer \"no\" to any overwrite prompts (respects user customizations)\n const result = await execa(cmd, args, {\n env,\n input: \"n\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\nn\\n\", // Answer \"no\" to up to 10 overwrite prompts\n stdout: \"pipe\",\n stderr: \"pipe\",\n reject: false,\n });\n\n registrySpinner.succeed();\n\n // Show installing spinner (already done at this point)\n const installSpinner = spinner(\"Installing components.\", {\n silent: isSilent,\n });\n installSpinner.succeed();\n\n // Parse the output to get file lists (stdout has paths, stderr has headers)\n const stdout = result.stdout || \"\";\n const stderr = result.stderr || \"\";\n\n if (isVerbose) {\n logger.info(`[bejamas-ui] Raw stdout: ${stdout}`);\n logger.info(`[bejamas-ui] Raw stderr: ${stderr}`);\n }\n\n const parsed = parseShadcnOutput(stdout, stderr);\n\n // Return parsed data - display is handled by caller after reorganization\n // This allows accurate reporting (shadcn says \"created\" but we may skip)\n\n if (result.exitCode !== 0) {\n // Show any error output\n if (result.stderr) {\n logger.error(result.stderr);\n }\n process.exit(result.exitCode);\n }\n\n return parsed;\n } catch (err) {\n registrySpinner.fail();\n logger.error(\"Failed to add components\");\n process.exit(1);\n }\n}\n\nexport const add = new Command()\n .name(\"add\")\n .description(\"Add components via shadcn@latest using registry URLs\")\n .argument(\"[components...]\", \"Component package names to add\")\n .option(\"-y, --yes\", \"skip confirmation prompt.\", false)\n .option(\"-o, --overwrite\", \"overwrite existing files.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd(),\n )\n .option(\"-a, --all\", \"add all available components\", false)\n .option(\"-p, --path <path>\", \"the path to add the component to.\")\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project.\",\n false,\n )\n .option(\n \"--no-src-dir\",\n \"do not use the src directory when creating a new project.\",\n )\n // .option(\"--css-variables\", \"use css variables for theming.\", true)\n // .option(\"--no-css-variables\", \"do not use css variables for theming.\")\n .action(async function action(packages: string[], _opts, cmd) {\n const root = cmd?.parent;\n const verbose = Boolean(root?.opts?.().verbose);\n const rawArgv = process.argv.slice(2);\n const forwardedOptions = extractOptionsForShadcn(rawArgv, cmd);\n const opts =\n typeof cmd.optsWithGlobals === \"function\"\n ? cmd.optsWithGlobals()\n : (cmd.opts?.() ?? {});\n const cwd = opts.cwd || process.cwd();\n\n // Get config for resolved paths (needed for reorganization)\n // In monorepos, we need to follow the alias chain to find the actual UI package config\n const config = await getConfig(cwd);\n const registryUrl = process.env.REGISTRY_URL || DEFAULT_REGISTRY_URL;\n\n // Try to get workspace config (follows aliases to find package-specific configs)\n let uiDir = config?.resolvedPaths?.ui || \"\";\n let uiConfig = config;\n\n if (config) {\n const workspaceConfig = await getWorkspaceConfig(config);\n if (workspaceConfig?.ui) {\n // Use the UI package's own config (e.g., packages/ui/components.json)\n uiConfig = workspaceConfig.ui;\n uiDir = uiConfig.resolvedPaths?.ui || uiDir;\n }\n }\n\n if (verbose) {\n logger.info(`[bejamas-ui] cwd: ${cwd}`);\n logger.info(`[bejamas-ui] uiDir: ${uiDir}`);\n logger.info(\n `[bejamas-ui] aliases.ui: ${uiConfig?.aliases?.ui || \"not set\"}`,\n );\n }\n\n // Process components ONE AT A TIME to avoid index.ts conflicts\n // When shadcn runs with multiple components, files with same name overwrite each other\n const isSilent = opts.silent || false;\n const componentsToAdd = packages || [];\n const totalComponents = componentsToAdd.length;\n\n for (let i = 0; i < componentsToAdd.length; i++) {\n const component = componentsToAdd[i];\n\n // Show component header when adding multiple\n if (totalComponents > 1 && !isSilent) {\n logger.break();\n logger.info(\n highlighter.info(`[${i + 1}/${totalComponents}]`) +\n ` Adding ${highlighter.success(component)}...`,\n );\n }\n\n // Build subfolder map for this single component\n const subfolderMapResult = await buildSubfolderMap(\n [component],\n registryUrl,\n );\n\n // Run shadcn for just this component\n const parsed = await addComponents(\n [component],\n forwardedOptions,\n verbose,\n isSilent,\n subfolderMapResult,\n );\n\n // Immediately reorganize this component's files before the next one\n let skippedCount = 0;\n if (uiDir) {\n const reorgResult = await reorganizeComponents(\n [component],\n uiDir,\n registryUrl,\n verbose,\n );\n skippedCount = reorgResult.skippedFiles.length;\n }\n\n // Display accurate results (accounting for files we skipped after shadcn \"created\" them)\n if (!isSilent) {\n const relativeUiDir = uiDir ? path.relative(cwd, uiDir) : \"\";\n\n // Files that were actually created (shadcn created minus our skipped)\n const actuallyCreated = Math.max(\n 0,\n parsed.created.length - skippedCount,\n );\n\n if (actuallyCreated > 0) {\n const createdPaths = rewritePaths(\n parsed.created.slice(0, actuallyCreated),\n subfolderMapResult,\n );\n logger.success(\n `Created ${createdPaths.length} file${createdPaths.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const file of createdPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Updated files (globals.css etc)\n if (parsed.updated.length > 0) {\n const uniqueUpdated = Array.from(new Set(parsed.updated));\n const updatedPaths = rewritePaths(uniqueUpdated, subfolderMapResult);\n logger.info(\n `Updated ${updatedPaths.length} file${updatedPaths.length > 1 ? \"s\" : \"\"}:`,\n );\n for (const file of updatedPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Files skipped because they already exist in subfolder\n if (skippedCount > 0) {\n logger.info(\n `Skipped ${skippedCount} file${skippedCount > 1 ? \"s\" : \"\"}: (already exists)`,\n );\n }\n\n // Files shadcn skipped (different from our reorganization skip)\n if (parsed.skipped.length > 0) {\n const skippedPaths = rewritePaths(parsed.skipped, subfolderMapResult);\n logger.info(\n `Skipped ${skippedPaths.length} file${skippedPaths.length > 1 ? \"s\" : \"\"}: (use --overwrite)`,\n );\n for (const file of skippedPaths) {\n logger.log(` ${highlighter.info(\"-\")} ${file}`);\n }\n }\n\n // Nothing happened\n if (\n actuallyCreated === 0 &&\n parsed.updated.length === 0 &&\n skippedCount === 0 &&\n parsed.skipped.length === 0\n ) {\n logger.info(\"Already up to date.\");\n }\n }\n }\n\n // Fix aliases inside Astro files until upstream adds .astro support.\n await fixAstroImports(cwd, verbose);\n });\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"module\";\nimport { init } from \"@/src/commands/init\";\nimport { docs } from \"@/src/commands/docs\";\nimport { docsCheck } from \"@/src/commands/docs-check\";\nimport { add } from \"@/src/commands/add\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\");\n\nconst program = new Command()\n .name(\"bejamas\")\n .description(\"bejamas/ui cli\")\n .configureHelp({\n helpWidth: Math.min(100, process.stdout.columns || 100),\n })\n .version(pkg.version, \"-v, --version\", \"output the version number\");\n\nprogram.addCommand(init);\nprogram.addCommand(add);\nprogram.addCommand(docs);\nprogram.addCommand(docsCheck);\n\nprogram.parse(process.argv);\n\nexport default program;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,MAAa,+BAA+B;;;;ACM5C,eAAsB,cACpB,SACA;CACA,MAAMA,SAAkC,EAAE;AAI1C,KACE,CAACC,QAAG,WAAW,QAAQ,IAAI,IAC3B,CAACA,QAAG,WAAW,KAAK,QAAQ,QAAQ,KAAK,eAAe,CAAC,EACzD;AACA,SAAOC,gCAAuC;AAC9C,SAAO;GACL;GACA,aAAa;GACd;;AAGH,QAAO;EACL;EACA,aAAa;EACd;;;;;ACvBH,IAAIC,UAA2B,EAC7B,SAAS,EAAE,EACZ;AAeD,SAAgB,uBAAuB;AACrC,SAAQ,UAAU,EAAE;;;;;ACpBtB,eAAsB,kBACpB,WACA,EAAE,iBAA6C,EAC7C,cAAc,OACf,EACkD;CACnD,MAAM,iBAAiB,MAAM,OAAO;EAAE,cAAc;EAAM,KAAK;EAAW,CAAC;AAE3E,KAAI,mBAAmB,aAAc,QAAO;AAC5C,KAAI,mBAAmB,SAAU,QAAO;AACxC,KAAI,mBAAmB,MAAO,QAAO;AACrC,KAAI,mBAAmB,OAAQ,QAAO;AACtC,KAAI,CAAC,aACH,QAAO,kBAAkB;CAI3B,MAAM,YAAY,QAAQ,IAAI,yBAAyB;AAEvD,KAAI,UAAU,WAAW,OAAO,CAC9B,QAAO;AAGT,KAAI,UAAU,WAAW,O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G,oBAC5D;AAIH,OAAI,OAAO,QAAQ,SAAS,GAAG;IAC7B,MAAM,eAAe,aAAa,OAAO,SAAS,mBAAmB;AACrE,WAAO,KACL,WAAW,aAAa,OAAO,OAAO,aAAa,SAAS,IAAI,MAAM,GAAG,qBAC1E;AACD,SAAK,MAAM,QAAQ,aACjB,QAAO,IAAI,KAAK,YAAY,KAAK,IAAI,CAAC,GAAG,OAAO;;AAKpD,OACE,oBAAoB,KACpB,OAAO,QAAQ,WAAW,KAC1B,iBAAiB,KACjB,OAAO,QAAQ,WAAW,EAE1B,QAAO,KAAK,sBAAsB;;;AAMxC,OAAM,gBAAgB,KAAK,QAAQ;EACnC;;;;AChhBJ,MAAM,MADU,cAAc,OAAO,KAAK,IAAI,CAC1B,kBAAkB;AAEtC,MAAM,UAAU,IAAI,SAAS,CAC1B,KAAK,UAAU,CACf,YAAY,iBAAiB,CAC7B,cAAc,EACb,WAAW,KAAK,IAAI,KAAK,QAAQ,OAAO,WAAW,IAAI,EACxD,CAAC,CACD,QAAQ,IAAI,SAAS,iBAAiB,4BAA4B;AAErE,QAAQ,WAAW,KAAK;AACxB,QAAQ,WAAW,IAAI;AACvB,QAAQ,WAAW,KAAK;AACxB,QAAQ,WAAW,UAAU;AAE7B,QAAQ,MAAM,QAAQ,KAAK;AAE3B,kBAAe"}
@@ -401,13 +401,10 @@ function extractPropsFromDeclaredProps(sourceFile) {
401
401
  if (iface) return iface.getProperties().map((prop) => {
402
402
  const name = prop.getName();
403
403
  const typeNode = prop.getTypeNode();
404
- const rawType = typeNode ? typeNode.getText() : prop.getType().getText();
405
- const typeText = normalizeTypeText(rawType);
406
- const optional = prop.hasQuestionToken();
407
404
  return {
408
405
  name,
409
- type: typeText,
410
- optional
406
+ type: normalizeTypeText(typeNode ? typeNode.getText() : prop.getType().getText()),
407
+ optional: prop.hasQuestionToken()
411
408
  };
412
409
  });
413
410
  const typeAlias = sourceFile.getTypeAlias("Props");
@@ -416,13 +413,10 @@ function extractPropsFromDeclaredProps(sourceFile) {
416
413
  if (typeNode && typeNode.getKind() === SyntaxKind.TypeLiteral) return typeNode.asKindOrThrow(SyntaxKind.TypeLiteral).getProperties().map((prop) => {
417
414
  const name = prop.getName();
418
415
  const tn = prop.getTypeNode();
419
- const rawType = tn ? tn.getText() : prop.getType().getText();
420
- const typeText = normalizeTypeText(rawType);
421
- const optional = prop.hasQuestionToken();
422
416
  return {
423
417
  name,
424
- type: typeText,
425
- optional
418
+ type: normalizeTypeText(tn ? tn.getText() : prop.getType().getText()),
419
+ optional: prop.hasQuestionToken()
426
420
  };
427
421
  });
428
422
  }
@@ -519,5 +513,5 @@ function createSourceFileFromFrontmatter(frontmatterCode) {
519
513
  }
520
514
 
521
515
  //#endregion
522
- export { BASE_COLORS, RESERVED_COMPONENTS, createSourceFileFromFrontmatter, detectHasImportTopLevel, discoverExamples, extractComponentTagsFromMDX, extractFrontmatter, extractPropsFromAstroProps, extractPropsFromDeclaredProps, getConfig, getProjectInfo, getWorkspaceConfig, highlighter, logger, normalizeBlockMDX, normalizeUsageMDX, parseJsDocMetadata, resolveOutDir, resolveUiRoot, slugify, spinner, toIdentifier };
523
- //# sourceMappingURL=utils-BA01hKci.js.map
516
+ export { BASE_COLORS as S, getWorkspaceConfig as _, extractComponentTagsFromMDX as a, logger as b, extractPropsFromDeclaredProps as c, parseJsDocMetadata as d, resolveOutDir as f, getConfig as g, toIdentifier as h, discoverExamples as i, normalizeBlockMDX as l, slugify as m, createSourceFileFromFrontmatter as n, extractFrontmatter as o, resolveUiRoot as p, detectHasImportTopLevel as r, extractPropsFromAstroProps as s, RESERVED_COMPONENTS as t, normalizeUsageMDX as u, getProjectInfo as v, highlighter as x, spinner as y };
517
+ //# sourceMappingURL=utils-BXyPCddm.js.map