heart-ui 0.0.16 → 0.1.0-alpha.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1588 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { chmod, link, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir, stat as stat$1 } from "node:fs/promises";
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { lstatSync, statSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { spawnSync } from "node:child_process";
10
+ import { createInterface } from "node:readline/promises";
11
+ // package.json
12
+ var version$1 = "0.1.0-alpha.0";
13
+ // src/errors.ts
14
+ /** A failure the CLI reports as one line, with its exit code. */
15
+ var CliError = class extends Error {
16
+ exitCode;
17
+ constructor(message, exitCode = 1) {
18
+ super(message);
19
+ this.name = "CliError";
20
+ this.exitCode = exitCode;
21
+ }
22
+ };
23
+ /**
24
+ * A character that can change what the terminal shows: C0, DEL, C1, and the bidi and zero-width
25
+ * controls that reorder or hide text.
26
+ */
27
+ function isControl(char) {
28
+ const code = char.charCodeAt(0);
29
+ return code < 32 || code >= 127 && code <= 159 || code === 1564 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8288 && code <= 8297 || code === 65279;
30
+ }
31
+ /** `text` without control characters, safe to print. */
32
+ function printable(text) {
33
+ return [...text].filter((char) => !isControl(char)).join("");
34
+ }
35
+ /** JSON text with every control character JSON.stringify left raw (DEL, C1, bidi) escaped. */
36
+ function escapeControls(json) {
37
+ return [...json].map((char) => isControl(char) ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : char).join("");
38
+ }
39
+ /** `text` in double quotes with every control character escaped, safe to print. */
40
+ function quoted(text) {
41
+ return escapeControls(JSON.stringify(text));
42
+ }
43
+ // src/aliases.ts
44
+ const prefixes = {
45
+ "@/components/ui": "ui",
46
+ "@/components/blocks": "blocks",
47
+ "@/layouts": "layouts",
48
+ "@/lib": "lib"
49
+ };
50
+ const specifier = new RegExp(`(\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bimport\\s*)(['"\`])(${Object.keys(prefixes).map((prefix) => prefix.replace(/[/]/g, "\\/")).join("|")})(?=\\/|\\2)`, "g");
51
+ /** Rewrites registry import prefixes in `source` to the project's aliases. */
52
+ function rewriteImports(source, aliases) {
53
+ return source.replace(specifier, (_, lead, quote, prefix) => `${lead}${quote}${aliases[prefixes[prefix]]}`);
54
+ }
55
+ /**
56
+ * The folder an import alias (`@/components/ui`) points to, from the project's own aliases
57
+ * (`@` → `src`), longest match first.
58
+ */
59
+ function aliasPath(alias, projectAliases) {
60
+ const key = Object.keys(projectAliases).sort((a, b) => b.length - a.length).find((name) => alias === name || alias.startsWith(`${name}/`));
61
+ if (key === void 0) throw new CliError(`The alias ${alias} in heart-ui.json points nowhere. Add it to compilerOptions.paths in tsconfig.json.`);
62
+ return join(projectAliases[key], alias.slice(key.length).replace(/^\//, ""));
63
+ }
64
+ // src/fs.ts
65
+ async function writeTemp(near, text) {
66
+ const temp = join(dirname(near), `.${randomBytes(6).toString("hex")}.tmp`);
67
+ const handle = await open(temp, "wx");
68
+ try {
69
+ await handle.writeFile(text);
70
+ await handle.sync();
71
+ } catch (error) {
72
+ await handle.close();
73
+ await rm(temp, { force: true });
74
+ throw error;
75
+ }
76
+ await handle.close();
77
+ return temp;
78
+ }
79
+ /** Writes `text` so that a crash at any moment leaves either the old file or the new one. */
80
+ async function writeFileAtomic(path, text) {
81
+ let temp = "";
82
+ try {
83
+ temp = await writeTemp(path, text);
84
+ await rename(temp, path);
85
+ } catch (error) {
86
+ if (temp) await rm(temp, { force: true });
87
+ throw error;
88
+ }
89
+ }
90
+ /** Reads and parses a JSON file; `undefined` when it does not exist. */
91
+ async function readJsonFile(path, parse = JSON.parse) {
92
+ let text;
93
+ try {
94
+ text = await readFile(path, "utf8");
95
+ } catch (error) {
96
+ if (error.code === "ENOENT") return void 0;
97
+ throw new CliError(`Could not read ${path}.`);
98
+ }
99
+ try {
100
+ return parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
101
+ } catch {
102
+ throw new CliError(`${path} is not valid JSON.`);
103
+ }
104
+ }
105
+ function isObject(value) {
106
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107
+ }
108
+ function stat(path) {
109
+ try {
110
+ return statSync(path, { throwIfNoEntry: false });
111
+ } catch {
112
+ return;
113
+ }
114
+ }
115
+ const isFile = (path) => stat(path)?.isFile() ?? false;
116
+ const isDirectory = (path) => stat(path)?.isDirectory() ?? false;
117
+ /** True when anything sits at `path`: a file, a folder, or a symlink, even a dangling one. */
118
+ function exists(path) {
119
+ try {
120
+ lstatSync(path);
121
+ return true;
122
+ } catch (error) {
123
+ const code = error.code;
124
+ return code !== "ENOENT" && code !== "ENOTDIR";
125
+ }
126
+ }
127
+ /** Creates `path` with `text`, failing with EEXIST rather than replacing anything already there. */
128
+ async function writeNewFile(path, text) {
129
+ const temp = await writeTemp(path, text);
130
+ try {
131
+ await link(temp, path);
132
+ } finally {
133
+ await rm(temp, { force: true });
134
+ }
135
+ }
136
+ /** Replaces the contents of an existing file in place of its link target, keeping its mode. */
137
+ async function editFile(path, text) {
138
+ const target = await realpath(path);
139
+ const { mode } = await stat$1(target);
140
+ const temp = await writeTemp(target, text);
141
+ try {
142
+ await chmod(temp, mode);
143
+ await rename(temp, target);
144
+ } catch (error) {
145
+ await rm(temp, { force: true });
146
+ throw error;
147
+ }
148
+ }
149
+ // src/config.ts
150
+ const CONFIG_FILE = "heart-ui.json";
151
+ const keys = [
152
+ "$schema",
153
+ "framework",
154
+ "css",
155
+ "aliases",
156
+ "iconSet",
157
+ "registries"
158
+ ];
159
+ const aliasKeys = [
160
+ "ui",
161
+ "blocks",
162
+ "layouts",
163
+ "lib"
164
+ ];
165
+ /** The namespace pattern of the shadcn CLI. */
166
+ const registryName = /^@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?$/;
167
+ const importPath = /^[^\s'"`\\]+$/;
168
+ /** Reads `heart-ui.json` from `cwd`; `null` when there is none. */
169
+ async function readConfig(cwd) {
170
+ const path = join(cwd, CONFIG_FILE);
171
+ const value = await readJsonFile(path);
172
+ return value === void 0 ? null : parseConfig(value, path);
173
+ }
174
+ /** Validates `config` and returns the text of its `heart-ui.json`. */
175
+ function formatConfig(config, path = CONFIG_FILE) {
176
+ parseConfig(config, path);
177
+ return `${JSON.stringify(config, null, 2)}\n`;
178
+ }
179
+ function parseConfig(value, path) {
180
+ if (!isObject(value)) throw new CliError(`${path} must hold a JSON object.`);
181
+ const fail = (message) => new CliError(`${path}: ${message}`);
182
+ const nonEmpty = (key) => {
183
+ if (typeof value[key] !== "string" || value[key] === "") throw fail(`"${key}" must be a non-empty string.`);
184
+ };
185
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw fail(`Unknown key "${key}".`);
186
+ if ("$schema" in value && typeof value.$schema !== "string") throw fail("\"$schema\" must be a string.");
187
+ if (value.framework !== "nuxt" && value.framework !== "vite") throw fail("\"framework\" must be \"nuxt\" or \"vite\".");
188
+ nonEmpty("css");
189
+ nonEmpty("iconSet");
190
+ const { aliases, registries } = value;
191
+ if (!isObject(aliases)) throw fail("\"aliases\" must be an object.");
192
+ for (const key of Object.keys(aliases)) if (!aliasKeys.includes(key)) throw fail(`Unknown key "aliases.${key}".`);
193
+ for (const key of aliasKeys) {
194
+ const alias = aliases[key];
195
+ if (typeof alias !== "string" || !importPath.test(alias) || alias.endsWith("/")) throw fail(`"aliases.${key}" must be an import path without a trailing slash.`);
196
+ }
197
+ if (!isObject(registries)) throw fail("\"registries\" must be an object.");
198
+ for (const [name, template] of Object.entries(registries)) {
199
+ if (!registryName.test(name)) throw fail(`"registries.${name}" is not a registry name (like "@acme").`);
200
+ if (typeof template === "string" && hasCredentials(template)) throw fail(`"registries.${name}" must not hold a user name or password.`);
201
+ if (typeof template !== "string" || !isItemUrlTemplate(template)) throw fail(`"registries.${name}" must be an https URL (http only for localhost) containing {name}.`);
202
+ }
203
+ return value;
204
+ }
205
+ function isItemUrlTemplate(template) {
206
+ if (!template.includes("{name}")) return false;
207
+ try {
208
+ return isSecureUrl(new URL(template.replaceAll("{name}", "item")));
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ function hasCredentials(template) {
214
+ try {
215
+ const url = new URL(template.replaceAll("{name}", "item"));
216
+ return url.username !== "" || url.password !== "";
217
+ } catch {
218
+ return false;
219
+ }
220
+ }
221
+ const loopbackHosts = [
222
+ "localhost",
223
+ "127.0.0.1",
224
+ "[::1]"
225
+ ];
226
+ /** https, or plain http to this machine: registry items are source copied into the project. */
227
+ function isSecureUrl(url) {
228
+ return url.protocol === "https:" || url.protocol === "http:" && loopbackHosts.includes(url.hostname);
229
+ }
230
+ // src/jsonc.ts
231
+ /** Parses JSON with comments and trailing commas, as `tsconfig.json` allows. */
232
+ function parseJsonc(text) {
233
+ return JSON.parse(withoutTrailingCommas(withoutComments(text)));
234
+ }
235
+ /** Copies a string literal starting at `start` and returns the index after it. */
236
+ function skipString(text, start) {
237
+ let i = start + 1;
238
+ while (i < text.length && text[i] !== "\"") i += text[i] === "\\" ? 2 : 1;
239
+ return i + 1;
240
+ }
241
+ function withoutComments(text) {
242
+ let out = "";
243
+ let i = 0;
244
+ while (i < text.length) {
245
+ const char = text[i];
246
+ const next = text[i + 1];
247
+ if (char === "\"") {
248
+ const end = skipString(text, i);
249
+ out += text.slice(i, end);
250
+ i = end;
251
+ } else if (char === "/" && next === "/") while (i < text.length && text[i] !== "\n") i++;
252
+ else if (char === "/" && next === "*") {
253
+ const end = text.indexOf("*/", i + 2);
254
+ i = end === -1 ? text.length : end + 2;
255
+ out += " ";
256
+ } else {
257
+ out += char;
258
+ i++;
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+ function withoutTrailingCommas(text) {
264
+ let out = "";
265
+ let i = 0;
266
+ while (i < text.length) {
267
+ const char = text[i];
268
+ if (char === "\"") {
269
+ const end = skipString(text, i);
270
+ out += text.slice(i, end);
271
+ i = end;
272
+ continue;
273
+ }
274
+ if (char === ",") {
275
+ let j = i + 1;
276
+ while (j < text.length && /\s/.test(text[j] ?? "")) j++;
277
+ if (text[j] === "}" || text[j] === "]") {
278
+ i++;
279
+ continue;
280
+ }
281
+ }
282
+ out += char;
283
+ i++;
284
+ }
285
+ return out;
286
+ }
287
+ // src/detect.ts
288
+ const lockFiles = [
289
+ ["pnpm-lock.yaml", "pnpm"],
290
+ ["yarn.lock", "yarn"],
291
+ ["bun.lock", "bun"],
292
+ ["bun.lockb", "bun"],
293
+ ["package-lock.json", "npm"]
294
+ ];
295
+ /** Detects the framework, package manager, Tailwind version and aliases of the project in `cwd`. */
296
+ async function detectProject(cwd) {
297
+ const root = resolve(cwd);
298
+ const manifestPath = join(root, "package.json");
299
+ const manifest = await readJsonFile(manifestPath);
300
+ if (manifest === void 0) throw new CliError(`No package.json in ${root}.`);
301
+ if (!isObject(manifest)) throw new CliError(`${manifestPath} must hold a JSON object.`);
302
+ const deps = {
303
+ ...isObject(manifest.devDependencies) ? manifest.devDependencies : {},
304
+ ...isObject(manifest.dependencies) ? manifest.dependencies : {}
305
+ };
306
+ const framework = "nuxt" in deps ? "nuxt" : "vite" in deps ? "vite" : null;
307
+ const dirs = await projectDirs(root);
308
+ return {
309
+ root,
310
+ framework,
311
+ packageManager: managerFromField(manifest.packageManager) ?? managerFromLockFile(dirs) ?? "npm",
312
+ tailwindMajor: await tailwindMajor(root),
313
+ aliases: framework === "nuxt" ? nuxtAliases(root) : await tsconfigAliases(root)
314
+ };
315
+ }
316
+ async function projectDirs(root) {
317
+ const home = homedir();
318
+ const dirs = [];
319
+ for (let dir = root;; dir = dirname(dir)) {
320
+ if (dir === home && dir !== root) return [root];
321
+ dirs.push(dir);
322
+ if (await isBoundary(dir)) return dirs;
323
+ if (dirname(dir) === dir) return [root];
324
+ }
325
+ }
326
+ async function isBoundary(dir) {
327
+ const git = join(dir, ".git");
328
+ if (isDirectory(git) || isFile(git) || isFile(join(dir, "pnpm-workspace.yaml"))) return true;
329
+ if (!isFile(join(dir, "package.json"))) return false;
330
+ const manifest = await readJsonFile(join(dir, "package.json")).catch(() => void 0);
331
+ return isObject(manifest) && manifest.workspaces !== void 0;
332
+ }
333
+ function managerFromField(field) {
334
+ return (typeof field === "string" ? /^(pnpm|yarn|bun|npm)@/.exec(field) : null)?.[1];
335
+ }
336
+ function managerFromLockFile(dirs) {
337
+ for (const dir of dirs) for (const [file, manager] of lockFiles) if (isFile(join(dir, file))) return manager;
338
+ }
339
+ async function tailwindMajor(root) {
340
+ const version = await findVersion(root, "tailwindcss");
341
+ return version === null || version === "unknown" ? null : version.major;
342
+ }
343
+ /**
344
+ * The version of `name` in the project at `root`: installed in its own node_modules, else the
345
+ * lowest the declared range allows, else hoisted in its workspace. `'unknown'` when declared with a
346
+ * range that names no version (`latest`) and not installed; `null` when absent.
347
+ */
348
+ async function findVersion(root, name) {
349
+ const installed = await installedVersion(root, name);
350
+ if (installed) return installed;
351
+ const manifest = await readJsonFile(join(root, "package.json")).catch(() => void 0);
352
+ const declared = isObject(manifest) ? declaredRange(manifest, name) : void 0;
353
+ const fromRange = parseVersion(declared);
354
+ if (fromRange) return fromRange;
355
+ for (const dir of (await projectDirs(root)).slice(1)) {
356
+ const hoisted = await installedVersion(dir, name);
357
+ if (hoisted) return hoisted;
358
+ }
359
+ return declared === void 0 ? null : "unknown";
360
+ }
361
+ function declaredRange(manifest, name) {
362
+ for (const field of ["dependencies", "devDependencies"]) {
363
+ const deps = manifest[field];
364
+ if (isObject(deps) && name in deps) return deps[name];
365
+ }
366
+ }
367
+ async function installedVersion(dir, name) {
368
+ const path = join(dir, "node_modules", name, "package.json");
369
+ if (!isFile(path)) return null;
370
+ const manifest = await readJsonFile(path).catch(() => void 0);
371
+ return isObject(manifest) ? parseVersion(manifest.version) : null;
372
+ }
373
+ /**
374
+ * The lowest version a semver range allows, for the ranges people write (`^4.1.0`, `~3.4`, `>=4`,
375
+ * `3.x`). `open` when the install may pick a later minor: `^` and `>=`, or no fixed minor (`3`).
376
+ */
377
+ function parseVersion(range) {
378
+ if (typeof range !== "string") return null;
379
+ const match = /^\s*(\^|~|>=|=)?\s*v?(\d+)(?:\.(\d+|x|X|\*))?(?=$|[.\-\s])/.exec(range);
380
+ if (!match) return null;
381
+ const [, operator, major, minor] = match;
382
+ const fixedMinor = minor !== void 0 && /^\d+$/.test(minor);
383
+ const version = {
384
+ major: Number(major),
385
+ minor: fixedMinor ? Number(minor) : 0
386
+ };
387
+ return operator === "^" || operator === ">=" || !fixedMinor ? {
388
+ ...version,
389
+ open: true
390
+ } : version;
391
+ }
392
+ function nuxtAliases(root) {
393
+ const src = isDirectory(join(root, "app")) ? join(root, "app") : root;
394
+ return {
395
+ "@": src,
396
+ "~": src,
397
+ "@@": root,
398
+ "~~": root
399
+ };
400
+ }
401
+ async function tsconfigAliases(root) {
402
+ const loaded = /* @__PURE__ */ new Map();
403
+ const aliases = {};
404
+ const add = (file, resolved) => {
405
+ for (const [alias, path] of Object.entries(folderAliases(resolved, dirname(file)))) aliases[alias] ??= path;
406
+ };
407
+ const rootFile = join(root, "tsconfig.json");
408
+ const top = await load(rootFile, loaded, []);
409
+ add(rootFile, top);
410
+ for (const reference of top.references) {
411
+ const file = isDirectory(reference) ? join(reference, "tsconfig.json") : reference;
412
+ add(file, await load(file, loaded, []));
413
+ }
414
+ return aliases;
415
+ }
416
+ function folderAliases(resolved, configDir) {
417
+ const { paths, baseUrl } = resolved;
418
+ const aliases = {};
419
+ for (const [pattern, targets] of Object.entries(paths?.patterns ?? {})) {
420
+ const target = Array.isArray(targets) ? targets[0] : void 0;
421
+ if (!pattern.endsWith("/*") || typeof target !== "string" || !target.endsWith("*")) continue;
422
+ const path = target.replaceAll("${configDir}", configDir).replace(/\/?\*$/, "");
423
+ aliases[pattern.slice(0, -2)] = resolve(baseUrl ?? paths?.dir ?? configDir, path);
424
+ }
425
+ return aliases;
426
+ }
427
+ function load(file, loaded, chain) {
428
+ if (chain.includes(file)) return Promise.resolve({ references: [] });
429
+ let result = loaded.get(file);
430
+ if (!result) {
431
+ result = resolveTsconfig(file, loaded, [...chain, file]);
432
+ loaded.set(file, result);
433
+ }
434
+ return result;
435
+ }
436
+ async function resolveTsconfig(file, loaded, chain) {
437
+ const config = await readJsonFile(file, parseJsonc);
438
+ if (config === void 0) return { references: [] };
439
+ if (!isObject(config)) throw new CliError(`${file} must hold a JSON object.`);
440
+ const dir = dirname(file);
441
+ let baseUrl;
442
+ let paths;
443
+ const parents = typeof config.extends === "string" ? [config.extends] : config.extends;
444
+ if (Array.isArray(parents)) for (const parent of parents) {
445
+ if (typeof parent !== "string" || !parent.startsWith(".")) continue;
446
+ const path = resolve(dir, parent);
447
+ const next = await load(isFile(path) || path.endsWith(".json") ? path : `${path}.json`, loaded, chain);
448
+ baseUrl = next.baseUrl ?? baseUrl;
449
+ paths = next.paths ?? paths;
450
+ }
451
+ const options = isObject(config.compilerOptions) ? config.compilerOptions : {};
452
+ if (typeof options.baseUrl === "string") baseUrl = resolve(dir, options.baseUrl);
453
+ if (isObject(options.paths)) paths = {
454
+ patterns: options.paths,
455
+ dir
456
+ };
457
+ const references = (Array.isArray(config.references) ? config.references : []).flatMap((reference) => isObject(reference) && typeof reference.path === "string" ? [resolve(dir, reference.path)] : []);
458
+ return {
459
+ baseUrl,
460
+ paths,
461
+ references
462
+ };
463
+ }
464
+ // src/install.ts
465
+ const packageSpec = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
466
+ /** Fails on any dependency of `item` that is not an exact npm spec, before anything is written. */
467
+ function checkSpecs(item, registry) {
468
+ for (const dep of item.dependencies ?? []) if (!packageSpec.test(dep)) throw new CliError(`${registry} lists ${quoted(dep)} as a dependency of ${item.name}, which is not an npm package.`);
469
+ }
470
+ /** The package manager's command that adds `deps`, pinned exactly. */
471
+ function installCommand(manager, deps, workspaceRoot = false) {
472
+ const verb = manager === "npm" ? "install" : "add";
473
+ const exact = manager === "npm" || manager === "pnpm" ? "--save-exact" : "--exact";
474
+ return {
475
+ command: manager,
476
+ args: [
477
+ verb,
478
+ ...manager === "pnpm" && workspaceRoot ? ["-w"] : [],
479
+ exact,
480
+ ...deps
481
+ ]
482
+ };
483
+ }
484
+ const isPnpmWorkspaceRoot = (dir) => isFile(join(dir, "pnpm-workspace.yaml"));
485
+ const spawnInstaller = async (manager, deps, cwd) => {
486
+ const { command, args } = installCommand(manager, deps, isPnpmWorkspaceRoot(cwd));
487
+ const result = spawnSync(command, args, {
488
+ cwd,
489
+ stdio: "inherit",
490
+ shell: process.platform === "win32"
491
+ });
492
+ if (result.error) throw new CliError(`${command} could not start`);
493
+ if (result.status !== 0) throw new CliError(`${command} exited with ${result.status}`);
494
+ };
495
+ /** Installs `deps` in `root`; a failure names the command to run by hand, or `retryMessage`'s text. */
496
+ async function install(manager, deps, root, installer = spawnInstaller, retryMessage) {
497
+ if (!deps.length) return;
498
+ try {
499
+ await installer(manager, deps, root);
500
+ } catch (error) {
501
+ const { command, args } = installCommand(manager, deps, isPnpmWorkspaceRoot(root));
502
+ const reason = error instanceof CliError ? error.message : "see the output above";
503
+ if (retryMessage) throw new CliError(retryMessage(reason));
504
+ throw new CliError(`Installing dependencies failed (${reason}). Run this in ${root}: ${command} ${args.join(" ")}`);
505
+ }
506
+ }
507
+ const splitSpec = (spec) => {
508
+ const at = spec.indexOf("@", 1);
509
+ return {
510
+ name: spec.slice(0, at),
511
+ version: spec.slice(at + 1)
512
+ };
513
+ };
514
+ /**
515
+ * The items' dependencies the project lacks. One declared at the same major (the same minor below
516
+ * 1.0) is kept, and so is a range that names no version (`catalog:`, `workspace:*`); another major
517
+ * (tailwind-merge 2 for an item built on 3) would leave the item broken, so it is installed.
518
+ */
519
+ async function missingDependencies(root, items) {
520
+ const manifest = await readJsonFile(join(root, "package.json"));
521
+ const declared = /* @__PURE__ */ new Map();
522
+ if (isObject(manifest)) for (const field of ["devDependencies", "dependencies"]) {
523
+ const deps = manifest[field];
524
+ if (isObject(deps)) for (const [name, range] of Object.entries(deps)) declared.set(name, range);
525
+ }
526
+ const missing = [];
527
+ const seen = /* @__PURE__ */ new Set();
528
+ for (const dep of items.flatMap((item) => item.dependencies ?? [])) {
529
+ const { name, version } = splitSpec(dep);
530
+ if (seen.has(name)) continue;
531
+ seen.add(name);
532
+ if (declared.has(name)) {
533
+ const range = parseVersion(declared.get(name));
534
+ const wanted = parseVersion(version);
535
+ const fits = range?.major === wanted?.major && (range?.major !== 0 || range.minor === wanted?.minor);
536
+ if (range === null || fits) continue;
537
+ }
538
+ missing.push(dep);
539
+ }
540
+ return missing;
541
+ }
542
+ // src/lock.ts
543
+ const LOCK_FILE = "heart-ui.lock.json";
544
+ /** The Subresource Integrity form of `text`'s SHA-256. */
545
+ function hashText(text) {
546
+ return `sha256-${createHash("sha256").update(text).digest("base64")}`;
547
+ }
548
+ /** Reads the lock file; an empty lock when there is none. */
549
+ async function readLock(path) {
550
+ const value = await readJsonFile(path);
551
+ if (value === void 0) return { lock: { items: {} } };
552
+ if (!isLock(value)) throw new CliError(`${path} is not a valid lock file.`);
553
+ return {
554
+ lock: value,
555
+ text: formatLock(value)
556
+ };
557
+ }
558
+ /** The lock as written: two-space JSON, items sorted by key, a final newline. */
559
+ function formatLock(lock) {
560
+ const items = Object.fromEntries(Object.entries(lock.items).sort(([a], [b]) => a < b ? -1 : 1));
561
+ return `${JSON.stringify({ items }, null, 2)}\n`;
562
+ }
563
+ function isLock(value) {
564
+ if (!isObject(value) || !isObject(value.items)) return false;
565
+ return Object.values(value.items).every((entry) => isObject(entry) && typeof entry.registry === "string" && (entry.version === null || typeof entry.version === "string") && isObject(entry.files) && Object.values(entry.files).every((digest) => typeof digest === "string"));
566
+ }
567
+ // src/registry.ts
568
+ const DEFAULT_REGISTRY$1 = "@heart-ui";
569
+ /** The `@heart-ui` item URL: the R2 bucket's public host (docs/registry.md, Hosting). */
570
+ const DEFAULT_REGISTRY_URL = "https://registry.heart.tammai.me/r/{name}.json";
571
+ const TIMEOUT_MS = 3e4;
572
+ const MAX_BYTES = 5242880;
573
+ const MAX_REDIRECTS = 5;
574
+ const itemName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
575
+ const version = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
576
+ /** `$XDG_CACHE_HOME/heart-ui`, else `~/.cache/heart-ui`; a relative value is ignored, as XDG says. */
577
+ function defaultCacheDir(env = process.env) {
578
+ const xdg = env.XDG_CACHE_HOME;
579
+ return join(xdg && isAbsolute(xdg) ? xdg : join(homedir(), ".cache"), "heart-ui");
580
+ }
581
+ /** The URL without credentials, query or fragment, safe to print. */
582
+ function shown(url) {
583
+ const copy = new URL(url);
584
+ copy.username = "";
585
+ copy.password = "";
586
+ copy.search = "";
587
+ copy.hash = "";
588
+ return copy.href;
589
+ }
590
+ var TooLarge = class extends Error {};
591
+ function isNetworkError(error) {
592
+ return error instanceof TypeError || error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
593
+ }
594
+ async function readBody(response) {
595
+ if (Number(response.headers.get("content-length")) > MAX_BYTES) {
596
+ await response.body?.cancel();
597
+ throw new TooLarge();
598
+ }
599
+ if (!response.body) return "";
600
+ const chunks = [];
601
+ let size = 0;
602
+ for await (const chunk of response.body) {
603
+ size += chunk.byteLength;
604
+ if (size > MAX_BYTES) throw new TooLarge();
605
+ chunks.push(chunk);
606
+ }
607
+ return Buffer.concat(chunks).toString("utf8");
608
+ }
609
+ /**
610
+ * Fetches items by name (`button`, `@acme/data-grid`), optionally pinned to a version, and the
611
+ * registry's index, which follows the unpinned rule. A pinned
612
+ * item never changes, so it comes from the cache when there; an unpinned one is always fetched and
613
+ * falls back to the cache only when the registry cannot give a usable answer.
614
+ */
615
+ function createRegistryClient(options) {
616
+ const { registries, cacheDir = defaultCacheDir(), fetch = globalThis.fetch, onWarn = () => {} } = options;
617
+ async function readCache(file, check) {
618
+ try {
619
+ const value = JSON.parse(await readFile(file, "utf8"));
620
+ return check(value) ? value : void 0;
621
+ } catch {
622
+ return;
623
+ }
624
+ }
625
+ async function writeCache(file, value) {
626
+ try {
627
+ await mkdir(cacheDir, { recursive: true });
628
+ await writeFileAtomic(file, JSON.stringify(value));
629
+ } catch {
630
+ onWarn(`Could not write the cache in ${cacheDir}.`);
631
+ }
632
+ }
633
+ const cacheFileFor = (url) => join(cacheDir, `${createHash("sha256").update(url).digest("hex")}.json`);
634
+ async function getJson(subject) {
635
+ const { scope, url, check } = subject;
636
+ const cacheFile = cacheFileFor(url);
637
+ const fallback = async (error, warning) => {
638
+ const cached = await readCache(cacheFile, check);
639
+ if (cached === void 0) throw new CliError(error);
640
+ onWarn(warning);
641
+ return cached;
642
+ };
643
+ const invalid = `${scope} sent ${subject.invalid}`;
644
+ const request = async () => {
645
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
646
+ let current = url;
647
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
648
+ const response = await fetch(current, {
649
+ signal,
650
+ redirect: "manual"
651
+ });
652
+ const location = response.headers.get("location");
653
+ if (response.status < 300 || response.status > 399 || location === null) return response;
654
+ await response.body?.cancel();
655
+ const next = new URL(location, current);
656
+ if (!isSecureUrl(next)) throw new CliError(`${scope} redirected to ${shown(next.href)}, which is not https.`);
657
+ current = next.href;
658
+ }
659
+ throw new CliError(`${scope} redirected too many times for ${shown(url)}.`);
660
+ };
661
+ let response;
662
+ let text;
663
+ try {
664
+ response = await request();
665
+ text = await readBody(response);
666
+ } catch (error) {
667
+ if (error instanceof TooLarge) {
668
+ const tooLarge = `${scope} sent more than 5 MB for ${subject.about}`;
669
+ return fallback(`${tooLarge}.`, `${tooLarge}; using ${subject.cached}.`);
670
+ }
671
+ if (!isNetworkError(error)) throw error;
672
+ return fallback(`Could not reach ${scope} (${shown(url)}). Check your connection.`, `Could not reach ${scope}; using ${subject.cachedOf}.`);
673
+ }
674
+ const { status } = response;
675
+ if (status === 404) throw new CliError(subject.notFound);
676
+ if (status >= 500) return fallback(`${scope} answered ${status} for ${shown(url)}.`, `${scope} answered ${status}; using ${subject.cachedOf}.`);
677
+ if (status < 200 || status > 299) throw new CliError(`${scope} answered ${status} for ${shown(url)}.`);
678
+ let value;
679
+ try {
680
+ value = JSON.parse(text);
681
+ } catch {
682
+ value = void 0;
683
+ }
684
+ if (!check(value)) return fallback(`${invalid}.`, `${invalid}; using ${subject.cached}.`);
685
+ await writeCache(cacheFile, value);
686
+ return value;
687
+ }
688
+ const templateFor = (scope) => {
689
+ const template = Object.hasOwn(registries, scope) ? registries[scope] : void 0;
690
+ if (template === void 0) throw new CliError(`Unknown registry "${scope}". Add it under "registries" in heart-ui.json.`);
691
+ return template;
692
+ };
693
+ async function fetchItem(ref, pinned) {
694
+ const scoped = /^(@[^/]+)\/(.*)$/.exec(ref);
695
+ const scope = scoped?.[1] ?? DEFAULT_REGISTRY$1;
696
+ const name = scoped ? scoped[2] ?? "" : ref;
697
+ if (scoped && !registryName.test(scope) || !itemName.test(name)) throw new CliError(`"${ref}" is not a valid item name.`);
698
+ if (pinned !== void 0 && !version.test(pinned)) throw new CliError(`"${pinned}" is not a valid version.`);
699
+ const url = templateFor(scope).replaceAll("{name}", pinned ? `${name}@${pinned}` : name);
700
+ const check = (value) => isItem(value, name);
701
+ if (pinned) {
702
+ const cached = await readCache(cacheFileFor(url), check);
703
+ if (cached) return cached;
704
+ }
705
+ return getJson({
706
+ scope,
707
+ url,
708
+ check,
709
+ about: `"${name}"`,
710
+ cached: "the cached copy",
711
+ cachedOf: `the cached copy of "${name}"`,
712
+ invalid: `an invalid item for "${name}"`,
713
+ notFound: `Item "${name}" not found in ${scope} (${shown(url)}).`
714
+ });
715
+ }
716
+ /**
717
+ * The default registry's index: `registry.json` beside the `r/` folder that holds the items
718
+ * (docs/registry.md, Hosting), or beside the items when they sit in another folder.
719
+ */
720
+ async function fetchIndex() {
721
+ const scope = DEFAULT_REGISTRY$1;
722
+ const template = templateFor(scope);
723
+ const marked = new URL(template.replaceAll("{name}", "heart-ui-item-name"));
724
+ if (!marked.pathname.slice(marked.pathname.lastIndexOf("/") + 1).includes("heart-ui-item-name") || marked.search.includes("heart-ui-item-name")) throw new CliError(`The ${scope} template names items outside its file name, so list cannot find its index.`);
725
+ const folder = new URL(".", marked);
726
+ const index = new URL("registry.json", folder.pathname.endsWith("/r/") ? new URL("..", folder) : folder);
727
+ index.search = marked.search;
728
+ const url = index.href;
729
+ return getJson({
730
+ scope,
731
+ url,
732
+ check: isIndex,
733
+ about: "its index",
734
+ cached: "the cached index",
735
+ cachedOf: "the cached index",
736
+ invalid: "an invalid index",
737
+ notFound: `${scope} has no index at ${shown(url)}.`
738
+ }).then((index) => ({ items: index.items.filter(isIndexItem) }));
739
+ }
740
+ return {
741
+ fetchItem,
742
+ fetchIndex
743
+ };
744
+ }
745
+ const isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
746
+ const optional = (value, check) => value === void 0 || check(value);
747
+ const isString = (value) => typeof value === "string";
748
+ function isSafeSegment(segment) {
749
+ const name = segment.replace(/[. ]+$/, "").toLowerCase();
750
+ return segment !== "" && !segment.startsWith(".") && name !== "node_modules" && !/~\d/.test(segment) && !segment.includes(":");
751
+ }
752
+ const hasControl = (text) => [...text].some(isControl);
753
+ function isContainedPath(value) {
754
+ if (typeof value !== "string" || hasControl(value)) return false;
755
+ const path = value.startsWith("~/") ? value.slice(2) : value;
756
+ if (path === "" || /^([/\\]|[A-Za-z]:)/.test(path)) return false;
757
+ return path.split(/[/\\]/).every(isSafeSegment);
758
+ }
759
+ function isItem(value, name) {
760
+ return isObject(value) && value.name === name && typeof value.type === "string" && optional(value.title, isString) && optional(value.description, isString) && optional(value.meta, isObject) && optional(value.dependencies, isStringArray) && optional(value.registryDependencies, isStringArray) && Array.isArray(value.files) && value.files.every((file) => isObject(file) && isContainedPath(file.path) && typeof file.type === "string" && typeof file.content === "string" && optional(file.target, isContainedPath));
761
+ }
762
+ function isIndex(value) {
763
+ return isObject(value) && Array.isArray(value.items);
764
+ }
765
+ function isIndexItem(item) {
766
+ return isObject(item) && typeof item.name === "string" && typeof item.type === "string" && optional(item.title, isString) && optional(item.description, isString) && optional(item.categories, isStringArray);
767
+ }
768
+ // src/write.ts
769
+ /**
770
+ * Runs `steps` in order, then `after` (an install, say). On any failure every step is undone
771
+ * (created files and folders removed, edits restored), and whatever could not be undone is named.
772
+ * `command` and `outcome` word the message: `init` and "nothing was set up". A failure of `after`
773
+ * keeps its own message.
774
+ */
775
+ async function writeSteps(steps, show, command, outcome, after) {
776
+ const created = [];
777
+ const createdDirs = [];
778
+ const edited = [];
779
+ let failure = "";
780
+ let afterError;
781
+ try {
782
+ for (const step of steps) {
783
+ failure = `Could not write ${show(step.path)}`;
784
+ if (step.kind === "create") {
785
+ const first = await mkdir(dirname(step.path), { recursive: true });
786
+ if (first) createdDirs.push(...newDirs(first, dirname(step.path)));
787
+ await writeNewFile(step.path, step.content);
788
+ created.push(step.path);
789
+ } else {
790
+ if (await readFile(step.path, "utf8") !== step.original) {
791
+ failure = `${show(step.path)} changed while ${command} was waiting`;
792
+ throw new Error(failure);
793
+ }
794
+ await editFile(step.path, step.content);
795
+ edited.push(step);
796
+ }
797
+ }
798
+ if (after) {
799
+ failure = "The last step failed";
800
+ try {
801
+ await after();
802
+ } catch (error) {
803
+ afterError = error;
804
+ throw error;
805
+ }
806
+ }
807
+ } catch {
808
+ const left = [];
809
+ for (const step of edited.reverse()) {
810
+ if (step.kind !== "edit") continue;
811
+ await editFile(step.path, step.original).catch(() => left.push(show(step.path)));
812
+ }
813
+ for (const path of created.reverse()) await rm(path, { force: true }).catch(() => left.push(show(path)));
814
+ for (const dir of createdDirs.reverse()) await rmdir(dir).catch(() => {});
815
+ if (afterError instanceof CliError) {
816
+ if (!left.length) throw afterError;
817
+ failure = afterError.message.replace(/\.$/, "");
818
+ }
819
+ if (left.length) throw new CliError(`${failure}, and could not undo ${left.join(", ")}. Restore them and run heart-ui ${command} again.`);
820
+ throw new CliError(`${failure}; ${outcome}.`);
821
+ }
822
+ }
823
+ function newDirs(first, last) {
824
+ const dirs = [];
825
+ for (let dir = last;; dir = dirname(dir)) {
826
+ dirs.unshift(dir);
827
+ if (dir === first || dirname(dir) === dir) return dirs;
828
+ }
829
+ }
830
+ /** Refuses to edit `path` when it links outside `root`, as a cloned repo's file may (~/.bashrc). */
831
+ async function refuseOutside(root, path, show, command) {
832
+ const [target, base] = await Promise.all([realpath(path), realpath(root)]);
833
+ const inside = relative(base, target);
834
+ if (inside.startsWith("..") || inside === "" || /^[/\\]|^[A-Za-z]:/.test(inside)) throw new CliError(`${show(path)} links outside the project, so ${command} will not edit it. Replace the link with a file and run heart-ui ${command} again.`);
835
+ }
836
+ // src/commands/add.ts
837
+ const DEFAULT_REGISTRY = "@heart-ui";
838
+ const addable = [
839
+ "registry:ui",
840
+ "registry:lib",
841
+ "registry:block"
842
+ ];
843
+ const folders = [
844
+ ["registry/ui/", "ui"],
845
+ ["registry/lib/", "lib"],
846
+ ["registry/blocks/", "blocks"],
847
+ ["registry/layouts/", "layouts"]
848
+ ];
849
+ /** The `add` command; `deps` replaces the network and the installer in tests. */
850
+ function createAdd(deps = {}) {
851
+ return {
852
+ summary: "Add components, blocks or layouts, with what they depend on.",
853
+ usage: "heart-ui add <item...> [--overwrite]",
854
+ options: { overwrite: {
855
+ type: "boolean",
856
+ description: "Replace your files for the items you name."
857
+ } },
858
+ run: (ctx) => add(ctx.cwd, ctx.args, ctx.options.overwrite === true, ctx.io, deps)
859
+ };
860
+ }
861
+ const lf = (text) => text.replace(/\r\n/g, "\n");
862
+ async function add(cwd, refs, overwrite, io, deps) {
863
+ if (!refs.length) throw new CliError("Name at least one item: heart-ui add <item...>.", 2);
864
+ const root = resolve(cwd);
865
+ const config = await readConfig(root);
866
+ if (!config) throw new CliError(`No heart-ui.json in ${root}. Run heart-ui init first.`);
867
+ const project = await detectProject(root);
868
+ const show = (path) => relative(root, path).split(sep).join("/");
869
+ const lockPath = join(root, LOCK_FILE);
870
+ const { lock, text: lockText } = await readLock(lockPath);
871
+ const client = createRegistryClient({
872
+ registries: config.registries,
873
+ cacheDir: deps.cacheDir,
874
+ fetch: deps.fetch,
875
+ onWarn: (message) => io.stderr(`heart-ui: ${message}\n`)
876
+ });
877
+ const seen = /* @__PURE__ */ new Set();
878
+ const named = /* @__PURE__ */ new Set();
879
+ const order = [];
880
+ const visit = async (ref, parent) => {
881
+ const scoped = /^(@[^/]+)\/(.*)$/.exec(ref);
882
+ const registry = scoped?.[1] ?? DEFAULT_REGISTRY;
883
+ const name = scoped ? scoped[2] ?? "" : ref;
884
+ const key = registry === DEFAULT_REGISTRY ? name : `${registry}/${name}`;
885
+ if (parent === void 0) named.add(key);
886
+ if (seen.has(key)) return;
887
+ seen.add(key);
888
+ const item = await client.fetchItem(`${registry}/${name}`);
889
+ if (!addable.includes(item.type)) throw new CliError(`${parent === void 0 ? name : `${key} (needed by ${parent})`} is a ${item.type} item; heart-ui add installs components, helpers, blocks and layouts.`);
890
+ checkSpecs(item, registry);
891
+ for (const dep of item.registryDependencies ?? []) await visit(dep, key);
892
+ order.push({
893
+ key,
894
+ registry,
895
+ item,
896
+ named: false
897
+ });
898
+ };
899
+ for (const ref of refs) await visit(ref);
900
+ const entries = order.map((entry) => ({
901
+ ...entry,
902
+ named: named.has(entry.key)
903
+ }));
904
+ const plans = /* @__PURE__ */ new Map();
905
+ const owners = /* @__PURE__ */ new Map();
906
+ for (const entry of entries) {
907
+ const planned = await plan(entry, root, config, project.aliases, show);
908
+ for (const file of planned) {
909
+ const owner = owners.get(file.path.toLowerCase());
910
+ if (owner !== void 0) throw new CliError(owner === entry.key ? `${entry.key} sends two files for ${show(file.path)}.` : `${owner} and ${entry.key} both write ${show(file.path)}.`);
911
+ owners.set(file.path.toLowerCase(), entry.key);
912
+ }
913
+ plans.set(entry.key, planned);
914
+ }
915
+ const steps = [];
916
+ const items = new Map(Object.entries(lock.items));
917
+ const added = [];
918
+ const written = [];
919
+ const replaced = [];
920
+ const kept = [];
921
+ const differ = [];
922
+ const newer = [];
923
+ const upToDate = [];
924
+ const installed = [];
925
+ const create = (file) => {
926
+ steps.push({
927
+ kind: "create",
928
+ path: file.path,
929
+ content: file.content
930
+ });
931
+ written.push(show(file.path));
932
+ };
933
+ for (const entry of entries) {
934
+ const planned = plans.get(entry.key) ?? [];
935
+ const locked = Object.hasOwn(lock.items, entry.key) ? lock.items[entry.key] : void 0;
936
+ const missing = planned.filter((file) => !file.present);
937
+ const differs = planned.filter((file) => file.present && (file.current === void 0 || lf(file.current) !== lf(file.content)));
938
+ const lockEntry = {
939
+ registry: entry.registry,
940
+ version: typeof entry.item.meta?.version === "string" ? entry.item.meta.version : null,
941
+ files: Object.fromEntries(planned.map((file) => [show(file.path), hashText(file.content)]))
942
+ };
943
+ if (!differs.length) {
944
+ missing.forEach(create);
945
+ (missing.length ? added : upToDate).push(entry.key);
946
+ items.set(entry.key, lockEntry);
947
+ installed.push(entry.item);
948
+ continue;
949
+ }
950
+ const untouched = (file) => {
951
+ const recorded = locked && Object.hasOwn(locked.files, show(file.path)) ? locked.files[show(file.path)] : void 0;
952
+ return file.current !== void 0 && (recorded === hashText(file.current) || recorded === hashText(lf(file.current)));
953
+ };
954
+ if (differs.every(untouched) && !(entry.named && overwrite)) {
955
+ newer.push(entry.key);
956
+ continue;
957
+ }
958
+ if (!entry.named) {
959
+ missing.forEach(create);
960
+ if (locked) {
961
+ const files = { ...locked.files };
962
+ for (const file of missing) files[show(file.path)] = hashText(file.content);
963
+ items.set(entry.key, {
964
+ ...locked,
965
+ files
966
+ });
967
+ }
968
+ (locked ? kept : differ).push(entry.key);
969
+ continue;
970
+ }
971
+ const notFile = differs.find((file) => file.current === void 0);
972
+ if (notFile) throw new CliError(`${show(notFile.path)} already exists and is not a file.`);
973
+ if (!overwrite) {
974
+ const paths = differs.map((file) => show(file.path));
975
+ throw new CliError(paths.length === 1 ? `${paths[0]} already exists. Run heart-ui add ${entry.key} --overwrite to replace it.` : `${paths.join(", ")} already exist. Run heart-ui add ${entry.key} --overwrite to replace them.`);
976
+ }
977
+ missing.forEach(create);
978
+ for (const file of differs) {
979
+ await refuseOutside(root, file.path, show, "add");
980
+ steps.push({
981
+ kind: "edit",
982
+ path: file.path,
983
+ content: file.content,
984
+ original: file.current
985
+ });
986
+ replaced.push(show(file.path));
987
+ }
988
+ added.push(entry.key);
989
+ items.set(entry.key, lockEntry);
990
+ installed.push(entry.item);
991
+ }
992
+ const newLock = formatLock({ items: Object.fromEntries(items) });
993
+ if (newLock !== lockText) {
994
+ if (lockText === void 0) steps.push({
995
+ kind: "create",
996
+ path: lockPath,
997
+ content: newLock
998
+ });
999
+ else {
1000
+ await refuseOutside(root, lockPath, show, "add");
1001
+ const original = await readFile(lockPath, "utf8");
1002
+ steps.push({
1003
+ kind: "edit",
1004
+ path: lockPath,
1005
+ content: newLock,
1006
+ original
1007
+ });
1008
+ }
1009
+ }
1010
+ const installs = await missingDependencies(root, installed);
1011
+ await writeSteps(steps, show, "add", "nothing was added", () => install(project.packageManager, installs, root, deps.install, (reason) => `Installing dependencies failed (${reason}); nothing was added. Fix the install and run heart-ui add again.`));
1012
+ if (added.length) io.stdout(`Added: ${added.join(", ")}\n`);
1013
+ if (written.length) io.stdout(`Wrote: ${written.join(", ")}\n`);
1014
+ if (replaced.length) io.stdout(`Replaced: ${replaced.join(", ")}\n`);
1015
+ for (const key of kept) io.stdout(`Kept your changes to ${key}; heart-ui update brings it up to date.\n`);
1016
+ for (const key of differ) io.stdout(`${key} differs from the registry; kept the copy you have.\n`);
1017
+ for (const key of newer) io.stdout(`${key} has a newer version; heart-ui update brings it in.\n`);
1018
+ if (installs.length) io.stdout(`Installed: ${installs.join(", ")}\n`);
1019
+ for (const ref of refs) {
1020
+ const key = ref.startsWith(`${DEFAULT_REGISTRY}/`) ? ref.slice(10) : ref;
1021
+ if (upToDate.includes(key)) io.stdout(`${key} is up to date.\n`);
1022
+ }
1023
+ return 0;
1024
+ }
1025
+ async function plan(entry, root, config, projectAliases, show) {
1026
+ const planned = [];
1027
+ for (const file of entry.item.files) {
1028
+ let path;
1029
+ if (file.target !== void 0) {
1030
+ const target = file.target.replace(/^~\//, "");
1031
+ if (dirname(join(root, target)) === root) throw new CliError(`${entry.registry} sent ${entry.item.name} with a file for the project root, ${quoted(file.target)}; items may write only into folders.`);
1032
+ path = join(root, target);
1033
+ await refuseLinkedFolder(root, path, show);
1034
+ } else {
1035
+ const folder = folders.find(([prefix]) => file.path.startsWith(prefix) && file.path.length > prefix.length);
1036
+ if (!folder) throw new CliError(`${entry.registry} sent ${entry.item.name} with a file outside registry/ui, lib, blocks and layouts: ${quoted(file.path)}.`);
1037
+ const [prefix, alias] = folder;
1038
+ path = join(aliasPath(config.aliases[alias], projectAliases), file.path.slice(prefix.length));
1039
+ }
1040
+ const present = exists(path);
1041
+ const current = present && isFile(path) ? await readFile(path, "utf8") : void 0;
1042
+ planned.push({
1043
+ path,
1044
+ content: rewriteImports(file.content, config.aliases),
1045
+ current,
1046
+ present
1047
+ });
1048
+ }
1049
+ return planned;
1050
+ }
1051
+ async function refuseLinkedFolder(root, path, show) {
1052
+ let dir = dirname(path);
1053
+ while (!exists(dir) && dirname(dir) !== dir) dir = dirname(dir);
1054
+ const target = await realpath(dir).catch(() => void 0);
1055
+ const inside = target === void 0 ? ".." : relative(await realpath(root), target);
1056
+ if (inside.startsWith("..") || /^[/\\]|^[A-Za-z]:/.test(inside)) throw new CliError(`${show(path)} is outside the project, so add will not write it.`);
1057
+ }
1058
+ // ../../registry/themes/default.json
1059
+ var default_default = {
1060
+ name: "default",
1061
+ primary: "oklch(0.55 0.2 260)",
1062
+ neutral: {
1063
+ "hue": 260,
1064
+ "chroma": .02
1065
+ },
1066
+ radius: .5,
1067
+ density: "default",
1068
+ font: {
1069
+ "sans": "Inter, system-ui, sans-serif",
1070
+ "mono": "ui-monospace, monospace"
1071
+ },
1072
+ shadow: "soft"
1073
+ };
1074
+ // src/agents.ts
1075
+ /** Starts the Heart UI block in AGENTS.md, so `init` adds it once. */
1076
+ const AGENTS_MARKER = "<!-- heart-ui:start -->";
1077
+ /** The Heart UI section of AGENTS.md (docs/agent-support.md, Project rule files). */
1078
+ function agentsBlock(config, folder) {
1079
+ const { ui, blocks, layouts, lib } = config.aliases;
1080
+ return `${AGENTS_MARKER}
1081
+ # Heart UI
1082
+
1083
+ This project builds its UI from Heart UI: Vue components copied in as source you own.
1084
+
1085
+ - Components: \`${ui}\` (${folder(ui)})
1086
+ - Blocks: \`${blocks}\` (${folder(blocks)})
1087
+ - Layouts: \`${layouts}\` (${folder(layouts)})
1088
+ - Helpers: \`${lib}\` (${folder(lib)})
1089
+ - Theme: ${config.css}, which imports tokens.css
1090
+
1091
+ ## Building a screen
1092
+
1093
+ 1. Write a brief: the user, the one primary task, content ranked by importance, the primary action.
1094
+ 2. Pick one layout from the catalog. Justify it against its \`useWhen\`.
1095
+ 3. Fill each region with blocks. Add bare components only where no block fits.
1096
+ 4. Build the empty, loading, error, and long-content states.
1097
+ 5. Screenshot at 375, 768, and 1280 px. Run \`heart-ui audit\`. Fix findings.
1098
+
1099
+ Use \`heart-ui list\` or the MCP \`search_items\` tool before writing new UI.
1100
+
1101
+ ## Rules
1102
+
1103
+ - Semantic token utilities only: \`bg-primary\`, \`text-muted-foreground\`, \`h-control-md\`.
1104
+ - No raw values: no hex or named colors, no pixel or rem literals, no Tailwind palette or arbitrary-value classes.
1105
+ - One primary action per view.
1106
+ - Every data region handles empty, loading, error, and long content.
1107
+
1108
+ ## Verify
1109
+
1110
+ Run \`heart-ui audit <files>\` on every screen you change.
1111
+ <!-- heart-ui:end -->
1112
+ `;
1113
+ }
1114
+ // src/commands/init.ts
1115
+ const presets = { default: default_default };
1116
+ const helpers = ["utils", "icon"];
1117
+ const defaultAliases = {
1118
+ ui: "@/components/ui",
1119
+ blocks: "@/components/blocks",
1120
+ layouts: "@/layouts",
1121
+ lib: "@/lib"
1122
+ };
1123
+ const tailwindImport = /^([ \t]*)@import\s+(["'])tailwindcss\2[ \t]*;?[ \t]*$/m;
1124
+ /** The `init` command; `deps` replaces the network, the installer and the Node version in tests. */
1125
+ function createInit(deps = {}) {
1126
+ return {
1127
+ summary: "Set up Heart UI in a Nuxt or Vite project.",
1128
+ usage: "heart-ui init [--theme <preset>] [--registry <url>] [--yes]",
1129
+ options: {
1130
+ theme: {
1131
+ type: "string",
1132
+ description: `Theme preset: ${Object.keys(presets).join(", ")}.`
1133
+ },
1134
+ yes: {
1135
+ type: "boolean",
1136
+ description: "Write without asking."
1137
+ },
1138
+ registry: {
1139
+ type: "string",
1140
+ description: "The @heart-ui item URL, with {name} for the item (a mirror, say)."
1141
+ }
1142
+ },
1143
+ run: (ctx) => init(ctx.cwd, ctx.options, ctx.io, deps)
1144
+ };
1145
+ }
1146
+ async function init(cwd, options, io, deps) {
1147
+ if (options.yes !== true && !io.confirm) throw new CliError("stdin is not a terminal, so init cannot ask. Run heart-ui init --yes.", 2);
1148
+ const project = await detectProject(cwd);
1149
+ const { root } = project;
1150
+ const show = (path) => relative(root, path).split(sep).join("/");
1151
+ const configPath = join(root, CONFIG_FILE);
1152
+ if (exists(configPath)) throw new CliError(`${CONFIG_FILE} already exists in ${root}; Heart UI is already set up here.`);
1153
+ await checkVersions(project, deps.nodeVersion ?? process.versions.node);
1154
+ const themeName = typeof options.theme === "string" ? options.theme : "default";
1155
+ const knobs = Object.hasOwn(presets, themeName) ? presets[themeName] : void 0;
1156
+ if (!knobs) throw new CliError(`No theme preset "${themeName}". Presets: ${Object.keys(presets).join(", ")}.`);
1157
+ const src = project.aliases["@"];
1158
+ if (src === void 0) throw new CliError("The import alias \"@\" points nowhere. Add \"@/*\": [\"./src/*\"] to compilerOptions.paths in tsconfig.json, and the same alias to your Vite config.");
1159
+ const aliasDir = (alias) => aliasPath(alias, project.aliases);
1160
+ const cssDir = join(src, "assets", "css");
1161
+ const themePath = join(cssDir, "theme.css");
1162
+ const config = {
1163
+ framework: project.framework === "nuxt" ? "nuxt" : "vite",
1164
+ css: show(themePath),
1165
+ aliases: defaultAliases,
1166
+ iconSet: "fluent",
1167
+ registries: { "@heart-ui": typeof options.registry === "string" ? options.registry : deps.registryUrl ?? "https://registry.heart.tammai.me/r/{name}.json" }
1168
+ };
1169
+ let configText;
1170
+ try {
1171
+ configText = formatConfig(config, configPath);
1172
+ } catch (error) {
1173
+ const about = error instanceof CliError && error.message.includes("\"registries.@heart-ui\"");
1174
+ if (typeof options.registry !== "string" || !about) throw error;
1175
+ throw new CliError(`--registry: ${error.message.replace(/^.*"registries\.@heart-ui" /, "")}`);
1176
+ }
1177
+ const client = createRegistryClient({
1178
+ registries: config.registries,
1179
+ cacheDir: deps.cacheDir,
1180
+ fetch: deps.fetch,
1181
+ onWarn: (message) => io.stderr(`heart-ui: ${message}\n`)
1182
+ });
1183
+ const items = await Promise.all(helpers.map((name) => client.fetchItem(name)));
1184
+ for (const item of items) checkSpecs(item, "@heart-ui");
1185
+ const { generateTheme } = await import("@heart-ui/theme");
1186
+ const creates = [{
1187
+ path: themePath,
1188
+ content: await readFile(createRequire(import.meta.url).resolve("@heart-ui/theme/theme.css"), "utf8")
1189
+ }, {
1190
+ path: join(cssDir, "tokens.css"),
1191
+ content: generateTheme(knobs)
1192
+ }];
1193
+ for (const item of items) for (const file of item.files) {
1194
+ const prefix = "registry/lib/";
1195
+ if (!file.path.startsWith(prefix) || file.path === prefix) throw new CliError(`@heart-ui sent ${item.name} with a file outside registry/lib/: ${quoted(file.path)}.`);
1196
+ creates.push({
1197
+ path: join(aliasDir(config.aliases.lib), file.path.slice(13)),
1198
+ content: rewriteImports(file.content, config.aliases)
1199
+ });
1200
+ }
1201
+ for (const { path } of creates) if (exists(path)) throw new CliError(`${show(path)} already exists. Move it away and run heart-ui init again.`);
1202
+ const agents = await agentFiles(root, config, aliasDir, show);
1203
+ for (const { path } of agents.edits) await refuseOutside(root, path, show, "init");
1204
+ creates.push(...agents.creates);
1205
+ const entry = await cssEntry(src, themePath);
1206
+ const edits = [...agents.edits, ...entry ? [entry] : []];
1207
+ const installs = await missingDependencies(root, items);
1208
+ const plan = [
1209
+ ...creates.map(({ path }) => show(path)),
1210
+ ...edits.map(({ path }) => show(path)),
1211
+ CONFIG_FILE
1212
+ ];
1213
+ const installLine = installs.length ? `and install:\n ${installs.join("\n ")}\n` : "";
1214
+ if (options.yes !== true) {
1215
+ io.stdout(`heart-ui init will write or edit:\n${plan.map((path) => ` ${path}\n`).join("")}${installLine}`);
1216
+ if (!await io.confirm?.("Continue?")) throw new CliError("Cancelled; nothing was written.");
1217
+ }
1218
+ await writeSteps([
1219
+ ...creates.map(({ path, content }) => ({
1220
+ kind: "create",
1221
+ path,
1222
+ content
1223
+ })),
1224
+ ...edits.map((edit) => ({
1225
+ kind: "edit",
1226
+ ...edit
1227
+ })),
1228
+ {
1229
+ kind: "create",
1230
+ path: configPath,
1231
+ content: configText
1232
+ }
1233
+ ], show, "init", "nothing was set up");
1234
+ await install(project.packageManager, installs, root, deps.install);
1235
+ io.stdout(`Wrote:\n${plan.map((path) => ` ${path}\n`).join("")}`);
1236
+ if (installs.length) io.stdout(`Installed:\n ${installs.join("\n ")}\n`);
1237
+ if (!entry) io.stdout(`Import ${show(themePath)} from your app's CSS entry in place of tailwindcss (it imports Tailwind itself).\n`);
1238
+ return 0;
1239
+ }
1240
+ async function checkVersions(project, nodeVersion) {
1241
+ if (!(Number(nodeVersion.split(".")[0]) >= 22)) throw new CliError(`Node ${nodeVersion} found; Heart UI needs Node 22 or later.`);
1242
+ if (project.framework === null) throw new CliError(`No Nuxt or Vite project in ${project.root}; Heart UI works with either.`);
1243
+ const needs = [
1244
+ [
1245
+ "vue",
1246
+ "Vue",
1247
+ 3,
1248
+ 5,
1249
+ project.framework === "vite" ? "required" : "optional"
1250
+ ],
1251
+ ...project.framework === "nuxt" ? [[
1252
+ "nuxt",
1253
+ "Nuxt",
1254
+ 4,
1255
+ 0,
1256
+ "required"
1257
+ ]] : [],
1258
+ [
1259
+ "tailwindcss",
1260
+ "Tailwind CSS",
1261
+ 4,
1262
+ 0,
1263
+ "required"
1264
+ ]
1265
+ ];
1266
+ for (const [pkg, label, major, minor, mode] of needs) {
1267
+ const wanted = minor ? `${major}.${minor}` : `${major}`;
1268
+ const found = await findVersion(project.root, pkg);
1269
+ if (found === null) {
1270
+ if (mode === "optional") continue;
1271
+ throw new CliError(`${label} not found; Heart UI needs ${label} ${wanted} or later.${pkg === "tailwindcss" ? " Set it up first: https://tailwindcss.com/docs/installation" : ""}`);
1272
+ }
1273
+ if (found === "unknown") continue;
1274
+ if (found.open ? found.major < major : found.major < major || found.major === major && found.minor < minor) throw new CliError(`${label} ${found.major}.${found.minor} found; Heart UI needs ${label} ${wanted} or later.`);
1275
+ }
1276
+ }
1277
+ async function agentFiles(root, config, aliasDir, show) {
1278
+ const creates = [];
1279
+ const edits = [];
1280
+ const block = agentsBlock(config, (alias) => show(aliasDir(alias)));
1281
+ const agentsPath = join(root, "AGENTS.md");
1282
+ const agents = await readText(agentsPath);
1283
+ if (agents === void 0) {
1284
+ if (exists(agentsPath)) throw new CliError("AGENTS.md is not a readable file. Move it away and run heart-ui init again.");
1285
+ creates.push({
1286
+ path: agentsPath,
1287
+ content: block
1288
+ });
1289
+ } else if (!agents.includes("<!-- heart-ui:start -->")) edits.push({
1290
+ path: agentsPath,
1291
+ content: `${withNewline(agents)}\n${block}`,
1292
+ original: agents
1293
+ });
1294
+ const claudePath = join(root, "CLAUDE.md");
1295
+ const claude = await readText(claudePath);
1296
+ const sameFile = claude !== void 0 && agents !== void 0 && await realpath(claudePath) === await realpath(agentsPath);
1297
+ if (claude !== void 0 && !sameFile && !claude.includes("AGENTS.md")) edits.push({
1298
+ path: claudePath,
1299
+ content: `${withNewline(claude)}\nFor UI work, follow the Heart UI rules in AGENTS.md.\n`,
1300
+ original: claude
1301
+ });
1302
+ return {
1303
+ creates,
1304
+ edits
1305
+ };
1306
+ }
1307
+ const withNewline = (text) => text.endsWith("\n") || text === "" ? text : `${text}\n`;
1308
+ async function readText(path) {
1309
+ if (!isFile(path)) return void 0;
1310
+ try {
1311
+ return await readFile(path, "utf8");
1312
+ } catch {
1313
+ throw new CliError(`Could not read ${path}.`);
1314
+ }
1315
+ }
1316
+ async function cssEntry(src, themePath) {
1317
+ const found = [];
1318
+ for (const path of await cssFiles(src)) {
1319
+ const text = await readText(path);
1320
+ const masked = text?.replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\r\n]/g, " "));
1321
+ const match = masked === void 0 ? null : tailwindImport.exec(masked);
1322
+ if (text === void 0 || !match) continue;
1323
+ let target = relative(dirname(path), themePath).split(sep).join("/");
1324
+ if (!target.startsWith(".")) target = `./${target}`;
1325
+ found.push({
1326
+ path,
1327
+ content: `${text.slice(0, match.index)}${match[1]}@import ${match[2]}${target}${match[2]};${text.slice(match.index + match[0].length)}`,
1328
+ original: text
1329
+ });
1330
+ }
1331
+ return found.length === 1 ? found[0] : void 0;
1332
+ }
1333
+ async function cssFiles(dir) {
1334
+ let entries;
1335
+ try {
1336
+ entries = await readdir(dir, { withFileTypes: true });
1337
+ } catch {
1338
+ return [];
1339
+ }
1340
+ const files = [];
1341
+ for (const entry of entries) {
1342
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
1343
+ const path = join(dir, entry.name);
1344
+ if (entry.isDirectory()) files.push(...await cssFiles(path));
1345
+ else if (entry.isFile() && entry.name.endsWith(".css")) files.push(path);
1346
+ }
1347
+ return files;
1348
+ }
1349
+ // src/commands/list.ts
1350
+ const types = [
1351
+ "ui",
1352
+ "lib",
1353
+ "block",
1354
+ "theme"
1355
+ ];
1356
+ /** The `list` command; `deps` replaces the network in tests. */
1357
+ function createList(deps = {}) {
1358
+ return {
1359
+ summary: "List the items in the registry.",
1360
+ usage: "heart-ui list [--type <type>] [--category <category>] [--json]",
1361
+ options: {
1362
+ type: {
1363
+ type: "string",
1364
+ description: "Only items of this type: ui, lib, block or theme."
1365
+ },
1366
+ category: {
1367
+ type: "string",
1368
+ description: "Only items in this category."
1369
+ },
1370
+ json: {
1371
+ type: "boolean",
1372
+ description: "Print the matching index entries as JSON."
1373
+ }
1374
+ },
1375
+ run: (ctx) => list(ctx.cwd, ctx.options, ctx.io, deps)
1376
+ };
1377
+ }
1378
+ async function list(cwd, options, io, deps) {
1379
+ let type;
1380
+ if (typeof options.type === "string") {
1381
+ const kind = options.type.toLowerCase().replace(/^registry:/, "");
1382
+ if (!types.includes(kind)) throw new CliError(`--type must be one of ${types.join(", ")}.`, 2);
1383
+ type = `registry:${kind}`;
1384
+ }
1385
+ let config = null;
1386
+ try {
1387
+ config = await readConfig(cwd);
1388
+ } catch (error) {
1389
+ if (!(error instanceof CliError)) throw error;
1390
+ io.stderr(`heart-ui: ${printable(error.message)} Listing the default registry.\n`);
1391
+ }
1392
+ const { items } = await createRegistryClient({
1393
+ registries: {
1394
+ "@heart-ui": DEFAULT_REGISTRY_URL,
1395
+ ...config?.registries
1396
+ },
1397
+ cacheDir: deps.cacheDir,
1398
+ fetch: deps.fetch,
1399
+ onWarn: (message) => io.stderr(`heart-ui: ${message}\n`)
1400
+ }).fetchIndex();
1401
+ const category = typeof options.category === "string" ? options.category : void 0;
1402
+ const matching = items.filter((item) => (type === void 0 || item.type === type) && (category === void 0 || (item.categories ?? []).includes(category)));
1403
+ if (options.json === true) {
1404
+ io.stdout(`${escapeControls(JSON.stringify(matching))}\n`);
1405
+ return 0;
1406
+ }
1407
+ if (!matching.length) {
1408
+ io.stdout("No items match.\n");
1409
+ return 0;
1410
+ }
1411
+ const rows = matching.map((item) => [
1412
+ printable(item.name),
1413
+ printable(item.type.replace(/^registry:/, "")),
1414
+ printable(item.description ?? "")
1415
+ ]);
1416
+ const widths = [0, 1].map((column) => rows.reduce((width, row) => Math.max(width, [...row[column] ?? ""].length), 0));
1417
+ for (const [name = "", kind = "", description] of rows) io.stdout(`${pad(name, widths[0] ?? 0)} ${pad(kind, widths[1] ?? 0)} ${description}`.trimEnd() + "\n");
1418
+ return 0;
1419
+ }
1420
+ const pad = (text, width) => text + " ".repeat(Math.max(0, width - [...text].length));
1421
+ // src/cli.ts
1422
+ /** The commands `heart-ui` runs, by name. */
1423
+ const commands = {
1424
+ init: createInit(),
1425
+ add: createAdd(),
1426
+ list: createList()
1427
+ };
1428
+ const globalOptions = {
1429
+ cwd: {
1430
+ type: "string",
1431
+ description: "Run in this folder instead of the current one."
1432
+ },
1433
+ help: {
1434
+ type: "boolean",
1435
+ short: "h",
1436
+ description: "Show help."
1437
+ },
1438
+ version: {
1439
+ type: "boolean",
1440
+ description: "Show the version."
1441
+ }
1442
+ };
1443
+ const USAGE_ERROR = 2;
1444
+ /** Runs the CLI with `argv` (no node or script path) and returns the exit code. */
1445
+ async function run(argv, io, table = commands) {
1446
+ try {
1447
+ return await dispatch(argv, io, table);
1448
+ } catch (error) {
1449
+ if (error instanceof CliError) {
1450
+ io.stderr(`heart-ui: ${printable(error.message)}\n`);
1451
+ return error.exitCode;
1452
+ }
1453
+ const code = error?.code;
1454
+ const tag = typeof code === "string" ? ` (${printable(code)})` : "";
1455
+ io.stderr(`heart-ui: Unexpected error${tag}. Please report it.\n`);
1456
+ return 1;
1457
+ }
1458
+ }
1459
+ const globalFlags = [
1460
+ "--help",
1461
+ "-h",
1462
+ "--version"
1463
+ ];
1464
+ function commandIndex(argv) {
1465
+ for (let i = 0; i < argv.length; i++) {
1466
+ const arg = argv[i] ?? "";
1467
+ if (arg === "--") return -1;
1468
+ if (!arg.startsWith("-")) return i;
1469
+ if (arg === "--cwd") i++;
1470
+ else if (!globalFlags.includes(arg) && !arg.startsWith("--cwd=")) throw new CliError(`Option ${arg.split("=")[0]} goes after the command name. Run heart-ui --help.`, USAGE_ERROR);
1471
+ }
1472
+ return -1;
1473
+ }
1474
+ async function dispatch(argv, io, table) {
1475
+ const index = commandIndex(argv);
1476
+ const name = index === -1 ? void 0 : argv[index];
1477
+ const command = name !== void 0 && Object.hasOwn(table, name) ? table[name] : void 0;
1478
+ if (name !== void 0 && !command) throw new CliError(`Unknown command "${name}". Run heart-ui --help to see the commands.`, USAGE_ERROR);
1479
+ const specs = {
1480
+ ...command?.options,
1481
+ ...globalOptions
1482
+ };
1483
+ const { tokens } = parseArgs({
1484
+ args: argv.filter((_, i) => i !== index),
1485
+ options: Object.fromEntries(Object.entries(specs).map(([key, { type, short }]) => [key, short ? {
1486
+ type,
1487
+ short
1488
+ } : { type }])),
1489
+ strict: false,
1490
+ allowPositionals: true,
1491
+ tokens: true
1492
+ });
1493
+ const args = [];
1494
+ const options = {};
1495
+ const where = name ? ` for "heart-ui ${name}". Run heart-ui ${name} --help.` : ". Run heart-ui --help.";
1496
+ for (const token of tokens) {
1497
+ if (token.kind === "positional") args.push(token.value);
1498
+ if (token.kind !== "option") continue;
1499
+ const spec = Object.hasOwn(specs, token.name) ? specs[token.name] : void 0;
1500
+ if (!spec) throw new CliError(`Unknown option ${token.rawName}${where}`, USAGE_ERROR);
1501
+ const missing = token.value === void 0 || !token.inlineValue && token.value.startsWith("-");
1502
+ if (spec.type === "string" && missing) throw new CliError(`Option ${token.rawName} needs a value.`, USAGE_ERROR);
1503
+ if (spec.type === "boolean" && token.value !== void 0) throw new CliError(`Option ${token.rawName} takes no value.`, USAGE_ERROR);
1504
+ options[token.name] = token.value ?? true;
1505
+ }
1506
+ const { cwd: cwdOption, help, version, ...commandOptions } = options;
1507
+ if (version) {
1508
+ io.stdout(`${version$1}\n`);
1509
+ return 0;
1510
+ }
1511
+ if (!command) {
1512
+ if (help) {
1513
+ io.stdout(mainHelp(table));
1514
+ return 0;
1515
+ }
1516
+ io.stderr(mainHelp(table));
1517
+ return USAGE_ERROR;
1518
+ }
1519
+ if (help) {
1520
+ io.stdout(commandHelp(command));
1521
+ return 0;
1522
+ }
1523
+ const cwd = resolve(io.cwd, typeof cwdOption === "string" ? cwdOption : ".");
1524
+ if (cwdOption !== void 0 && !isDirectory(cwd)) throw new CliError(`No such folder: ${cwd}.`, USAGE_ERROR);
1525
+ const code = await command.run({
1526
+ cwd,
1527
+ args,
1528
+ options: commandOptions,
1529
+ io
1530
+ });
1531
+ return typeof code === "number" ? code : 0;
1532
+ }
1533
+ function columns(rows) {
1534
+ const width = Math.max(...rows.map(([left]) => left.length)) + 2;
1535
+ return rows.map(([left, right]) => ` ${left.padEnd(width)}${right}\n`).join("");
1536
+ }
1537
+ function optionRows(specs) {
1538
+ return Object.entries(specs).map(([key, spec]) => [(spec.short ? `-${spec.short}, ` : "") + (spec.type === "string" ? `--${key} ${key === "cwd" ? "<path>" : "<value>"}` : `--${key}`), spec.description]);
1539
+ }
1540
+ function mainHelp(table) {
1541
+ const names = Object.keys(table);
1542
+ return [
1543
+ "Usage: heart-ui <command> [options]\n\n",
1544
+ "Commands:\n",
1545
+ names.length ? columns(names.map((name) => [name, table[name]?.summary ?? ""])) : " (none yet)\n",
1546
+ "\nOptions:\n",
1547
+ columns(optionRows(globalOptions)),
1548
+ "\nRun heart-ui <command> --help for its options.\n"
1549
+ ].join("");
1550
+ }
1551
+ function commandHelp(command) {
1552
+ return [
1553
+ `Usage: ${command.usage}\n\n`,
1554
+ `${command.summary}\n\n`,
1555
+ "Options:\n",
1556
+ columns(optionRows({
1557
+ ...command.options,
1558
+ ...globalOptions
1559
+ }))
1560
+ ].join("");
1561
+ }
1562
+ // src/prompt.ts
1563
+ /** Asks `question`; anything but y or yes, Ctrl+C and the end of input (Ctrl+D) mean no. */
1564
+ async function askYesNo(question, input, output) {
1565
+ const prompt = createInterface({
1566
+ input,
1567
+ output
1568
+ });
1569
+ const cancel = new AbortController();
1570
+ prompt.on("SIGINT", () => cancel.abort());
1571
+ prompt.on("close", () => cancel.abort());
1572
+ try {
1573
+ const answer = await prompt.question(`${question} (y/N) `, { signal: cancel.signal });
1574
+ return /^y(es)?$/i.test(answer.trim());
1575
+ } catch {
1576
+ return false;
1577
+ } finally {
1578
+ prompt.close();
1579
+ }
1580
+ }
1581
+ // src/index.ts
1582
+ process.exitCode = await run(process.argv.slice(2), {
1583
+ cwd: process.cwd(),
1584
+ stdout: (text) => process.stdout.write(text),
1585
+ stderr: (text) => process.stderr.write(text),
1586
+ confirm: process.stdin.isTTY ? (question) => askYesNo(question, process.stdin, process.stdout) : void 0
1587
+ });
1588
+ export {};