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