import fs from 'node:fs/promises'; import path from 'node:path'; import type { Command } from 'commander'; import { z } from 'zod'; import { assertContainedRoot, assertNoPathCollisions, assertNoSymlinkChain, assertSafeRelativePath, sha256Hex, writeFileAtomic, } from '../shared/safe-path'; import { assertSecureUrl, expandEnvTemplate, loadProjectEnv, readRequiredEnvToken, secureFetchJson, } from '../shared/secure-fetch'; import { createUnifiedDiff } from '../shared/unified-diff'; const DEFAULT_STATE_FILE = '.plate-ui-sync/last-sync.json'; const DEFAULT_REVIEW_DIR = '.plate-ui-sync/review'; const ICON_LIBRARY_PACKAGES: Record = { hugeicons: '@hugeicons/core-free-icons', lucide: 'lucide-react', phosphor: '@phosphor-icons/react', remixicon: '@remixicon/react', tabler: '@tabler/icons-react', }; const ICON_PLACEHOLDER_IMPORT_REGEX = /import\s*\{\s*IconPlaceholder\s*\}\s*from\s*['"]@\/components\/icon-placeholder['"];?\n?/; const ICON_LIBRARY_ATTR_REGEX = /[ \t]*(?:lucide|tabler|hugeicons|phosphor|remixicon)="[^"]*"/g; const RegistryFileSchema = z.object({ content: z.string(), path: z.string().min(1), target: z.string().optional(), type: z.string().optional(), }); export const ShadcnRegistryItemSchema = z.object({ dependencies: z.array(z.string()).optional(), description: z.string().optional(), devDependencies: z.array(z.string()).optional(), files: z.array(RegistryFileSchema).min(1), name: z.string().min(1), registryDependencies: z.array(z.string()).optional(), title: z.string().optional(), type: z.string().min(1), }); const ComponentsJsonRegistryObjectSchema = z.object({ headers: z.record(z.string(), z.string()).optional(), params: z.record(z.string(), z.string()).optional(), url: z.string().min(1), }); const ComponentsJsonSchema = z.object({ aliases: z .object({ components: z.string().optional(), hooks: z.string().optional(), lib: z.string().optional(), ui: z.string().optional(), utils: z.string().optional(), }) .optional(), iconLibrary: z.string().optional(), registries: z .record( z.string(), z.union([z.string(), ComponentsJsonRegistryObjectSchema]) ) .optional(), style: z.string().optional(), tsx: z.boolean().optional(), }); const TrackedItemSourceSchema = z.object({ registry: z.string().optional(), registryDir: z.string().optional(), style: z.string().optional(), }); const UiSyncStateV1Schema = z.object({ files: z.record( z.string(), z.object({ item: z.string().min(1), sha256: z.string().regex(/^[0-9a-f]{64}$/), }) ), items: z.record(z.string(), TrackedItemSourceSchema).optional(), registry: z.string().min(1), style: z.string().optional(), version: z.literal(1), }); type ComponentsJson = z.infer; type ShadcnRegistryItem = z.infer; type TrackedItemSource = z.infer; type UiSyncStateV1 = z.infer; export type UiSyncFileStatus = | 'added' | 'review' | 'synced' | 'unchanged' | 'updated'; export type UiSyncFileReport = { diff?: string; item: string; path: string; patchPath?: string; status: UiSyncFileStatus; upstreamPath?: string; }; export type SyncRegistryOptions = Readonly<{ accept?: boolean; check?: boolean; cwd?: string; diff?: boolean; dir?: string; dryRun?: boolean; fetchImpl?: typeof fetch; items?: readonly string[]; registry?: string; registryDir?: string; reviewDir?: string; stateFile?: string; style?: string; tokenEnv?: string; }>; export type SyncRegistryResult = { changed: boolean; files: UiSyncFileReport[]; hasReviews: boolean; items: string[]; registryDependencies: string[]; }; function stripJsonc(raw: string): string { let out = ''; let inString = false; let quote = ''; let i = 0; while (i < raw.length) { const ch = raw[i]; const next = raw[i + 1]; if (inString) { out += ch; if (ch === '\\' && i + 1 < raw.length) { out += next; i += 2; continue; } if (ch === quote) { inString = false; } i += 1; continue; } if (ch === '"' || ch === "'") { inString = true; quote = ch; out += ch; i += 1; continue; } if (ch === '/' && next === '/') { i += 2; while (i < raw.length && raw[i] !== '\n') i += 1; continue; } if (ch === '/' && next === '*') { i += 2; while (i + 1 < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) { i += 1; } i += 2; continue; } out += ch; i += 1; } return out.replaceAll(/,\s*([}\]])/g, '$1'); } async function dirExists(dirPath: string): Promise { try { const stats = await fs.stat(dirPath); return stats.isDirectory(); } catch { return false; } } async function resolveAtAliasPrefix(cwd: string): Promise { for (const configName of ['tsconfig.json', 'jsconfig.json']) { const configPath = path.join(cwd, configName); try { const raw = await fs.readFile(configPath, 'utf-8'); const parsed = JSON.parse(stripJsonc(raw)) as { compilerOptions?: { baseUrl?: string; paths?: Record; }; }; const target = parsed.compilerOptions?.paths?.['@/*']?.[0]; if (typeof target === 'string' && target.length > 0) { const baseUrl = parsed.compilerOptions?.baseUrl ?? '.'; const combined = path.posix .normalize( path.posix.join( baseUrl.replaceAll('\\', '/'), target.replaceAll('\\', '/').replace(/\/?\*$/, '') ) ) .replace(/^\.\/?/, '') .replace(/\/+$/, ''); return combined === '.' ? '' : combined; } } catch { // Ignore missing or unparseable tsconfig/jsconfig and fall back to layout detection. } } if (await dirExists(path.join(cwd, 'src'))) { return 'src'; } if ( (await dirExists(path.join(cwd, 'components'))) || (await dirExists(path.join(cwd, 'app'))) ) { return ''; } return 'src'; } function joinRelPrefix(prefix: string, suffix: string): string { const cleanPrefix = prefix.replace(/^\/+|\/+$/g, ''); const cleanSuffix = suffix.replace(/^\/+/, ''); return cleanPrefix ? `${cleanPrefix}/${cleanSuffix}` : cleanSuffix; } function aliasToDir( alias: string | undefined, fallbackSuffix: string, atPrefix: string ): string { if (!alias) return joinRelPrefix(atPrefix, fallbackSuffix); if (alias.startsWith('@/')) { return joinRelPrefix(atPrefix, alias.slice(2)); } if (alias.startsWith('~/')) { return alias.slice(2).replace(/^\/+/, ''); } return alias.replace(/^\.\//, '').replace(/^\/+/, ''); } function resolveAliases( componentsConfig: ComponentsJson | null, atPrefix = 'src' ) { const aliases = componentsConfig?.aliases; return { componentsDir: aliasToDir(aliases?.components, 'components', atPrefix), componentsImport: aliases?.components ?? '@/components', hooksDir: aliasToDir(aliases?.hooks, 'hooks', atPrefix), hooksImport: aliases?.hooks ?? '@/hooks', libDir: aliasToDir(aliases?.lib, 'lib', atPrefix), libImport: aliases?.lib ?? '@/lib', uiDir: aliasToDir(aliases?.ui, 'components/ui', atPrefix), uiImport: aliases?.ui ?? '@/components/ui', utilsImport: aliases?.utils ?? '@/lib/utils', }; } /** * Quote- and brace-aware scanner for `` tags so arrow * functions inside JSX props (e.g. `onClick={() => ...}`) never truncate the tag. */ function replaceIconPlaceholderTags( content: string, replacer: (fullMatch: string, attrsBlock: string, closing: string) => string ): string { const marker = '') { tagEnd = i + 2; closing = '/>'; break; } if (ch === '>') { tagEnd = i + 1; closing = '>'; break; } } i += 1; } if (tagEnd === -1) { throw new Error( `Unterminated JSX tag near offset ${start}.` ); } const fullMatch = content.slice(start, tagEnd); const attrsBlock = content.slice( start + marker.length, tagEnd - closing.length ); result += replacer(fullMatch, attrsBlock, closing); cursor = tagEnd; } return result; } function transformIcons(content: string, iconLibrary: string): string { if (!content.includes('IconPlaceholder')) { return content; } const pkg = ICON_LIBRARY_PACKAGES[iconLibrary]; if (!pkg) { throw new Error( `Unsupported iconLibrary "${iconLibrary}" for IconPlaceholder transform. Supported: ${Object.keys(ICON_LIBRARY_PACKAGES).join(', ')}.` ); } const iconNames = new Set(); const attrPattern = new RegExp(`\\b${iconLibrary}="([^"]+)"`); let out = replaceIconPlaceholderTags( content, (fullMatch, attrsBlock, closing) => { const match = attrPattern.exec(attrsBlock); if (!match?.[1]) { throw new Error( `IconPlaceholder element is missing "${iconLibrary}" attribute: ${fullMatch}` ); } iconNames.add(match[1]); const rest = attrsBlock.replace(ICON_LIBRARY_ATTR_REGEX, ''); const normalizedRest = rest.trim() === '' ? ' ' : rest; if (iconLibrary === 'hugeicons') { const hasStrokeWidth = /\bstrokeWidth=/.test(rest); const strokeProp = hasStrokeWidth ? '' : ' strokeWidth={2}'; return ` 0) { replacement = iconLibrary === 'hugeicons' ? `import { HugeiconsIcon } from '@hugeicons/react';\nimport { ${sortedIcons} } from '${pkg}';\n` : `import { ${sortedIcons} } from '${pkg}';\n`; } out = out.replace(ICON_PLACEHOLDER_IMPORT_REGEX, replacement); } if (out.includes('IconPlaceholder')) { throw new Error( `Unresolved IconPlaceholder remained after transforming for iconLibrary "${iconLibrary}".` ); } return out; } export function transformRegistryFileContent( rawContent: string, componentsConfig: ComponentsJson | null ): string { if (componentsConfig?.tsx === false) { throw new Error( 'plate sync currently requires TypeScript projects (tsx: true in components.json).' ); } const aliases = resolveAliases(componentsConfig); const iconLibrary = componentsConfig?.iconLibrary ?? 'lucide'; let out = rawContent; out = out.replaceAll( /(['"])@\/registry\/components\/editor\//g, `$1${aliases.componentsImport}/editor/` ); out = out.replaceAll( /(['"])@\/registry\/bases\/[^/'"]+\/ui\//g, `$1${aliases.uiImport}/` ); out = out.replaceAll(/(['"])@\/components\/ui\//g, `$1${aliases.uiImport}/`); out = out.replaceAll(/(['"])@\/registry\/lib\//g, `$1${aliases.libImport}/`); out = out.replaceAll( /(['"])@\/registry\/hooks\//g, `$1${aliases.hooksImport}/` ); // Anchor `cn` rewrite to import/export specifiers so literals like `locale === 'cn'` stay untouched. out = out.replaceAll( /(\bfrom\s+)(['"])cn\2/g, `$1$2${aliases.utilsImport}$2` ); return transformIcons(out, iconLibrary); } function normalizeOverrideDir(rawDir: string): string { const trimmed = rawDir.trim().replaceAll('\\', '/'); if (trimmed === '.' || trimmed === './') { return ''; } let normalized = trimmed; while (normalized.startsWith('./')) { normalized = normalized.slice(2); } normalized = normalized.replace(/\/+$/, ''); if (!normalized || normalized === '.') { return ''; } return assertSafeRelativePath(normalized); } export function resolveRegistryTargetPath( file: ShadcnRegistryItem['files'][number], componentsConfig: ComponentsJson | null, overrideDir?: string, atPrefix = 'src' ): string { const aliases = resolveAliases(componentsConfig, atPrefix); const rawTarget = file.target?.trim(); if (overrideDir !== undefined) { const base = normalizeOverrideDir(overrideDir); const stripped = rawTarget ? rawTarget .replace(/^@(?:components|ui|lib|hooks)\//, '') .replace(/^~\//, '') : file.path.replace(/^src\/registry\//, '').replace(/^registry\//, ''); return assertSafeRelativePath(base ? `${base}/${stripped}` : stripped); } if (rawTarget) { if (rawTarget.startsWith('~/')) { return assertSafeRelativePath(rawTarget.slice(2)); } if (rawTarget.startsWith('@components/')) { return assertSafeRelativePath( `${aliases.componentsDir}/${rawTarget.slice('@components/'.length)}` ); } if (rawTarget.startsWith('@ui/')) { return assertSafeRelativePath( `${aliases.uiDir}/${rawTarget.slice('@ui/'.length)}` ); } if (rawTarget.startsWith('@lib/')) { return assertSafeRelativePath( `${aliases.libDir}/${rawTarget.slice('@lib/'.length)}` ); } if (rawTarget.startsWith('@hooks/')) { return assertSafeRelativePath( `${aliases.hooksDir}/${rawTarget.slice('@hooks/'.length)}` ); } return assertSafeRelativePath(rawTarget); } const normalizedSource = file.path .replace(/^src\/registry\//, '') .replace(/^registry\//, ''); const baseName = path.posix.basename(normalizedSource); switch (file.type) { case 'registry:ui': { return assertSafeRelativePath(`${aliases.uiDir}/${baseName}`); } case 'registry:hook': { return assertSafeRelativePath(`${aliases.hooksDir}/${baseName}`); } case 'registry:lib': { return assertSafeRelativePath(`${aliases.libDir}/${baseName}`); } case 'registry:component': { return assertSafeRelativePath(`${aliases.componentsDir}/${baseName}`); } default: { return assertSafeRelativePath(normalizedSource); } } } async function readOptionalComponentsJson( cwd: string ): Promise { const filePath = path.join(cwd, 'components.json'); try { const raw = await fs.readFile(filePath, 'utf-8'); return ComponentsJsonSchema.parse(JSON.parse(raw)); } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { return null; } throw new Error( `Failed to parse components.json: ${error instanceof Error ? error.message : String(error)}`, { cause: error } ); } } async function readOptionalState( statePath: string ): Promise { try { const raw = await fs.readFile(statePath, 'utf-8'); return UiSyncStateV1Schema.parse(JSON.parse(raw)); } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { return null; } throw new Error( `Failed to read sync state at ${statePath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error } ); } } function buildItemRequest( itemSpecifier: string, options: Readonly<{ componentsConfig: ComponentsJson | null; env: Readonly>; registry?: string; style?: string; tokenEnv?: string; }> ): { headers: Record; itemName: string; url: string } { const style = options.style ?? options.componentsConfig?.style ?? 'base-nova'; const namespaceMatch = /^(@[a-z0-9-]+)\/([a-z0-9-]+)$/.exec(itemSpecifier); if (options.registry) { const itemName = namespaceMatch ? namespaceMatch[2] : itemSpecifier; if (!/^[a-z0-9-]+$/.test(itemName)) { throw new Error(`Invalid registry item name: ${itemSpecifier}`); } let url = options.registry; if (url.includes('{style}')) { url = url.replaceAll('{style}', encodeURIComponent(style)); } if (url.includes('{name}')) { url = url.replaceAll('{name}', encodeURIComponent(itemName)); } else { url = `${url.replace(/\/+$/, '')}/${encodeURIComponent(itemName)}.json`; } const headers: Record = {}; if (options.tokenEnv) { headers.Authorization = `Bearer ${readRequiredEnvToken(options.tokenEnv, options.env)}`; } return { headers, itemName, url }; } if (namespaceMatch) { const [, namespace, itemName] = namespaceMatch; const configEntry = options.componentsConfig?.registries?.[namespace]; if (!configEntry) { throw new Error( `Registry namespace "${namespace}" is not configured in components.json and --registry was not passed.` ); } const rawTemplate = typeof configEntry === 'string' ? configEntry : configEntry.url; let url = expandEnvTemplate( rawTemplate, options.env, `components.json registries.${namespace}.url` ); url = url .replaceAll('{style}', encodeURIComponent(style)) .replaceAll('{name}', encodeURIComponent(itemName)); const headers: Record = {}; if (typeof configEntry !== 'string' && configEntry.headers) { for (const [key, val] of Object.entries(configEntry.headers)) { headers[key] = expandEnvTemplate( val, options.env, `components.json registries.${namespace}.headers.${key}` ); } } if (options.tokenEnv) { headers.Authorization = `Bearer ${readRequiredEnvToken(options.tokenEnv, options.env)}`; } if (typeof configEntry !== 'string' && configEntry.params) { const parsed = assertSecureUrl(url); for (const [key, val] of Object.entries(configEntry.params)) { parsed.searchParams.set( key, expandEnvTemplate( val, options.env, `components.json registries.${namespace}.params.${key}` ) ); } url = parsed.toString(); } return { headers, itemName: itemSpecifier, url }; } throw new Error( `No registry configured for "${itemSpecifier}". Pass --registry , --registry-dir , or use @namespace/item configured in components.json.` ); } async function loadRegistryItem( itemSpecifier: string, options: Readonly<{ componentsConfig: ComponentsJson | null; cwd: string; env: Readonly>; fetchImpl?: typeof fetch; registry?: string; registryDir?: string; style?: string; tokenEnv?: string; }> ): Promise { if (options.registryDir) { const bareName = itemSpecifier.includes('/') ? (itemSpecifier.split('/').at(-1) ?? '') : itemSpecifier; if (!/^[a-z0-9-]+$/.test(bareName)) { throw new Error(`Invalid registry item name: ${itemSpecifier}`); } const dir = path.resolve(options.cwd, options.registryDir); const style = options.style ?? options.componentsConfig?.style; const candidates = [ ...(style ? [path.join(dir, style, `${bareName}.json`)] : []), path.join(dir, `${bareName}.json`), ]; for (const candidate of candidates) { try { const raw = await fs.readFile(candidate, 'utf-8'); return ShadcnRegistryItemSchema.parse(JSON.parse(raw)); } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { continue; } throw error; } } throw new Error( `Registry item "${itemSpecifier}" not found in ${options.registryDir}.` ); } const req = buildItemRequest(itemSpecifier, options); return secureFetchJson(req.url, { fetchImpl: options.fetchImpl, headers: req.headers, schema: ShadcnRegistryItemSchema, }); } async function readOptionalText(filePath: string): Promise { try { return await fs.readFile(filePath, 'utf-8'); } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { return null; } throw error; } } function resolveItemSource( specifier: string, options: SyncRegistryOptions, existingState: UiSyncStateV1 | null, defaultStyle: string | undefined ): TrackedItemSource { if (options.registryDir) { return { registryDir: options.registryDir, ...(defaultStyle ? { style: defaultStyle } : {}), }; } if (options.registry) { return { registry: options.registry, ...(defaultStyle ? { style: defaultStyle } : {}), }; } const saved = existingState?.items?.[specifier]; if (saved) { return { ...saved, ...(options.style ? { style: options.style } : {}), }; } // Legacy state files without per-item `items` map fall back to top-level registry. if (existingState && !specifier.startsWith('@')) { if (existingState.registry.startsWith('local:')) { return { registryDir: existingState.registry.slice('local:'.length), ...(defaultStyle ? { style: defaultStyle } : {}), }; } if (existingState.registry !== 'components.json') { return { registry: existingState.registry, ...(defaultStyle ? { style: defaultStyle } : {}), }; } } return defaultStyle ? { style: defaultStyle } : {}; } export async function syncRegistryItems( options: SyncRegistryOptions ): Promise { const cwd = await fs.realpath(path.resolve(options.cwd ?? process.cwd())); const env = loadProjectEnv(cwd); const stateFileOption = options.stateFile ?? DEFAULT_STATE_FILE; const stateDir = await assertContainedRoot( cwd, path.dirname(stateFileOption) ); const statePath = await assertNoSymlinkChain( stateDir, path.basename(stateFileOption) ); const [componentsConfig, atPrefix, baseRoot, reviewRoot, existingState] = await Promise.all([ readOptionalComponentsJson(cwd), resolveAtAliasPrefix(cwd), assertContainedRoot( cwd, path.join(path.dirname(stateFileOption), 'base') ), assertContainedRoot(cwd, options.reviewDir ?? DEFAULT_REVIEW_DIR), readOptionalState(statePath), ]); const requestedItems = options.items && options.items.length > 0 ? [...new Set(options.items)] : existingState ? [ ...new Set([ ...Object.keys(existingState.items ?? {}), ...Object.values(existingState.files).map((entry) => entry.item), ]), ].sort() : []; if (requestedItems.length === 0) { throw new Error( 'No registry items specified and no tracked items exist in .plate-ui-sync/last-sync.json. Pass item names, for example: plate sync @plate/callout' ); } const registrySource = options.registry ?? (options.registryDir ? `local:${options.registryDir}` : (existingState?.registry ?? 'components.json')); const style = options.style ?? componentsConfig?.style ?? existingState?.style; const nextItemsState: Record = { ...existingState?.items, }; const loadedItems: Array<{ item: ShadcnRegistryItem; specifier: string }> = []; const allRegistryDeps = new Set(); for (const specifier of requestedItems) { const itemSource = resolveItemSource( specifier, options, existingState, style ); const item = await loadRegistryItem(specifier, { componentsConfig, cwd, env, fetchImpl: options.fetchImpl, registry: itemSource.registry, registryDir: itemSource.registryDir, style: itemSource.style ?? style, tokenEnv: options.tokenEnv, }); loadedItems.push({ item, specifier }); nextItemsState[specifier] = itemSource; for (const dep of item.registryDependencies ?? []) { allRegistryDeps.add(dep); } } const planned: Array<{ content: string; itemSpecifier: string; relPath: string; upstreamHash: string; }> = []; for (const { item, specifier } of loadedItems) { for (const file of item.files) { const relPath = resolveRegistryTargetPath( file, componentsConfig, options.dir, atPrefix ); const transformed = transformRegistryFileContent( file.content, componentsConfig ); planned.push({ content: transformed, itemSpecifier: specifier, relPath, upstreamHash: sha256Hex(transformed), }); } } // Fail closed on duplicate or colliding target paths across items before writing anything. assertNoPathCollisions(planned.map((entry) => entry.relPath)); // Preflight all target, base, and review symlink checks before writing any byte to disk. const preflightPaths = await Promise.all( planned.map(async (entry) => ({ baseAbs: await assertNoSymlinkChain(baseRoot, entry.relPath), destAbs: await assertNoSymlinkChain(cwd, entry.relPath), patchAbs: await assertNoSymlinkChain( reviewRoot, `${entry.relPath}.patch` ), upstreamAbs: await assertNoSymlinkChain( reviewRoot, `${entry.relPath}.upstream` ), })) ); const nextFilesState: UiSyncStateV1['files'] = { ...existingState?.files, }; const reports: UiSyncFileReport[] = []; const dryRun = Boolean(options.check || options.dryRun); for (let i = 0; i < planned.length; i += 1) { const entry = planned[i]; const { baseAbs, destAbs, patchAbs, upstreamAbs } = preflightPaths[i]; const localContent = await readOptionalText(destAbs); const localHash = localContent === null ? null : sha256Hex(localContent); const recordedBase = existingState?.files[entry.relPath]; const baseHash = recordedBase?.sha256 ?? null; const baseContent = baseHash ? await readOptionalText(baseAbs) : null; let status: UiSyncFileStatus; let diffText = ''; let patchPath: string | undefined; let upstreamPath: string | undefined; if (localHash === null) { status = 'added'; if (!dryRun) { await writeFileAtomic(destAbs, entry.content); await writeFileAtomic(baseAbs, entry.content); } nextFilesState[entry.relPath] = { item: entry.itemSpecifier, sha256: entry.upstreamHash, }; } else if (localHash === entry.upstreamHash) { status = baseHash === entry.upstreamHash ? 'unchanged' : 'synced'; if (!dryRun && baseHash !== entry.upstreamHash) { await writeFileAtomic(baseAbs, entry.content); } nextFilesState[entry.relPath] = { item: entry.itemSpecifier, sha256: entry.upstreamHash, }; } else if (baseHash !== null && entry.upstreamHash === baseHash) { status = 'unchanged'; nextFilesState[entry.relPath] = { item: entry.itemSpecifier, sha256: baseHash, }; } else if (baseHash !== null && localHash === baseHash) { status = 'updated'; diffText = createUnifiedDiff( entry.relPath, localContent ?? '', entry.content ); if (!dryRun) { await writeFileAtomic(destAbs, entry.content); await writeFileAtomic(baseAbs, entry.content); } nextFilesState[entry.relPath] = { item: entry.itemSpecifier, sha256: entry.upstreamHash, }; } else { const reviewedUpstream = options.accept ? await readOptionalText(upstreamAbs) : null; const canAcceptReviewed = Boolean(options.accept) && reviewedUpstream !== null && sha256Hex(reviewedUpstream) === entry.upstreamHash; if (canAcceptReviewed) { status = 'synced'; if (!dryRun) { await writeFileAtomic(baseAbs, entry.content); await fs.rm(upstreamAbs, { force: true }).catch(() => undefined); await fs.rm(patchAbs, { force: true }).catch(() => undefined); } nextFilesState[entry.relPath] = { item: entry.itemSpecifier, sha256: entry.upstreamHash, }; } else { status = 'review'; diffText = baseContent !== null ? createUnifiedDiff(entry.relPath, baseContent, entry.content) : createUnifiedDiff( entry.relPath, localContent ?? '', entry.content ); upstreamPath = path.relative(cwd, upstreamAbs).replaceAll('\\', '/'); if (!dryRun) { await writeFileAtomic(upstreamAbs, entry.content); if (baseContent !== null && diffText) { patchPath = path.relative(cwd, patchAbs).replaceAll('\\', '/'); await writeFileAtomic(patchAbs, diffText); } } else if (baseContent !== null && diffText) { patchPath = path.relative(cwd, patchAbs).replaceAll('\\', '/'); } } } reports.push({ diff: options.diff ? diffText : undefined, item: entry.itemSpecifier, path: entry.relPath, patchPath, status, upstreamPath, }); } const changed = reports.some( (r) => r.status === 'added' || r.status === 'updated' || r.status === 'review' ); const hasReviews = reports.some((r) => r.status === 'review'); if (!dryRun) { const sortedFiles = Object.fromEntries( Object.entries(nextFilesState).sort(([a], [b]) => a.localeCompare(b)) ); const sortedItems = Object.fromEntries( Object.entries(nextItemsState).sort(([a], [b]) => a.localeCompare(b)) ); await writeFileAtomic( statePath, `${JSON.stringify( { files: sortedFiles, items: sortedItems, registry: registrySource, ...(style ? { style } : {}), version: 1, }, null, 2 )}\n` ); } return { changed, files: reports, hasReviews, items: requestedItems, registryDependencies: [...allRegistryDeps].sort(), }; } export function registerSyncCommand(program: Command): void { program .command('sync') .description( 'Three-way sync copied shadcn registry UI files while preserving local customizations.' ) .argument( '[items...]', 'Registry items (e.g. @plate/callout or callout). Defaults to items tracked in .plate-ui-sync/last-sync.json.' ) .option( '--registry ', 'Registry URL or template containing {name} and optional {style}' ) .option( '--registry-dir ', 'Local directory containing registry JSON files' ) .option('--style ', 'Registry style overlay name') .option( '--token-env ', 'Environment variable holding the Bearer API token' ) .option('--dir ', 'Override target root directory for synced files') .option('--state-file ', 'Sync state JSON path', DEFAULT_STATE_FILE) .option( '--review-dir ', 'Directory for upstream review patches', DEFAULT_REVIEW_DIR ) .option('--diff', 'Print unified diffs for updated and review files') .option( '--accept', 'Advance the recorded upstream base hash on review files after merging manually' ) .option( '--check', 'Exit nonzero when any file needs adding, updating, or review' ) .option('--dry-run', 'Show planned changes without writing files') .option('--cwd ', 'Working directory', process.cwd()) .action( async ( items: string[], options: Readonly<{ accept?: boolean; check?: boolean; cwd: string; diff?: boolean; dir?: string; dryRun?: boolean; registry?: string; registryDir?: string; reviewDir: string; stateFile: string; style?: string; tokenEnv?: string; }> ) => { const result = await syncRegistryItems({ accept: options.accept, check: options.check, cwd: options.cwd, diff: options.diff, dir: options.dir, dryRun: options.dryRun, items, registry: options.registry, registryDir: options.registryDir, reviewDir: options.reviewDir, stateFile: options.stateFile, style: options.style, tokenEnv: options.tokenEnv, }); const verb = options.check ? 'Checked' : options.dryRun ? 'Would sync' : 'Synced'; process.stdout.write( `${verb} ${result.files.length} file${result.files.length === 1 ? '' : 's'} from ${result.items.length} item${result.items.length === 1 ? '' : 's'}\n` ); for (const file of result.files) { const extra = file.status === 'review' ? ` (review: ${file.patchPath ?? file.upstreamPath})` : ''; process.stdout.write( ` ${file.status.padEnd(9)} ${file.path}${extra}\n` ); if (options.diff && file.diff) { process.stdout.write(`${file.diff}\n`); } } if (result.registryDependencies.length > 0) { process.stdout.write( `\nRegistry dependencies (install via shadcn if missing): ${result.registryDependencies.join(', ')}\n` ); } if (options.check && result.changed) { process.exitCode = 1; } } ); }