Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

Refactor CLI command structure by adding multiple command imports and removing the deprecated build command, enhancing modularity and organization.

vholik094f7b33aeb8
diff --git a/packages/cli/src/commands/build-registry.ts b/packages/cli/src/commands/build-registry.ts
new file mode 100644
index 000000000..5b9ca0eda
--- /dev/null
+++ b/packages/cli/src/commands/build-registry.ts
@@ -0,0 +1,223 @@
+import * as fs from "fs/promises";
+import * as path from "path";
+import { preFlightRegistryBuild } from "@/src/preflights/preflight-registry";
+import { recursivelyResolveFileImports } from "@/src/registry/utils";
+import { registryItemSchema, registrySchema } from "@/src/registry/schema";
+import { configSchema } from "@/src/schema";
+import * as ERRORS from "@/src/utils/errors";
+import { type ProjectInfo, getProjectInfo } from "@/src/utils/get-project-info";
+import { handleError } from "@/src/utils/handle-error";
+import { highlighter } from "@/src/utils/highlighter";
+import { logger } from "@/src/utils/logger";
+import { spinner } from "@/src/utils/spinner";
+import { Command } from "commander";
+import { z } from "zod";
+
+export const buildOptionsSchema = z.object({
+ cwd: z.string(),
+ registryFile: z.string(),
+ outputDir: z.string(),
+ verbose: z.boolean().optional().default(false),
+});
+
+export const build = new Command()
+ .name("build")
+ .description("build registry")
+ .argument("[registry]", "path to registry.json file", "./registry.json")
+ .option(
+ "-o, --output <path>",
+ "destination directory for json files",
+ "./registry"
+ )
+ .option(
+ "-c, --cwd <cwd>",
+ "the working directory. defaults to the current directory.",
+ process.cwd()
+ )
+ .option("-v, --verbose", "verbose output")
+ .action(async (registry: string, opts) => {
+ await buildRegistry({
+ cwd: path.resolve(opts.cwd),
+ registryFile: registry,
+ outputDir: opts.output,
+ verbose: opts.verbose,
+ });
+ });
+
+async function buildRegistry(opts: z.infer<typeof buildOptionsSchema>) {
+ try {
+ const options = buildOptionsSchema.parse(opts);
+
+ const [{ errors, resolvePaths, config }, projectInfo] = await Promise.all([
+ preFlightRegistryBuild(options),
+ getProjectInfo(options.cwd),
+ ]);
+
+ if (errors[ERRORS.MISSING_CONFIG] || !config || !projectInfo) {
+ logger.error(
+ `A ${highlighter.info(
+ "blocks.json"
+ )} file is required to build the registry. Run ${highlighter.info(
+ "mercur init"
+ )} to create one.`
+ );
+ logger.break();
+ process.exit(1);
+ }
+
+ if (errors[ERRORS.BUILD_MISSING_REGISTRY_FILE] || !resolvePaths) {
+ logger.error(
+ `We could not find a registry file at ${highlighter.info(
+ path.resolve(options.cwd, options.registryFile)
+ )}.`
+ );
+ logger.break();
+ process.exit(1);
+ }
+
+ const content = await fs.readFile(resolvePaths.registryFile, "utf-8");
+ const result = registrySchema.safeParse(JSON.parse(content));
+
+ if (!result.success) {
+ logger.error(
+ `Invalid registry file found at ${highlighter.info(
+ resolvePaths.registryFile
+ )}.`
+ );
+ logger.break();
+ process.exit(1);
+ }
+
+ const buildSpinner = spinner("Building registry...");
+
+ // Recursively resolve the registry items.
+ const resolvedRegistry = await resolveRegistryItems(
+ result.data,
+ config,
+ projectInfo
+ );
+
+ // Loop through the registry items and remove duplicates files i.e same path.
+ for (const registryItem of resolvedRegistry.items) {
+ // Deduplicate files
+ registryItem.files = registryItem.files?.filter(
+ (file, index, self) =>
+ index === self.findIndex((t) => t.path === file.path)
+ );
+
+ // Deduplicate dependencies
+ if (registryItem.dependencies) {
+ registryItem.dependencies = registryItem.dependencies.filter(
+ (dep, index, self) => index === self.findIndex((d) => d === dep)
+ );
+ }
+ }
+
+ for (const registryItem of resolvedRegistry.items) {
+ if (!registryItem.files) {
+ continue;
+ }
+
+ buildSpinner.start(`Building ${registryItem.name}...`);
+
+ // Add the schema to the registry item.
+ registryItem["$schema"] =
+ "https://mercurjs.com/schema/registry-item.json";
+
+ for (const file of registryItem.files) {
+ const absPath = path.resolve(resolvePaths.cwd, file.path);
+ try {
+ const stat = await fs.stat(absPath);
+ if (!stat.isFile()) {
+ continue;
+ }
+ file["content"] = await fs.readFile(absPath, "utf-8");
+ } catch (err) {
+ console.error("Error reading file in registry build:", absPath, err);
+ continue;
+ }
+ }
+
+ const validationResult = registryItemSchema.safeParse(registryItem);
+ if (!validationResult.success) {
+ logger.error(
+ `Invalid registry item found for ${highlighter.info(
+ registryItem.name
+ )}.`
+ );
+ continue;
+ }
+
+ // Write the registry item to the output directory.
+ await fs.writeFile(
+ path.resolve(
+ resolvePaths.outputDir,
+ `${validationResult.data.name}.json`
+ ),
+ JSON.stringify(validationResult.data, null, 2)
+ );
+ }
+
+ // Copy registry.json to the output directory.
+ await fs.copyFile(
+ resolvePaths.registryFile,
+ path.resolve(resolvePaths.outputDir, "registry.json")
+ );
+
+ buildSpinner.succeed("Building registry.");
+
+ if (options.verbose) {
+ spinner(
+ `The registry has ${highlighter.info(
+ resolvedRegistry.items.length.toString()
+ )} items:`
+ ).succeed();
+ for (const item of resolvedRegistry.items) {
+ logger.log(` - ${item.name} (${highlighter.info(item.type)})`);
+ for (const file of item.files ?? []) {
+ logger.log(` - ${file.path}`);
+ }
+ }
+ }
+ } catch (error) {
+ logger.break();
+ handleError(error);
+ }
+}
+
+// This reads the registry and recursively resolves the file imports.
+async function resolveRegistryItems(
+ registry: z.infer<typeof registrySchema>,
+ config: z.infer<typeof configSchema>,
+ projectInfo: ProjectInfo
+): Promise<z.infer<typeof registrySchema>> {
+ for (const item of registry.items) {
+ if (!item.files?.length) {
+ continue;
+ }
+
+ // Process all files in the array instead of just the first one
+ for (const file of item.files) {
+ const results = await recursivelyResolveFileImports(
+ file.path,
+ config,
+ projectInfo
+ );
+
+ // Remove file from results.files
+ results.files = results.files?.filter((f) => f.path !== file.path);
+
+ if (results.files) {
+ item.files.push(...results.files);
+ }
+
+ if (results.dependencies) {
+ item.dependencies = item.dependencies
+ ? item.dependencies.concat(results.dependencies)
+ : results.dependencies;
+ }
+ }
+ }
+
+ return registry;
+}
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
deleted file mode 100644
index 0710550ce..000000000
--- a/packages/cli/src/commands/build.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import * as fs from "fs/promises";
-import * as path from "path";
-import { handleError } from "@/src/utils/handle-error";
-import { highlighter } from "@/src/utils/highlighter";
-import { logger } from "@/src/utils/logger";
-import { spinner } from "@/src/utils/spinner";
-import { Command } from "commander";
-import { z } from "zod";
-import { registryItemSchema, registrySchema } from "../registry/schema";
-import { preFlightBuild } from "../preflights/preflight-build";
-
-export const buildOptionsSchema = z.object({
- cwd: z.string(),
- registryFile: z.string(),
- outputDir: z.string(),
-});
-
-export const build = new Command()
- .name("build")
- .description("build blocks for a Mercur registry")
- .argument("[registry]", "path to registry.json file", "./registry.json")
- .option(
- "-o, --output <path>",
- "destination directory for json files",
- "./registry"
- )
- .option(
- "-c, --cwd <cwd>",
- "the working directory. defaults to the current directory.",
- process.cwd()
- )
- .action(async (registry: string, opts) => {
- try {
- const options = buildOptionsSchema.parse({
- cwd: path.resolve(opts.cwd),
- registryFile: registry,
- outputDir: opts.output,
- });
-
- const { resolvePaths } = await preFlightBuild(options);
- const content = await fs.readFile(resolvePaths.registryFile, "utf-8");
-
- const result = registrySchema.safeParse(JSON.parse(content));
-
- if (!result.success) {
- logger.error(
- `Invalid registry file found at ${highlighter.info(
- resolvePaths.registryFile
- )}.`
- );
- process.exit(1);
- }
-
- const buildSpinner = spinner("Building registry...");
- for (const registryItem of result.data.items) {
- buildSpinner.start(`Building ${registryItem.name}...`);
-
- // Add the schema to the registry item.
- registryItem["$schema"] =
- "https://mercurjs.com/schema/registry-item.json";
-
- // Loop through each file in the files array.
- for (const file of registryItem.files ?? []) {
- file["content"] = await fs.readFile(
- path.resolve(resolvePaths.cwd, file.path),
- "utf-8"
- );
- }
-
- // Validate the registry item.
- const result = registryItemSchema.safeParse(registryItem);
- if (!result.success) {
- logger.error(
- `Invalid registry item found for ${highlighter.info(
- registryItem.name
- )}.`
- );
- continue;
- }
-
- // Write the registry item to the output directory.
- await fs.writeFile(
- path.resolve(resolvePaths.outputDir, `${result.data.name}.json`),
- JSON.stringify(result.data, null, 2)
- );
- }
-
- // Copy registry.json to the output directory.
- await fs.copyFile(
- resolvePaths.registryFile,
- path.resolve(resolvePaths.outputDir, "registry.json")
- );
-
- buildSpinner.succeed("Building registry.");
- } catch (error) {
- logger.break();
- handleError(error);
- }
- });
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 48e9a2e56..e18df28bb 100755
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,6 +1,14 @@
#!/usr/bin/env bun
import { Command } from "commander";
import packageJson from "../package.json";
+import { add } from "./commands/add";
+import { build } from "./commands/build-registry";
+import { create } from "./commands/create";
+import { diff } from "./commands/diff";
+import { info } from "./commands/info";
+import { init } from "./commands/init";
+import { search } from "./commands/search";
+import { view } from "./commands/view";
process.on("SIGINT", () => process.exit(0));
process.on("SIGTERM", () => process.exit(0));
@@ -17,7 +25,15 @@ async function main() {
"display the version number"
);
- program;
+ program
+ .addCommand(add)
+ .addCommand(build)
+ .addCommand(create)
+ .addCommand(diff)
+ .addCommand(info)
+ .addCommand(init)
+ .addCommand(search)
+ .addCommand(view);
program.parse();
}
diff --git a/packages/cli/src/preflights/preflight-build.ts b/packages/cli/src/preflights/preflight-build.ts
deleted file mode 100644
index 1af34f073..000000000
--- a/packages/cli/src/preflights/preflight-build.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import path from "path";
-import { buildOptionsSchema } from "@/src/commands/build";
-import * as ERRORS from "@/src/utils/errors";
-import { highlighter } from "@/src/utils/highlighter";
-import { logger } from "@/src/utils/logger";
-import fs from "fs-extra";
-import { z } from "zod";
-
-export async function preFlightBuild(
- options: z.infer<typeof buildOptionsSchema>
-) {
- const errors: Record<string, boolean> = {};
-
- const resolvePaths = {
- cwd: options.cwd,
- registryFile: path.resolve(options.cwd, options.registryFile),
- outputDir: path.resolve(options.cwd, options.outputDir),
- };
-
- // Ensure registry file exists.
- if (!fs.existsSync(resolvePaths.registryFile)) {
- errors[ERRORS.BUILD_MISSING_REGISTRY_FILE] = true;
- }
-
- // Create output directory if it doesn't exist.
- await fs.mkdir(resolvePaths.outputDir, { recursive: true });
-
- if (Object.keys(errors).length > 0) {
- if (errors[ERRORS.BUILD_MISSING_REGISTRY_FILE]) {
- logger.break();
- logger.error(
- `The path ${highlighter.info(
- resolvePaths.registryFile
- )} does not exist.`
- );
- }
-
- logger.break();
- process.exit(1);
- }
-
- return {
- errors,
- resolvePaths,
- };
-}
diff --git a/packages/cli/src/preflights/preflight-registry.ts b/packages/cli/src/preflights/preflight-registry.ts
new file mode 100644
index 000000000..767205d02
--- /dev/null
+++ b/packages/cli/src/preflights/preflight-registry.ts
@@ -0,0 +1,66 @@
+import path from "path";
+import { buildOptionsSchema } from "@/src/commands/build-registry";
+import * as ERRORS from "@/src/utils/errors";
+import { getConfig } from "@/src/utils/get-config";
+import { highlighter } from "@/src/utils/highlighter";
+import { logger } from "@/src/utils/logger";
+import fs from "fs-extra";
+import { z } from "zod";
+
+export async function preFlightRegistryBuild(
+ options: z.infer<typeof buildOptionsSchema>
+) {
+ const errors: Record<string, boolean> = {};
+
+ const resolvePaths = {
+ cwd: options.cwd,
+ registryFile: path.resolve(options.cwd, options.registryFile),
+ outputDir: path.resolve(options.cwd, options.outputDir),
+ };
+
+ // Ensure registry file exists.
+ if (!fs.existsSync(resolvePaths.registryFile)) {
+ errors[ERRORS.BUILD_MISSING_REGISTRY_FILE] = true;
+ return {
+ errors,
+ resolvePaths: null,
+ config: null,
+ };
+ }
+
+ // Check for existing blocks.json file.
+ if (!fs.existsSync(path.resolve(options.cwd, "blocks.json"))) {
+ errors[ERRORS.MISSING_CONFIG] = true;
+ return {
+ errors,
+ resolvePaths: null,
+ config: null,
+ };
+ }
+
+ // Create output directory if it doesn't exist.
+ await fs.mkdir(resolvePaths.outputDir, { recursive: true });
+
+ try {
+ const config = await getConfig(options.cwd);
+
+ return {
+ errors,
+ config: config!,
+ resolvePaths,
+ };
+ } catch (error) {
+ logger.break();
+ logger.error(
+ `An invalid ${highlighter.info(
+ "blocks.json"
+ )} file was found at ${highlighter.info(
+ options.cwd
+ )}.\nBefore you can build the registry, you must create a valid ${highlighter.info(
+ "blocks.json"
+ )} file by running the ${highlighter.info("init")} command.`
+ );
+ logger.break();
+ process.exit(1);
+ }
+}
diff --git a/packages/cli/src/registry/utils.ts b/packages/cli/src/registry/utils.ts
index 64740cb72..190dbd748 100644
--- a/packages/cli/src/registry/utils.ts
+++ b/packages/cli/src/registry/utils.ts
@@ -1,18 +1,344 @@
-export function isUrl(string: string): boolean {
+import * as fs from "fs/promises";
+import { tmpdir } from "os";
+import * as path from "path";
+import {
+ registryItemFileSchema,
+ registryItemSchema,
+ registryItemTypeSchema,
+} from "@/src/registry/schema";
+import { configSchema, type Config } from "@/src/schema";
+import { type ProjectInfo } from "@/src/utils/get-project-info";
+import { resolveImport } from "@/src/utils/resolve-import";
+import { Project, ScriptKind } from "ts-morph";
+import { loadConfig } from "tsconfig-paths";
+import { z } from "zod";
+
+const FILE_EXTENSIONS_FOR_LOOKUP = [".tsx", ".ts"];
+const FILE_PATH_SKIP_LIST = ["lib/utils.ts"];
+const DEPENDENCY_SKIP_LIST = [
+ /^(react|react-dom)(\/.*)?$/, // Matches react, react-dom and their submodules
+ /^(node|jsr|npm):.*$/, // Matches node:, jsr:, and npm: prefixed modules
+];
+
+const project = new Project({
+ compilerOptions: {},
+});
+
+// This returns the dependency from the module specifier.
+// Here dependency means an npm package.
+export function getDependencyFromModuleSpecifier(
+ moduleSpecifier: string
+): string | null {
+ // Skip if the dependency matches any pattern in the skip list
+ if (DEPENDENCY_SKIP_LIST.some((pattern) => pattern.test(moduleSpecifier))) {
+ return null;
+ }
+
+ // If the module specifier does not start with `@` and has a /, add the dependency first part only.
+ // E.g. `foo/bar` -> `foo`
+ if (!moduleSpecifier.startsWith("@") && moduleSpecifier.includes("/")) {
+ moduleSpecifier = moduleSpecifier.split("/")[0];
+ }
+
+ // For scoped packages, we want to keep the first two parts
+ // E.g. `@types/react/dom` -> `@types/react`
+ if (moduleSpecifier.startsWith("@")) {
+ const parts = moduleSpecifier.split("/");
+ if (parts.length > 2) {
+ moduleSpecifier = parts.slice(0, 2).join("/");
+ }
+ }
+
+ return moduleSpecifier;
+}
+
+export async function recursivelyResolveFileImports(
+ filePath: string,
+ config: z.infer<typeof configSchema>,
+ projectInfo: ProjectInfo,
+ processedFiles: Set<string> = new Set()
+): Promise<Pick<z.infer<typeof registryItemSchema>, "files" | "dependencies">> {
+ const resolvedFilePath = path.resolve(config.resolvedPaths.cwd, filePath);
+ const relativeRegistryFilePath = path.relative(
+ config.resolvedPaths.cwd,
+ resolvedFilePath
+ );
+
+ // Skip if the file is in the skip list
+ if (FILE_PATH_SKIP_LIST.includes(relativeRegistryFilePath)) {
+ return { dependencies: [], files: [] };
+ }
+
+ // Skip if the file extension is not one of the supported extensions
+ const fileExtension = path.extname(filePath);
+ if (!FILE_EXTENSIONS_FOR_LOOKUP.includes(fileExtension)) {
+ return { dependencies: [], files: [] };
+ }
+
+ // Prevent infinite loop: skip if already processed
+ if (processedFiles.has(relativeRegistryFilePath)) {
+ return { dependencies: [], files: [] };
+ }
+ processedFiles.add(relativeRegistryFilePath);
+
try {
- const url = new URL(string);
- // Only accept http and https protocols
- return url.protocol === "http:" || url.protocol === "https:";
+ const stat = await fs.stat(resolvedFilePath);
+ if (!stat.isFile()) {
+ return { dependencies: [], files: [] };
+ }
} catch {
+ return { dependencies: [], files: [] };
+ }
+
+ const content = await fs.readFile(resolvedFilePath, "utf-8");
+ const tempFile = await createTempSourceFile(path.basename(resolvedFilePath));
+ const sourceFile = project.createSourceFile(tempFile, content, {
+ scriptKind: ScriptKind.TSX,
+ });
+ const tsConfig = await loadConfig(config.resolvedPaths.cwd);
+ if (tsConfig.resultType === "failed") {
+ return { dependencies: [], files: [] };
+ }
+
+ const files: z.infer<typeof registryItemSchema>["files"] = [];
+ const dependencies = new Set<string>();
+
+ // Add the original file first
+ const fileType = determineFileType(filePath);
+ const originalFile = {
+ path: relativeRegistryFilePath,
+ type: fileType,
+ target: "",
+ content: "",
+ };
+ files.push(originalFile);
+
+ // 1. Find all import statements in the file.
+ const importStatements = sourceFile.getImportDeclarations();
+ for (const importStatement of importStatements) {
+ const moduleSpecifier = importStatement.getModuleSpecifierValue();
+
+ const isRelativeImport = moduleSpecifier.startsWith(".");
+ const isAliasImport =
+ projectInfo.aliasPrefix &&
+ moduleSpecifier.startsWith(`${projectInfo.aliasPrefix}/`);
+
+ // If not a local import, add to the dependencies array.
+ if (!isAliasImport && !isRelativeImport) {
+ const dependency = getDependencyFromModuleSpecifier(moduleSpecifier);
+ if (dependency) {
+ dependencies.add(dependency);
+ }
+ continue;
+ }
+
+ let probableImportFilePath = await resolveImport(moduleSpecifier, tsConfig);
+
+ if (isRelativeImport) {
+ probableImportFilePath = path.resolve(
+ path.dirname(resolvedFilePath),
+ moduleSpecifier
+ );
+ }
+
+ if (!probableImportFilePath) {
+ continue;
+ }
+
+ // Check if the probable import path has a file extension.
+ // Try each extension until we find a file that exists.
+ const hasExtension = path.extname(probableImportFilePath);
+ if (!hasExtension) {
+ for (const ext of FILE_EXTENSIONS_FOR_LOOKUP) {
+ const pathWithExt: string = `${probableImportFilePath}${ext}`;
+ try {
+ await fs.access(pathWithExt);
+ probableImportFilePath = pathWithExt;
+ break;
+ } catch {
+ continue;
+ }
+ }
+ }
+
+ const nestedRelativeRegistryFilePath = path.relative(
+ config.resolvedPaths.cwd,
+ probableImportFilePath
+ );
+
+ // Skip if we've already processed this file or if it's in the skip list
+ if (
+ processedFiles.has(nestedRelativeRegistryFilePath) ||
+ FILE_PATH_SKIP_LIST.includes(nestedRelativeRegistryFilePath)
+ ) {
+ continue;
+ }
+
+ const nestedFileType = determineFileType(moduleSpecifier);
+ const file = {
+ path: nestedRelativeRegistryFilePath,
+ type: nestedFileType,
+ target: "",
+ content: "",
+ };
+
+ files.push(file);
+
+ // Recursively process the imported file, passing the shared processedFiles set
+ const nestedResults = await recursivelyResolveFileImports(
+ nestedRelativeRegistryFilePath,
+ config,
+ projectInfo,
+ processedFiles
+ );
+
+ if (nestedResults.files) {
+ // Only add files that haven't been processed yet
+ for (const nestedFile of nestedResults.files) {
+ if (!processedFiles.has(nestedFile.path)) {
+ processedFiles.add(nestedFile.path);
+ files.push(nestedFile);
+ }
+ }
+ }
+
+ if (nestedResults.dependencies) {
+ nestedResults.dependencies.forEach((dep) => dependencies.add(dep));
+ }
+ }
+
+ // Deduplicate files by path
+ const uniqueFiles = Array.from(
+ new Map(files.map((file) => [file.path, file])).values()
+ );
+
+ return {
+ dependencies: Array.from(dependencies),
+ files: uniqueFiles,
+ };
+}
+
+async function createTempSourceFile(filename: string) {
+ const dir = await fs.mkdtemp(path.join(tmpdir(), "mercur-"));
+ return path.join(dir, filename);
+}
+
+// This determines the registry type based on the file path.
+function determineFileType(
+ moduleSpecifier: string
+): z.infer<typeof registryItemTypeSchema> {
+ if (moduleSpecifier.includes("/workflows/")) {
+ return "registry:workflow";
+ }
+
+ if (moduleSpecifier.includes("/api/")) {
+ return "registry:api";
+ }
+
+ if (moduleSpecifier.includes("/links/")) {
+ return "registry:link";
+ }
+
+ if (moduleSpecifier.includes("/modules/")) {
+ return "registry:module";
+ }
+
+ if (
+ moduleSpecifier.includes("/vendor") ||
+ moduleSpecifier.includes("/vendorPages/")
+ ) {
+ return "registry:vendor";
+ }
+
+ if (
+ moduleSpecifier.includes("/admin") ||
+ moduleSpecifier.includes("/adminPages/")
+ ) {
+ return "registry:admin";
+ }
+
+ if (moduleSpecifier.includes("/lib/")) {
+ return "registry:lib";
+ }
+
+ // Default to lib for unknown types
+ return "registry:lib";
+}
+
+// Additional utility functions for local file support
+export function isUrl(path: string) {
+ try {
+ new URL(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function isLocalFile(path: string) {
+ return path.endsWith(".json") && !isUrl(path);
+}
+
+/**
+ * Check if a registry item is universal (framework-agnostic).
+ * A universal registry item must:
+ * 1. Have files with explicit targets
+ * It can be installed without framework detection or blocks.json.
+ */
+export function isUniversalRegistryItem(
+ registryItem:
+ | Pick<z.infer<typeof registryItemSchema>, "files" | "type">
+ | null
+ | undefined
+): boolean {
+ if (!registryItem) {
return false;
}
+
+ const files = registryItem.files ?? [];
+
+ // If there are files, all must have targets
+ return files.every((file) => !!file.target);
+}
+
+// Deduplicates files based on their resolved target paths.
+// When multiple files resolve to the same target path, the last one wins.
+export async function deduplicateFilesByTarget(
+ filesArrays: Array<z.infer<typeof registryItemFileSchema>[] | undefined>,
+ config: Config
+) {
+ // Fallback to simple concatenation when we don't have complete config.
+ if (!canDeduplicateFiles(config)) {
+ return z
+ .array(registryItemFileSchema)
+ .parse(filesArrays.flat().filter(Boolean));
+ }
+
+ const targetMap = new Map<string, z.infer<typeof registryItemFileSchema>>();
+ const allFiles = z
+ .array(registryItemFileSchema)
+ .parse(filesArrays.flat().filter(Boolean));
+
+ allFiles.forEach((file) => {
+ // Use file path as the key for deduplication
+ const resolvedPath = file.target || file.path;
+
+ if (resolvedPath) {
+ // Last one wins - overwrites previous entry.
+ targetMap.set(resolvedPath, file);
+ }
+ });
+
+ return Array.from(targetMap.values());
}
-export function isLocalFile(string: string): boolean {
- return (
- string.startsWith("file://") ||
- string.startsWith("./") ||
- string.startsWith("../") ||
- string.startsWith("/")
+// Checks if the config has the minimum required paths for file deduplication.
+export function canDeduplicateFiles(config: Config) {
+ return !!(
+ config?.resolvedPaths?.cwd &&
+ (config?.resolvedPaths?.lib ||
+ config?.resolvedPaths?.workflows ||
+ config?.resolvedPaths?.api ||
+ config?.resolvedPaths?.modules)
);
}