@barqjs/ui-cli 0.0.0-stage → 0.2.0-next.1

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.js ADDED
@@ -0,0 +1,1761 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+ import { stdin, stdout } from "node:process";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createHash } from "node:crypto";
7
+ import { spawnSync } from "node:child_process";
8
+ import { createInterface } from "node:readline/promises";
9
+ // src/files.ts
10
+ /**
11
+ * Writing a component into a project, and the import rewriting that needs.
12
+ *
13
+ * A registry file's own imports are relative — `../lib/slot.ts` from
14
+ * `ui/button.tsx` — because that is what they are in the package they came
15
+ * from. A project may put `ui` and `lib` somewhere else entirely, so every
16
+ * relative specifier is recomputed against where the two files ACTUALLY land.
17
+ *
18
+ * That is the whole of it. shadcn rewrites imports to an alias
19
+ * (`@/components/ui/button`) and needs the project's `tsconfig` paths to agree;
20
+ * a relative path needs nothing to agree, and it is right in a project with no
21
+ * aliases at all.
22
+ */
23
+ /**
24
+ * Where a file of this type goes, as an absolute directory.
25
+ *
26
+ * `page` and `file` have none of their own and answer with the project root,
27
+ * which is what their `target` is relative to.
28
+ */
29
+ function directoryFor(config, cwd, type) {
30
+ const paths = config.paths;
31
+ const chosen = {
32
+ "registry:ui": paths.ui,
33
+ "registry:lib": paths.lib,
34
+ "registry:theme": paths.theme,
35
+ "registry:hook": paths.hooks,
36
+ "registry:block": paths.components,
37
+ "registry:component": paths.components,
38
+ "registry:example": paths.components,
39
+ "registry:page": ".",
40
+ "registry:file": "."
41
+ };
42
+ return resolve(cwd, chosen[type]);
43
+ }
44
+ /** The three whose registry path is a tree to keep rather than a name to file. */
45
+ const NESTED = /* @__PURE__ */ new Set([
46
+ "registry:block",
47
+ "registry:component",
48
+ "registry:example"
49
+ ]);
50
+ /**
51
+ * The absolute path a registry file is written to.
52
+ *
53
+ * A registry is someone else's data, and a `target` or a path that climbs out
54
+ * of the project would let `add` write anywhere the user can. So the answer is
55
+ * checked against the root before anything is written to it.
56
+ */
57
+ function targetOf(config, cwd, file) {
58
+ const root = resolve(cwd);
59
+ const name = file.path.split("/").at(-1) ?? file.path;
60
+ const absolute = file.target !== void 0 ? resolve(root, file.target.replace(/^~\//, "")) : NESTED.has(file.type) ? join(directoryFor(config, cwd, file.type), file.path.replace(/^components\//, "")) : join(directoryFor(config, cwd, file.type), name);
61
+ const inside = relative(root, absolute);
62
+ if (inside.startsWith("..") || isAbsolute(inside)) throw new Error(`${file.path} would be written to ${absolute}, which is outside the project`);
63
+ return absolute;
64
+ }
65
+ /** The directory a registry path starts with, as the type it stands for. */
66
+ function typeOfPath(path) {
67
+ const directory = path.split("/")[0];
68
+ if (directory === "lib") return "registry:lib";
69
+ if (directory === "theme") return "registry:theme";
70
+ if (directory === "hooks") return "registry:hook";
71
+ if (directory === "blocks") return "registry:block";
72
+ if (directory === "components") return "registry:component";
73
+ return "registry:ui";
74
+ }
75
+ function placed(items) {
76
+ const out = /* @__PURE__ */ new Map();
77
+ for (const item of items) for (const file of item.files) out.set(file.path, file);
78
+ return out;
79
+ }
80
+ const SPECIFIER = /(from\s*|import\s*)(["'])(\.[^"']*)\2/g;
81
+ /**
82
+ * The file's own text, with every relative import pointed at where that file
83
+ * will be.
84
+ *
85
+ * The extension is kept: this package's own source imports `./button.tsx`, and
86
+ * so does what it writes. A project whose bundler wants extensionless imports
87
+ * is the one case this does not serve, and it is the rarer one now.
88
+ */
89
+ function rewrite(config, cwd, file, together = /* @__PURE__ */ new Map()) {
90
+ const here = dirname(targetOf(config, cwd, file));
91
+ return file.content.replaceAll(SPECIFIER, (_whole, lead, quote, specifier) => {
92
+ const inRegistry = join(dirname(file.path), specifier).replaceAll("\\", "/");
93
+ const there = targetOf(config, cwd, together.get(inRegistry) ?? {
94
+ path: inRegistry,
95
+ type: typeOfPath(inRegistry),
96
+ content: ""
97
+ });
98
+ let next = relative(here, there).replaceAll("\\", "/");
99
+ if (!next.startsWith(".")) next = `./${next}`;
100
+ return `${lead}${quote}${next}${quote}`;
101
+ });
102
+ }
103
+ function hashOf(content) {
104
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
105
+ }
106
+ function write(path, content) {
107
+ mkdirSync(dirname(path), { recursive: true });
108
+ writeFileSync(path, content);
109
+ }
110
+ function read(path) {
111
+ try {
112
+ return readFileSync(path, "utf8");
113
+ } catch {
114
+ return;
115
+ }
116
+ }
117
+ // src/add.ts
118
+ /**
119
+ * `add`: the item, everything it needs, and the files that result.
120
+ *
121
+ * A file already on disk is the only interesting case. Three answers, and which
122
+ * one applies is decided by the hash `components.json` recorded when the file
123
+ * was written:
124
+ *
125
+ * - **The same content**: nothing to do, and nothing is said about it.
126
+ * - **Unchanged since it was added**: replaced, because the project did not
127
+ * write it.
128
+ * - **Edited**: left alone and reported, unless `--overwrite`. That is the
129
+ * whole point of owning the code, and a tool that silently reverted an edit
130
+ * would be taking it back.
131
+ */
132
+ function applyItems(config, root, items, options = {}) {
133
+ const files = [];
134
+ const recorded = { ...config.items };
135
+ const together = placed(items);
136
+ const put = options.dryRun === true ? () => {} : write;
137
+ const planned = items.map((item) => ({
138
+ item,
139
+ files: item.files.map((file) => {
140
+ const absolute = targetOf(config, root, file);
141
+ return {
142
+ key: file.path,
143
+ absolute,
144
+ path: relative(root, absolute).replaceAll("\\", "/"),
145
+ incoming: rewrite(config, root, file, together)
146
+ };
147
+ })
148
+ }));
149
+ for (const { item, files: own } of planned) {
150
+ const forItem = { ...recorded[item.name] };
151
+ for (const { key, absolute, path, incoming } of own) {
152
+ const hash = hashOf(incoming);
153
+ const existing = read(absolute);
154
+ const common = {
155
+ item: item.name,
156
+ path,
157
+ absolute,
158
+ incoming
159
+ };
160
+ if (existing === void 0) {
161
+ put(absolute, incoming);
162
+ files.push({
163
+ ...common,
164
+ outcome: "written",
165
+ hash
166
+ });
167
+ } else if (existing === incoming) files.push({
168
+ ...common,
169
+ outcome: "unchanged",
170
+ hash,
171
+ existing
172
+ });
173
+ else if (options.overwrite === true || hashOf(existing) === forItem[key]) {
174
+ put(absolute, incoming);
175
+ files.push({
176
+ ...common,
177
+ outcome: "replaced",
178
+ hash,
179
+ existing
180
+ });
181
+ } else {
182
+ files.push({
183
+ ...common,
184
+ outcome: "kept",
185
+ hash: hashOf(existing),
186
+ existing
187
+ });
188
+ continue;
189
+ }
190
+ forItem[key] = hash;
191
+ }
192
+ recorded[item.name] = forItem;
193
+ }
194
+ return {
195
+ files,
196
+ config: {
197
+ ...config,
198
+ items: recorded
199
+ }
200
+ };
201
+ }
202
+ /** `zod@^3` and `@acme/kit@1` are `zod` and `@acme/kit` in a `package.json`. */
203
+ function packageName(dependency) {
204
+ const at = dependency.indexOf("@", 1);
205
+ return at < 0 ? dependency : dependency.slice(0, at);
206
+ }
207
+ /**
208
+ * The npm packages these items want, minus what the project already has.
209
+ *
210
+ * `field` is which list to read: what the code imports, or what only its build
211
+ * and its tests need.
212
+ */
213
+ function missingDependencies(items, installed, field = "dependencies") {
214
+ const wanted = /* @__PURE__ */ new Set();
215
+ for (const item of items) for (const dependency of item[field]) if (!installed.has(packageName(dependency))) wanted.add(dependency);
216
+ return [...wanted].toSorted();
217
+ }
218
+ // src/schema.ts
219
+ const TYPES = /* @__PURE__ */ new Set([
220
+ "registry:ui",
221
+ "registry:lib",
222
+ "registry:theme",
223
+ "registry:block",
224
+ "registry:component",
225
+ "registry:hook",
226
+ "registry:page",
227
+ "registry:file",
228
+ "registry:example"
229
+ ]);
230
+ /** The two that are not components, so no directory in `paths` is theirs. */
231
+ const NEEDS_TARGET = /* @__PURE__ */ new Set(["registry:page", "registry:file"]);
232
+ function fail(message) {
233
+ throw new Error(message);
234
+ }
235
+ function record(value, where) {
236
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail(`${where} must be an object`);
237
+ return value;
238
+ }
239
+ function text(value, where) {
240
+ if (typeof value !== "string") fail(`${where} must be a string`);
241
+ return value;
242
+ }
243
+ function list$1(value, where) {
244
+ if (!Array.isArray(value)) fail(`${where} must be an array`);
245
+ return value;
246
+ }
247
+ function itemType(value, where) {
248
+ const name = text(value, where);
249
+ if (!TYPES.has(name)) fail(`${where} must be one of ${[...TYPES].join(", ")}, not "${name}"`);
250
+ return name;
251
+ }
252
+ function texts(value, where) {
253
+ return list$1(value ?? [], where).map((one, index) => text(one, `${where}[${String(index)}]`));
254
+ }
255
+ function strings(value, where) {
256
+ return Object.fromEntries(Object.entries(record(value, where)).map(([key, one]) => [key, text(one, `${where}.${key}`)]));
257
+ }
258
+ function cssVars(value, where) {
259
+ const entry = record(value, where);
260
+ const mode = (name) => entry[name] === void 0 ? {} : { [name]: strings(entry[name], `${where}.${name}`) };
261
+ return {
262
+ ...mode("theme"),
263
+ ...mode("light"),
264
+ ...mode("dark")
265
+ };
266
+ }
267
+ function cssRules(value, where) {
268
+ return Object.fromEntries(Object.entries(record(value, where)).map(([key, one]) => [key, typeof one === "string" ? one : cssRules(one, `${where}.${key}`)]));
269
+ }
270
+ function parseItem(value, where = "the item") {
271
+ const entry = record(value, where);
272
+ const name = text(entry["name"], `${where}.name`);
273
+ return {
274
+ name,
275
+ type: itemType(entry["type"], `${where}.type`),
276
+ title: typeof entry["title"] === "string" ? entry["title"] : name,
277
+ ...typeof entry["description"] === "string" ? { description: entry["description"] } : {},
278
+ dependencies: texts(entry["dependencies"], `${where}.dependencies`),
279
+ devDependencies: texts(entry["devDependencies"], `${where}.devDependencies`),
280
+ registryDependencies: texts(entry["registryDependencies"], `${where}.registryDependencies`),
281
+ files: list$1(entry["files"] ?? [], `${where}.files`).map((one, index) => {
282
+ const at = `${where}.files[${String(index)}]`;
283
+ const file = record(one, at);
284
+ const type = itemType(file["type"], `${at}.type`);
285
+ if (NEEDS_TARGET.has(type) && file["target"] === void 0) fail(`${at}.target is required for ${type}, which has no directory of its own`);
286
+ return {
287
+ path: text(file["path"], `${at}.path`),
288
+ type,
289
+ content: text(file["content"], `${at}.content`),
290
+ ...file["target"] === void 0 ? {} : { target: text(file["target"], `${at}.target`) }
291
+ };
292
+ }),
293
+ categories: texts(entry["categories"], `${where}.categories`),
294
+ ...entry["meta"] === void 0 ? {} : { meta: record(entry["meta"], `${where}.meta`) },
295
+ ...entry["cssVars"] === void 0 ? {} : { cssVars: cssVars(entry["cssVars"], `${where}.cssVars`) },
296
+ ...entry["css"] === void 0 ? {} : { css: cssRules(entry["css"], `${where}.css`) }
297
+ };
298
+ }
299
+ function parseIndex(value) {
300
+ const entry = record(value, "the registry");
301
+ return {
302
+ name: text(entry["name"] ?? "registry", "the registry's name"),
303
+ ...typeof entry["homepage"] === "string" ? { homepage: entry["homepage"] } : {},
304
+ items: list$1(entry["items"] ?? [], "the registry's items").map((one, index) => {
305
+ const item = record(one, `items[${String(index)}]`);
306
+ const name = text(item["name"], `items[${String(index)}].name`);
307
+ return {
308
+ name,
309
+ type: itemType(item["type"], `items[${String(index)}].type`),
310
+ title: typeof item["title"] === "string" ? item["title"] : name,
311
+ ...typeof item["description"] === "string" ? { description: item["description"] } : {},
312
+ dependencies: list$1(item["dependencies"] ?? [], "dependencies").map((one_, at) => text(one_, `items[${String(index)}].dependencies[${String(at)}]`)),
313
+ registryDependencies: list$1(item["registryDependencies"] ?? [], "registryDependencies").map((one_, at) => text(one_, `items[${String(index)}].registryDependencies[${String(at)}]`)),
314
+ files: list$1(item["files"] ?? [], "files").map((one_, at) => text(one_, `items[${String(index)}].files[${String(at)}]`)),
315
+ categories: texts(item["categories"], `items[${String(index)}].categories`)
316
+ };
317
+ })
318
+ };
319
+ }
320
+ const DEFAULT_PATHS = {
321
+ ui: "src/components/ui",
322
+ lib: "src/components/lib",
323
+ theme: "src/components/theme",
324
+ components: "src/components",
325
+ hooks: "src/hooks"
326
+ };
327
+ /**
328
+ * Where components go when only `ui` was chosen: the directory `ui` is in.
329
+ *
330
+ * `init` asks one question, and a project whose `ui` is `app/widgets/ui` wants
331
+ * its blocks in `app/widgets/blocks`, not in a `src` it does not have.
332
+ */
333
+ function componentsBeside(ui) {
334
+ const at = ui.lastIndexOf("/");
335
+ return ui.endsWith("/ui") && at > 0 ? ui.slice(0, at) : ui;
336
+ }
337
+ function hooksBeside(components) {
338
+ const at = components.lastIndexOf("/");
339
+ return at > 0 ? `${components.slice(0, at)}/hooks` : "hooks";
340
+ }
341
+ function endpoint(value, where) {
342
+ const entry = typeof value === "string" ? { url: value } : record(value, where);
343
+ const url = text(entry["url"], `${where}.url`);
344
+ if (!url.includes("{name}")) fail(`${where} must contain {name}, which is where the item goes`);
345
+ return {
346
+ url,
347
+ headers: strings(entry["headers"] ?? {}, `${where}.headers`)
348
+ };
349
+ }
350
+ function registries(value) {
351
+ return Object.fromEntries(Object.entries(record(value, "components.json.registries")).map(([scope, one]) => {
352
+ if (!/^@[\w-]+$/.test(scope)) fail(`components.json.registries: "${scope}" must be a scope, like @acme`);
353
+ return [scope, endpoint(one, `components.json.registries.${scope}`)];
354
+ }));
355
+ }
356
+ function pattern(value) {
357
+ const url = text(value, "components.json.registry");
358
+ if (!url.includes("{name}")) fail(`components.json.registry must contain {name}, as in https://example.com/r/{name}.json`);
359
+ return url;
360
+ }
361
+ function parseConfig(value) {
362
+ const entry = record(value, "components.json");
363
+ const paths = record(entry["paths"] ?? {}, "components.json.paths");
364
+ const theme = record(entry["theme"] ?? {}, "components.json.theme");
365
+ const items = record(entry["items"] ?? {}, "components.json.items");
366
+ const ui = text(paths["ui"] ?? DEFAULT_PATHS.ui, "components.json.paths.ui");
367
+ const components = text(paths["components"] ?? componentsBeside(ui), "components.json.paths.components");
368
+ return {
369
+ ...typeof entry["$schema"] === "string" ? { $schema: entry["$schema"] } : {},
370
+ ...entry["registry"] === void 0 ? {} : { registry: pattern(entry["registry"]) },
371
+ registries: registries(entry["registries"] ?? {}),
372
+ paths: {
373
+ ui,
374
+ lib: text(paths["lib"] ?? DEFAULT_PATHS.lib, "components.json.paths.lib"),
375
+ theme: text(paths["theme"] ?? DEFAULT_PATHS.theme, "components.json.paths.theme"),
376
+ components,
377
+ hooks: text(paths["hooks"] ?? hooksBeside(components), "components.json.paths.hooks")
378
+ },
379
+ theme: {
380
+ ...typeof theme["style"] === "string" ? { style: theme["style"] } : {},
381
+ base: text(theme["base"] ?? "neutral", "components.json.theme.base"),
382
+ ...typeof theme["accent"] === "string" ? { accent: theme["accent"] } : {},
383
+ ...typeof theme["radius"] === "string" ? { radius: theme["radius"] } : {},
384
+ ...typeof theme["dark"] === "string" ? { dark: theme["dark"] } : {},
385
+ ...theme["cssVars"] === void 0 ? {} : { cssVars: cssVars(theme["cssVars"], "components.json.theme.cssVars") },
386
+ ...theme["css"] === void 0 ? {} : { css: cssRules(theme["css"], "components.json.theme.css") }
387
+ },
388
+ reset: entry["reset"] !== false,
389
+ items: Object.fromEntries(Object.entries(items).map(([name, files]) => [name, Object.fromEntries(Object.entries(record(files, `components.json.items.${name}`)).map(([path, hash]) => [path, text(hash, `components.json.items.${name}.${path}`)]))]))
390
+ };
391
+ }
392
+ // src/config.ts
393
+ /**
394
+ * `components.json`: finding it, reading it, writing it back.
395
+ *
396
+ * At the project root rather than anywhere on the path, and the root is where
397
+ * the file IS — so a command run from a subdirectory of a monorepo package
398
+ * finds that package's configuration and not the workspace's.
399
+ */
400
+ const CONFIG_FILE = "components.json";
401
+ /** The nearest directory at or above `from` holding a `components.json`. */
402
+ function findRoot(from) {
403
+ let directory = resolve(from);
404
+ for (;;) {
405
+ if (existsSync(join(directory, "components.json"))) return directory;
406
+ const parent = dirname(directory);
407
+ if (parent === directory) return void 0;
408
+ directory = parent;
409
+ }
410
+ }
411
+ function readConfig(root) {
412
+ const path = join(root, CONFIG_FILE);
413
+ return parseConfig(JSON.parse(readFileSync(path, "utf8")));
414
+ }
415
+ /**
416
+ * Written with the keys in a fixed order and the item table last.
417
+ *
418
+ * The table grows with every `add`, and a person reading the file wants to see
419
+ * the settings they chose above the bookkeeping they did not.
420
+ */
421
+ function writeConfig(root, config) {
422
+ const ordered = {
423
+ ...config.$schema === void 0 ? {} : { $schema: config.$schema },
424
+ ...config.registry === void 0 ? {} : { registry: config.registry },
425
+ ...Object.keys(config.registries).length === 0 ? {} : { registries: Object.fromEntries(Object.entries(config.registries).toSorted(([a], [b]) => a.localeCompare(b)).map(([scope, endpoint]) => [scope, Object.keys(endpoint.headers).length === 0 ? endpoint.url : endpoint])) },
426
+ paths: config.paths,
427
+ theme: config.theme,
428
+ reset: config.reset,
429
+ items: Object.fromEntries(Object.entries(config.items).toSorted(([a], [b]) => a.localeCompare(b)).map(([name, files]) => [name, Object.fromEntries(Object.entries(files).toSorted(([a], [b]) => a.localeCompare(b)))]))
430
+ };
431
+ writeFileSync(join(root, CONFIG_FILE), `${JSON.stringify(ordered, null, 2)}\n`);
432
+ }
433
+ /** The config, or an error naming the command that would create one. */
434
+ function requireConfig(cwd) {
435
+ const root = findRoot(cwd);
436
+ if (root === void 0) throw new Error(`no ${CONFIG_FILE} here or above. Run \`barq-ui init\` first.`);
437
+ return {
438
+ root,
439
+ config: readConfig(root)
440
+ };
441
+ }
442
+ // src/project.ts
443
+ /**
444
+ * What the project already has, and the package manager that gives it more.
445
+ *
446
+ * The manager is read from the LOCKFILE, nearest first, because that is the one
447
+ * fact a project states about itself: a pnpm workspace invoked through `npx`
448
+ * still wants `pnpm add`. What ran this process is the fallback, for a project
449
+ * that has not installed anything yet.
450
+ */
451
+ function installedPackages(root) {
452
+ const path = join(root, "package.json");
453
+ if (!existsSync(path)) return /* @__PURE__ */ new Set();
454
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
455
+ const out = /* @__PURE__ */ new Set();
456
+ for (const field of [
457
+ "dependencies",
458
+ "devDependencies",
459
+ "peerDependencies"
460
+ ]) {
461
+ const entry = manifest[field];
462
+ if (typeof entry !== "object" || entry === null) continue;
463
+ for (const name of Object.keys(entry)) out.add(name);
464
+ }
465
+ return out;
466
+ }
467
+ const LOCKFILES = [
468
+ ["bun.lock", "bun"],
469
+ ["bun.lockb", "bun"],
470
+ ["pnpm-lock.yaml", "pnpm"],
471
+ ["yarn.lock", "yarn"],
472
+ ["package-lock.json", "npm"]
473
+ ];
474
+ /** `npm_config_user_agent` is set by all four, and names the one that ran us. */
475
+ function fromUserAgent() {
476
+ const name = process.env["npm_config_user_agent"]?.split(" ")[0]?.split("/")[0];
477
+ return name === "bun" || name === "pnpm" || name === "yarn" || name === "npm" ? name : void 0;
478
+ }
479
+ /**
480
+ * Walks up from `root`, because a workspace keeps its one lockfile at the top
481
+ * and the package a component is added to is somewhere under it.
482
+ */
483
+ function packageManager(root) {
484
+ let directory = resolve(root);
485
+ for (;;) {
486
+ for (const [file, name] of LOCKFILES) if (existsSync(join(directory, file))) return name;
487
+ const parent = dirname(directory);
488
+ if (parent === directory) break;
489
+ directory = parent;
490
+ }
491
+ return fromUserAgent() ?? "npm";
492
+ }
493
+ /** The command as its arguments, which is what runs it and what prints it. */
494
+ function installArguments(manager, packages, options = {}) {
495
+ return [
496
+ manager,
497
+ manager === "npm" ? "install" : "add",
498
+ ...options.dev === true ? ["-D"] : [],
499
+ ...packages
500
+ ];
501
+ }
502
+ function installCommand(root, packages, options = {}) {
503
+ return installArguments(packageManager(root), packages, options).join(" ");
504
+ }
505
+ /**
506
+ * Runs the install in the project, with the manager's own output on the
507
+ * terminal: a resolution failure is that tool's to explain.
508
+ */
509
+ function install(root, packages, options = {}) {
510
+ const [command, ...args] = installArguments(packageManager(root), packages, options);
511
+ const result = spawnSync(command, args, {
512
+ cwd: root,
513
+ stdio: "inherit",
514
+ shell: process.platform === "win32"
515
+ });
516
+ if (result.error !== void 0) throw new Error(`could not run ${command}: ${result.error.message}\nRun it yourself: ${[command, ...args].join(" ")}`);
517
+ if (result.status !== 0) throw new Error(`${[command, ...args].join(" ")} exited with ${String(result.status)}.\nThe files were written; the packages were not installed.`);
518
+ }
519
+ // src/registry.ts
520
+ /**
521
+ * Where an item comes from, and what else it needs.
522
+ *
523
+ * Every registry is a pattern with `{name}` in it, a URL or a path, serving one
524
+ * JSON file per item plus `index.json`. The project's own registry is
525
+ * `registry` in `components.json`; without one it is this CLI's own release of
526
+ * `@barqjs/ui`, read from the repository at the tag the CLI was published
527
+ * under, so a CLI and the components it writes always come from one commit.
528
+ *
529
+ * `registries` in `components.json` names more of them, and an item from one
530
+ * is addressed as `@scope/name`.
531
+ */
532
+ /** Replaces the default registry, for a fork, a mirror or a local build. */
533
+ const REGISTRY_ENV = "BARQ_UI_REGISTRY";
534
+ function ownVersion() {
535
+ const manifest = new URL("../package.json", import.meta.url);
536
+ return JSON.parse(readFileSync(manifest, "utf8")).version;
537
+ }
538
+ function defaultRegistry() {
539
+ const override = process.env[REGISTRY_ENV];
540
+ if (override !== void 0 && override !== "") return override;
541
+ return `https://raw.githubusercontent.com/salamaashoush/barq/refs/tags/@barqjs/ui-cli@${ownVersion()}/packages/ui/registry/{name}.json`;
542
+ }
543
+ /** `${NAME}` from the environment, so a token never has to be written down. */
544
+ function expand(value, where) {
545
+ return value.replaceAll(/\$\{(\w+)\}/g, (_whole, name) => {
546
+ const found = process.env[name];
547
+ if (found === void 0) throw new Error(`${where} reads \${${name}}, which is not set`);
548
+ return found;
549
+ });
550
+ }
551
+ /**
552
+ * A registry behind a pattern with `{name}` in it: a URL, or a path.
553
+ *
554
+ * A path is what `build` leaves behind, so a registry can be used from the
555
+ * directory it was built into before anything serves it.
556
+ */
557
+ function fromPattern(endpoint, cwd, where) {
558
+ const remote = /^https?:\/\//.test(endpoint.url);
559
+ const at = (name) => {
560
+ const filled = expand(endpoint.url, where).replaceAll("{name}", name);
561
+ return remote ? filled : resolve(cwd, filled);
562
+ };
563
+ const get = async (name) => {
564
+ const location = at(name);
565
+ if (!remote) {
566
+ if (!existsSync(location)) throw new Error(`no item named "${name}" at ${location}`);
567
+ return JSON.parse(readFileSync(location, "utf8"));
568
+ }
569
+ const response = await fetch(location, { headers: Object.fromEntries(Object.entries(endpoint.headers).map(([key, value]) => [key, expand(value, where)])) });
570
+ if (!response.ok) throw new Error(`${location} answered ${String(response.status)} ${response.statusText}`);
571
+ return await response.json();
572
+ };
573
+ return {
574
+ describe: endpoint.url,
575
+ index: async () => parseIndex(await get("index")),
576
+ item: async (name) => parseItem(await get(name), name),
577
+ data: get
578
+ };
579
+ }
580
+ function sourceFor(config, cwd) {
581
+ return config.registry === void 0 ? fromPattern({
582
+ url: defaultRegistry(),
583
+ headers: {}
584
+ }, cwd, REGISTRY_ENV) : fromPattern({
585
+ url: config.registry,
586
+ headers: {}
587
+ }, cwd, "components.json.registry");
588
+ }
589
+ /**
590
+ * The project's registry and the ones it names, each opened when first asked for,
591
+ * so a project that only ever adds `@acme/…` never reads the default one.
592
+ */
593
+ function registriesFor(config, cwd) {
594
+ const opened = /* @__PURE__ */ new Map();
595
+ const source = (scope) => {
596
+ const key = scope ?? "";
597
+ const found = opened.get(key);
598
+ if (found !== void 0) return found;
599
+ let made;
600
+ if (scope === void 0) made = sourceFor(config, cwd);
601
+ else {
602
+ const endpoint = config.registries[scope];
603
+ if (endpoint === void 0) {
604
+ const known = Object.keys(config.registries).toSorted();
605
+ throw new Error(`no registry named "${scope}" in components.json.` + (known.length === 0 ? " Add it under `registries`." : ` It has: ${known.join(", ")}`));
606
+ }
607
+ made = fromPattern(endpoint, cwd, `components.json.registries.${scope}`);
608
+ }
609
+ opened.set(key, made);
610
+ return made;
611
+ };
612
+ return {
613
+ scopes: Object.keys(config.registries).toSorted(),
614
+ source,
615
+ locate(address) {
616
+ if (!address.startsWith("@")) return {
617
+ source: source(),
618
+ name: address
619
+ };
620
+ const split = address.indexOf("/");
621
+ const scope = split < 0 ? address : address.slice(0, split);
622
+ const found = source(scope);
623
+ if (split < 0 || split === address.length - 1) throw new Error(`"${address}" names a registry and no item in it`);
624
+ return {
625
+ source: found,
626
+ name: address.slice(split + 1)
627
+ };
628
+ }
629
+ };
630
+ }
631
+ /**
632
+ * Every item these addresses need, dependencies first.
633
+ *
634
+ * Depth-first with a seen set, so a diamond — `dialog` and `sheet` both wanting
635
+ * `button` — resolves once, and a cycle terminates rather than recursing until
636
+ * the stack goes.
637
+ *
638
+ * An item from a named registry is recorded under its whole address, so
639
+ * `@acme/button` and the project's own `button` are two items rather than one
640
+ * overwriting the other. A bare dependency always means the project's own
641
+ * registry, whichever registry the item asking for it came from.
642
+ */
643
+ async function resolveItems(registries, addresses) {
644
+ const seen = /* @__PURE__ */ new Set();
645
+ const out = [];
646
+ const visit = async (address) => {
647
+ if (seen.has(address)) return;
648
+ seen.add(address);
649
+ const { source, name } = registries.locate(address);
650
+ const item = await source.item(name);
651
+ for (const dependency of item.registryDependencies) await visit(dependency);
652
+ out.push(item.name === address ? item : {
653
+ ...item,
654
+ name: address
655
+ });
656
+ };
657
+ for (const address of addresses) await visit(address);
658
+ return out;
659
+ }
660
+ // src/theme.ts
661
+ /**
662
+ * A chosen radius REPLACES the base's own, rather than following it.
663
+ *
664
+ * Every base declares `radius` among its tokens, so appending wrote `--radius`
665
+ * twice. The cascade took the second one and the page was right, but the file
666
+ * is the project's to read and edit and said two different things.
667
+ */
668
+ function declarations(tokens, radius, indent) {
669
+ const all = radius === void 0 ? tokens : {
670
+ ...tokens,
671
+ radius
672
+ };
673
+ return Object.entries(all).map(([token, value]) => `${indent}--${token}: ${value};`).join("\n");
674
+ }
675
+ /**
676
+ * Rules as CSS text, nested the way the object is.
677
+ *
678
+ * A string is a declaration's value and an object is a rule, so
679
+ * `{ "@keyframes spin": { to: { rotate: "360deg" } } }` is written as it reads.
680
+ */
681
+ function rules(css, indent) {
682
+ return Object.entries(css).map(([key, value]) => typeof value === "string" ? `${indent}${key}: ${value};` : `${indent}${key} {\n${rules(value, `${indent} `)}\n${indent}}`).join("\n");
683
+ }
684
+ /**
685
+ * What one more item's `cssVars` and `css` make of what the project has.
686
+ *
687
+ * Later wins, token by token and rule by rule, which is the cascade's own
688
+ * answer and the one a person adding a second item over a first expects.
689
+ */
690
+ function withItemCss(choice, added) {
691
+ const bare = (tokens) => Object.fromEntries(Object.entries(tokens ?? {}).map(([token, value]) => [token.replace(/^--/, ""), value]));
692
+ const vars = added.cssVars;
693
+ const merged = {
694
+ theme: {
695
+ ...choice.cssVars?.theme,
696
+ ...bare(vars?.theme)
697
+ },
698
+ light: {
699
+ ...choice.cssVars?.light,
700
+ ...bare(vars?.light)
701
+ },
702
+ dark: {
703
+ ...choice.cssVars?.dark,
704
+ ...bare(vars?.dark)
705
+ }
706
+ };
707
+ const some = (tokens) => tokens !== void 0 && Object.keys(tokens).length > 0;
708
+ const kept = {
709
+ ...some(merged.theme) ? { theme: merged.theme } : {},
710
+ ...some(merged.light) ? { light: merged.light } : {},
711
+ ...some(merged.dark) ? { dark: merged.dark } : {}
712
+ };
713
+ const css = mergeRules(choice.css ?? {}, added.css ?? {});
714
+ return {
715
+ ...choice,
716
+ ...Object.keys(kept).length > 0 ? { cssVars: kept } : {},
717
+ ...Object.keys(css).length > 0 ? { css } : {}
718
+ };
719
+ }
720
+ function mergeRules(base, over) {
721
+ const out = { ...base };
722
+ for (const [key, value] of Object.entries(over)) {
723
+ const had = out[key];
724
+ out[key] = typeof value === "string" || typeof had !== "object" ? value : mergeRules(had, value);
725
+ }
726
+ return out;
727
+ }
728
+ /**
729
+ * A length, or a function that produces one.
730
+ *
731
+ * `--radius` is written into the project's own stylesheet, where a typo is a
732
+ * corner that silently stops being round. The units are CSS's absolute and
733
+ * relative lengths; the functions are the four that can stand where a length
734
+ * can, plus `var`, because a project layering this over tokens of its own is
735
+ * the case the plain token names exist for.
736
+ */
737
+ const LENGTH = /^(?:0|[+-]?(?:\d+\.?\d*|\.\d+)(?:px|rem|em|ex|ch|vw|vh|vmin|vmax|cm|mm|in|pt|pc|q)|(?:calc|clamp|min|max|var)\(.*\))$/i;
738
+ function names(themes, kind) {
739
+ return themes.filter((theme) => theme.kind === kind).map((theme) => theme.name).join(", ");
740
+ }
741
+ /**
742
+ * The chosen pair, looked up, or an error naming what does exist.
743
+ *
744
+ * Separate from `themeModule` so a caller can check a selection BEFORE it acts
745
+ * on it. `init` writes four files before it reaches the theme, and a mistyped
746
+ * `--theme` used to leave all four on disk with no `components.json` beside
747
+ * them — a project too far in to `add` to and too far in for `init` to be the
748
+ * first thing you run.
749
+ */
750
+ function resolveTheme(choice, themes) {
751
+ const base = themes.find((theme) => theme.name === choice.base && theme.kind === "base");
752
+ if (base === void 0) throw new Error(`no base theme named "${choice.base}". Try one of: ${names(themes, "base")}`);
753
+ const accent = choice.accent === void 0 ? void 0 : themes.find((theme) => theme.name === choice.accent && theme.kind === "accent");
754
+ if (choice.accent !== void 0 && accent === void 0) throw new Error(`no accent theme named "${choice.accent}". Try one of: ${names(themes, "accent")}`);
755
+ if (choice.radius !== void 0 && !LENGTH.test(choice.radius)) throw new Error(`--radius wants a CSS length, like 0.5rem or 8px, not "${choice.radius}"`);
756
+ return {
757
+ base,
758
+ ...accent === void 0 ? {} : { accent },
759
+ title: accent === void 0 ? base.title : `${base.title} with ${accent.title}`
760
+ };
761
+ }
762
+ function themeModule(choice, themes, options) {
763
+ const { base, accent, title } = resolveTheme(choice, themes);
764
+ const light = {
765
+ ...base.light,
766
+ ...accent?.light,
767
+ ...choice.cssVars?.theme,
768
+ ...choice.cssVars?.light
769
+ };
770
+ const dark = {
771
+ ...base.dark,
772
+ ...accent?.dark,
773
+ ...choice.cssVars?.dark
774
+ };
775
+ const darkSelector = choice.dark ?? ".dark";
776
+ const extra = choice.css === void 0 ? "" : `\n@layer barq.theme {\n${rules(choice.css, " ")}\n}`;
777
+ const darkRule = darkSelector === "media" ? ` @media (prefers-color-scheme: dark) {\n :root {\n${declarations(dark, void 0, " ")}\n }\n }` : ` ${darkSelector} {\n${declarations(dark, void 0, " ")}\n }`;
778
+ return `/**
779
+ * The colour theme: ${title}.
780
+ *
781
+ * Written by \`barq-ui init\`, and yours to edit. The barq compiler folds this
782
+ * block into a stylesheet at build time, so nothing here reaches the browser as
783
+ * JavaScript.
784
+ *
785
+ * To change theme, run \`barq-ui theme <name>\` — or edit the values, which is
786
+ * what they are here for.
787
+ */
788
+
789
+ import { globalCss } from "@barqjs/css";
790
+
791
+ import ${JSON.stringify(options.base)};
792
+ ${options.reset ? `import ${JSON.stringify(options.resetPath)};\n` : ""}
793
+ globalCss\`
794
+ @layer barq.theme {
795
+ :root {
796
+ ${declarations(light, choice.radius, " ")}
797
+ }
798
+ ${darkRule}
799
+ }${extra}
800
+ \`;
801
+ `;
802
+ }
803
+ // src/diff.ts
804
+ /** The edit script turning `before` into `after`. */
805
+ function diffLines(before, after) {
806
+ const n = before.length;
807
+ const m = after.length;
808
+ const max = n + m;
809
+ const trace = [];
810
+ let v = /* @__PURE__ */ new Map([[1, 0]]);
811
+ for (let d = 0; d <= max; d++) {
812
+ trace.push(new Map(v));
813
+ for (let k = -d; k <= d; k += 2) {
814
+ let x = k === -d || k !== d && (v.get(k - 1) ?? 0) < (v.get(k + 1) ?? 0) ? v.get(k + 1) ?? 0 : (v.get(k - 1) ?? 0) + 1;
815
+ let y = x - k;
816
+ while (x < n && y < m && before[x] === after[y]) {
817
+ x++;
818
+ y++;
819
+ }
820
+ v.set(k, x);
821
+ if (x >= n && y >= m) return walk(trace, before, after, d);
822
+ }
823
+ v = new Map(v);
824
+ }
825
+ return [];
826
+ }
827
+ function walk(trace, before, after, end) {
828
+ const out = [];
829
+ let x = before.length;
830
+ let y = after.length;
831
+ for (let d = end; d > 0; d--) {
832
+ const v = trace[d];
833
+ const k = x - y;
834
+ const down = k === -d || k !== d && (v.get(k - 1) ?? 0) < (v.get(k + 1) ?? 0);
835
+ const previousK = down ? k + 1 : k - 1;
836
+ const previousX = v.get(previousK) ?? 0;
837
+ const previousY = previousX - previousK;
838
+ while (x > previousX && y > previousY) {
839
+ out.push({
840
+ op: "keep",
841
+ line: before[--x]
842
+ });
843
+ y--;
844
+ }
845
+ if (down) out.push({
846
+ op: "add",
847
+ line: after[--y]
848
+ });
849
+ else out.push({
850
+ op: "remove",
851
+ line: before[--x]
852
+ });
853
+ }
854
+ while (x > 0 && y > 0) {
855
+ out.push({
856
+ op: "keep",
857
+ line: before[--x]
858
+ });
859
+ y--;
860
+ }
861
+ return out.toReversed();
862
+ }
863
+ /**
864
+ * The changes as a unified diff, with the runs of untouched lines collapsed.
865
+ *
866
+ * A component is mostly untouched, so printing every line would bury the three
867
+ * that moved.
868
+ */
869
+ function unified(before, after, options = {}) {
870
+ const context = options.context ?? 3;
871
+ const changes = diffLines(before.split("\n"), after.split("\n"));
872
+ if (!changes.some((change) => change.op !== "keep")) return "";
873
+ const keep = /* @__PURE__ */ new Set();
874
+ changes.forEach((change, index) => {
875
+ if (change.op === "keep") return;
876
+ for (let at = index - context; at <= index + context; at++) keep.add(at);
877
+ });
878
+ const out = [];
879
+ let skipping = false;
880
+ changes.forEach((change, index) => {
881
+ if (!keep.has(index)) {
882
+ if (!skipping) out.push(" ...");
883
+ skipping = true;
884
+ return;
885
+ }
886
+ skipping = false;
887
+ out.push(`${change.op === "add" ? "+ " : change.op === "remove" ? "- " : " "}${change.line}`);
888
+ });
889
+ return out.join("\n");
890
+ }
891
+ // src/tty.ts
892
+ /**
893
+ * Writing to a terminal, and asking it a question.
894
+ *
895
+ * No colour library and no prompt library: six escape codes are the whole of
896
+ * what this needs, and `readline/promises` asks a question in three lines. A
897
+ * package a person downloads in order to write eight files should not download
898
+ * eight of its own first.
899
+ */
900
+ const CSI = "\x1B[";
901
+ /** `NO_COLOR` is the convention every tool honours, and a pipe is not a terminal. */
902
+ const styled = stdout.isTTY && process.env["NO_COLOR"] === void 0;
903
+ const code = (open) => styled ? (text) => `${CSI}${open}m${text}${CSI}0m` : (text) => text;
904
+ const dim = code("2");
905
+ const bold = code("1");
906
+ const green = code("32");
907
+ const red = code("31");
908
+ const yellow = code("33");
909
+ const cyan = code("36");
910
+ function say(line = "") {
911
+ stdout.write(`${line}\n`);
912
+ }
913
+ /** A diff, coloured. The marker in column one is what carries it without colour. */
914
+ function paint(diff) {
915
+ return diff.split("\n").map((line) => line.startsWith("+") ? green(line) : line.startsWith("-") ? red(line) : dim(line)).join("\n");
916
+ }
917
+ /**
918
+ * What one answer to a `choose` list means, or `undefined` to ask again.
919
+ *
920
+ * Separate from the reading so it can be tested without a terminal: this is
921
+ * where a list prompt is actually wrong or right, and the half above it is
922
+ * three lines of `readline`.
923
+ *
924
+ * A number picks a line and a name picks itself, because a person reading
925
+ * `1 Neutral` reasonably types either. An empty answer is the default, which
926
+ * is what makes the whole prompt skippable.
927
+ */
928
+ function pick(answer, options, fallback) {
929
+ const trimmed = answer.trim();
930
+ if (trimmed === "") return fallback;
931
+ const index = Number(trimmed);
932
+ if (Number.isInteger(index) && index >= 1 && index <= options.length) return options[index - 1]?.value;
933
+ return options.find((option) => option.value === trimmed)?.value;
934
+ }
935
+ /**
936
+ * Piped into a script there is nowhere to prompt, so every question takes its
937
+ * default. That is what makes `--yes` unnecessary in CI rather than merely
938
+ * available.
939
+ *
940
+ * `allowed` is the CALLER's opinion — `--yes` says do not ask — and it is
941
+ * ANDed with whether there is a terminal to ask on. Trusting the caller alone
942
+ * hung: `sync` in a pipeline opened a readline on a stdin that would never
943
+ * answer.
944
+ */
945
+ function ask(allowed = true) {
946
+ const rl = allowed && stdin.isTTY ? createInterface({
947
+ input: stdin,
948
+ output: stdout
949
+ }) : null;
950
+ return {
951
+ async question(text, fallback) {
952
+ if (rl === null) return fallback;
953
+ const answer = (await rl.question(`${text} ${dim(`(${fallback})`)} `)).trim();
954
+ return answer === "" ? fallback : answer;
955
+ },
956
+ async confirm(text, fallback) {
957
+ if (rl === null) return fallback;
958
+ const answer = (await rl.question(`${text} ${dim(fallback ? "(Y/n)" : "(y/N)")} `)).trim().toLowerCase();
959
+ if (answer === "") return fallback;
960
+ return answer.startsWith("y");
961
+ },
962
+ async choose(text, options, fallback) {
963
+ if (rl === null) return fallback;
964
+ const width = String(options.length).length;
965
+ say(text);
966
+ for (const [index, option] of options.entries()) {
967
+ const number = String(index + 1).padStart(width);
968
+ say(` ${option.value === fallback ? cyan("›") : " "} ${dim(number)} ${option.label}`);
969
+ }
970
+ for (;;) {
971
+ const chosen = pick(await rl.question(`Which? ${dim(`(${fallback})`)} `), options, fallback);
972
+ if (chosen !== void 0) return chosen;
973
+ say(red(` Not one of them. A number from 1 to ${String(options.length)}.`));
974
+ }
975
+ },
976
+ close() {
977
+ rl?.close();
978
+ }
979
+ };
980
+ }
981
+ // src/index.ts
982
+ /**
983
+ * `barq-ui` — copy barq's components into a project, and keep them in
984
+ * sync with the registry they came from.
985
+ *
986
+ * NO DEPENDENCIES. The argument parsing, the prompts, the diff and the schema
987
+ * checks are each smaller than the library that would do them, and a tool
988
+ * someone runs once to write eight files should not download eight of its own
989
+ * first. `create-barq` in this repository makes the same trade for the same
990
+ * reason.
991
+ *
992
+ * ## What `sync` is, and why it is not `add` again
993
+ *
994
+ * shadcn's `diff` shows what upstream changed and leaves the applying to you,
995
+ * because it cannot tell an edited file from an untouched one. `init` and `add`
996
+ * here record a hash per file, so `sync` can: an untouched file is replaced
997
+ * without asking, an edited one is shown as a diff and kept unless you say
998
+ * otherwise. Owning the code means the edit wins by default.
999
+ */
1000
+ const HELP = `\
1001
+ Usage: barq-ui <command> [options]
1002
+
1003
+ init set up ${CONFIG_FILE}, the theme and the base styles
1004
+ add <name...> add components and blocks, with whatever they need
1005
+ diff [name...] what the registry has that your copy does not
1006
+ sync [name...] take the registry's version, keeping your edits
1007
+ list what the registry offers
1008
+ search <query> find items by name, description or category
1009
+ view <name...> print items as the registry serves them
1010
+ info what this project is set up with
1011
+ theme <name> change the colour theme
1012
+ style <name> change the component style
1013
+ build <dir> turn a directory of components into a registry
1014
+
1015
+ A name is an item in the project's registry, or @scope/name for one of the
1016
+ registries ${CONFIG_FILE} lists. Without a \`registry\` in ${CONFIG_FILE}, items
1017
+ come from the @barqjs/ui release this CLI belongs to; ${REGISTRY_ENV} replaces it.
1018
+
1019
+ Options:
1020
+ -c, --cwd <dir> where the project is. Defaults to here
1021
+ --overwrite replace a file you have edited
1022
+ --yes take every default without asking
1023
+ --no-install print the install command instead of running it
1024
+ --all add: every ui component the registry has
1025
+ --dry-run add: say what would be written, and write nothing
1026
+ --diff[=<file>] add: show what would change, and write nothing
1027
+ --view[=<file>] add: show what would be written, and write nothing
1028
+ --json search, info: print JSON
1029
+ --path <dir> init: where components go
1030
+ --registry <url> init: a registry URL containing {name}
1031
+ --style <name> init: the component style (vega, nova, lyra, …)
1032
+ --theme <name> init: the base colour theme
1033
+ --accent <name> init: an accent over it
1034
+ --radius <len> init: --radius
1035
+ --dark <sel> init: the dark-mode selector, or "media"
1036
+ --no-reset init: do not install the CSS reset
1037
+ -h, --help show this
1038
+ `;
1039
+ function parse(argv) {
1040
+ const rest = [];
1041
+ let command;
1042
+ let cwd = process.cwd();
1043
+ let overwrite = false;
1044
+ let yes = false;
1045
+ let reset = true;
1046
+ let path;
1047
+ let registry;
1048
+ let style;
1049
+ let theme;
1050
+ let accent;
1051
+ let radius;
1052
+ let dark;
1053
+ let help = false;
1054
+ let install_ = true;
1055
+ let all = false;
1056
+ let dryRun = false;
1057
+ let diff;
1058
+ let viewing;
1059
+ let json = false;
1060
+ const value = (index, flag) => {
1061
+ const next = argv[index];
1062
+ if (next === void 0) throw new Error(`${flag} needs a value`);
1063
+ return next;
1064
+ };
1065
+ for (let index = 0; index < argv.length; index++) {
1066
+ const arg = argv[index] ?? "";
1067
+ if (arg === "-h" || arg === "--help") help = true;
1068
+ else if (arg === "--overwrite") overwrite = true;
1069
+ else if (arg === "-y" || arg === "--yes") yes = true;
1070
+ else if (arg === "--no-reset") reset = false;
1071
+ else if (arg === "--no-install") install_ = false;
1072
+ else if (arg === "-a" || arg === "--all") all = true;
1073
+ else if (arg === "--dry-run") dryRun = true;
1074
+ else if (arg === "--json") json = true;
1075
+ else if (arg === "--diff") diff = true;
1076
+ else if (arg === "--view") viewing = true;
1077
+ else if (arg.startsWith("--diff=")) diff = arg.slice(7);
1078
+ else if (arg.startsWith("--view=")) viewing = arg.slice(7);
1079
+ else if (arg === "-c" || arg === "--cwd") cwd = value(++index, arg);
1080
+ else if (arg === "--path") path = value(++index, arg);
1081
+ else if (arg === "--registry") registry = value(++index, arg);
1082
+ else if (arg === "--style") style = value(++index, arg);
1083
+ else if (arg === "--theme") theme = value(++index, arg);
1084
+ else if (arg === "--accent") accent = value(++index, arg);
1085
+ else if (arg === "--radius") radius = value(++index, arg);
1086
+ else if (arg === "--dark") dark = value(++index, arg);
1087
+ else if (arg.startsWith("--")) {
1088
+ const split = arg.indexOf("=");
1089
+ if (split < 0) throw new Error(`unknown option ${arg}`);
1090
+ argv = [
1091
+ ...argv.slice(0, index),
1092
+ arg.slice(0, split),
1093
+ arg.slice(split + 1),
1094
+ ...argv.slice(index + 1)
1095
+ ];
1096
+ index--;
1097
+ } else if (command === void 0) command = arg;
1098
+ else rest.push(arg);
1099
+ }
1100
+ return {
1101
+ command,
1102
+ rest,
1103
+ cwd: resolve(cwd),
1104
+ overwrite,
1105
+ yes,
1106
+ reset,
1107
+ path,
1108
+ registry,
1109
+ style,
1110
+ theme,
1111
+ accent,
1112
+ radius,
1113
+ dark,
1114
+ help,
1115
+ install: install_,
1116
+ all,
1117
+ dryRun,
1118
+ diff,
1119
+ view: viewing,
1120
+ json
1121
+ };
1122
+ }
1123
+ const MARK = {
1124
+ written: green("+"),
1125
+ replaced: cyan("~"),
1126
+ unchanged: dim("="),
1127
+ kept: yellow("!")
1128
+ };
1129
+ function report(files) {
1130
+ const interesting = files.filter((file) => file.outcome !== "unchanged");
1131
+ if (interesting.length === 0) {
1132
+ say(dim("Everything was already up to date."));
1133
+ return;
1134
+ }
1135
+ for (const file of interesting) say(` ${MARK[file.outcome]} ${file.path}`);
1136
+ const kept = files.filter((file) => file.outcome === "kept");
1137
+ if (kept.length > 0) {
1138
+ say();
1139
+ say(yellow(`${String(kept.length)} file${kept.length === 1 ? "" : "s"} you have edited ${kept.length === 1 ? "was" : "were"} left alone.`));
1140
+ say(dim("`barq-ui diff` shows what the registry has; `--overwrite` takes it."));
1141
+ }
1142
+ }
1143
+ /**
1144
+ * The packages the items import that the project does not have: installed, or
1145
+ * with `--no-install` named so a person can.
1146
+ */
1147
+ function settle(root, items, installing) {
1148
+ const installed = installedPackages(root);
1149
+ const runtime = missingDependencies(items, installed);
1150
+ const development = missingDependencies(items, installed, "devDependencies");
1151
+ if (runtime.length === 0 && development.length === 0) return;
1152
+ say();
1153
+ if (!installing) {
1154
+ say(bold("Install what they need:"));
1155
+ if (runtime.length > 0) say(` ${installCommand(root, runtime)}`);
1156
+ if (development.length > 0) say(` ${installCommand(root, development, { dev: true })}`);
1157
+ return;
1158
+ }
1159
+ say(bold("Installing what they need:"));
1160
+ if (runtime.length > 0) install(root, runtime);
1161
+ if (development.length > 0) install(root, development, { dev: true });
1162
+ }
1163
+ /**
1164
+ * What a list answers with when the answer is "leave it alone".
1165
+ *
1166
+ * A prompt has to return a string, and the config's `accent` and `radius` are
1167
+ * both absent rather than empty when they are not chosen — an empty `--radius`
1168
+ * would write `--radius: ;`.
1169
+ */
1170
+ const NONE = "";
1171
+ const NO_ACCENT = {
1172
+ value: NONE,
1173
+ label: dim("None, the base's own colours")
1174
+ };
1175
+ /** shadcn's own four, plus leaving whatever the base declares. */
1176
+ const RADII = [
1177
+ {
1178
+ value: NONE,
1179
+ label: dim("The theme's own")
1180
+ },
1181
+ {
1182
+ value: "0",
1183
+ label: "None"
1184
+ },
1185
+ {
1186
+ value: "0.45rem",
1187
+ label: "Small"
1188
+ },
1189
+ {
1190
+ value: "0.625rem",
1191
+ label: "Medium"
1192
+ },
1193
+ {
1194
+ value: "0.875rem",
1195
+ label: "Large"
1196
+ }
1197
+ ];
1198
+ function blank(answer) {
1199
+ return answer === NONE ? void 0 : answer;
1200
+ }
1201
+ /** The styles the registry serves, read rather than listed. */
1202
+ async function styles(source) {
1203
+ return (await source.data("styles")).toSorted().map((name) => ({
1204
+ value: name,
1205
+ label: name[0]?.toUpperCase() + name.slice(1)
1206
+ }));
1207
+ }
1208
+ /**
1209
+ * The chosen style, copied into the project beside the theme: what the tool
1210
+ * writes is yours, and a style is ordinary CSS you may want to edit.
1211
+ */
1212
+ async function writeStyle(root, config, name, source) {
1213
+ const { css } = await source.data(`style-${name}`);
1214
+ const target = targetOf(config, root, {
1215
+ path: "theme/style.css",
1216
+ type: "registry:theme",
1217
+ content: ""
1218
+ });
1219
+ writeFileSync(target, css);
1220
+ return target;
1221
+ }
1222
+ async function themes(source) {
1223
+ return await source.data("themes");
1224
+ }
1225
+ async function init(args) {
1226
+ const prompt = ask(!args.yes);
1227
+ try {
1228
+ const source = sourceFor(parseConfig(args.registry === void 0 ? {} : { registry: args.registry }), args.cwd);
1229
+ const table = await themes(source);
1230
+ const options = (kind) => table.filter((theme) => theme.kind === kind).map((theme) => ({
1231
+ value: theme.name,
1232
+ label: theme.title
1233
+ }));
1234
+ const path = args.path ?? await prompt.question("Where do components go?", DEFAULT_PATHS.ui);
1235
+ const available = await styles(source);
1236
+ const style = args.style ?? (available.length === 0 ? void 0 : blank(await prompt.choose("Component style?", [{
1237
+ value: NONE,
1238
+ label: dim("None, the components' own look")
1239
+ }, ...available], NONE)));
1240
+ const base = args.theme ?? await prompt.choose("Colour theme?", options("base"), "neutral");
1241
+ const accent = args.accent ?? blank(await prompt.choose("An accent over it?", [NO_ACCENT, ...options("accent")], NONE));
1242
+ const radius = args.radius ?? blank(await prompt.choose("Corner radius?", RADII, NONE));
1243
+ const reset = args.reset && await prompt.confirm("Install the CSS reset?", true);
1244
+ const root = args.cwd;
1245
+ const parent = path.replace(/\/ui$/, "");
1246
+ const config = parseConfig({
1247
+ ...args.registry === void 0 ? {} : { registry: args.registry },
1248
+ paths: {
1249
+ ui: path,
1250
+ lib: path.endsWith("/ui") ? `${parent}/lib` : `${path}/lib`,
1251
+ theme: path.endsWith("/ui") ? `${parent}/theme` : `${path}/theme`
1252
+ },
1253
+ theme: {
1254
+ ...style === void 0 ? {} : { style },
1255
+ base,
1256
+ ...accent === void 0 ? {} : { accent },
1257
+ ...radius === void 0 ? {} : { radius },
1258
+ ...args.dark === void 0 ? {} : { dark: args.dark }
1259
+ },
1260
+ reset,
1261
+ items: {}
1262
+ });
1263
+ resolveTheme(config.theme, table);
1264
+ if (style !== void 0 && !available.some((each) => each.value === style)) throw new Error(`no style named "${style}". Try one of: ${available.map((each) => each.value).join(", ")}`);
1265
+ const wanted = [
1266
+ "base",
1267
+ "layers",
1268
+ ...config.reset ? ["reset"] : [],
1269
+ "utils"
1270
+ ];
1271
+ const items = await resolveItems(registriesFor(config, root), wanted);
1272
+ const applied = applyItems(config, root, items);
1273
+ const themeFile = themeTarget(config, root);
1274
+ const module_ = themeModule(config.theme, table, {
1275
+ reset: config.reset,
1276
+ base: "./base.ts",
1277
+ resetPath: "./reset.ts"
1278
+ });
1279
+ write(themeFile, module_);
1280
+ const styleFile = style === void 0 ? void 0 : await writeStyle(root, config, style, source);
1281
+ writeConfig(root, {
1282
+ ...applied.config,
1283
+ items: {
1284
+ ...applied.config.items,
1285
+ theme: { [THEME_KEY]: hashOf(module_) }
1286
+ }
1287
+ });
1288
+ say(`${green("Set up")} ${bold(CONFIG_FILE)} and the theme.`);
1289
+ report([...applied.files, {
1290
+ item: "theme",
1291
+ path: themeFile.slice(root.length + 1),
1292
+ absolute: themeFile,
1293
+ outcome: "written",
1294
+ hash: hashOf(module_),
1295
+ incoming: module_
1296
+ }]);
1297
+ say();
1298
+ say(bold("Import the theme once, at your application's entry:"));
1299
+ say(` import "./${config.paths.theme.replace(/^(\.\/)?/, "")}/theme.ts";`);
1300
+ if (styleFile !== void 0 && style !== void 0) {
1301
+ say();
1302
+ say(bold("And the style, with its class on the element it applies to:"));
1303
+ say(` import "./${config.paths.theme.replace(/^(\.\/)?/, "")}/style.css";`);
1304
+ say(` <html class="style-${style}">`);
1305
+ }
1306
+ settle(root, items, args.install);
1307
+ say();
1308
+ say(`Then: ${cyan("barq-ui add button card")}`);
1309
+ } finally {
1310
+ prompt.close();
1311
+ }
1312
+ }
1313
+ const THEME_KEY = "theme/theme.ts";
1314
+ function themeTarget(config, root) {
1315
+ return targetOf(config, root, {
1316
+ path: THEME_KEY,
1317
+ type: "registry:theme",
1318
+ content: ""
1319
+ });
1320
+ }
1321
+ /**
1322
+ * What the items' `cssVars` and `css` make of the theme, written the way a
1323
+ * component is: replaced when the project has not touched `theme.ts`, kept when
1324
+ * it has.
1325
+ *
1326
+ * The choice is recorded either way. A kept file is the project's to merge,
1327
+ * and the next `barq-ui theme` writes the tokens with the colours it picks.
1328
+ */
1329
+ async function extendTheme(config, root, items, options) {
1330
+ if (!items.some((item) => item.cssVars !== void 0 || item.css !== void 0)) return { config };
1331
+ const theme = items.reduce(withItemCss, config.theme);
1332
+ const incoming = themeModule(theme, await themes(sourceFor(config, root)), {
1333
+ reset: config.reset,
1334
+ base: "./base.ts",
1335
+ resetPath: "./reset.ts"
1336
+ });
1337
+ const absolute = themeTarget(config, root);
1338
+ const existing = read(absolute);
1339
+ const common = {
1340
+ item: "theme",
1341
+ path: absolute.slice(root.length + 1),
1342
+ absolute,
1343
+ incoming
1344
+ };
1345
+ const recorded = config.items["theme"]?.[THEME_KEY];
1346
+ if (existing !== void 0 && existing !== incoming) {
1347
+ if (!options.overwrite && hashOf(existing) !== recorded) return {
1348
+ config: {
1349
+ ...config,
1350
+ theme
1351
+ },
1352
+ file: {
1353
+ ...common,
1354
+ outcome: "kept",
1355
+ hash: hashOf(existing),
1356
+ existing
1357
+ }
1358
+ };
1359
+ }
1360
+ if (!options.dryRun && existing !== incoming) write(absolute, incoming);
1361
+ return {
1362
+ config: {
1363
+ ...config,
1364
+ theme,
1365
+ items: {
1366
+ ...config.items,
1367
+ theme: { [THEME_KEY]: hashOf(incoming) }
1368
+ }
1369
+ },
1370
+ file: {
1371
+ ...common,
1372
+ outcome: existing === void 0 ? "written" : existing === incoming ? "unchanged" : "replaced",
1373
+ hash: hashOf(incoming),
1374
+ ...existing === void 0 ? {} : { existing }
1375
+ }
1376
+ };
1377
+ }
1378
+ /** The files a `--diff=` or `--view=` asked about: all of them, or the ones named. */
1379
+ function asked(files, which) {
1380
+ return which === true ? [...files] : files.filter((file) => file.path.endsWith(which));
1381
+ }
1382
+ /**
1383
+ * What `add` would do, shown rather than done.
1384
+ *
1385
+ * `--diff` and `--view` are the same preview read two ways: what would change
1386
+ * in a file the project has, and what a file would be.
1387
+ */
1388
+ function preview(root, args, items, files) {
1389
+ if (args.view !== void 0) {
1390
+ for (const file of asked(files, args.view)) {
1391
+ say();
1392
+ say(bold(file.path));
1393
+ say(file.incoming);
1394
+ }
1395
+ return;
1396
+ }
1397
+ if (args.diff !== void 0) {
1398
+ const changed = asked(files, args.diff).filter((file) => file.outcome !== "unchanged");
1399
+ if (changed.length === 0) {
1400
+ say(dim("Nothing would change."));
1401
+ return;
1402
+ }
1403
+ for (const file of changed) {
1404
+ say();
1405
+ say(`${bold(file.path)}${file.existing === void 0 ? dim(" (new)") : ""}`);
1406
+ say(paint(file.existing === void 0 ? file.incoming.split("\n").map((line) => `+ ${line}`).join("\n") : unified(file.existing, file.incoming)));
1407
+ }
1408
+ return;
1409
+ }
1410
+ say(bold("Dry run. Nothing was written."));
1411
+ report(files);
1412
+ const installed = installedPackages(root);
1413
+ const runtime = missingDependencies(items, installed);
1414
+ const development = missingDependencies(items, installed, "devDependencies");
1415
+ if (runtime.length > 0 || development.length > 0) {
1416
+ say();
1417
+ say(bold("Would install:"));
1418
+ if (runtime.length > 0) say(` ${installCommand(root, runtime)}`);
1419
+ if (development.length > 0) say(` ${installCommand(root, development, { dev: true })}`);
1420
+ }
1421
+ }
1422
+ async function add(args) {
1423
+ const { root, config } = requireConfig(args.cwd);
1424
+ const names = args.all ? (await sourceFor(config, root).index()).items.filter((item) => item.type === "registry:ui").map((item) => item.name) : args.rest;
1425
+ if (names.length === 0) throw new Error("which component? `barq-ui list` shows them all");
1426
+ const items = await resolveItems(registriesFor(config, root), names);
1427
+ const dryRun = args.dryRun || args.diff !== void 0 || args.view !== void 0;
1428
+ const applied = applyItems(config, root, items, {
1429
+ overwrite: args.overwrite,
1430
+ dryRun
1431
+ });
1432
+ const themed = await extendTheme(applied.config, root, items, {
1433
+ overwrite: args.overwrite,
1434
+ dryRun
1435
+ });
1436
+ const files = [...applied.files, ...themed.file === void 0 ? [] : [themed.file]];
1437
+ if (dryRun) {
1438
+ preview(root, args, items, files);
1439
+ return;
1440
+ }
1441
+ writeConfig(root, themed.config);
1442
+ report(files);
1443
+ settle(root, items, args.install);
1444
+ }
1445
+ /** What each item's files look like now, against what the registry has. */
1446
+ async function compare(config, root, registries, names) {
1447
+ const items = await resolveItems(registries, names.length > 0 ? names : Object.keys(config.items).filter((n) => n !== "theme"));
1448
+ const together = placed(items);
1449
+ const out = [];
1450
+ for (const item of items) for (const file of item.files) {
1451
+ const absolute = targetOf(config, root, file);
1452
+ const mine = read(absolute);
1453
+ if (mine === void 0) continue;
1454
+ const theirs = rewrite(config, root, file, together);
1455
+ const diff = unified(mine, theirs);
1456
+ if (diff === "") continue;
1457
+ out.push({
1458
+ item: item.name,
1459
+ key: file.path,
1460
+ path: absolute.slice(root.length + 1),
1461
+ absolute,
1462
+ diff,
1463
+ theirs
1464
+ });
1465
+ }
1466
+ return out;
1467
+ }
1468
+ async function showDiff(args) {
1469
+ const { root, config } = requireConfig(args.cwd);
1470
+ const changes = await compare(config, root, registriesFor(config, root), args.rest);
1471
+ if (changes.length === 0) {
1472
+ say(dim("Nothing has changed."));
1473
+ return;
1474
+ }
1475
+ for (const change of changes) {
1476
+ say();
1477
+ say(bold(change.path));
1478
+ say(paint(change.diff));
1479
+ }
1480
+ say();
1481
+ say(dim(`${String(changes.length)} file(s). \`barq-ui sync\` takes the registry's version.`));
1482
+ }
1483
+ async function sync(args) {
1484
+ const { root, config } = requireConfig(args.cwd);
1485
+ const changes = await compare(config, root, registriesFor(config, root), args.rest);
1486
+ if (changes.length === 0) {
1487
+ say(dim("Nothing to sync."));
1488
+ return;
1489
+ }
1490
+ const prompt = ask(!args.yes);
1491
+ const items = { ...config.items };
1492
+ let taken = 0;
1493
+ try {
1494
+ for (const change of changes) {
1495
+ const mine = read(change.absolute) ?? "";
1496
+ const recorded = items[change.item]?.[change.key];
1497
+ if (!(recorded !== void 0 && hashOf(mine) === recorded) && !args.overwrite) {
1498
+ say();
1499
+ say(`${bold(change.path)} ${yellow("(you have edited this)")}`);
1500
+ say(paint(change.diff));
1501
+ if (!await prompt.confirm("Take the registry's version?", false)) continue;
1502
+ }
1503
+ write(change.absolute, change.theirs);
1504
+ taken++;
1505
+ items[change.item] = {
1506
+ ...items[change.item],
1507
+ [change.key]: hashOf(change.theirs)
1508
+ };
1509
+ }
1510
+ } finally {
1511
+ prompt.close();
1512
+ }
1513
+ writeConfig(root, {
1514
+ ...config,
1515
+ items
1516
+ });
1517
+ say();
1518
+ say(taken === 0 ? dim("Nothing was replaced.") : `${green("Synced")} ${String(taken)} file${taken === 1 ? "" : "s"}.`);
1519
+ }
1520
+ async function list(args) {
1521
+ const root = requireConfigOrCwd(args.cwd);
1522
+ const config = root.config;
1523
+ const index = await sourceFor(config, root.root).index();
1524
+ const groups = /* @__PURE__ */ new Map();
1525
+ for (const item of index.items) groups.set(item.type, [...groups.get(item.type) ?? [], item]);
1526
+ for (const [type, items] of [...groups].toSorted(([a], [b]) => a.localeCompare(b))) {
1527
+ say();
1528
+ say(bold(type.replace("registry:", "")));
1529
+ for (const item of items) {
1530
+ const have = config.items[item.name] !== void 0 ? green(" (added)") : "";
1531
+ say(` ${item.name.padEnd(18)}${dim(item.description?.slice(0, 60) ?? "")}${have}`);
1532
+ }
1533
+ }
1534
+ }
1535
+ /** `list` works before `init`, against the default registry. */
1536
+ function requireConfigOrCwd(cwd) {
1537
+ try {
1538
+ return requireConfig(cwd);
1539
+ } catch {
1540
+ return {
1541
+ root: cwd,
1542
+ config: parseConfig({
1543
+ paths: DEFAULT_PATHS,
1544
+ items: {}
1545
+ })
1546
+ };
1547
+ }
1548
+ }
1549
+ /** `view` works before `init` too: reading an item needs a registry, not a project. */
1550
+ async function view(args) {
1551
+ if (args.rest.length === 0) throw new Error("which item? `barq-ui list` shows them all");
1552
+ const { root, config } = requireConfigOrCwd(args.cwd);
1553
+ const registries = registriesFor(config, root);
1554
+ const items = [];
1555
+ for (const address of args.rest) {
1556
+ const { source, name } = registries.locate(address);
1557
+ items.push({
1558
+ ...await source.item(name),
1559
+ name: address
1560
+ });
1561
+ }
1562
+ say(JSON.stringify(items, null, 2));
1563
+ }
1564
+ /** Every word of the query, somewhere in what the entry says about itself. */
1565
+ function matches(entry, words) {
1566
+ const haystack = [
1567
+ entry.name,
1568
+ entry.title,
1569
+ entry.description ?? "",
1570
+ ...entry.categories
1571
+ ].join(" ").toLowerCase();
1572
+ return words.every((word) => haystack.includes(word));
1573
+ }
1574
+ async function search(args) {
1575
+ const words = args.rest.map((word) => word.toLowerCase());
1576
+ if (words.length === 0) throw new Error("search for what? `barq-ui search sidebar`");
1577
+ const { root, config } = requireConfigOrCwd(args.cwd);
1578
+ const registries = registriesFor(config, root);
1579
+ const found = [];
1580
+ const unreachable = [];
1581
+ for (const scope of [void 0, ...registries.scopes]) try {
1582
+ const source = registries.source(scope);
1583
+ for (const entry of (await source.index()).items) {
1584
+ if (!matches(entry, words)) continue;
1585
+ found.push({
1586
+ name: scope === void 0 ? entry.name : `${scope}/${entry.name}`,
1587
+ type: entry.type,
1588
+ title: entry.title,
1589
+ ...entry.description === void 0 ? {} : { description: entry.description },
1590
+ categories: entry.categories,
1591
+ registry: source.describe
1592
+ });
1593
+ }
1594
+ } catch (error) {
1595
+ unreachable.push(`${scope ?? "the registry"}: ${error instanceof Error ? error.message : String(error)}`);
1596
+ }
1597
+ if (args.json) {
1598
+ say(JSON.stringify({
1599
+ items: found,
1600
+ errors: unreachable
1601
+ }, null, 2));
1602
+ return;
1603
+ }
1604
+ for (const line of unreachable) say(yellow(line));
1605
+ if (found.length === 0) {
1606
+ say(dim(`Nothing matches "${args.rest.join(" ")}".`));
1607
+ return;
1608
+ }
1609
+ const width = Math.max(...found.map((item) => item.name.length)) + 2;
1610
+ for (const item of found) say(` ${item.name.padEnd(width)}${dim(item.type.replace("registry:", "").padEnd(11))}${dim(item.description?.slice(0, 60) ?? "")}`);
1611
+ say();
1612
+ say(dim(`${String(found.length)} item${found.length === 1 ? "" : "s"}. \`barq-ui add <name>\` takes one.`));
1613
+ }
1614
+ async function info(args) {
1615
+ const root = findRoot(args.cwd);
1616
+ const { config } = requireConfigOrCwd(args.cwd);
1617
+ const project = root ?? args.cwd;
1618
+ const added = Object.keys(config.items).filter((name) => name !== "theme").toSorted();
1619
+ const facts = {
1620
+ root: project,
1621
+ config: root === void 0 ? null : join(root, CONFIG_FILE),
1622
+ registry: config.registry ?? defaultRegistry(),
1623
+ registries: Object.fromEntries(Object.entries(config.registries).map(([scope, endpoint]) => [scope, endpoint.url])),
1624
+ paths: config.paths,
1625
+ theme: config.theme,
1626
+ packageManager: packageManager(project),
1627
+ packages: [...installedPackages(project)].filter((name) => name.startsWith("@barqjs/")).toSorted(),
1628
+ items: added
1629
+ };
1630
+ if (args.json) {
1631
+ say(JSON.stringify(facts, null, 2));
1632
+ return;
1633
+ }
1634
+ const row = (label, value) => say(` ${label.padEnd(17)}${value}`);
1635
+ say(bold("Project"));
1636
+ row("root", facts.root);
1637
+ row("config", facts.config ?? dim(`none. \`barq-ui init\` writes components.json`));
1638
+ row("package manager", facts.packageManager);
1639
+ row("barq packages", facts.packages.length === 0 ? dim("none") : facts.packages.join(", "));
1640
+ say();
1641
+ say(bold("Registries"));
1642
+ row("(default)", facts.registry);
1643
+ for (const [scope, url] of Object.entries(facts.registries)) row(scope, url);
1644
+ say();
1645
+ say(bold("Paths"));
1646
+ for (const kind of [
1647
+ "ui",
1648
+ "lib",
1649
+ "theme",
1650
+ "components",
1651
+ "hooks"
1652
+ ]) row(kind, config.paths[kind]);
1653
+ say();
1654
+ say(bold("Theme"));
1655
+ row("base", config.theme.base);
1656
+ if (config.theme.accent !== void 0) row("accent", config.theme.accent);
1657
+ if (config.theme.style !== void 0) row("style", config.theme.style);
1658
+ if (config.theme.radius !== void 0) row("radius", config.theme.radius);
1659
+ say();
1660
+ say(bold(`Added (${String(added.length)})`));
1661
+ say(added.length === 0 ? dim(" nothing yet") : ` ${added.join(", ")}`);
1662
+ await Promise.resolve();
1663
+ }
1664
+ async function chooseTheme(args) {
1665
+ const name = args.rest[0];
1666
+ if (name === void 0) throw new Error("which theme? `barq-ui list` shows the components");
1667
+ const { root, config } = requireConfig(args.cwd);
1668
+ const table = await themes(sourceFor(config, root));
1669
+ const chosen = table.find((entry) => entry.name === name);
1670
+ if (chosen === void 0) throw new Error(`no theme named "${name}". Try one of: ${table.map((entry) => entry.name).join(", ")}`);
1671
+ const next = {
1672
+ ...config.theme,
1673
+ ...chosen.kind === "base" ? { base: name } : { accent: name },
1674
+ ...args.radius === void 0 ? {} : { radius: args.radius }
1675
+ };
1676
+ const module_ = themeModule(next, table, {
1677
+ reset: config.reset,
1678
+ base: "./base.ts",
1679
+ resetPath: "./reset.ts"
1680
+ });
1681
+ const path = themeTarget(config, root);
1682
+ write(path, module_);
1683
+ writeConfig(root, {
1684
+ ...config,
1685
+ theme: next,
1686
+ items: {
1687
+ ...config.items,
1688
+ theme: { [THEME_KEY]: hashOf(module_) }
1689
+ }
1690
+ });
1691
+ say(`${green("Theme")} ${bold(chosen.title)} written to ${path.slice(root.length + 1)}.`);
1692
+ }
1693
+ /** `barq-ui style nova`, the shape `barq-ui theme` already has. */
1694
+ async function chooseStyle(args) {
1695
+ const name = args.rest[0] ?? args.style;
1696
+ const { root, config } = requireConfig(args.cwd);
1697
+ const source = sourceFor(config, root);
1698
+ const available = await styles(source);
1699
+ if (name === void 0) throw new Error(`which style? ${available.map((each) => each.value).join(", ")}`);
1700
+ if (!available.some((each) => each.value === name)) throw new Error(`no style named "${name}". Try one of: ${available.map((each) => each.value).join(", ")}`);
1701
+ const path = await writeStyle(root, config, name, source);
1702
+ writeConfig(root, {
1703
+ ...config,
1704
+ theme: {
1705
+ ...config.theme,
1706
+ style: name
1707
+ }
1708
+ });
1709
+ say(`${green("Style")} ${bold(name)} written to ${path.slice(root.length + 1)}.`);
1710
+ say(dim(`Put class="style-${name}" on the element it applies to.`));
1711
+ }
1712
+ async function build(args) {
1713
+ const directory = args.rest[0];
1714
+ if (directory === void 0) throw new Error("which directory? `barq-ui build ./src/ui`");
1715
+ const { buildRegistry } = await import("./build-C65qsG0d.js");
1716
+ const written = buildRegistry(resolve(args.cwd, directory), resolve(args.cwd, "registry"));
1717
+ say(`${green("Built")} ${String(written)} items into registry/`);
1718
+ }
1719
+ async function main() {
1720
+ const args = parse(process.argv.slice(2));
1721
+ if (args.help || args.command === void 0) {
1722
+ stdout.write(HELP);
1723
+ return;
1724
+ }
1725
+ switch (args.command) {
1726
+ case "init": return await init(args);
1727
+ case "style": return await chooseStyle(args);
1728
+ case "add": return await add(args);
1729
+ case "diff": return await showDiff(args);
1730
+ case "sync": return await sync(args);
1731
+ case "list": return await list(args);
1732
+ case "search": return await search(args);
1733
+ case "view": return await view(args);
1734
+ case "info": return await info(args);
1735
+ case "theme": return await chooseTheme(args);
1736
+ case "build": return await build(args);
1737
+ default: throw new Error(`unknown command "${args.command}". Try \`barq-ui --help\``);
1738
+ }
1739
+ }
1740
+ /**
1741
+ * Exported so the suite can drive the commands, and guarded so importing it
1742
+ * does not run one. The guard compares the script node was asked to run with
1743
+ * this module rather than reading `import.meta.main`, which node only defines
1744
+ * from 24.2 and so is `undefined` for the built `bin` on every older node the
1745
+ * engines range admits. `argv[1]` is the `.bin` symlink under a package
1746
+ * manager, hence the realpath.
1747
+ */
1748
+ async function run() {
1749
+ try {
1750
+ await main();
1751
+ } catch (error) {
1752
+ say(red(error instanceof Error ? error.message : String(error)));
1753
+ process.exitCode = 1;
1754
+ }
1755
+ }
1756
+ function invokedDirectly() {
1757
+ const script = process.argv[1];
1758
+ return script !== void 0 && realpathSync(script) === fileURLToPath(import.meta.url);
1759
+ }
1760
+ if (invokedDirectly()) await run();
1761
+ export { run };