@kolamui/registry 0.0.0-canary-32a322e

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kolam contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # @kolamui/registry
2
+
3
+ Resolve, fetch, verify, build and install Kolam registry items. Used by the `kolam` CLI and by tools that work with Kolam registries.
4
+
5
+ > Kolam is in private alpha. Nothing is released yet; only canary builds are published.
6
+
7
+ ```ts
8
+ import { fetchItem, resolveRegistry, writeItemFiles } from "@kolamui/registry";
9
+
10
+ const registry = resolveRegistry(); // KOLAM_REGISTRY_URL and KOLAM_REGISTRY_TOKEN
11
+ const item = await fetchItem(registry, "button"); // checks the schema and every file's sha256
12
+ ```
13
+
14
+ Errors are `KolamError`s with a `code` (`E_REGISTRY`, `E_INTEGRITY`, `E_UNSAFE_ITEM`, …) and the CLI `exitCode` for it.
15
+
16
+ ## Licence
17
+
18
+ MIT
@@ -0,0 +1,116 @@
1
+ import { BuiltFile, KolamJson, ManifestItem, RegistryIndex, RegistryItem } from "@kolamui/schema";
2
+ interface BuildOptions {
3
+ /** The registry project's root folder; every file must resolve inside it. */
4
+ readonly root: string;
5
+ /** Staging builds include `internal` items; public builds leave them out. */
6
+ readonly staging?: boolean;
7
+ }
8
+ interface BuildResult {
9
+ readonly items: RegistryItem[];
10
+ readonly index: RegistryIndex;
11
+ }
12
+ /**
13
+ * Builds a registry from its source manifest: validates the manifest, reads and hashes every
14
+ * file, and refuses anything unsafe to ship. Every problem is collected and reported at once.
15
+ */
16
+ export declare function buildRegistry(manifestInput: unknown, options: BuildOptions): Promise<BuildResult>;
17
+ /** The folder a file installs into, from its item's kind and where it sits in the source. */
18
+ export declare function defaultTarget(kind: ManifestItem["kind"], sourcePath: string): string;
19
+ /** Error codes shared by the CLI, the MCP server and registry tools, with their CLI exit codes. */
20
+ export declare const exitCodes: {
21
+ readonly E_UNAUTHENTICATED: 3;
22
+ readonly E_FORBIDDEN: 3;
23
+ readonly E_NOT_FOUND: 1;
24
+ readonly E_VALIDATION: 1;
25
+ readonly E_REGISTRY: 1;
26
+ readonly E_INTEGRITY: 1;
27
+ readonly E_UNSAFE_ITEM: 1;
28
+ };
29
+ type ErrorCode = keyof typeof exitCodes;
30
+ interface FieldError {
31
+ path: string;
32
+ message: string;
33
+ }
34
+ export declare class KolamError extends Error {
35
+ readonly code: ErrorCode;
36
+ readonly exitCode: number;
37
+ readonly fields: FieldError[] | undefined;
38
+ constructor(code: ErrorCode, message: string, options?: {
39
+ fields?: FieldError[];
40
+ cause?: unknown;
41
+ });
42
+ }
43
+ export declare function isKolamError(error: unknown): error is KolamError;
44
+ interface RegistryConfig {
45
+ /** Base URL that item files live under: `<baseUrl>/<name>.json`. No trailing slash. */
46
+ readonly baseUrl: string;
47
+ /** Headers sent with every request to this registry. */
48
+ readonly headers: Readonly<Record<string, string>>;
49
+ }
50
+ interface ResolveRegistryOptions {
51
+ /** A registry URL given on the command line; wins over the environment. */
52
+ readonly url?: string | undefined;
53
+ /** A token for that registry; wins over the environment. */
54
+ readonly token?: string | undefined;
55
+ readonly env?: Readonly<Record<string, string | undefined>>;
56
+ }
57
+ /**
58
+ * Works out which registry to use. KOLAM_REGISTRY_URL replaces the Kolam registry base URL
59
+ * (testers use it to reach the password-protected staging registry) and KOLAM_REGISTRY_TOKEN
60
+ * is sent to it as a bearer token.
61
+ */
62
+ export declare function resolveRegistry(options?: ResolveRegistryOptions): RegistryConfig;
63
+ interface FetchItemOptions {
64
+ /** Fetch an exact version (`<name>/<version>.json`) instead of the latest. */
65
+ readonly version?: string | undefined;
66
+ /** How many times to retry network failures and 5xx responses. */
67
+ readonly retries?: number;
68
+ readonly fetch?: typeof globalThis.fetch;
69
+ /** Delay before each retry, in milliseconds. */
70
+ readonly retryDelayMs?: number;
71
+ }
72
+ export declare function itemUrl(registry: RegistryConfig, name: string, version?: string): string;
73
+ /** Fetches a built item, checks it against the schema and verifies every file's sha256. */
74
+ export declare function fetchItem(registry: RegistryConfig, name: string, options?: FetchItemOptions): Promise<RegistryItem>;
75
+ /** Throws E_INTEGRITY when any file's content doesn't match its sha256. */
76
+ export declare function verifyItem(item: RegistryItem): void;
77
+ /** The sha256 of a file's bytes as an integrity value: `sha256-<base64>`. */
78
+ export declare function integrity(content: string | Uint8Array): string;
79
+ /** Bytes of a file as stored in a built item (`utf8` text or `base64` binary). */
80
+ export declare function fileBytes(content: string, encoding?: "utf8" | "base64"): Uint8Array;
81
+ /** `compilerOptions.paths` from the project's tsconfig.json, or {} when there is none. */
82
+ export declare function readTsconfigPaths(projectDir: string): Promise<Record<string, string[]>>;
83
+ /**
84
+ * Turns an import alias such as `@/components/ui` into a folder relative to the project, using
85
+ * the tsconfig paths. An alias no path matches is taken as a folder relative to the project.
86
+ */
87
+ export declare function aliasToDirectory(alias: string, paths: Record<string, string[]>): string;
88
+ /** Removes // and /* *\/ comments and trailing commas outside strings, so JSONC parses as JSON. */
89
+ export declare function stripJsonComments(text: string): string;
90
+ interface PlannedFile {
91
+ /** Where the file goes, relative to the project root, with forward slashes. */
92
+ readonly path: string;
93
+ readonly content: Uint8Array;
94
+ }
95
+ interface WrittenFile {
96
+ readonly path: string;
97
+ readonly status: "written";
98
+ }
99
+ /** The files for the project's primitives: the radix variant replaces the default files. */
100
+ export declare function selectFiles(item: RegistryItem, config: Pick<KolamJson, "primitives">): BuiltFile[];
101
+ /**
102
+ * Plans where each file of an item goes and what it contains after the install transforms
103
+ * that need no project analysis: the primitives variant, the target folder and import aliases.
104
+ * Refuses targets outside the project or inside .git, .kolam or node_modules.
105
+ */
106
+ export declare function planItemFiles(item: RegistryItem, projectDir: string, config: KolamJson): Promise<PlannedFile[]>;
107
+ /** Writes an item's files into the project. Nothing is written when any file is unsafe. */
108
+ export declare function writeItemFiles(item: RegistryItem, projectDir: string, config: KolamJson): Promise<WrittenFile[]>;
109
+ /** Rewrites the registry's default import aliases to the project's aliases. */
110
+ export declare function rewriteImports(content: string, config: Pick<KolamJson, "aliases">): string;
111
+ /**
112
+ * Writes a built registry: `<name>.json` (latest), the immutable `<name>/<version>.json`
113
+ * and `index.json`. The output folder is replaced.
114
+ */
115
+ export declare function writeRegistry(outDir: string, result: BuildResult): Promise<string[]>;
116
+ export type { BuildOptions, BuildResult, ErrorCode, FetchItemOptions, FieldError, PlannedFile, RegistryConfig, ResolveRegistryOptions, WrittenFile };
package/dist/index.js ADDED
@@ -0,0 +1,501 @@
1
+ import { glob, lstat, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { aliasKey, registryItem, registryManifest } from "@kolamui/schema";
4
+ import semver from "semver";
5
+ import { createHash } from "node:crypto";
6
+ // src/errors.ts
7
+ /** Error codes shared by the CLI, the MCP server and registry tools, with their CLI exit codes. */
8
+ const exitCodes = {
9
+ E_UNAUTHENTICATED: 3,
10
+ E_FORBIDDEN: 3,
11
+ E_NOT_FOUND: 1,
12
+ E_VALIDATION: 1,
13
+ E_REGISTRY: 1,
14
+ E_INTEGRITY: 1,
15
+ E_UNSAFE_ITEM: 1
16
+ };
17
+ var KolamError = class extends Error {
18
+ code;
19
+ exitCode;
20
+ fields;
21
+ constructor(code, message, options) {
22
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
23
+ this.name = "KolamError";
24
+ this.code = code;
25
+ this.exitCode = exitCodes[code];
26
+ this.fields = options?.fields;
27
+ }
28
+ };
29
+ function isKolamError(error) {
30
+ return error instanceof KolamError;
31
+ }
32
+ // src/integrity.ts
33
+ /** The sha256 of a file's bytes as an integrity value: `sha256-<base64>`. */
34
+ function integrity(content) {
35
+ return `sha256-${createHash("sha256").update(content).digest("base64")}`;
36
+ }
37
+ /** Bytes of a file as stored in a built item (`utf8` text or `base64` binary). */
38
+ function fileBytes(content, encoding = "utf8") {
39
+ return encoding === "base64" ? Buffer.from(content, "base64") : Buffer.from(content, "utf8");
40
+ }
41
+ // src/build.ts
42
+ const MAX_ASSET_BYTES = 307200;
43
+ const MAX_ITEM_ASSET_BYTES = 2097152;
44
+ const ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
45
+ ".webp",
46
+ ".jpg",
47
+ ".jpeg",
48
+ ".png",
49
+ ".svg"
50
+ ]);
51
+ const SECRET_FILE = /(^|\/)(\.env(\..*)?|.*\.(pem|key|p12|pfx))$/i;
52
+ const SECRET_CONTENT = [
53
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
54
+ /\bgh[pousr]_[A-Za-z0-9]{36,}\b/,
55
+ /\bgithub_pat_[A-Za-z0-9_]{40,}\b/,
56
+ /\bnpm_[A-Za-z0-9]{36}\b/,
57
+ /\bsk_live_[A-Za-z0-9]{16,}\b/,
58
+ /\bAKIA[0-9A-Z]{16}\b/,
59
+ /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/
60
+ ];
61
+ /**
62
+ * Builds a registry from its source manifest: validates the manifest, reads and hashes every
63
+ * file, and refuses anything unsafe to ship. Every problem is collected and reported at once.
64
+ */
65
+ async function buildRegistry(manifestInput, options) {
66
+ const parsed = registryManifest.safeParse(manifestInput);
67
+ if (!parsed.success) throw new KolamError("E_VALIDATION", "kolam-registry.json has errors.", { fields: parsed.error.issues.map((issue) => ({
68
+ path: issue.path.join("."),
69
+ message: issue.message
70
+ })) });
71
+ const manifest = parsed.data;
72
+ const problems = [];
73
+ const names = new Set(manifest.items.map((item) => item.name));
74
+ const root = path.resolve(options.root);
75
+ const items = [];
76
+ for (const [index, item] of manifest.items.entries()) {
77
+ const at = (field) => `items.${index}.${field}`;
78
+ if (item.status === "preview" && semver.gte(item.version, "1.0.0")) problems.push({
79
+ path: at("version"),
80
+ message: "A preview item stays below 1.0.0."
81
+ });
82
+ for (const used of item.uses ?? []) if (!used.startsWith("@") && !names.has(used)) problems.push({
83
+ path: at("uses"),
84
+ message: `${used} isn't an item in this registry.`
85
+ });
86
+ const range = item.kolam ?? manifest.kolam;
87
+ if (range && !semver.validRange(range)) problems.push({
88
+ path: at("kolam"),
89
+ message: `${range} isn't a valid version range.`
90
+ });
91
+ const files = await readFiles(root, item, item.files ?? [], problems, at("files"));
92
+ const variants = {};
93
+ for (const key of [
94
+ "radix",
95
+ "next",
96
+ "vite"
97
+ ]) {
98
+ const variant = item.variants?.[key];
99
+ if (variant) variants[key] = { files: await readFiles(root, item, variant.files, problems, at(`variants.${key}`)) };
100
+ }
101
+ if (item.primitives?.includes("radix") && item.primitives.length > 1 && !variants.radix) problems.push({
102
+ path: at("variants.radix"),
103
+ message: "The item lists radix but has no radix files."
104
+ });
105
+ checkAssets([...files, ...Object.values(variants).flatMap((v) => v.files)], problems, at);
106
+ items.push(toBuiltItem(item, range, files, variants));
107
+ }
108
+ if (problems.length > 0) throw new KolamError("E_VALIDATION", "The registry has build errors.", { fields: problems });
109
+ const shipped = items.filter((item) => options.staging || item.status !== "internal");
110
+ return {
111
+ items: shipped,
112
+ index: toIndex(manifest, shipped)
113
+ };
114
+ }
115
+ function toBuiltItem(item, range, files, variants) {
116
+ const built = {
117
+ name: item.name,
118
+ kind: item.kind,
119
+ version: item.version,
120
+ title: item.title,
121
+ status: item.status ?? "stable",
122
+ files
123
+ };
124
+ if (range) built.kolam = range;
125
+ if (item.summary) built.summary = item.summary;
126
+ if (item.deprecatedBy) built.deprecatedBy = item.deprecatedBy;
127
+ if (item.primitives) built.primitives = item.primitives;
128
+ if (item.packages) built.packages = item.packages;
129
+ if (item.uses) built.uses = item.uses;
130
+ if (Object.keys(variants).length > 0) built.variants = variants;
131
+ if (item.tokens) built.tokens = item.tokens;
132
+ if (item.modes) built.modes = item.modes;
133
+ if (item.seed) built.seed = item.seed;
134
+ if (item.meta) built.meta = item.meta;
135
+ if (item.builder) built.builder = item.builder;
136
+ return built;
137
+ }
138
+ function toIndex(manifest, items) {
139
+ return {
140
+ name: manifest.name,
141
+ ...manifest.homepage ? { homepage: manifest.homepage } : {},
142
+ items: items.map((item) => ({
143
+ name: item.name,
144
+ kind: item.kind,
145
+ version: item.version,
146
+ title: item.title,
147
+ status: item.status,
148
+ ...item.summary ? { summary: item.summary } : {},
149
+ ...item.pro ? { pro: item.pro } : {},
150
+ ...item.primitives ? { primitives: item.primitives } : {},
151
+ ...item.meta ? { meta: item.meta } : {}
152
+ }))
153
+ };
154
+ }
155
+ /** The folder a file installs into, from its item's kind and where it sits in the source. */
156
+ function defaultTarget(kind, sourcePath) {
157
+ const normalized = sourcePath.split(path.sep).join("/");
158
+ if (/(^|\/)registry\/hooks\//.test(normalized)) return "hooks";
159
+ if (/(^|\/)registry\/lib\//.test(normalized)) return "lib";
160
+ switch (kind) {
161
+ case "component": return "ui";
162
+ case "hook": return "hooks";
163
+ case "lib": return "lib";
164
+ default: return "components";
165
+ }
166
+ }
167
+ async function readFiles(root, item, entries, problems, at) {
168
+ const files = [];
169
+ for (const entry of entries) {
170
+ const spec = typeof entry === "string" ? { path: entry } : entry;
171
+ const matches = await expand(root, spec.path);
172
+ if (matches.length === 0) {
173
+ problems.push({
174
+ path: at,
175
+ message: `${spec.path} doesn't match any file.`
176
+ });
177
+ continue;
178
+ }
179
+ for (const match of matches) {
180
+ const problem = await checkInsideRoot(root, match.source);
181
+ if (problem) {
182
+ problems.push({
183
+ path: at,
184
+ message: problem
185
+ });
186
+ continue;
187
+ }
188
+ if (SECRET_FILE.test(match.source)) {
189
+ problems.push({
190
+ path: at,
191
+ message: `${match.source} looks like a secret file.`
192
+ });
193
+ continue;
194
+ }
195
+ const encoding = "encoding" in spec && spec.encoding ? spec.encoding : ASSET_EXTENSIONS.has(path.extname(match.source).toLowerCase()) && path.extname(match.source).toLowerCase() !== ".svg" ? "base64" : "utf8";
196
+ const bytes = await readFile(path.join(root, match.source));
197
+ const content = encoding === "base64" ? bytes.toString("base64") : bytes.toString("utf8");
198
+ if (encoding === "utf8" && SECRET_CONTENT.some((pattern) => pattern.test(content))) {
199
+ problems.push({
200
+ path: at,
201
+ message: `${match.source} contains what looks like a secret.`
202
+ });
203
+ continue;
204
+ }
205
+ const file = {
206
+ path: match.relative,
207
+ target: "target" in spec && spec.target || defaultTarget(item.kind, match.source),
208
+ content,
209
+ sha256: integrity(bytes)
210
+ };
211
+ if (encoding === "base64") file.encoding = "base64";
212
+ files.push(file);
213
+ }
214
+ }
215
+ return files;
216
+ }
217
+ /** Expands a path or glob. A file's install path is relative to the glob's fixed prefix. */
218
+ async function expand(root, pattern) {
219
+ const normalized = pattern.replace(/\\/g, "/");
220
+ if (!/[*?[\]{}]/.test(normalized)) return [{
221
+ source: normalized,
222
+ relative: path.posix.basename(normalized)
223
+ }];
224
+ const fixed = normalized.split("/").findIndex((segment) => /[*?[\]{}]/.test(segment));
225
+ const base = normalized.split("/").slice(0, fixed).join("/");
226
+ const results = [];
227
+ for await (const match of glob(normalized, {
228
+ cwd: root,
229
+ withFileTypes: false
230
+ })) {
231
+ const source = String(match).split(path.sep).join("/");
232
+ const stat = await lstat(path.join(root, source)).catch(() => void 0);
233
+ if (!stat?.isFile() && !stat?.isSymbolicLink()) continue;
234
+ results.push({
235
+ source,
236
+ relative: base ? path.posix.relative(base, source) : source
237
+ });
238
+ }
239
+ return results.sort((a, b) => a.source.localeCompare(b.source));
240
+ }
241
+ /** Files must resolve inside the project without following symbolic links. */
242
+ async function checkInsideRoot(root, source) {
243
+ const absolute = path.resolve(root, source);
244
+ const relative = path.relative(root, absolute);
245
+ if (relative.startsWith("..") || path.isAbsolute(relative)) return `${source} is outside the registry project.`;
246
+ let current = root;
247
+ for (const segment of relative.split(path.sep)) {
248
+ current = path.join(current, segment);
249
+ const stat = await lstat(current).catch(() => void 0);
250
+ if (!stat) return `${source} doesn't exist.`;
251
+ if (stat.isSymbolicLink()) return `${source} goes through a symbolic link.`;
252
+ }
253
+ }
254
+ function checkAssets(files, problems, at) {
255
+ let total = 0;
256
+ for (const file of files) {
257
+ if (file.encoding !== "base64") continue;
258
+ const extension = path.extname(file.path).toLowerCase();
259
+ const size = Buffer.from(file.content, "base64").byteLength;
260
+ total += size;
261
+ if (!ASSET_EXTENSIONS.has(extension)) problems.push({
262
+ path: at("files"),
263
+ message: `${file.path}: use webp, jpg, png or svg.`
264
+ });
265
+ if (size > MAX_ASSET_BYTES) problems.push({
266
+ path: at("files"),
267
+ message: `${file.path} is larger than 300 KB.`
268
+ });
269
+ }
270
+ if (total > MAX_ITEM_ASSET_BYTES) problems.push({
271
+ path: at("files"),
272
+ message: "The item's assets are larger than 2 MB."
273
+ });
274
+ }
275
+ // src/fetch-item.ts
276
+ function itemUrl(registry, name, version) {
277
+ const path = version ? `${encodeURIComponent(name)}/${encodeURIComponent(version)}` : encodeURIComponent(name);
278
+ return `${registry.baseUrl}/${path}.json`;
279
+ }
280
+ /** Fetches a built item, checks it against the schema and verifies every file's sha256. */
281
+ async function fetchItem(registry, name, options = {}) {
282
+ const url = itemUrl(registry, name, options.version);
283
+ const response = await fetchWithRetries(url, registry, options);
284
+ if (response.status === 401) throw new KolamError("E_UNAUTHENTICATED", `The registry at ${registry.baseUrl} needs a token. Set KOLAM_REGISTRY_TOKEN and try again.`);
285
+ if (response.status === 403) throw new KolamError("E_FORBIDDEN", `The registry at ${registry.baseUrl} refused the token. Check KOLAM_REGISTRY_TOKEN.`);
286
+ if (response.status === 404) throw new KolamError("E_NOT_FOUND", `We couldn't find ${name} in ${registry.baseUrl}.`);
287
+ if (!response.ok) throw new KolamError("E_REGISTRY", `Couldn't reach the registry at ${registry.baseUrl}.`);
288
+ let body;
289
+ try {
290
+ body = await response.json();
291
+ } catch (cause) {
292
+ throw new KolamError("E_REGISTRY", `${url} didn't return a valid Kolam item.`, { cause });
293
+ }
294
+ const parsed = registryItem.safeParse(body);
295
+ if (!parsed.success) throw new KolamError("E_REGISTRY", `${url} didn't return a valid Kolam item.`, { fields: parsed.error.issues.map((issue) => ({
296
+ path: issue.path.join("."),
297
+ message: issue.message
298
+ })) });
299
+ verifyItem(parsed.data);
300
+ return parsed.data;
301
+ }
302
+ /** Throws E_INTEGRITY when any file's content doesn't match its sha256. */
303
+ function verifyItem(item) {
304
+ const files = [...item.files, ...Object.values(item.variants ?? {}).flatMap((variant) => variant?.files ?? [])];
305
+ for (const file of files) if (integrity(fileBytes(file.content, file.encoding)) !== file.sha256) throw new KolamError("E_INTEGRITY", `${item.name} failed its integrity check. Nothing was written.`);
306
+ }
307
+ async function fetchWithRetries(url, registry, options) {
308
+ const doFetch = options.fetch ?? globalThis.fetch;
309
+ const retries = options.retries ?? 2;
310
+ const delay = options.retryDelayMs ?? 250;
311
+ let lastError;
312
+ for (let attempt = 0; attempt <= retries; attempt++) {
313
+ if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, delay * attempt));
314
+ try {
315
+ const response = await doFetch(url, { headers: registry.headers });
316
+ if (response.status < 500) return response;
317
+ lastError = /* @__PURE__ */ new Error(`HTTP ${response.status}`);
318
+ } catch (error) {
319
+ lastError = error;
320
+ }
321
+ }
322
+ throw new KolamError("E_REGISTRY", `Couldn't reach the registry at ${registry.baseUrl}.`, { cause: lastError });
323
+ }
324
+ // src/project-paths.ts
325
+ /** `compilerOptions.paths` from the project's tsconfig.json, or {} when there is none. */
326
+ async function readTsconfigPaths(projectDir) {
327
+ let text;
328
+ try {
329
+ text = await readFile(path.join(projectDir, "tsconfig.json"), "utf8");
330
+ } catch {
331
+ return {};
332
+ }
333
+ const config = JSON.parse(stripJsonComments(text));
334
+ const baseUrl = config.compilerOptions?.baseUrl ?? ".";
335
+ const paths = {};
336
+ for (const [pattern, targets] of Object.entries(config.compilerOptions?.paths ?? {})) paths[pattern] = targets.map((target) => path.posix.join(baseUrl, target));
337
+ return paths;
338
+ }
339
+ /**
340
+ * Turns an import alias such as `@/components/ui` into a folder relative to the project, using
341
+ * the tsconfig paths. An alias no path matches is taken as a folder relative to the project.
342
+ */
343
+ function aliasToDirectory(alias, paths) {
344
+ for (const [pattern, targets] of Object.entries(paths)) {
345
+ const target = targets[0];
346
+ if (!target) continue;
347
+ if (pattern.endsWith("/*") && target.endsWith("/*")) {
348
+ const prefix = pattern.slice(0, -1);
349
+ if (alias.startsWith(prefix)) return path.posix.normalize(target.slice(0, -1) + alias.slice(prefix.length));
350
+ if (`${alias}/` === prefix) return path.posix.normalize(target.slice(0, -2));
351
+ } else if (pattern === alias) return path.posix.normalize(target);
352
+ }
353
+ return path.posix.normalize(alias);
354
+ }
355
+ /** Removes // and /* *\/ comments and trailing commas outside strings, so JSONC parses as JSON. */
356
+ function stripJsonComments(text) {
357
+ let out = "";
358
+ let inString = false;
359
+ for (let i = 0; i < text.length; i++) {
360
+ const char = text[i];
361
+ const next = text[i + 1];
362
+ if (inString) {
363
+ out += char;
364
+ if (char === "\\") {
365
+ out += next ?? "";
366
+ i++;
367
+ } else if (char === "\"") inString = false;
368
+ continue;
369
+ }
370
+ if (char === "\"") {
371
+ inString = true;
372
+ out += char;
373
+ } else if (char === "/" && next === "/") {
374
+ while (i < text.length && text[i] !== "\n") i++;
375
+ out += "\n";
376
+ } else if (char === "/" && next === "*") {
377
+ i += 2;
378
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++;
379
+ i++;
380
+ } else out += char;
381
+ }
382
+ return out.replace(/,(\s*[}\]])/g, "$1");
383
+ }
384
+ // src/registry-config.ts
385
+ /**
386
+ * Works out which registry to use. KOLAM_REGISTRY_URL replaces the Kolam registry base URL
387
+ * (testers use it to reach the password-protected staging registry) and KOLAM_REGISTRY_TOKEN
388
+ * is sent to it as a bearer token.
389
+ */
390
+ function resolveRegistry(options = {}) {
391
+ const env = options.env ?? process.env;
392
+ const url = options.url ?? env.KOLAM_REGISTRY_URL;
393
+ if (!url) throw new KolamError("E_REGISTRY", "No registry URL is set. Set KOLAM_REGISTRY_URL to the registry you were given.");
394
+ let parsed;
395
+ try {
396
+ parsed = new URL(url);
397
+ } catch (cause) {
398
+ throw new KolamError("E_VALIDATION", `The registry URL ${url} isn't a valid URL.`, { cause });
399
+ }
400
+ if (parsed.protocol !== "https:" && !isLoopback(parsed)) throw new KolamError("E_VALIDATION", `The registry URL ${url} must use https (http is allowed only for localhost).`);
401
+ const token = options.token ?? env.KOLAM_REGISTRY_TOKEN;
402
+ const headers = { Accept: "application/json" };
403
+ if (token) headers.Authorization = `Bearer ${token}`;
404
+ return {
405
+ baseUrl: parsed.href.replace(/\/+$/, ""),
406
+ headers
407
+ };
408
+ }
409
+ function isLoopback(url) {
410
+ return url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
411
+ }
412
+ // src/write-files.ts
413
+ const FORBIDDEN_FOLDERS = /* @__PURE__ */ new Set([
414
+ ".git",
415
+ ".kolam",
416
+ "node_modules"
417
+ ]);
418
+ /** The files for the project's primitives: the radix variant replaces the default files. */
419
+ function selectFiles(item, config) {
420
+ if (config.primitives === "radix" && item.variants?.radix) return item.variants.radix.files;
421
+ return item.files;
422
+ }
423
+ /**
424
+ * Plans where each file of an item goes and what it contains after the install transforms
425
+ * that need no project analysis: the primitives variant, the target folder and import aliases.
426
+ * Refuses targets outside the project or inside .git, .kolam or node_modules.
427
+ */
428
+ async function planItemFiles(item, projectDir, config) {
429
+ const root = path.resolve(projectDir);
430
+ const paths = await readTsconfigPaths(root);
431
+ return selectFiles(item, config).map((file) => {
432
+ const directory = targetDirectory(item, file, config, paths);
433
+ const relative = path.posix.normalize(path.posix.join(directory, file.path));
434
+ const absolute = path.resolve(root, relative);
435
+ const fromRoot = path.relative(root, absolute);
436
+ const segments = fromRoot.split(path.sep);
437
+ if (fromRoot.startsWith("..") || path.isAbsolute(fromRoot) || segments.some((segment) => FORBIDDEN_FOLDERS.has(segment))) throw new KolamError("E_UNSAFE_ITEM", `${item.name} tries to write outside your project (${file.path}). Nothing was written.`);
438
+ const bytes = fileBytes(file.content, file.encoding);
439
+ const content = file.encoding === "base64" ? bytes : Buffer.from(rewriteImports(file.content, config));
440
+ return {
441
+ path: fromRoot.split(path.sep).join("/"),
442
+ content
443
+ };
444
+ });
445
+ }
446
+ /** Writes an item's files into the project. Nothing is written when any file is unsafe. */
447
+ async function writeItemFiles(item, projectDir, config) {
448
+ const planned = await planItemFiles(item, projectDir, config);
449
+ for (const file of planned) {
450
+ const absolute = path.join(projectDir, file.path);
451
+ await mkdir(path.dirname(absolute), { recursive: true });
452
+ await writeFile(absolute, file.content);
453
+ }
454
+ return planned.map((file) => ({
455
+ path: file.path,
456
+ status: "written"
457
+ }));
458
+ }
459
+ function targetDirectory(item, file, config, paths) {
460
+ const key = aliasKey.safeParse(file.target);
461
+ if (!key.success) throw new KolamError("E_UNSAFE_ITEM", `${item.name} has a file with an unknown target (${file.target}). Nothing was written.`);
462
+ const alias = config.aliases[key.data];
463
+ const directory = key.data === "public" ? alias : aliasToDirectory(alias, paths);
464
+ return item.kind === "block" && key.data === "components" ? path.posix.join(directory, "blocks", item.name) : directory;
465
+ }
466
+ const DEFAULT_ALIASES = {
467
+ "@/components/ui/": "ui",
468
+ "@/components/": "components",
469
+ "@/lib/": "lib",
470
+ "@/hooks/": "hooks"
471
+ };
472
+ /** Rewrites the registry's default import aliases to the project's aliases. */
473
+ function rewriteImports(content, config) {
474
+ return content.replace(/(\bfrom\s+|\bimport\s*\(\s*|\bimport\s+)(["'])(@\/(?:components\/ui|components|lib|hooks)\/)/g, (_match, keyword, quote, prefix) => `${keyword}${quote}${config.aliases[DEFAULT_ALIASES[prefix]]}/`);
475
+ }
476
+ // src/write-registry.ts
477
+ /**
478
+ * Writes a built registry: `<name>.json` (latest), the immutable `<name>/<version>.json`
479
+ * and `index.json`. The output folder is replaced.
480
+ */
481
+ async function writeRegistry(outDir, result) {
482
+ await rm(outDir, {
483
+ recursive: true,
484
+ force: true
485
+ });
486
+ await mkdir(outDir, { recursive: true });
487
+ const written = [];
488
+ const write = async (relative, data) => {
489
+ const file = path.join(outDir, relative);
490
+ await mkdir(path.dirname(file), { recursive: true });
491
+ await writeFile(file, `${JSON.stringify(data, null, 2)}\n`);
492
+ written.push(relative.split(path.sep).join("/"));
493
+ };
494
+ for (const item of result.items) {
495
+ await write(`${item.name}.json`, item);
496
+ await write(path.join(item.name, `${item.version}.json`), item);
497
+ }
498
+ await write("index.json", result.index);
499
+ return written;
500
+ }
501
+ export { KolamError, aliasToDirectory, buildRegistry, defaultTarget, exitCodes, fetchItem, fileBytes, integrity, isKolamError, itemUrl, planItemFiles, readTsconfigPaths, resolveRegistry, rewriteImports, selectFiles, stripJsonComments, verifyItem, writeItemFiles, writeRegistry };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@kolamui/registry",
3
+ "version": "0.0.0-canary-32a322e",
4
+ "description": "Resolve, fetch, verify and install Kolam registry items.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/haribrothers/kolam#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/haribrothers/kolam.git",
11
+ "directory": "packages/registry"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/haribrothers/kolam/issues"
15
+ },
16
+ "engines": {
17
+ "node": ">=22"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "provenance": true
22
+ },
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "dependencies": {
37
+ "semver": "~7.8.6",
38
+ "@kolamui/schema": "0.0.0-canary-32a322e"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "~24.19.4",
42
+ "@types/semver": "~7.8.0",
43
+ "tsdown": "~0.23.8",
44
+ "typescript": "~5.9.3",
45
+ "vitest": "~5.1.2",
46
+ "@internal/config": "0.0.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "typecheck": "tsc -p tsconfig.json",
51
+ "test": "vitest run"
52
+ }
53
+ }