-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathshadcn-sync.js
More file actions
executable file
·476 lines (406 loc) · 15.4 KB
/
Copy pathshadcn-sync.js
File metadata and controls
executable file
·476 lines (406 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/env node
/**
* Shadcn Components Sync Script
*
* This script compares ObjectUI components with the latest Shadcn UI components
* and provides options to update them to the latest version.
*
* Usage:
* node scripts/shadcn-sync.js [options]
*
* Options:
* --check Check for component differences (default)
* --update <name> Update specific component from Shadcn registry
* --update-all Update all components from Shadcn registry
* --diff <name> Show detailed diff for a component
* --list List all components
* --backup Create backup before updating
*/
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import https from 'https';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const REPO_ROOT = path.join(__dirname, '..');
const COMPONENTS_DIR = path.join(REPO_ROOT, 'packages/components/src/ui');
const MANIFEST_PATH = path.join(REPO_ROOT, 'packages/components/shadcn-components.json');
const BACKUP_DIR = path.join(REPO_ROOT, 'packages/components/.backup');
// ANSI color codes
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
cyan: '\x1b[36m',
white: '\x1b[37m',
};
function log(message, color = 'white') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function logSection(title) {
console.log('\n' + '='.repeat(60));
log(title, 'bright');
console.log('='.repeat(60) + '\n');
}
async function fetchUrl(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (e) {
resolve(data);
}
});
}).on('error', reject);
});
}
async function loadManifest() {
try {
const content = await fs.readFile(MANIFEST_PATH, 'utf-8');
return JSON.parse(content);
} catch (error) {
log(`Error loading manifest: ${error.message}`, 'red');
process.exit(1);
}
}
async function getLocalComponents() {
try {
const files = await fs.readdir(COMPONENTS_DIR);
return files
.filter(f => f.endsWith('.tsx'))
.map(f => f.replace('.tsx', ''));
} catch (error) {
log(`Error reading components directory: ${error.message}`, 'red');
process.exit(1);
}
}
/**
* Registry `@/…` alias → ObjectUI relative path.
*
* Shadcn ships components with alias specifiers that assume its own repo
* layout, and it has changed that layout at least once: the older generation
* was `@/components/ui/x`, while every endpoint this manifest points at now
* serves `@/registry/<style>/{ui,hooks,lib}/x`. Both forms are listed so a
* pinned or re-pointed source keeps working.
*
* Synced files land in `packages/components/src/ui/`, so `ui/` resolves to a
* sibling (`./x`) while `hooks/` and `lib/` step up one level (`../hooks/x`).
*
* Matching is on the quoted specifier rather than on `from "…"`, so
* `export … from`, dynamic `import()` and `vi.mock()` are covered too. The
* backreference keeps the original quote style.
*/
const IMPORT_REWRITES = [
[/(["'])@\/registry\/[^/"']+\/ui\/([^"']+)\1/g, '$1./$2$1'],
[/(["'])@\/registry\/[^/"']+\/hooks\/([^"']+)\1/g, '$1../hooks/$2$1'],
[/(["'])@\/registry\/[^/"']+\/lib\/([^"']+)\1/g, '$1../lib/$2$1'],
[/(["'])@\/components\/ui\/([^"']+)\1/g, '$1./$2$1'],
[/(["'])@\/hooks\/([^"']+)\1/g, '$1../hooks/$2$1'],
[/(["'])@\/lib\/([^"']+)\1/g, '$1../lib/$2$1'],
];
function rewriteRegistryImports(content) {
return IMPORT_REWRITES.reduce((acc, [pattern, replacement]) => acc.replace(pattern, replacement), content);
}
/**
* Any `@/…` specifier the table above did not map. These do not resolve from
* `src/ui/`, so writing a file that still contains one produces a component
* that cannot compile — which is how `resizable` reached `customComponents`.
* Callers must treat a non-empty result as a hard failure, not a warning:
* this is the only thing standing between a Shadcn layout change and a
* broken build.
*/
function findUnmappedAliases(content) {
return [...new Set([...content.matchAll(/["'](@\/[^"']+)["']/g)].map((m) => m[1]))];
}
async function checkComponent(name, manifest) {
const componentInfo = manifest.components[name];
if (!componentInfo) {
return {
name,
status: 'custom',
message: 'Custom ObjectUI component (not in Shadcn)',
};
}
const localPath = path.join(COMPONENTS_DIR, `${name}.tsx`);
try {
const localContent = await fs.readFile(localPath, 'utf-8');
const localLines = localContent.split('\n').length;
// Fetch latest from registry
try {
const registryData = await fetchUrl(componentInfo.source);
// Rewrite before comparing, so import-path style alone does not read as
// a difference — the local file has already been through this transform.
const shadcnContent = rewriteRegistryImports(registryData.files?.[0]?.content || '');
const shadcnLines = shadcnContent.split('\n').length;
// Simple heuristic: check if significantly different
const lineDiff = Math.abs(localLines - shadcnLines);
const isDifferent = lineDiff > 10 || localContent.includes('ObjectUI') || localContent.includes('data-slot');
return {
name,
status: isDifferent ? 'modified' : 'synced',
localLines,
shadcnLines,
lineDiff,
message: isDifferent ?
`Modified (${lineDiff} lines difference)` :
'Synced with Shadcn',
};
} catch (fetchError) {
return {
name,
status: 'error',
message: `Error fetching from registry: ${fetchError.message}`,
};
}
} catch (error) {
return {
name,
status: 'error',
message: `Error reading local file: ${error.message}`,
};
}
}
async function checkAllComponents() {
logSection('Checking Components Status');
const manifest = await loadManifest();
const localComponents = await getLocalComponents();
log(`Found ${localComponents.length} local components`, 'cyan');
log(`Tracking ${Object.keys(manifest.components).length} Shadcn components`, 'cyan');
log(`Tracking ${Object.keys(manifest.customComponents).length} custom components\n`, 'cyan');
const results = {
synced: [],
modified: [],
custom: [],
error: [],
};
for (const component of localComponents) {
const result = await checkComponent(component, manifest);
results[result.status].push(result);
const symbol = {
synced: '✓',
modified: '⚠',
custom: '●',
error: '✗',
}[result.status];
const color = {
synced: 'green',
modified: 'yellow',
custom: 'blue',
error: 'red',
}[result.status];
log(`${symbol} ${result.name.padEnd(25)} ${result.message}`, color);
}
// Summary
logSection('Summary');
log(`✓ Synced: ${results.synced.length} components`, 'green');
log(`⚠ Modified: ${results.modified.length} components`, 'yellow');
log(`● Custom: ${results.custom.length} components`, 'blue');
log(`✗ Errors: ${results.error.length} components`, 'red');
if (results.modified.length > 0) {
log('\nTo update a component:', 'cyan');
log(' node scripts/shadcn-sync.js --update <component-name>', 'dim');
log(' node scripts/shadcn-sync.js --update-all', 'dim');
}
return results;
}
async function createBackup(componentName) {
await fs.mkdir(BACKUP_DIR, { recursive: true });
const sourcePath = path.join(COMPONENTS_DIR, `${componentName}.tsx`);
const backupPath = path.join(BACKUP_DIR, `${componentName}.tsx.${Date.now()}.backup`);
try {
await fs.copyFile(sourcePath, backupPath);
log(`Created backup: ${path.basename(backupPath)}`, 'dim');
} catch (error) {
log(`Warning: Could not create backup: ${error.message}`, 'yellow');
}
}
async function updateComponent(name, manifest, options = {}) {
const componentInfo = manifest.components[name];
if (!componentInfo) {
log(`Component "${name}" not found in Shadcn registry (might be custom)`, 'red');
return false;
}
log(`\nUpdating ${name}...`, 'cyan');
try {
// Fetch from registry
const registryData = await fetchUrl(componentInfo.source);
if (!registryData.files || registryData.files.length === 0) {
log(`No files found in registry for ${name}`, 'red');
return false;
}
// Only files[0] is written. Say so rather than truncating silently — a
// multi-file entry (e.g. `toast`) needs its extra files placed by hand.
if (registryData.files.length > 1) {
const extra = registryData.files.slice(1).map((f) => f.path || f.name || '?');
log(` ⚠ Registry ships ${registryData.files.length} files; only the first is written.`, 'yellow');
log(` Not written: ${extra.join(', ')}`, 'yellow');
}
// Transform imports to match ObjectUI structure
let content = rewriteRegistryImports(registryData.files[0].content);
// Fail closed. An unmapped `@/…` specifier does not resolve from src/ui/,
// so writing the file would swap working code for code that cannot
// compile. Better to refuse and have someone extend IMPORT_REWRITES.
const unmapped = findUnmappedAliases(content);
if (unmapped.length > 0) {
log(`✗ Refusing to write ${name}.tsx — unmapped registry import path(s):`, 'red');
unmapped.forEach((spec) => log(` ${spec}`, 'red'));
log(` Shadcn's alias layout changed. Add a rule to IMPORT_REWRITES in this script.`, 'yellow');
return false;
}
// Add ObjectUI header
const header = `/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
`;
content = header + content;
// Create backup if requested
if (options.backup) {
await createBackup(name);
}
// Write updated component
const targetPath = path.join(COMPONENTS_DIR, `${name}.tsx`);
await fs.writeFile(targetPath, content, 'utf-8');
log(`✓ Updated ${name}.tsx`, 'green');
// Check and log dependencies
if (componentInfo.dependencies.length > 0) {
log(` Dependencies: ${componentInfo.dependencies.join(', ')}`, 'dim');
}
if (componentInfo.registryDependencies.length > 0) {
log(` Registry deps: ${componentInfo.registryDependencies.join(', ')}`, 'dim');
}
return true;
} catch (error) {
log(`✗ Error updating ${name}: ${error.message}`, 'red');
return false;
}
}
async function updateAllComponents(options = {}) {
logSection('Updating All Components from Shadcn Registry');
const manifest = await loadManifest();
const componentNames = Object.keys(manifest.components);
if (options.backup) {
log('Creating backups...', 'cyan');
}
let updated = 0;
let failed = 0;
for (const name of componentNames) {
const success = await updateComponent(name, manifest, options);
if (success) {
updated++;
} else {
failed++;
}
// Small delay to avoid rate limiting
await new Promise(resolve => setTimeout(resolve, 100));
}
logSection('Update Complete');
log(`✓ Updated: ${updated} components`, 'green');
if (failed > 0) {
log(`✗ Failed: ${failed} components`, 'red');
}
log('\nNext steps:', 'cyan');
log('1. Review the changes: git diff packages/components/src/ui/', 'dim');
log('2. Test the components: pnpm test', 'dim');
log('3. Build the package: pnpm --filter @object-ui/components build', 'dim');
}
async function showDiff(name) {
logSection(`Component Diff: ${name}`);
const manifest = await loadManifest();
const componentInfo = manifest.components[name];
if (!componentInfo) {
log(`Component "${name}" not found in registry`, 'red');
return;
}
try {
const localPath = path.join(COMPONENTS_DIR, `${name}.tsx`);
const localContent = await fs.readFile(localPath, 'utf-8');
const registryData = await fetchUrl(componentInfo.source);
// Same transform `--update` would apply, so the two sides are comparable.
const shadcnContent = rewriteRegistryImports(registryData.files?.[0]?.content || '');
log('Local version:', 'cyan');
console.log(localContent.substring(0, 500) + '...\n');
log('Shadcn version (import paths rewritten):', 'cyan');
console.log(shadcnContent.substring(0, 500) + '...\n');
log(`Local: ${localContent.split('\n').length} lines`, 'dim');
log(`Shadcn: ${shadcnContent.split('\n').length} lines`, 'dim');
const unmapped = findUnmappedAliases(shadcnContent);
if (unmapped.length > 0) {
log(`\n⚠ Unmapped registry import path(s) — \`--update ${name}\` would refuse:`, 'yellow');
unmapped.forEach((spec) => log(` ${spec}`, 'yellow'));
}
} catch (error) {
log(`Error: ${error.message}`, 'red');
}
}
async function listComponents() {
logSection('Component List');
const manifest = await loadManifest();
log('Shadcn Components:', 'cyan');
Object.keys(manifest.components).sort().forEach(name => {
console.log(` • ${name}`);
});
log('\nCustom ObjectUI Components:', 'blue');
Object.entries(manifest.customComponents).sort().forEach(([name, info]) => {
console.log(` • ${name.padEnd(20)} ${colors.dim}${info.description}${colors.reset}`);
});
}
// Main CLI
async function main() {
const args = process.argv.slice(2);
if (args.length === 0 || args.includes('--check')) {
await checkAllComponents();
} else if (args.includes('--update-all')) {
const backup = args.includes('--backup');
await updateAllComponents({ backup });
} else if (args.includes('--update')) {
const idx = args.indexOf('--update');
const componentName = args[idx + 1];
if (!componentName) {
log('Error: --update requires a component name', 'red');
process.exit(1);
}
const manifest = await loadManifest();
const backup = args.includes('--backup');
await updateComponent(componentName, manifest, { backup });
} else if (args.includes('--diff')) {
const idx = args.indexOf('--diff');
const componentName = args[idx + 1];
if (!componentName) {
log('Error: --diff requires a component name', 'red');
process.exit(1);
}
await showDiff(componentName);
} else if (args.includes('--list')) {
await listComponents();
} else if (args.includes('--help') || args.includes('-h')) {
logSection('Shadcn Components Sync Script');
console.log('Usage: node scripts/shadcn-sync.js [options]\n');
console.log('Options:');
console.log(' --check Check for component differences (default)');
console.log(' --update <name> Update specific component from Shadcn');
console.log(' --update-all Update all components from Shadcn');
console.log(' --diff <name> Show detailed diff for a component');
console.log(' --list List all components');
console.log(' --backup Create backup before updating');
console.log(' --help, -h Show this help message\n');
} else {
log('Unknown option. Use --help for usage information.', 'red');
process.exit(1);
}
}
main().catch(error => {
log(`Fatal error: ${error.message}`, 'red');
console.error(error);
process.exit(1);
});