@usalyt/registry 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,492 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const REGISTRY_PACKAGE_MANIFEST = fs.readJsonSync(
6
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../package.json")
7
+ ) as { version?: string };
8
+
9
+ export const REGISTRY_NAME = "usalyt";
10
+ export const REGISTRY_VERSION = REGISTRY_PACKAGE_MANIFEST.version ?? "0.0.1";
11
+ export const REGISTRY_LICENSE = "MIT";
12
+ export const REGISTRY_SCHEMA_REFERENCE = "./schema/registry.schema.json";
13
+ export const REGISTRY_REPOSITORY = {
14
+ type: "git",
15
+ url: "git+https://github.com/Usalyt/ui.git",
16
+ directory: "packages/registry",
17
+ } as const;
18
+
19
+ export interface RegistryFile {
20
+ path: string;
21
+ type: string;
22
+ content: string;
23
+ }
24
+
25
+ export interface RegistryItem {
26
+ name: string;
27
+ type: string;
28
+ title: string;
29
+ description: string;
30
+ license: string;
31
+ dependencies: string[];
32
+ devDependencies: string[];
33
+ registryDependencies: string[];
34
+ dependencyVersions: Record<string, string>;
35
+ files: RegistryFile[];
36
+ }
37
+
38
+ export interface Registry {
39
+ $schema: string;
40
+ name: string;
41
+ version: string;
42
+ license: string;
43
+ repository: typeof REGISTRY_REPOSITORY;
44
+ dependencyLicenses: Record<string, string>;
45
+ items: RegistryItem[];
46
+ }
47
+
48
+ export interface RegistryBuildStats {
49
+ primitives: number;
50
+ blocks: number;
51
+ libraries: number;
52
+ styles: number;
53
+ items: number;
54
+ }
55
+
56
+ export interface RegistryBuildResult {
57
+ registry: Registry;
58
+ json: string;
59
+ stats: RegistryBuildStats;
60
+ }
61
+
62
+ export interface RegistryBuildOptions {
63
+ /** UI source root that contains `components/`, `blocks/`, and `lib/`. */
64
+ sourceRoot: string;
65
+ /** Root of the `@usalyt/registry` package, used for the notices file. */
66
+ packageRoot: string;
67
+ }
68
+
69
+ interface UiPackageManifest {
70
+ name?: string;
71
+ dependencies?: Record<string, string>;
72
+ peerDependencies?: Record<string, string>;
73
+ }
74
+
75
+ const IMPORT_PATTERN =
76
+ /(?:import|export)\s+(?:[^"'()]*?\s+from\s+)?["']([^"']+)["']/g;
77
+
78
+ const RUNTIME_PEERS = new Set(["react", "react-dom"]);
79
+
80
+ const posix = path.posix;
81
+
82
+ function toTitle(name: string): string {
83
+ return name
84
+ .split("-")
85
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
86
+ .join(" ");
87
+ }
88
+
89
+ function extractSpecifiers(content: string): string[] {
90
+ const specifiers = new Set<string>();
91
+ for (const match of content.matchAll(IMPORT_PATTERN)) {
92
+ specifiers.add(match[1]);
93
+ }
94
+ return [...specifiers];
95
+ }
96
+
97
+ function packageNameFromSpecifier(specifier: string): string | null {
98
+ if (specifier.startsWith(".") || specifier.startsWith("node:")) {
99
+ return null;
100
+ }
101
+ const root = specifier.startsWith("@")
102
+ ? specifier.split("/").slice(0, 2).join("/")
103
+ : specifier.split("/")[0];
104
+ if (RUNTIME_PEERS.has(root)) {
105
+ return null;
106
+ }
107
+ return root;
108
+ }
109
+
110
+ function isItemSourceFile(fileName: string): boolean {
111
+ if (fileName.endsWith(".test.ts") || fileName.endsWith(".test.tsx")) {
112
+ return false;
113
+ }
114
+ if (fileName.endsWith(".stories.ts") || fileName.endsWith(".stories.tsx")) {
115
+ return false;
116
+ }
117
+ return fileName.endsWith(".ts") || fileName.endsWith(".tsx");
118
+ }
119
+
120
+ async function listItemDirectories(root: string): Promise<string[]> {
121
+ const entries = await fs.readdir(root, { withFileTypes: true });
122
+ return entries
123
+ .filter((entry) => entry.isDirectory())
124
+ .map((entry) => entry.name)
125
+ .sort();
126
+ }
127
+
128
+ async function readItemFiles(
129
+ sourceRoot: string,
130
+ kind: "components" | "blocks",
131
+ itemName: string,
132
+ type: string
133
+ ): Promise<RegistryFile[]> {
134
+ const itemDir = path.join(sourceRoot, kind, itemName);
135
+ const fileNames = (await fs.readdir(itemDir))
136
+ .filter(isItemSourceFile)
137
+ .sort();
138
+
139
+ const files: RegistryFile[] = [];
140
+ for (const fileName of fileNames) {
141
+ files.push({
142
+ path: `${kind}/${itemName}/${fileName}`,
143
+ type,
144
+ content: await fs.readFile(path.join(itemDir, fileName), "utf-8"),
145
+ });
146
+ }
147
+
148
+ return files;
149
+ }
150
+
151
+ function sourcePathFor(
152
+ itemName: string,
153
+ fileName: string,
154
+ kind: "components" | "blocks"
155
+ ): string {
156
+ return `${kind}/${itemName}/${fileName}`;
157
+ }
158
+
159
+ function resolveRelativeImport(
160
+ sourcePath: string,
161
+ specifier: string,
162
+ knownPaths: Set<string>
163
+ ): string | null {
164
+ if (!specifier.startsWith(".")) {
165
+ return null;
166
+ }
167
+
168
+ const base = posix.normalize(
169
+ posix.join(posix.dirname(sourcePath), specifier)
170
+ );
171
+ const candidates = [
172
+ base,
173
+ `${base}.tsx`,
174
+ `${base}.ts`,
175
+ `${base}/index.ts`,
176
+ `${base}/index.tsx`,
177
+ ];
178
+
179
+ return candidates.find((candidate) => knownPaths.has(candidate)) ?? null;
180
+ }
181
+
182
+ function sortedRecord(entries: Iterable<[string, string]>): Record<string, string> {
183
+ return Object.fromEntries(
184
+ [...entries].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
185
+ );
186
+ }
187
+
188
+ async function readUiPackageManifest(
189
+ sourceRoot: string
190
+ ): Promise<UiPackageManifest> {
191
+ const candidates = [
192
+ path.resolve(sourceRoot, "..", "package.json"),
193
+ path.resolve(sourceRoot, "package.json"),
194
+ ];
195
+
196
+ for (const candidate of candidates) {
197
+ if (!(await fs.pathExists(candidate))) {
198
+ continue;
199
+ }
200
+ const manifest = (await fs.readJson(candidate)) as UiPackageManifest;
201
+ if (manifest.name === "@usalyt/ui" && manifest.dependencies) {
202
+ return manifest;
203
+ }
204
+ }
205
+
206
+ throw new Error(
207
+ `Cannot find the @usalyt/ui package.json next to source root: ${sourceRoot}`
208
+ );
209
+ }
210
+
211
+ async function readNoticeLicenses(
212
+ packageRoot: string
213
+ ): Promise<Record<string, string>> {
214
+ const noticesPath = path.join(packageRoot, "THIRD_PARTY_NOTICES.md");
215
+ if (!(await fs.pathExists(noticesPath))) {
216
+ throw new Error(`Third-party notices file not found: ${noticesPath}`);
217
+ }
218
+
219
+ const licenses: Record<string, string> = {};
220
+ const text = await fs.readFile(noticesPath, "utf-8");
221
+
222
+ for (const rawLine of text.split("\n")) {
223
+ const line = rawLine.trimEnd();
224
+ const match = line.match(/^\| `([^`]+)` \| [^|]+ \| ([^|]+) \|$/);
225
+ if (match) {
226
+ licenses[match[1]] = match[2].trim();
227
+ }
228
+ }
229
+
230
+ return licenses;
231
+ }
232
+
233
+ function buildDependencyLicenses(
234
+ directDependencyNames: string[],
235
+ notices: Record<string, string>
236
+ ): Record<string, string> {
237
+ const entries: Array<[string, string]> = [];
238
+ const missing: string[] = [];
239
+
240
+ for (const name of directDependencyNames) {
241
+ const license = notices[name];
242
+ if (!license) {
243
+ missing.push(name);
244
+ continue;
245
+ }
246
+ entries.push([name, license]);
247
+ }
248
+
249
+ if (missing.length > 0) {
250
+ throw new Error(
251
+ `Missing audited licenses in THIRD_PARTY_NOTICES.md for: ${missing.join(", ")}`
252
+ );
253
+ }
254
+
255
+ return sortedRecord(entries);
256
+ }
257
+
258
+ async function resolveThemeCssPath(sourceRoot: string): Promise<string> {
259
+ const candidates = [
260
+ path.resolve(sourceRoot, "..", "styles", "theme.css"),
261
+ path.resolve(sourceRoot, "styles", "theme.css"),
262
+ ];
263
+ for (const candidate of candidates) {
264
+ if (await fs.pathExists(candidate)) {
265
+ return candidate;
266
+ }
267
+ }
268
+ throw new Error(
269
+ `Shared theme stylesheet not found next to source root: ${sourceRoot}`
270
+ );
271
+ }
272
+
273
+ /**
274
+ * Builds the registry data from an explicit UI source root. The function only
275
+ * reads files below `sourceRoot` (plus its sibling `styles/theme.css`) and the
276
+ * package-local notices file, and it never records absolute paths or timestamps.
277
+ */
278
+ export async function buildRegistry(
279
+ options: RegistryBuildOptions
280
+ ): Promise<RegistryBuildResult> {
281
+ const sourceRoot = path.resolve(options.sourceRoot);
282
+ const componentsDir = path.join(sourceRoot, "components");
283
+ const blocksDir = path.join(sourceRoot, "blocks");
284
+ const utilsPath = path.join(sourceRoot, "lib", "utils.ts");
285
+ const themeCssPath = await resolveThemeCssPath(sourceRoot);
286
+
287
+ if (!(await fs.pathExists(componentsDir))) {
288
+ throw new Error(`UI source root not found or incomplete: ${sourceRoot}`);
289
+ }
290
+ if (!(await fs.pathExists(blocksDir))) {
291
+ throw new Error(`UI blocks directory not found: ${blocksDir}`);
292
+ }
293
+ if (!(await fs.pathExists(utilsPath))) {
294
+ throw new Error(`Shared utils source not found: ${utilsPath}`);
295
+ }
296
+
297
+ const uiPackage = await readUiPackageManifest(sourceRoot);
298
+ const declaredVersions: Record<string, string> = {
299
+ ...(uiPackage.dependencies ?? {}),
300
+ ...(uiPackage.peerDependencies ?? {}),
301
+ };
302
+
303
+ const primitiveNames = await listItemDirectories(componentsDir);
304
+ const blockNames = await listItemDirectories(blocksDir);
305
+
306
+ const sourceIndex = new Map<string, string>();
307
+ for (const name of primitiveNames) {
308
+ for (const fileName of (await fs.readdir(path.join(componentsDir, name))).sort()) {
309
+ if (isItemSourceFile(fileName)) {
310
+ sourceIndex.set(sourcePathFor(name, fileName, "components"), name);
311
+ }
312
+ }
313
+ }
314
+ for (const name of blockNames) {
315
+ for (const fileName of (await fs.readdir(path.join(blocksDir, name))).sort()) {
316
+ if (isItemSourceFile(fileName)) {
317
+ sourceIndex.set(sourcePathFor(name, fileName, "blocks"), name);
318
+ }
319
+ }
320
+ }
321
+ sourceIndex.set("lib/utils.ts", "utils");
322
+
323
+ const knownPaths = new Set(sourceIndex.keys());
324
+
325
+ const registryDependenciesFor = (itemName: string, files: RegistryFile[]): string[] => {
326
+ const dependencies = new Set<string>();
327
+ for (const file of files) {
328
+ for (const specifier of extractSpecifiers(file.content)) {
329
+ const resolved = resolveRelativeImport(file.path, specifier, knownPaths);
330
+ if (!resolved) {
331
+ continue;
332
+ }
333
+ const dependency = sourceIndex.get(resolved);
334
+ if (dependency && dependency !== itemName) {
335
+ dependencies.add(dependency);
336
+ }
337
+ }
338
+ }
339
+ return [...dependencies].sort();
340
+ };
341
+
342
+ const dependencyVersionsFor = (
343
+ itemName: string,
344
+ files: RegistryFile[]
345
+ ): { dependencies: string[]; dependencyVersions: Record<string, string> } => {
346
+ const dependencies = new Set<string>();
347
+
348
+ for (const file of files) {
349
+ for (const specifier of extractSpecifiers(file.content)) {
350
+ const packageName = packageNameFromSpecifier(specifier);
351
+ if (!packageName) {
352
+ continue;
353
+ }
354
+ if (!declaredVersions[packageName]) {
355
+ throw new Error(
356
+ `${itemName}: imported package "${packageName}" is not declared by @usalyt/ui`
357
+ );
358
+ }
359
+ dependencies.add(packageName);
360
+ }
361
+ }
362
+
363
+ const sortedDependencies = [...dependencies].sort();
364
+ return {
365
+ dependencies: sortedDependencies,
366
+ dependencyVersions: sortedRecord(
367
+ sortedDependencies.map((name) => [name, declaredVersions[name]])
368
+ ),
369
+ };
370
+ };
371
+
372
+ const items: RegistryItem[] = [];
373
+
374
+ for (const name of primitiveNames) {
375
+ const files = await readItemFiles(sourceRoot, "components", name, "registry:ui");
376
+ const title = toTitle(name);
377
+ const { dependencies, dependencyVersions } = dependencyVersionsFor(name, files);
378
+
379
+ items.push({
380
+ name,
381
+ type: "registry:ui",
382
+ title,
383
+ description: `Accessible ${title} primitive component built with Base UI and Tailwind v4.`,
384
+ license: REGISTRY_LICENSE,
385
+ dependencies,
386
+ devDependencies: [],
387
+ registryDependencies: registryDependenciesFor(name, files),
388
+ dependencyVersions,
389
+ files,
390
+ });
391
+ }
392
+
393
+ for (const name of blockNames) {
394
+ const files = await readItemFiles(sourceRoot, "blocks", name, "registry:block");
395
+ const title = toTitle(name);
396
+ const blockTitle = title.endsWith(" Block") ? title : `${title} Block`;
397
+ const { dependencies, dependencyVersions } = dependencyVersionsFor(name, files);
398
+
399
+ items.push({
400
+ name,
401
+ type: "registry:block",
402
+ title: blockTitle,
403
+ description: `Composed ${title} block built from Usalyt primitives, Base UI and Tailwind v4.`,
404
+ license: REGISTRY_LICENSE,
405
+ dependencies,
406
+ devDependencies: [],
407
+ registryDependencies: registryDependenciesFor(name, files),
408
+ dependencyVersions,
409
+ files,
410
+ });
411
+ }
412
+
413
+ const utilsFiles: RegistryFile[] = [
414
+ {
415
+ path: "lib/utils.ts",
416
+ type: "registry:lib",
417
+ content: await fs.readFile(utilsPath, "utf-8"),
418
+ },
419
+ ];
420
+ const utilsDependencies = dependencyVersionsFor("utils", utilsFiles);
421
+
422
+ items.push({
423
+ name: "utils",
424
+ type: "registry:lib",
425
+ title: "Utils",
426
+ description: "Shared cn() class merge utility for Usalyt components.",
427
+ license: REGISTRY_LICENSE,
428
+ dependencies: utilsDependencies.dependencies,
429
+ devDependencies: [],
430
+ registryDependencies: registryDependenciesFor("utils", utilsFiles),
431
+ dependencyVersions: utilsDependencies.dependencyVersions,
432
+ files: utilsFiles,
433
+ });
434
+
435
+ items.push({
436
+ name: "theme",
437
+ type: "registry:style",
438
+ title: "Theme",
439
+ description:
440
+ "Usalyt Tailwind CSS v4 @theme tokens, dark/light surfaces, and motion primitives.",
441
+ license: REGISTRY_LICENSE,
442
+ dependencies: [],
443
+ devDependencies: [],
444
+ registryDependencies: [],
445
+ dependencyVersions: {},
446
+ files: [
447
+ {
448
+ path: "styles/theme.css",
449
+ type: "registry:style",
450
+ content: await fs.readFile(themeCssPath, "utf-8"),
451
+ },
452
+ ],
453
+ });
454
+
455
+ items.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
456
+
457
+ const notices = await readNoticeLicenses(options.packageRoot);
458
+ const directDependencyNames = [
459
+ ...new Set([
460
+ ...Object.keys(uiPackage.dependencies ?? {}),
461
+ ...Object.keys(uiPackage.peerDependencies ?? {}),
462
+ ]),
463
+ ].sort();
464
+
465
+ const registryManifestPath = path.join(options.packageRoot, "package.json");
466
+ const registryManifest = (await fs.pathExists(registryManifestPath))
467
+ ? ((await fs.readJson(registryManifestPath)) as { version?: string })
468
+ : undefined;
469
+ const version = registryManifest?.version ?? REGISTRY_VERSION;
470
+
471
+ const registry: Registry = {
472
+ $schema: REGISTRY_SCHEMA_REFERENCE,
473
+ name: REGISTRY_NAME,
474
+ version,
475
+ license: REGISTRY_LICENSE,
476
+ repository: REGISTRY_REPOSITORY,
477
+ dependencyLicenses: buildDependencyLicenses(directDependencyNames, notices),
478
+ items,
479
+ };
480
+
481
+ return {
482
+ registry,
483
+ json: `${JSON.stringify(registry, null, 2)}\n`,
484
+ stats: {
485
+ primitives: primitiveNames.length,
486
+ blocks: blockNames.length,
487
+ libraries: 1,
488
+ styles: 1,
489
+ items: items.length,
490
+ },
491
+ };
492
+ }