frakment 0.0.1 → 3.0.0

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,381 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync } from "node:fs";
14
+ import { lstat, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
15
+ import path from "node:path";
16
+ import chalk from "chalk";
17
+ import { execa } from "execa";
18
+ import ora from "ora";
19
+ import prompts from "prompts";
20
+ import { detectPackageManager, findProjectRoot } from "../utils/detect.js";
21
+ import { logger } from "../utils/logger.js";
22
+ const componentNamePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
23
+ const dependencyPattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[0-9A-Za-z*~^<>=|.+_-]+)?$/u;
24
+ const maxRegistryPayloadBytes = 10 * 1024 * 1024;
25
+ const defaultWebRegistry = "https://www.arrafi.dev/frakment/r";
26
+ const defaultAliases = {
27
+ components: "@/components",
28
+ ui: "@/components/ui",
29
+ utils: "@/lib/utils",
30
+ };
31
+ const normalizeAliases = (input) => {
32
+ var _a, _b, _c;
33
+ const aliases = isRecord(input) ? input : {};
34
+ const components = (_a = aliases.components) !== null && _a !== void 0 ? _a : defaultAliases.components;
35
+ const ui = (_b = aliases.ui) !== null && _b !== void 0 ? _b : `${components}/ui`;
36
+ const utils = (_c = aliases.utils) !== null && _c !== void 0 ? _c : defaultAliases.utils;
37
+ return {
38
+ components: String(components),
39
+ ui: String(ui),
40
+ utils: String(utils),
41
+ };
42
+ };
43
+ export const rewriteImports = (content, aliases) => {
44
+ const a = normalizeAliases(aliases);
45
+ let out = content;
46
+ out = out.replaceAll("@/components/ui/", `${a.ui}/`);
47
+ out = out.replaceAll("@/components/", `${a.components}/`);
48
+ out = out.replace(/@\/lib\/utils\b/g, a.utils);
49
+ return out;
50
+ };
51
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
52
+ const canonicalize = (value) => {
53
+ if (Array.isArray(value)) {
54
+ return `[${value.map(canonicalize).join(",")}]`;
55
+ }
56
+ if (isRecord(value)) {
57
+ return `{${Object.keys(value)
58
+ .sort()
59
+ .map((key) => `${JSON.stringify(key)}:${canonicalize(value[key])}`)
60
+ .join(",")}}`;
61
+ }
62
+ return JSON.stringify(value);
63
+ };
64
+ const createIntegrity = (payload) => `sha256:${createHash("sha256")
65
+ .update(canonicalize(payload), "utf8")
66
+ .digest("hex")}`;
67
+ function assertComponentName(name) {
68
+ if (typeof name !== "string" || !componentNamePattern.test(name)) {
69
+ throw new Error(`Invalid component name: ${String(name)}`);
70
+ }
71
+ }
72
+ function assertDependency(dependency) {
73
+ if (typeof dependency !== "string" || !dependencyPattern.test(dependency)) {
74
+ throw new Error(`Invalid dependency in registry payload: ${String(dependency)}`);
75
+ }
76
+ }
77
+ const getDependencyName = (dependency) => {
78
+ if (dependency.startsWith("@")) {
79
+ return dependency.slice(0, dependency.indexOf("@", 1));
80
+ }
81
+ return dependency.split("@")[0];
82
+ };
83
+ const hasDependencyVersion = (dependency) => dependency.lastIndexOf("@") > (dependency.startsWith("@") ? 0 : -1);
84
+ const isBase64 = (value) => /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(value);
85
+ export const validateRegistryPayload = (payload, expectedName) => {
86
+ var _a, _b;
87
+ if (!isRecord(payload) || payload.name !== expectedName) {
88
+ throw new Error("Registry payload has an unexpected component name");
89
+ }
90
+ if (typeof payload.integrity !== "string" ||
91
+ !/^sha256:[a-f0-9]{64}$/u.test(payload.integrity)) {
92
+ throw new Error("Registry payload has invalid integrity metadata");
93
+ }
94
+ if (!Array.isArray(payload.files) || payload.files.length === 0) {
95
+ throw new Error("Registry payload must include at least one file");
96
+ }
97
+ if (payload.files.length > 100) {
98
+ throw new Error("Registry payload has too many files");
99
+ }
100
+ for (const file of payload.files) {
101
+ if (!isRecord(file) || typeof file.path !== "string") {
102
+ throw new Error("Registry payload contains an invalid file");
103
+ }
104
+ if (typeof file.content !== "string") {
105
+ throw new Error(`Registry file ${file.path} has invalid content`);
106
+ }
107
+ if (file.encoding !== undefined && file.encoding !== "base64") {
108
+ throw new Error(`Registry file ${file.path} has an unsupported encoding`);
109
+ }
110
+ if (file.encoding === "base64" && !isBase64(file.content)) {
111
+ throw new Error(`Registry file ${file.path} has invalid base64 content`);
112
+ }
113
+ }
114
+ if (!(Array.isArray((_a = payload.dependencies) !== null && _a !== void 0 ? _a : []) &&
115
+ Array.isArray((_b = payload.registryDependencies) !== null && _b !== void 0 ? _b : []))) {
116
+ throw new Error("Registry payload has invalid dependency lists");
117
+ }
118
+ const dependencies = Array.isArray(payload.dependencies)
119
+ ? payload.dependencies
120
+ : [];
121
+ const registryDependencies = Array.isArray(payload.registryDependencies)
122
+ ? payload.registryDependencies
123
+ : [];
124
+ for (const dependency of dependencies) {
125
+ assertDependency(dependency);
126
+ }
127
+ for (const dependency of registryDependencies) {
128
+ assertComponentName(dependency);
129
+ }
130
+ const { integrity } = payload, unsignedPayload = __rest(payload, ["integrity"]);
131
+ if (integrity !== createIntegrity(unsignedPayload)) {
132
+ throw new Error("Registry payload integrity check failed");
133
+ }
134
+ return payload;
135
+ };
136
+ const getRegistryUrl = (value) => {
137
+ const url = new URL(value);
138
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
139
+ throw new Error("Registry URL must use HTTP or HTTPS");
140
+ }
141
+ if (url.username || url.password || url.search || url.hash) {
142
+ throw new Error("Registry URL must not include credentials, a query, or a fragment");
143
+ }
144
+ return url.href.replace(/\/$/u, "");
145
+ };
146
+ export function resolveRegistryUrl(config, options = {}) {
147
+ var _a, _b;
148
+ const configRecord = isRecord(config) ? config : {};
149
+ const registries = isRecord(configRecord.registries)
150
+ ? configRecord.registries
151
+ : {};
152
+ const registry = typeof configRecord.registry === "string"
153
+ ? configRecord.registry
154
+ : undefined;
155
+ const web = typeof registries.web === "string" ? registries.web : undefined;
156
+ const configured = (_a = registry !== null && registry !== void 0 ? registry : web) !== null && _a !== void 0 ? _a : defaultWebRegistry;
157
+ return getRegistryUrl((_b = options.registry) !== null && _b !== void 0 ? _b : configured);
158
+ }
159
+ async function fetchComponent(name, registryUrl, spinner) {
160
+ try {
161
+ const res = await fetch(`${registryUrl}/${name}.json`, {
162
+ signal: AbortSignal.timeout(30000),
163
+ });
164
+ if (!res.ok) {
165
+ throw new Error(`HTTP ${res.status}`);
166
+ }
167
+ const contentLength = Number(res.headers.get("content-length"));
168
+ if (contentLength > maxRegistryPayloadBytes) {
169
+ throw new Error("Registry response is too large");
170
+ }
171
+ const raw = await res.text();
172
+ if (Buffer.byteLength(raw, "utf8") > maxRegistryPayloadBytes) {
173
+ throw new Error("Registry response is too large");
174
+ }
175
+ const payload = validateRegistryPayload(JSON.parse(raw), name);
176
+ spinner.text = `Fetching ${name}...`;
177
+ return payload;
178
+ }
179
+ catch (error) {
180
+ spinner.fail(`Registry fetch failed for ${name}: ${error instanceof Error ? error.message : "unknown error"}`);
181
+ process.exit(1);
182
+ }
183
+ }
184
+ export async function assertSafePath(cwd, relativePath) {
185
+ if (typeof relativePath !== "string" || relativePath.length === 0) {
186
+ throw new Error("Invalid file path in registry payload");
187
+ }
188
+ if (relativePath.includes("\0")) {
189
+ throw new Error(`Null byte in path: ${relativePath}`);
190
+ }
191
+ if (path.isAbsolute(relativePath) || /^[a-zA-Z]:/.test(relativePath)) {
192
+ throw new Error(`Absolute path rejected: ${relativePath}`);
193
+ }
194
+ if (relativePath.split(/[\\/]/).some((seg) => seg === "..")) {
195
+ throw new Error(`Parent traversal rejected: ${relativePath}`);
196
+ }
197
+ const root = path.resolve(cwd);
198
+ const target = path.resolve(root, relativePath);
199
+ if (target !== root && !target.startsWith(root + path.sep)) {
200
+ throw new Error(`Path escapes project root: ${relativePath}`);
201
+ }
202
+ const realRoot = await realpath(root).catch(() => root);
203
+ let existingParent = path.dirname(target);
204
+ while (!existsSync(existingParent)) {
205
+ existingParent = path.dirname(existingParent);
206
+ }
207
+ const realParent = await realpath(existingParent).catch(() => existingParent);
208
+ if (realParent !== realRoot && !realParent.startsWith(realRoot + path.sep)) {
209
+ throw new Error(`Symlink escape rejected: ${relativePath}`);
210
+ }
211
+ if (existsSync(target) && (await lstat(target)).isSymbolicLink()) {
212
+ throw new Error(`Symlink target rejected: ${relativePath}`);
213
+ }
214
+ return target;
215
+ }
216
+ async function writeFileSafely(file, cwd, options, aliases) {
217
+ const targetPath = await assertSafePath(cwd, file.path);
218
+ if (existsSync(targetPath) && !options.overwrite) {
219
+ const { overwrite } = await prompts({
220
+ initial: false,
221
+ message: `${file.path} already exists. Overwrite?`,
222
+ name: "overwrite",
223
+ type: "confirm",
224
+ });
225
+ if (overwrite === undefined || !overwrite) {
226
+ logger.info(`Skipped ${file.path}.`);
227
+ return null;
228
+ }
229
+ }
230
+ await mkdir(path.dirname(targetPath), { recursive: true });
231
+ const output = file.encoding === "base64"
232
+ ? Buffer.from(file.content, "base64")
233
+ : rewriteImports(file.content, aliases).replaceAll("\r\n", "\n");
234
+ await writeFile(targetPath, output);
235
+ return file.path;
236
+ }
237
+ export async function add(componentNamesInput, options = {}) {
238
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
239
+ const componentNames = Array.isArray(componentNamesInput)
240
+ ? [...new Set(componentNamesInput)]
241
+ : [componentNamesInput];
242
+ if (componentNames.length === 0) {
243
+ logger.error(`${chalk.red("Error:")} At least one component name is required.`);
244
+ process.exit(1);
245
+ }
246
+ let cwd;
247
+ const preflight = ora("Preflight checks").start();
248
+ try {
249
+ cwd = findProjectRoot(process.cwd());
250
+ preflight.succeed("Preflight checks. Found project root.");
251
+ }
252
+ catch (error) {
253
+ preflight.fail(error instanceof Error ? error.message : "Unknown error");
254
+ process.exit(1);
255
+ }
256
+ const configPath = path.join(cwd, "components.json");
257
+ if (!existsSync(configPath)) {
258
+ logger.error(`${chalk.red("Error:")} components.json not found.`);
259
+ logger.info("Run `frakment init` first.");
260
+ process.exit(1);
261
+ }
262
+ let config;
263
+ let registryUrl;
264
+ try {
265
+ for (const name of componentNames) {
266
+ assertComponentName(name);
267
+ }
268
+ const configRaw = await readFile(configPath, "utf-8");
269
+ config = JSON.parse(configRaw.replace(/^\uFEFF/u, ""));
270
+ registryUrl = resolveRegistryUrl(config, options);
271
+ }
272
+ catch (error) {
273
+ logger.error(error instanceof Error ? error.message : "Invalid configuration.");
274
+ process.exit(1);
275
+ }
276
+ const registrySpinner = ora("Checking registry").start();
277
+ const roots = new Set(componentNames);
278
+ const queue = [...roots];
279
+ const fetched = new Map();
280
+ const npmDeps = new Map();
281
+ while (queue.length) {
282
+ const name = queue.shift();
283
+ if (!name) {
284
+ continue;
285
+ }
286
+ if (fetched.has(name)) {
287
+ continue;
288
+ }
289
+ const payload = await fetchComponent(name, registryUrl, registrySpinner);
290
+ fetched.set(name, payload);
291
+ for (const d of (_a = payload.dependencies) !== null && _a !== void 0 ? _a : []) {
292
+ const packageName = getDependencyName(d);
293
+ const existing = npmDeps.get(packageName);
294
+ if (!existing ||
295
+ (!hasDependencyVersion(existing) && hasDependencyVersion(d))) {
296
+ npmDeps.set(packageName, d);
297
+ }
298
+ }
299
+ for (const d of (_b = payload.registryDependencies) !== null && _b !== void 0 ? _b : []) {
300
+ if (!fetched.has(d)) {
301
+ queue.push(d);
302
+ }
303
+ }
304
+ }
305
+ registrySpinner.succeed("Checking registry.");
306
+ const aliases = normalizeAliases(config.aliases);
307
+ const isSrcLayout = (_e = (_d = (_c = config.tailwind) === null || _c === void 0 ? void 0 : _c.css) === null || _d === void 0 ? void 0 : _d.startsWith("src/")) !== null && _e !== void 0 ? _e : false;
308
+ const resolveTargetPath = (p) => {
309
+ if (!isSrcLayout) {
310
+ return p;
311
+ }
312
+ if (p.startsWith("public/")) {
313
+ return p;
314
+ }
315
+ return `src/${p}`;
316
+ };
317
+ const order = [...fetched.keys()].filter((n) => !roots.has(n));
318
+ order.push(...roots);
319
+ const written = [];
320
+ const getMissingDependencies = async () => {
321
+ const pkgPath = path.join(cwd, "package.json");
322
+ const pkgRaw = await readFile(pkgPath, "utf-8");
323
+ const pkg = JSON.parse(pkgRaw.replace(/^\uFEFF/u, ""));
324
+ const allDeps = Object.assign(Object.assign({}, pkg.dependencies), pkg.devDependencies);
325
+ return [...npmDeps].filter(([packageName]) => !allDeps[packageName]);
326
+ };
327
+ if (options.dryRun) {
328
+ for (const name of order) {
329
+ for (const file of (_g = (_f = fetched.get(name)) === null || _f === void 0 ? void 0 : _f.files) !== null && _g !== void 0 ? _g : []) {
330
+ const targetPath = resolveTargetPath(file.path);
331
+ await assertSafePath(cwd, targetPath);
332
+ logger.log(`Would create ${targetPath}.`);
333
+ }
334
+ }
335
+ const missing = await getMissingDependencies();
336
+ for (const [, dependency] of missing) {
337
+ logger.log(`Would install ${dependency}.`);
338
+ }
339
+ logger.success("Dry run complete. No files or dependencies were changed.");
340
+ logger.break();
341
+ return;
342
+ }
343
+ for (const name of order) {
344
+ for (const file of (_j = (_h = fetched.get(name)) === null || _h === void 0 ? void 0 : _h.files) !== null && _j !== void 0 ? _j : []) {
345
+ const targetFile = Object.assign(Object.assign({}, file), { path: resolveTargetPath(file.path) });
346
+ const result = await writeFileSafely(targetFile, cwd, options, aliases);
347
+ if (result) {
348
+ written.push(result);
349
+ }
350
+ }
351
+ }
352
+ if (written.length > 0) {
353
+ logger.success(`Created ${written.length} file${written.length === 1 ? "" : "s"}:`);
354
+ for (const p of written) {
355
+ logger.log(` - ${p}`);
356
+ }
357
+ }
358
+ if (npmDeps.size > 0) {
359
+ const missing = await getMissingDependencies();
360
+ if (missing.length > 0) {
361
+ if (options.skipDependencies) {
362
+ logger.info(`Skipped ${missing.length} dependency installation(s).`);
363
+ logger.break();
364
+ return;
365
+ }
366
+ const s = ora("Installing dependencies").start();
367
+ const packages = missing.map(([, dependency]) => dependency);
368
+ try {
369
+ const pm = detectPackageManager(cwd);
370
+ const args = pm === "npm" ? ["install", ...packages] : ["add", ...packages];
371
+ await execa(pm, args, { cwd, stdio: "ignore" });
372
+ s.succeed(`Installed ${missing.length} package(s).`);
373
+ }
374
+ catch (error) {
375
+ s.fail("Failed to install dependencies.");
376
+ logger.warn(error instanceof Error ? error.message : "Unknown error");
377
+ }
378
+ }
379
+ }
380
+ logger.break();
381
+ }
@@ -0,0 +1,145 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import chalk from "chalk";
5
+ import { execa } from "execa";
6
+ import ora from "ora";
7
+ import prompts from "prompts";
8
+ import { detectGlobalsCss, detectPackageManager, findProjectRoot, } from "../utils/detect.js";
9
+ import { logger } from "../utils/logger.js";
10
+ const __dirname = import.meta.dirname;
11
+ const templatesDir = path.resolve(__dirname, "../../templates");
12
+ const defaultRegistry = "https://www.arrafi.dev/frakment/r";
13
+ const configFile = "components.json";
14
+ const themeMarkerStart = "/* ==== FRAKMENT THEME START ==== */";
15
+ const themeMarkerEnd = "/* ==== FRAKMENT THEME END ==== */";
16
+ function escapeRegex(s) {
17
+ return s.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
18
+ }
19
+ export async function init() {
20
+ let cwd;
21
+ const preflight = ora("Preflight checks").start();
22
+ try {
23
+ cwd = findProjectRoot(process.cwd());
24
+ preflight.succeed("Preflight checks. Found project root.");
25
+ }
26
+ catch (error) {
27
+ preflight.fail(error instanceof Error ? error.message : "Unknown error");
28
+ process.exit(1);
29
+ }
30
+ const cssPath = detectGlobalsCss(cwd);
31
+ const cssFullPath = path.join(cwd, cssPath);
32
+ const cssCheck = ora("Verifying Tailwind CSS config").start();
33
+ if (!existsSync(cssFullPath)) {
34
+ cssCheck.fail(`CSS file not found: ${cssPath}`);
35
+ logger.error("Frakment needs an existing Tailwind v4 entry file.");
36
+ process.exit(1);
37
+ }
38
+ let css = await readFile(cssFullPath, "utf-8");
39
+ css = css.replace(/^\uFEFF/u, "");
40
+ if (!/^@import\s+["']tailwindcss(\/|["'])/mu.test(css)) {
41
+ cssCheck.fail("Frakment requires Tailwind v4.");
42
+ logger.error(`Could not find @import "tailwindcss" in ${cssPath}`);
43
+ process.exit(1);
44
+ }
45
+ cssCheck.succeed(`Verifying Tailwind CSS config. Found ${chalk.cyan("v4")} in ${chalk.cyan(cssPath)}.`);
46
+ const configPath = path.join(cwd, configFile);
47
+ const configExists = existsSync(configPath);
48
+ let shouldWriteConfig = !configExists;
49
+ if (configExists) {
50
+ const { overwrite } = await prompts({
51
+ initial: false,
52
+ message: `${configFile} already exists. Overwrite?`,
53
+ name: "overwrite",
54
+ type: "confirm",
55
+ });
56
+ if (overwrite === undefined) {
57
+ logger.break();
58
+ logger.info("Cancelled.");
59
+ process.exit(0);
60
+ }
61
+ shouldWriteConfig = overwrite === true;
62
+ if (!shouldWriteConfig) {
63
+ logger.break();
64
+ logger.info(`Keeping existing ${configFile}.`);
65
+ }
66
+ }
67
+ if (shouldWriteConfig) {
68
+ const s = ora("Writing components.json").start();
69
+ const template = JSON.parse(await readFile(path.join(templatesDir, "components.json"), "utf-8"));
70
+ const config = Object.assign(Object.assign({}, template), { registry: defaultRegistry, tailwind: Object.assign(Object.assign({}, template.tailwind), { css: cssPath }) });
71
+ await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`);
72
+ s.succeed("Writing components.json.");
73
+ }
74
+ const themeSpinner = ora("Updating CSS variables").start();
75
+ css = css.replaceAll(new RegExp(`\\n*${escapeRegex(themeMarkerStart)}[\\s\\S]*?${escapeRegex(themeMarkerEnd)}\\n*`, "g"), "\n");
76
+ css = css.replaceAll(/^@import\s+["']\.\/theme\.css["'];?\s*$\n?/gmu, "");
77
+ css = `${css.replaceAll(/\n{3,}/gu, "\n\n").trimEnd()}\n`;
78
+ const themeContent = await readFile(path.join(templatesDir, "theme.css"), "utf-8");
79
+ const wrapped = `${themeMarkerStart}\n${themeContent.trim()}\n${themeMarkerEnd}`;
80
+ const importMatches = [...css.matchAll(/^@import\s+[^;\n]+;\s*$/gmu)];
81
+ if (importMatches.length > 0) {
82
+ const lastMatch = importMatches.at(-1);
83
+ if ((lastMatch === null || lastMatch === void 0 ? void 0 : lastMatch.index) === undefined) {
84
+ css = `${css.trimEnd()}\n\n${wrapped}\n`;
85
+ }
86
+ else {
87
+ const insertAt = lastMatch.index + lastMatch[0].length;
88
+ css = `${css.slice(0, insertAt)}\n\n${wrapped}${css.slice(insertAt)}`;
89
+ }
90
+ }
91
+ else {
92
+ css = `${css.trimEnd()}\n\n${wrapped}\n`;
93
+ }
94
+ await writeFile(cssFullPath, css);
95
+ themeSpinner.succeed(`Updating CSS variables in ${cssPath}`);
96
+ if (!existsSync(path.join(cwd, "lib/utils.ts"))) {
97
+ const s = ora("Creating lib/utils.ts").start();
98
+ await mkdir(path.join(cwd, "lib"), { recursive: true });
99
+ await writeFile(path.join(cwd, "lib/utils.ts"), `import { clsx, type ClassValue } from "clsx";
100
+ import { twMerge } from "tailwind-merge";
101
+
102
+ export function cn(...inputs: ClassValue[]) {
103
+ return twMerge(clsx(inputs));
104
+ }
105
+ `);
106
+ s.succeed("Created 1 file:");
107
+ logger.log(" - lib/utils.ts");
108
+ }
109
+ if (existsSync(path.join(cwd, "lib/motion.ts"))) {
110
+ }
111
+ else {
112
+ const s = ora("Creating lib/motion.ts").start();
113
+ await mkdir(path.join(cwd, "lib"), { recursive: true });
114
+ const motion = await readFile(path.join(templatesDir, "lib/motion.ts"), "utf-8");
115
+ await writeFile(path.join(cwd, "lib/motion.ts"), motion);
116
+ s.succeed("Created 1 file:");
117
+ logger.log(" - lib/motion.ts");
118
+ }
119
+ const pkgPath = path.join(cwd, "package.json");
120
+ const pkgRaw = await readFile(pkgPath, "utf-8");
121
+ const pkg = JSON.parse(pkgRaw.replace(/^\uFEFF/u, ""));
122
+ const allDeps = Object.assign(Object.assign({}, pkg.dependencies), pkg.devDependencies);
123
+ const missing = [
124
+ "clsx",
125
+ "tailwind-merge",
126
+ "class-variance-authority",
127
+ "lucide-react",
128
+ ].filter((d) => !allDeps[d]);
129
+ if (missing.length > 0) {
130
+ const s = ora("Installing dependencies").start();
131
+ const pm = detectPackageManager(cwd);
132
+ try {
133
+ const args = pm === "npm" ? ["install", ...missing] : ["add", ...missing];
134
+ await execa(pm, args, { cwd, stdio: "ignore" });
135
+ s.succeed(`Installed ${missing.length} package(s).`);
136
+ }
137
+ catch (error) {
138
+ s.fail("Failed to install dependencies.");
139
+ logger.warn(error instanceof Error ? error.message : "Unknown error");
140
+ }
141
+ }
142
+ logger.break();
143
+ logger.log(`${chalk.green("Success!")} Project initialization completed. You may now add components.`);
144
+ logger.break();
145
+ }
@@ -0,0 +1,55 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import chalk from "chalk";
5
+ import ora from "ora";
6
+ import { findProjectRoot } from "../utils/detect.js";
7
+ import { logger } from "../utils/logger.js";
8
+ export async function list(options) {
9
+ var _a, _b;
10
+ let cwd;
11
+ const preflight = ora("Preflight checks").start();
12
+ try {
13
+ cwd = findProjectRoot(process.cwd());
14
+ preflight.succeed("Preflight checks. Found project root.");
15
+ }
16
+ catch (error) {
17
+ preflight.fail(error instanceof Error ? error.message : "Unknown error");
18
+ process.exit(1);
19
+ }
20
+ const configPath = path.join(cwd, "components.json");
21
+ if (!existsSync(configPath)) {
22
+ logger.error(`${chalk.red("Error:")} components.json not found.`);
23
+ logger.info("Run `frakment init` first.");
24
+ process.exit(1);
25
+ }
26
+ const config = JSON.parse(await readFile(configPath, "utf-8"));
27
+ const registryUrl = ((_a = options.registry) !== null && _a !== void 0 ? _a : config.registry).replace(/\/$/u, "");
28
+ const s = ora("Fetching components").start();
29
+ let index;
30
+ try {
31
+ const res = await fetch(`${registryUrl}/index.json`);
32
+ if (!res.ok) {
33
+ throw new Error(`HTTP ${res.status}`);
34
+ }
35
+ index = await res.json();
36
+ }
37
+ catch (_c) {
38
+ s.fail("Failed to fetch component list.");
39
+ process.exit(1);
40
+ }
41
+ s.succeed(`Found ${index.components.length} component(s).`);
42
+ if (!index.components.length) {
43
+ logger.break();
44
+ logger.log(chalk.dim("No components available yet."));
45
+ return;
46
+ }
47
+ const nameWidth = Math.max(...index.components.map((c) => c.name.length));
48
+ logger.break();
49
+ for (const c of index.components) {
50
+ logger.log(` ${chalk.cyan(c.name.padEnd(nameWidth))} ${chalk.dim((_b = c.description) !== null && _b !== void 0 ? _b : "")}`);
51
+ }
52
+ logger.break();
53
+ logger.log(`Add one with ${chalk.cyan("frakment add <name>")}`);
54
+ logger.break();
55
+ }
@@ -0,0 +1,34 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ export function findProjectRoot(startDir) {
4
+ let dir = startDir;
5
+ while (dir !== path.dirname(dir)) {
6
+ if (existsSync(path.join(dir, "package.json"))) {
7
+ return dir;
8
+ }
9
+ dir = path.dirname(dir);
10
+ }
11
+ throw new Error("No package.json found. Are you inside a project?");
12
+ }
13
+ export function detectPackageManager(cwd) {
14
+ if (existsSync(path.join(cwd, "pnpm-lock.yaml"))) {
15
+ return "pnpm";
16
+ }
17
+ if (existsSync(path.join(cwd, "yarn.lock"))) {
18
+ return "yarn";
19
+ }
20
+ if (existsSync(path.join(cwd, "bun.lockb"))) {
21
+ return "bun";
22
+ }
23
+ return "npm";
24
+ }
25
+ export function detectGlobalsCss(cwd) {
26
+ var _a;
27
+ const candidates = [
28
+ "app/globals.css",
29
+ "src/app/globals.css",
30
+ "styles/globals.css",
31
+ "src/styles/globals.css",
32
+ ];
33
+ return ((_a = candidates.find((p) => existsSync(path.join(cwd, p)))) !== null && _a !== void 0 ? _a : "app/globals.css");
34
+ }
@@ -0,0 +1,11 @@
1
+ import chalk from "chalk";
2
+ import ora from "ora";
3
+ export const logger = {
4
+ break: () => console.log(""),
5
+ error: (...args) => console.log(chalk.red(...args.map((value) => String(value)))),
6
+ info: (...args) => console.log(chalk.cyan(...args.map((value) => String(value)))),
7
+ log: (...args) => console.log(...args),
8
+ spinner: (text) => ora(text),
9
+ success: (...args) => console.log(chalk.green(...args.map((value) => String(value)))),
10
+ warn: (...args) => console.log(chalk.yellow(...args.map((value) => String(value)))),
11
+ };
@@ -1,5 +1,5 @@
1
1
  {
2
- "registry": "https://frakment.vercel.app/r",
2
+ "registry": "https://www.arrafi.dev/frakment/r",
3
3
  "aliases": {
4
4
  "components": "@/components",
5
5
  "ui": "@/components/ui",