kira-kit 0.2.1 → 0.3.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.
Files changed (71) hide show
  1. package/README.md +132 -43
  2. package/dist/index.mjs +2472 -0
  3. package/package.json +38 -17
  4. package/templates/monorepo/components.json +23 -0
  5. package/templates/monorepo/package.json +13 -0
  6. package/templates/monorepo/packages/app/index.html +13 -0
  7. package/templates/monorepo/packages/app/package.json +27 -0
  8. package/templates/monorepo/packages/app/src/App.tsx +21 -0
  9. package/templates/monorepo/packages/app/src/index.css +3 -0
  10. package/templates/monorepo/packages/app/src/main.tsx +10 -0
  11. package/templates/monorepo/packages/app/tsconfig.json +8 -0
  12. package/templates/monorepo/packages/app/vite.config.ts +10 -0
  13. package/templates/monorepo/packages/ui/package.json +32 -0
  14. package/templates/monorepo/packages/ui/src/components/ui/welcome.tsx +52 -0
  15. package/templates/monorepo/packages/ui/src/index.css +123 -0
  16. package/templates/monorepo/packages/ui/src/index.ts +3 -0
  17. package/templates/monorepo/packages/ui/src/lib/utils.ts +1 -0
  18. package/templates/monorepo/packages/ui/tsconfig.json +7 -0
  19. package/templates/monorepo/tsconfig.json +23 -0
  20. package/templates/next/app/globals.css +124 -0
  21. package/templates/next/app/layout.tsx +18 -0
  22. package/templates/next/app/page.tsx +9 -0
  23. package/templates/next/components/ui/welcome.tsx +62 -0
  24. package/templates/next/components.json +23 -0
  25. package/templates/next/lib/utils.ts +1 -0
  26. package/templates/next/next-env.d.ts +2 -0
  27. package/templates/next/next.config.ts +5 -0
  28. package/templates/next/package.json +28 -0
  29. package/templates/next/postcss.config.mjs +7 -0
  30. package/templates/next/tsconfig.json +24 -0
  31. package/templates/tanstack-start/README.md +16 -0
  32. package/templates/tanstack-start/components.json +23 -0
  33. package/templates/tanstack-start/package.json +30 -0
  34. package/templates/tanstack-start/src/components/ui/welcome.tsx +52 -0
  35. package/templates/tanstack-start/src/index.css +123 -0
  36. package/templates/tanstack-start/src/lib/utils.ts +1 -0
  37. package/templates/tanstack-start/src/router.tsx +15 -0
  38. package/templates/tanstack-start/src/routes/__root.tsx +41 -0
  39. package/templates/tanstack-start/src/routes/index.tsx +26 -0
  40. package/{tsconfig.json → templates/tanstack-start/tsconfig.json} +6 -7
  41. package/templates/tanstack-start/vite.config.ts +11 -0
  42. package/templates/vite/components.json +23 -0
  43. package/templates/vite/index.html +16 -0
  44. package/templates/vite/package.json +28 -0
  45. package/templates/vite/src/App.tsx +9 -0
  46. package/templates/vite/src/components/ui/welcome.tsx +60 -0
  47. package/templates/vite/src/index.css +124 -0
  48. package/templates/vite/src/lib/utils.ts +1 -0
  49. package/templates/vite/src/main.tsx +10 -0
  50. package/templates/vite/tsconfig.json +29 -0
  51. package/templates/vite/tsconfig.node.json +22 -0
  52. package/templates/vite/vite.config.ts +13 -0
  53. package/bin/kira-kit.js +0 -27329
  54. package/bun.lock +0 -247
  55. package/src/commands/add.ts +0 -146
  56. package/src/commands/build.ts +0 -212
  57. package/src/commands/init.ts +0 -164
  58. package/src/commands/list.ts +0 -31
  59. package/src/index.ts +0 -118
  60. package/src/lib/build-config.ts +0 -81
  61. package/src/lib/config.ts +0 -109
  62. package/src/lib/deps.ts +0 -135
  63. package/src/lib/file.ts +0 -64
  64. package/src/lib/logger.ts +0 -102
  65. package/src/lib/registry.ts +0 -81
  66. package/src/lib/templates.ts +0 -123
  67. package/src/lib/theme-generator.ts +0 -246
  68. package/src/prompts/base-color.ts +0 -20
  69. package/src/prompts/primary-color.ts +0 -23
  70. package/src/prompts/project-type.ts +0 -71
  71. package/src/types.ts +0 -61
package/dist/index.mjs ADDED
@@ -0,0 +1,2472 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { Command } from "commander";
4
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, relative, resolve } from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { existsSync as existsSync$1, readFileSync as readFileSync$1, writeFileSync as writeFileSync$1 } from "fs";
8
+ import { join as join$1 } from "path";
9
+ import { z } from "zod";
10
+ import picocolors from "picocolors";
11
+ import * as p from "@clack/prompts";
12
+ import { clampChroma, converter, formatCss, parse, wcagLuminance } from "culori";
13
+ import { APCAcontrast, sRGBtoY } from "apca-w3";
14
+ import ts from "typescript";
15
+ import { fileURLToPath } from "node:url";
16
+ import { detect } from "package-manager-detector";
17
+ import { readFile, readdir, stat, writeFile } from "node:fs/promises";
18
+ // src/version.ts
19
+ function getVersion() {
20
+ return "0.3.0";
21
+ }
22
+ /**
23
+ * Error carrying the kira-kit exit-code contract:
24
+ * 0 ok, 1 user/validation error, 2 network/registry error, 3 check failures.
25
+ * `nextStep` is always printed — errors must tell the user what to do next.
26
+ */
27
+ var CliError = class extends Error {
28
+ exitCode;
29
+ nextStep;
30
+ constructor(message, exitCode, nextStep) {
31
+ super(message);
32
+ this.name = "CliError";
33
+ this.exitCode = exitCode;
34
+ this.nextStep = nextStep;
35
+ }
36
+ };
37
+ var ValidationError = class extends CliError {
38
+ constructor(message, nextStep) {
39
+ super(message, 1, nextStep);
40
+ this.name = "ValidationError";
41
+ }
42
+ };
43
+ var RegistryError = class extends CliError {
44
+ constructor(message, nextStep) {
45
+ super(message, 2, nextStep);
46
+ this.name = "RegistryError";
47
+ }
48
+ };
49
+ function printError(error) {
50
+ if (error instanceof CliError) {
51
+ console.error(`error: ${error.message}`);
52
+ if (error.nextStep) console.error(`next step: ${error.nextStep}`);
53
+ return error.exitCode;
54
+ }
55
+ const message = error instanceof Error ? error.message : String(error);
56
+ console.error(`error: ${message}`);
57
+ return 1;
58
+ }
59
+ // src/lib/shadcn.ts
60
+ const require = createRequire(import.meta.url);
61
+ /** Resolved export of shadcn's "." entry — its CLI bin target. */
62
+ const SHADCN_EXPORTS = [
63
+ ".",
64
+ "./schema",
65
+ "./registry"
66
+ ];
67
+ /**
68
+ * Resolve the shadcn CLI entry point from kira-kit's own node_modules so
69
+ * behavior is locked to the pinned version, never PATH drift.
70
+ *
71
+ * shadcn's package.json restricts subpath exports (no "./package.json"), so
72
+ * we resolve the "." export, which maps to the same dist/index.js as its bin.
73
+ */
74
+ function resolveShadcnBin() {
75
+ for (const subpath of SHADCN_EXPORTS) try {
76
+ return require.resolve(`shadcn${subpath === "." ? "" : subpath}`);
77
+ } catch {
78
+ continue;
79
+ }
80
+ throw new Error("shadcn CLI entry could not be resolved");
81
+ }
82
+ /**
83
+ * Run the pinned shadcn CLI with passthrough stdio.
84
+ * Returns the child's exit code; never throws except on spawn failure.
85
+ */
86
+ function runShadcn(args, cwd = process.cwd()) {
87
+ const bin = resolveShadcnBin();
88
+ const child = spawn(process.execPath, [
89
+ ...process.execArgv,
90
+ bin,
91
+ ...args
92
+ ], {
93
+ stdio: "inherit",
94
+ cwd,
95
+ env: process.env
96
+ });
97
+ return new Promise((resolvePromise, reject) => {
98
+ child.on("error", reject);
99
+ child.on("exit", (code) => resolvePromise({ code: code ?? 0 }));
100
+ });
101
+ }
102
+ /**
103
+ * Run shadcn and map failures onto the kira-kit exit-code contract.
104
+ * Returns 0 on success, 2 when the shadcn binary itself is missing/unlaunchable.
105
+ */
106
+ async function runShadcnChecked(args, cwd = process.cwd()) {
107
+ try {
108
+ const { code } = await runShadcn(args, cwd);
109
+ return code;
110
+ } catch (error) {
111
+ if ((error instanceof Error ? error.message : String(error)).includes("ENOENT")) {
112
+ console.error("error: the pinned shadcn CLI could not be launched. Reinstall kira-kit (e.g. npm install kira-kit) and retry.");
113
+ return 2;
114
+ }
115
+ throw error;
116
+ }
117
+ }
118
+ // src/lib/schemas.ts
119
+ const KIRA_NAMESPACE = "@kira-kit";
120
+ const DEFAULT_REGISTRY_URL = "https://kira-kit.vercel.app/r/{name}.json";
121
+ /**
122
+ * components.json as written by shadcn init. We are deliberately loose:
123
+ * shadcn owns this file's shape; we only read the parts we need.
124
+ */
125
+ const componentsConfigSchema = z.looseObject({
126
+ $schema: z.string().optional(),
127
+ style: z.string().optional(),
128
+ rsc: z.boolean().optional(),
129
+ tsx: z.boolean().optional(),
130
+ tailwind: z.looseObject({
131
+ css: z.string().optional(),
132
+ baseColor: z.string().optional(),
133
+ cssVariables: z.boolean().optional()
134
+ }).optional(),
135
+ iconLibrary: z.string().optional(),
136
+ aliases: z.looseObject({
137
+ components: z.string().optional(),
138
+ utils: z.string().optional(),
139
+ ui: z.string().optional(),
140
+ lib: z.string().optional(),
141
+ hooks: z.string().optional()
142
+ }).optional(),
143
+ registries: z.record(z.string(), z.string()).optional()
144
+ });
145
+ /** A registry item in our source registries (before build inlines files). */
146
+ const sourceRegistryItemSchema = z.object({
147
+ name: z.string().regex(/^[a-z0-9-]+$/, "item name must be kebab-case"),
148
+ type: z.enum([
149
+ "registry:ui",
150
+ "registry:hook",
151
+ "registry:theme",
152
+ "registry:style",
153
+ "registry:base",
154
+ "registry:file",
155
+ "registry:lib",
156
+ "registry:block",
157
+ "registry:page"
158
+ ]),
159
+ title: z.string().min(1),
160
+ description: z.string().min(1),
161
+ categories: z.array(z.string()).optional(),
162
+ dependencies: z.array(z.string()).optional(),
163
+ registryDependencies: z.array(z.string()).optional(),
164
+ files: z.array(z.object({
165
+ path: z.string(),
166
+ type: z.string().optional(),
167
+ target: z.string().optional(),
168
+ content: z.string().optional()
169
+ })).optional(),
170
+ cssVars: z.looseObject({
171
+ theme: z.record(z.string(), z.string()).optional(),
172
+ light: z.record(z.string(), z.string()).optional(),
173
+ dark: z.record(z.string(), z.string()).optional()
174
+ }).optional(),
175
+ docs: z.string().optional()
176
+ });
177
+ /** Source registry file. Only the root registry.json carries a name. */
178
+ const sourceRegistrySchema = z.object({
179
+ $schema: z.string().optional(),
180
+ name: z.string().optional(),
181
+ homepage: z.string().optional(),
182
+ include: z.array(z.string()).optional(),
183
+ items: z.array(sourceRegistryItemSchema).optional()
184
+ });
185
+ // src/lib/config.ts
186
+ function findConfigFile(cwd) {
187
+ const path = join$1(cwd, "components.json");
188
+ return existsSync$1(path) ? path : null;
189
+ }
190
+ function readConfig(cwd) {
191
+ const configPath = findConfigFile(cwd);
192
+ if (!configPath) return null;
193
+ try {
194
+ const content = readFileSync$1(configPath, "utf-8");
195
+ return componentsConfigSchema.parse(JSON.parse(content));
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+ /** Read components.json without zod defaults; preserves unknown keys on write. */
201
+ function readRawConfig(cwd) {
202
+ const configPath = findConfigFile(cwd);
203
+ if (!configPath) return null;
204
+ try {
205
+ return JSON.parse(readFileSync$1(configPath, "utf-8"));
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+ /**
211
+ * Idempotently register the @kira-kit namespace in components.json.
212
+ * Never clobbers other registries or unknown keys.
213
+ */
214
+ function upsertKiraRegistry(cwd, url = DEFAULT_REGISTRY_URL) {
215
+ const next = readRawConfig(cwd) ?? {};
216
+ const registries = { ...next.registries };
217
+ if (registries["@kira-kit"]) return false;
218
+ registries[KIRA_NAMESPACE] = url;
219
+ next.registries = registries;
220
+ writeFileSync$1(join$1(cwd, "components.json"), JSON.stringify(next, null, 2) + "\n", "utf-8");
221
+ return true;
222
+ }
223
+ /** Resolve the @kira-kit registry base URL (without {name}.json suffix). */
224
+ function getRegistryUrl(cwd) {
225
+ const url = readConfig(cwd)?.registries?.[KIRA_NAMESPACE];
226
+ if (!url) return DEFAULT_REGISTRY_URL.replace("/{name}.json", "");
227
+ return url.replace("/{name}.json", "");
228
+ }
229
+ // src/lib/logger.ts
230
+ const colors = {
231
+ primary: picocolors.cyan,
232
+ success: picocolors.green,
233
+ error: picocolors.red,
234
+ warning: picocolors.yellow,
235
+ dim: picocolors.dim,
236
+ bold: picocolors.bold
237
+ };
238
+ function info(message) {
239
+ console.log(colors.primary("info") + " " + message);
240
+ }
241
+ function success(message) {
242
+ console.log(colors.success("success") + " " + message);
243
+ }
244
+ function error(message) {
245
+ console.error(colors.error("error") + " " + message);
246
+ }
247
+ function warning(message) {
248
+ console.warn(colors.warning("warn") + " " + message);
249
+ }
250
+ // src/lib/prompts.ts
251
+ function isInteractive() {
252
+ return !process.env.CI && process.stdin.isTTY === true && process.stdout.isTTY === true;
253
+ }
254
+ /** True when no prompt must be shown: flag given, --yes, CI, or non-TTY. */
255
+ function shouldSkipPrompt(ctx) {
256
+ return ctx.flagValue !== void 0 || ctx.yes === true || !isInteractive();
257
+ }
258
+ async function select(ctx, message, options, fallback) {
259
+ if (shouldSkipPrompt(ctx)) return ctx.flagValue ?? fallback;
260
+ const answer = await p.select({
261
+ message,
262
+ options: options.map((option) => ({
263
+ value: option.value,
264
+ label: option.label,
265
+ hint: option.hint
266
+ }))
267
+ });
268
+ if (p.isCancel(answer)) {
269
+ p.cancel("Cancelled.");
270
+ process.exit(1);
271
+ }
272
+ return answer;
273
+ }
274
+ async function confirm(ctx, message, fallback) {
275
+ if (shouldSkipPrompt(ctx)) return ctx.flagValue ?? fallback;
276
+ const answer = await p.confirm({
277
+ message,
278
+ initialValue: fallback
279
+ });
280
+ if (p.isCancel(answer)) {
281
+ p.cancel("Cancelled.");
282
+ process.exit(1);
283
+ }
284
+ return answer;
285
+ }
286
+ async function text(ctx, message, fallback, validate) {
287
+ if (shouldSkipPrompt(ctx)) return ctx.flagValue ?? fallback;
288
+ const answer = await p.text({
289
+ message,
290
+ initialValue: fallback,
291
+ validate: validate ? (value) => validate(value ?? "") : void 0
292
+ });
293
+ if (p.isCancel(answer)) {
294
+ p.cancel("Cancelled.");
295
+ process.exit(1);
296
+ }
297
+ return answer;
298
+ }
299
+ // src/core/theme/color.ts
300
+ const oklch = converter("oklch");
301
+ const rgbConverter = converter("rgb");
302
+ function parseToOklch(input) {
303
+ const parsed = parse(input.trim());
304
+ if (!parsed) throw new Error(`Invalid color: "${input}". Use a hex like #e2694a, a named CSS color, oklch(...), hsl(...), or rgb(...).`);
305
+ const converted = oklch(parsed);
306
+ if (converted === void 0 || Number.isNaN(converted.l)) throw new Error(`Color "${input}" could not be converted to OKLCH.`);
307
+ return {
308
+ l: converted.l,
309
+ c: converted.c,
310
+ h: converted.h ?? 0
311
+ };
312
+ }
313
+ /** Numeric OKLCH → CSS string. Numeric output, no string interpolation. */
314
+ function oklchCss(color) {
315
+ const l = round(color.l, 3);
316
+ const c = round(color.c, 3);
317
+ const h = round(color.h, 1);
318
+ return formatCss({
319
+ mode: "oklch",
320
+ l,
321
+ c,
322
+ h
323
+ });
324
+ }
325
+ /** WCAG 2.x relative luminance, computed on the sRGB-clamped color. */
326
+ function luminance(color) {
327
+ const clamped = clampChroma({
328
+ mode: "oklch",
329
+ ...color
330
+ }, "rgb");
331
+ return wcagLuminance(clamped);
332
+ }
333
+ function wcagRatio(fg, bg) {
334
+ const lf = luminance(fg);
335
+ const lb = luminance(bg);
336
+ const hi = Math.max(lf, lb);
337
+ const lo = Math.min(lf, lb);
338
+ return (hi + .05) / (lo + .05);
339
+ }
340
+ /** APCA Lc (non-blocking, informational). Absolute value reported. */
341
+ function apcaLc(fg, bg) {
342
+ const fgY = sRGBtoY(toRgb255(fg));
343
+ const bgY = sRGBtoY(toRgb255(bg));
344
+ const value = APCAcontrast(fgY, bgY);
345
+ if (typeof value === "number") return Math.abs(value);
346
+ return 0;
347
+ }
348
+ function rgbChannel(v) {
349
+ return Math.round(Math.min(1, Math.max(0, v ?? 0)) * 255);
350
+ }
351
+ function toRgb255(color) {
352
+ const rgb = rgbConverter(clampChroma({
353
+ mode: "oklch",
354
+ ...color
355
+ }, "rgb"));
356
+ return [
357
+ rgbChannel(rgb.r),
358
+ rgbChannel(rgb.g),
359
+ rgbChannel(rgb.b)
360
+ ];
361
+ }
362
+ function round(value, decimals) {
363
+ const factor = 10 ** decimals;
364
+ return Math.round(value * factor) / factor;
365
+ }
366
+ // src/core/theme/palette.ts
367
+ /** Subtle hue/chroma signature per base color (OKLCH). */
368
+ const BASE_COLORS = {
369
+ neutral: {
370
+ l: 0,
371
+ c: 0,
372
+ h: 0
373
+ },
374
+ stone: {
375
+ l: 0,
376
+ c: .004,
377
+ h: 67
378
+ },
379
+ zinc: {
380
+ l: 0,
381
+ c: .002,
382
+ h: 263
383
+ },
384
+ gray: {
385
+ l: 0,
386
+ c: .002,
387
+ h: 220
388
+ },
389
+ slate: {
390
+ l: 0,
391
+ c: .004,
392
+ h: 233
393
+ },
394
+ mauve: {
395
+ l: 0,
396
+ c: .004,
397
+ h: 320
398
+ },
399
+ olive: {
400
+ l: 0,
401
+ c: .005,
402
+ h: 110
403
+ },
404
+ mist: {
405
+ l: 0,
406
+ c: .006,
407
+ h: 200
408
+ },
409
+ taupe: {
410
+ l: 0,
411
+ c: .005,
412
+ h: 80
413
+ }
414
+ };
415
+ const BASE_COLOR_NAMES = Object.keys(BASE_COLORS);
416
+ const DEFAULT_CHART_HUES = [
417
+ 60,
418
+ 120,
419
+ 200,
420
+ 280
421
+ ];
422
+ function lightScheme(base, primary, hueOffsets) {
423
+ return {
424
+ background: {
425
+ l: 1,
426
+ c: base.c * .1,
427
+ h: base.h
428
+ },
429
+ foreground: {
430
+ l: .16,
431
+ c: base.c,
432
+ h: base.h
433
+ },
434
+ card: {
435
+ l: 1,
436
+ c: base.c * .1,
437
+ h: base.h
438
+ },
439
+ "card-foreground": {
440
+ l: .16,
441
+ c: base.c,
442
+ h: base.h
443
+ },
444
+ popover: {
445
+ l: 1,
446
+ c: base.c * .1,
447
+ h: base.h
448
+ },
449
+ "popover-foreground": {
450
+ l: .16,
451
+ c: base.c,
452
+ h: base.h
453
+ },
454
+ primary,
455
+ "primary-foreground": {
456
+ l: .99,
457
+ c: .01,
458
+ h: primary.h
459
+ },
460
+ secondary: {
461
+ l: .965,
462
+ c: base.c * 1.5,
463
+ h: base.h
464
+ },
465
+ "secondary-foreground": {
466
+ l: .25,
467
+ c: base.c,
468
+ h: base.h
469
+ },
470
+ muted: {
471
+ l: .965,
472
+ c: base.c * 1.5,
473
+ h: base.h
474
+ },
475
+ "muted-foreground": {
476
+ l: .55,
477
+ c: base.c,
478
+ h: base.h
479
+ },
480
+ accent: {
481
+ l: .965,
482
+ c: base.c * 1.5,
483
+ h: base.h
484
+ },
485
+ "accent-foreground": {
486
+ l: .2,
487
+ c: base.c,
488
+ h: base.h
489
+ },
490
+ destructive: {
491
+ l: .58,
492
+ c: .21,
493
+ h: 27
494
+ },
495
+ "destructive-foreground": {
496
+ l: .985,
497
+ c: .01,
498
+ h: 27
499
+ },
500
+ border: {
501
+ l: .9,
502
+ c: base.c * 2,
503
+ h: base.h
504
+ },
505
+ input: {
506
+ l: .9,
507
+ c: base.c * 2,
508
+ h: base.h
509
+ },
510
+ ring: { ...primary },
511
+ "chart-1": {
512
+ l: .6,
513
+ c: Math.min(primary.c, .16),
514
+ h: primary.h
515
+ },
516
+ "chart-2": {
517
+ l: .62,
518
+ c: Math.min(primary.c, .15),
519
+ h: wrapHue(primary.h + hueOffsets[0])
520
+ },
521
+ "chart-3": {
522
+ l: .62,
523
+ c: Math.min(primary.c, .15),
524
+ h: wrapHue(primary.h + hueOffsets[1])
525
+ },
526
+ "chart-4": {
527
+ l: .62,
528
+ c: Math.min(primary.c, .15),
529
+ h: wrapHue(primary.h + hueOffsets[2])
530
+ },
531
+ "chart-5": {
532
+ l: .62,
533
+ c: Math.min(primary.c, .15),
534
+ h: wrapHue(primary.h + hueOffsets[3])
535
+ },
536
+ sidebar: {
537
+ l: .99,
538
+ c: base.c * .5,
539
+ h: base.h
540
+ },
541
+ "sidebar-foreground": {
542
+ l: .16,
543
+ c: base.c,
544
+ h: base.h
545
+ },
546
+ "sidebar-primary": { ...primary },
547
+ "sidebar-primary-foreground": {
548
+ l: .99,
549
+ c: .01,
550
+ h: primary.h
551
+ },
552
+ "sidebar-accent": {
553
+ l: .955,
554
+ c: base.c * 1.5,
555
+ h: base.h
556
+ },
557
+ "sidebar-accent-foreground": {
558
+ l: .2,
559
+ c: base.c,
560
+ h: base.h
561
+ },
562
+ "sidebar-border": {
563
+ l: .9,
564
+ c: base.c * 2,
565
+ h: base.h
566
+ },
567
+ "sidebar-ring": { ...primary }
568
+ };
569
+ }
570
+ function darkScheme(base, primary, hueOffsets) {
571
+ const darkPrimary = {
572
+ l: .72,
573
+ c: primary.c,
574
+ h: primary.h
575
+ };
576
+ return {
577
+ background: {
578
+ l: .145,
579
+ c: base.c * 1.2,
580
+ h: base.h
581
+ },
582
+ foreground: {
583
+ l: .97,
584
+ c: base.c * .5,
585
+ h: base.h
586
+ },
587
+ card: {
588
+ l: .18,
589
+ c: base.c * 1.2,
590
+ h: base.h
591
+ },
592
+ "card-foreground": {
593
+ l: .97,
594
+ c: base.c * .5,
595
+ h: base.h
596
+ },
597
+ popover: {
598
+ l: .18,
599
+ c: base.c * 1.2,
600
+ h: base.h
601
+ },
602
+ "popover-foreground": {
603
+ l: .97,
604
+ c: base.c * .5,
605
+ h: base.h
606
+ },
607
+ primary: darkPrimary,
608
+ "primary-foreground": {
609
+ l: .16,
610
+ c: primary.c * .25,
611
+ h: primary.h
612
+ },
613
+ secondary: {
614
+ l: .24,
615
+ c: base.c * 2.5,
616
+ h: base.h
617
+ },
618
+ "secondary-foreground": {
619
+ l: .9,
620
+ c: base.c,
621
+ h: base.h
622
+ },
623
+ muted: {
624
+ l: .22,
625
+ c: base.c * 2,
626
+ h: base.h
627
+ },
628
+ "muted-foreground": {
629
+ l: .7,
630
+ c: base.c,
631
+ h: base.h
632
+ },
633
+ accent: {
634
+ l: .27,
635
+ c: base.c * 2.5,
636
+ h: base.h
637
+ },
638
+ "accent-foreground": {
639
+ l: .97,
640
+ c: base.c * .5,
641
+ h: base.h
642
+ },
643
+ destructive: {
644
+ l: .58,
645
+ c: .2,
646
+ h: 27
647
+ },
648
+ "destructive-foreground": {
649
+ l: .985,
650
+ c: .01,
651
+ h: 27
652
+ },
653
+ border: {
654
+ l: .3,
655
+ c: base.c * 2,
656
+ h: base.h
657
+ },
658
+ input: {
659
+ l: .3,
660
+ c: base.c * 2,
661
+ h: base.h
662
+ },
663
+ ring: { ...darkPrimary },
664
+ "chart-1": {
665
+ l: .72,
666
+ c: Math.min(primary.c, .15),
667
+ h: primary.h
668
+ },
669
+ "chart-2": {
670
+ l: .72,
671
+ c: Math.min(primary.c, .14),
672
+ h: wrapHue(primary.h + hueOffsets[0])
673
+ },
674
+ "chart-3": {
675
+ l: .72,
676
+ c: Math.min(primary.c, .14),
677
+ h: wrapHue(primary.h + hueOffsets[1])
678
+ },
679
+ "chart-4": {
680
+ l: .72,
681
+ c: Math.min(primary.c, .14),
682
+ h: wrapHue(primary.h + hueOffsets[2])
683
+ },
684
+ "chart-5": {
685
+ l: .72,
686
+ c: Math.min(primary.c, .14),
687
+ h: wrapHue(primary.h + hueOffsets[3])
688
+ },
689
+ sidebar: {
690
+ l: .16,
691
+ c: base.c,
692
+ h: base.h
693
+ },
694
+ "sidebar-foreground": {
695
+ l: .97,
696
+ c: base.c * .5,
697
+ h: base.h
698
+ },
699
+ "sidebar-primary": { ...darkPrimary },
700
+ "sidebar-primary-foreground": {
701
+ l: .16,
702
+ c: primary.c * .25,
703
+ h: primary.h
704
+ },
705
+ "sidebar-accent": {
706
+ l: .25,
707
+ c: base.c * 2,
708
+ h: base.h
709
+ },
710
+ "sidebar-accent-foreground": {
711
+ l: .97,
712
+ c: base.c * .5,
713
+ h: base.h
714
+ },
715
+ "sidebar-border": {
716
+ l: .3,
717
+ c: base.c * 2,
718
+ h: base.h
719
+ },
720
+ "sidebar-ring": { ...darkPrimary }
721
+ };
722
+ }
723
+ /**
724
+ * Build the initial light + dark token maps numerically from the primary
725
+ * and base color. Foregrounds are derived from the primary (or base) hue;
726
+ * contrast verification adjusts lightness afterwards.
727
+ */
728
+ function buildSchemes(input) {
729
+ const base = BASE_COLORS[input.baseColor];
730
+ const primary = { ...input.primary };
731
+ const hueOffsets = input.chartHues ?? DEFAULT_CHART_HUES;
732
+ return {
733
+ light: lightScheme(base, primary, hueOffsets),
734
+ dark: darkScheme(base, primary, hueOffsets)
735
+ };
736
+ }
737
+ function wrapHue(h) {
738
+ return (h % 360 + 360) % 360;
739
+ }
740
+ // src/core/theme/contrast.ts
741
+ /** Text pairs: WCAG 2.2 AA requires >= 4.5:1. Blocking. */
742
+ const TEXT_PAIRS = [
743
+ ["foreground", "background"],
744
+ ["card-foreground", "card"],
745
+ ["popover-foreground", "popover"],
746
+ ["primary-foreground", "primary"],
747
+ ["secondary-foreground", "secondary"],
748
+ ["muted-foreground", "muted"],
749
+ ["muted-foreground", "background"],
750
+ ["accent-foreground", "accent"],
751
+ ["destructive-foreground", "destructive"],
752
+ ["sidebar-foreground", "sidebar"],
753
+ ["sidebar-primary-foreground", "sidebar-primary"],
754
+ ["sidebar-accent-foreground", "sidebar-accent"]
755
+ ];
756
+ /** UI-boundary pairs: WCAG 2.2 requires >= 3:1. Blocking. */
757
+ const UI_PAIRS = [
758
+ ["ring", "background"],
759
+ ["border", "background"],
760
+ ["sidebar-ring", "sidebar"],
761
+ ["sidebar-border", "sidebar"]
762
+ ];
763
+ function verifyScheme(scheme, tokens) {
764
+ const failures = [];
765
+ for (const [fg, bg] of TEXT_PAIRS) {
766
+ if (!tokens[fg] || !tokens[bg]) continue;
767
+ const ratio = wcagRatio(tokens[fg], tokens[bg]);
768
+ if (ratio < 4.5) failures.push({
769
+ scheme,
770
+ fg,
771
+ bg,
772
+ ratio,
773
+ threshold: 4.5,
774
+ kind: "text"
775
+ });
776
+ }
777
+ for (const [fg, bg] of UI_PAIRS) {
778
+ if (!tokens[fg] || !tokens[bg]) continue;
779
+ const ratio = wcagRatio(tokens[fg], tokens[bg]);
780
+ if (ratio < 3) failures.push({
781
+ scheme,
782
+ fg,
783
+ bg,
784
+ ratio,
785
+ threshold: 3,
786
+ kind: "ui"
787
+ });
788
+ }
789
+ return failures;
790
+ }
791
+ const SCAN_STEP = .02;
792
+ /**
793
+ * Find the passing lightness for the foreground token closest to its current
794
+ * value. Scans the full [0,1] range so a light fg on a vivid mid-lightness
795
+ * background can flip to a dark tinted fg (and vice versa).
796
+ */
797
+ function adjustToken(tokens, fg, bg, threshold) {
798
+ const fgColor = tokens[fg];
799
+ const bgColor = tokens[bg];
800
+ if (!fgColor || !bgColor) return null;
801
+ const startL = fgColor.l;
802
+ let best = null;
803
+ for (let candidateL = SCAN_STEP; candidateL <= 1; candidateL += SCAN_STEP) {
804
+ const rounded = Math.round(candidateL * 100) / 100;
805
+ tokens[fg] = {
806
+ ...fgColor,
807
+ l: rounded
808
+ };
809
+ if (wcagRatio(tokens[fg], tokens[bg]) >= threshold) {
810
+ const distance = Math.abs(rounded - startL);
811
+ if (!best || distance < best.distance) best = {
812
+ toL: rounded,
813
+ distance
814
+ };
815
+ }
816
+ }
817
+ tokens[fg] = fgColor;
818
+ if (!best) return null;
819
+ tokens[fg] = {
820
+ ...fgColor,
821
+ l: best.toL
822
+ };
823
+ return { toL: best.toL };
824
+ }
825
+ /**
826
+ * Auto-adjust failing pairs (bounded), recording every change.
827
+ * Mutates the token map. Returns failures that could not be fixed.
828
+ */
829
+ function autoAdjust(scheme, tokens) {
830
+ const adjustments = [];
831
+ for (let pass = 0; pass < 3; pass++) {
832
+ const failures = verifyScheme(scheme, tokens);
833
+ if (failures.length === 0) break;
834
+ for (const failure of failures) {
835
+ const fgColor = tokens[failure.fg];
836
+ const fixed = adjustToken(tokens, failure.fg, failure.bg, failure.threshold);
837
+ if (fixed) adjustments.push({
838
+ scheme,
839
+ token: failure.fg,
840
+ fromL: fgColor.l,
841
+ toL: fixed.toL
842
+ });
843
+ }
844
+ }
845
+ return {
846
+ fixed: adjustments,
847
+ remaining: verifyScheme(scheme, tokens)
848
+ };
849
+ }
850
+ function buildApcaReport(scheme, tokens) {
851
+ const entries = [];
852
+ for (const [fg, bg] of TEXT_PAIRS) {
853
+ if (!tokens[fg] || !tokens[bg]) continue;
854
+ entries.push({
855
+ scheme,
856
+ pair: `${fg}/${bg}`,
857
+ lc: apcaLc(tokens[fg], tokens[bg])
858
+ });
859
+ }
860
+ return entries;
861
+ }
862
+ // src/core/theme/theme.ts
863
+ var ThemeContrastError = class extends Error {
864
+ failures;
865
+ constructor(failures) {
866
+ const details = failures.map((f) => ` ${f.scheme} ${f.fg} on ${f.bg}: ${f.ratio.toFixed(2)}:1 (needs ${f.threshold}:1) — try primary lightness around ${suggestLightness(f)}`).join("\n");
867
+ super(`Theme failed WCAG AA contrast for ${failures.length} pair(s):\n${details}`);
868
+ this.name = "ThemeContrastError";
869
+ this.failures = failures;
870
+ }
871
+ };
872
+ /**
873
+ * Generate a complete theme: numeric OKLCH palette, contrast verification with
874
+ * bounded auto-adjustment, APCA reporting, and a shadcn registry:theme item.
875
+ * Throws ThemeContrastError when a pair still fails after adjustment.
876
+ */
877
+ function generateTheme(definition) {
878
+ const baseColor = BASE_COLOR_NAMES.includes(definition.baseColor) ? definition.baseColor : "neutral";
879
+ const schemes = buildSchemes({
880
+ primary: parseToOklch(definition.primary),
881
+ baseColor,
882
+ chartHues: definition.chartHues
883
+ });
884
+ const adjustments = [];
885
+ const failures = [];
886
+ for (const schemeName of ["light", "dark"]) {
887
+ const result = autoAdjust(schemeName, schemes[schemeName]);
888
+ adjustments.push(...result.fixed);
889
+ failures.push(...result.remaining);
890
+ }
891
+ const apca = [...buildApcaReport("light", schemes.light), ...buildApcaReport("dark", schemes.dark)];
892
+ if (failures.length > 0) throw new ThemeContrastError(failures);
893
+ return {
894
+ item: {
895
+ name: `theme-${definition.name}`,
896
+ type: "registry:theme",
897
+ title: definition.title,
898
+ description: definition.description,
899
+ cssVars: {
900
+ theme: { "--radius": "0.625rem" },
901
+ light: toCssVars(schemes.light),
902
+ dark: toCssVars(schemes.dark)
903
+ }
904
+ },
905
+ adjustments,
906
+ failures,
907
+ apca
908
+ };
909
+ }
910
+ function toCssVars(tokens) {
911
+ const vars = {};
912
+ for (const [token, color] of Object.entries(tokens)) vars[`--${token}`] = oklchCss(color);
913
+ return vars;
914
+ }
915
+ function suggestLightness(failure) {
916
+ if (failure.scheme === "light") return failure.kind === "text" ? .2 : .66;
917
+ return failure.kind === "text" ? .95 : .45;
918
+ }
919
+ // src/commands/init.ts
920
+ function themeCssPath(cwd) {
921
+ const css = readConfig(cwd)?.tailwind?.css;
922
+ if (css) return join(cwd, css);
923
+ for (const candidate of [
924
+ "src/index.css",
925
+ "src/app/globals.css",
926
+ "app/globals.css"
927
+ ]) {
928
+ const path = join(cwd, candidate);
929
+ if (existsSync(path)) return path;
930
+ }
931
+ return null;
932
+ }
933
+ function themeExists(cwd) {
934
+ const cssPath = themeCssPath(cwd);
935
+ if (!cssPath || !existsSync(cssPath)) return false;
936
+ return readFileSync(cssPath, "utf-8").includes(":root");
937
+ }
938
+ async function applyCustomTheme(cwd, primary, baseColor, force) {
939
+ let generated;
940
+ try {
941
+ generated = generateTheme({
942
+ name: "custom",
943
+ title: "Custom Kira Kit theme",
944
+ description: `Custom OKLCH theme generated from primary ${primary}.`,
945
+ primary,
946
+ baseColor: baseColor ?? "neutral"
947
+ });
948
+ } catch (error) {
949
+ if (error instanceof ThemeContrastError) {
950
+ console.error(`error: ${error.message}`);
951
+ return 1;
952
+ }
953
+ throw error;
954
+ }
955
+ const outPath = join(cwd, "kira-theme.json");
956
+ writeFileSync(outPath, JSON.stringify(generated.item, null, 2) + "\n", "utf-8");
957
+ const args = [
958
+ "add",
959
+ outPath,
960
+ "--yes"
961
+ ];
962
+ if (force) args.push("--overwrite");
963
+ const code = await runShadcnChecked([
964
+ ...args,
965
+ "--cwd",
966
+ cwd
967
+ ], cwd);
968
+ if (code === 0) success("Custom theme applied.");
969
+ return code;
970
+ }
971
+ async function ensureBaseConfig(cwd, yes) {
972
+ if (readConfig(cwd)) return 0;
973
+ info("No components.json found — delegating base setup to shadcn (Base UI)…");
974
+ const args = [
975
+ "init",
976
+ "--base",
977
+ "base"
978
+ ];
979
+ if (yes) args.push("--yes");
980
+ return runShadcnChecked([
981
+ ...args,
982
+ "--cwd",
983
+ cwd
984
+ ], cwd);
985
+ }
986
+ function registerRegistry(cwd) {
987
+ if (upsertKiraRegistry(cwd)) success("Registered the @kira-kit registry in components.json.");
988
+ else info("The @kira-kit registry is already registered.");
989
+ }
990
+ async function applyPreset(cwd, options) {
991
+ const args = [
992
+ "add",
993
+ `@kira-kit/theme-${options.preset}`,
994
+ "--yes"
995
+ ];
996
+ if (options.force) args.push("--overwrite");
997
+ const code = await runShadcnChecked([
998
+ ...args,
999
+ "--cwd",
1000
+ cwd
1001
+ ], cwd);
1002
+ if (code === 0) success(`Theme preset "${options.preset}" applied.`);
1003
+ return code;
1004
+ }
1005
+ /** Interactive theme choice; null means "keep the current theme". */
1006
+ async function interactiveTheme(cwd, options, hasTheme) {
1007
+ if (options.yes || !process.stdin.isTTY) return null;
1008
+ const ctx = { yes: options.yes };
1009
+ if (await select(ctx, "How should the theme be set up?", [{
1010
+ value: "keep",
1011
+ label: "Keep the current theme"
1012
+ }, {
1013
+ value: "custom",
1014
+ label: "Generate a custom theme from a primary color"
1015
+ }], "keep") !== "custom") return null;
1016
+ const primary = await text(ctx, "Primary color (hex, e.g. #e2694a)", "#e2694a", (value) => /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value.trim()) ? void 0 : "Enter a hex color like #e2694a");
1017
+ const force = hasTheme ? await confirm(ctx, "A theme already exists. Overwrite it?", true) : true;
1018
+ return applyCustomTheme(cwd, primary, options.baseColor, force);
1019
+ }
1020
+ async function init(options) {
1021
+ const cwd = options.cwd || process.cwd();
1022
+ const baseCode = await ensureBaseConfig(cwd, Boolean(options.yes));
1023
+ if (baseCode !== 0) return baseCode;
1024
+ registerRegistry(cwd);
1025
+ if (options.preset) return applyPreset(cwd, options);
1026
+ if (options.primary) return applyCustomTheme(cwd, options.primary, options.baseColor, options.force);
1027
+ const hasTheme = themeExists(cwd);
1028
+ const interactiveCode = await interactiveTheme(cwd, options, hasTheme);
1029
+ if (interactiveCode !== null) return interactiveCode;
1030
+ if (hasTheme && !options.force) {
1031
+ info("A theme is already configured — leaving it untouched.");
1032
+ info("To replace it: kira-kit init --preset <name> --force, or kira-kit theme --primary <color> --apply");
1033
+ }
1034
+ success("Kira Kit initialized. Try: kira-kit add button");
1035
+ return 0;
1036
+ }
1037
+ // src/lib/namespace.ts
1038
+ /** Map a bare item name to the @kira-kit namespace; pass through addresses. */
1039
+ function toItemAddress(name) {
1040
+ if (name.startsWith("@") || name.startsWith("http://") || name.startsWith("https://") || name.startsWith("./") || name.startsWith("../") || name.startsWith("/") || name === "." || name === "..") return name;
1041
+ return `@kira-kit/${name}`;
1042
+ }
1043
+ // src/commands/add.ts
1044
+ async function fetchAllItemNames(cwd) {
1045
+ const registryUrl = getRegistryUrl(cwd);
1046
+ let response;
1047
+ try {
1048
+ response = await fetch(`${registryUrl}/registry.json`);
1049
+ } catch {
1050
+ throw new RegistryError(`Could not reach the Kira Kit registry at ${registryUrl}`, "Check your internet connection and retry, or run 'kira-kit list' to see what's cached.");
1051
+ }
1052
+ if (!response.ok) throw new RegistryError(`Registry index request failed (HTTP ${response.status}) at ${registryUrl}/registry.json`, "Verify your components.json '@kira-kit' registry URL, then retry.");
1053
+ return ((await response.json()).items ?? []).map((item) => item.name);
1054
+ }
1055
+ function shadcnFlags(options) {
1056
+ const args = [];
1057
+ if (options.yes) args.push("--yes");
1058
+ if (options.overwrite) args.push("--overwrite");
1059
+ if (options.path) args.push("--path", options.path);
1060
+ if (options.dryRun) args.push("--dry-run");
1061
+ if (options.diff) args.push("--diff");
1062
+ if (options.view) args.push("--view");
1063
+ return args;
1064
+ }
1065
+ async function resolveItems(options, cwd) {
1066
+ const items = options.items ?? [];
1067
+ if (!options.all) {
1068
+ if (items.length === 0) throw new ValidationError("No items specified.", "Use 'kira-kit add button' or 'kira-kit add --all'.");
1069
+ return items.map(toItemAddress);
1070
+ }
1071
+ if (items.length > 0) throw new ValidationError("--all cannot be combined with explicit item names.", "Pass either item names or --all, not both.");
1072
+ const names = await fetchAllItemNames(cwd);
1073
+ if (names.length === 0) throw new RegistryError("The registry index contains no items.", "Check the '@kira-kit' registry URL in components.json.");
1074
+ return names.map(toItemAddress);
1075
+ }
1076
+ async function addComponents(options) {
1077
+ const cwd = options.cwd || process.cwd();
1078
+ const items = await resolveItems(options, cwd);
1079
+ return runShadcnChecked([
1080
+ "add",
1081
+ ...shadcnFlags(options),
1082
+ "--cwd",
1083
+ cwd,
1084
+ ...items
1085
+ ], cwd);
1086
+ }
1087
+ // src/commands/list.ts
1088
+ async function listComponents(options) {
1089
+ const args = ["list", "@kira-kit"];
1090
+ if (options.json) args.push("--json");
1091
+ return runShadcnChecked(args);
1092
+ }
1093
+ // src/commands/view.ts
1094
+ async function viewItems(options) {
1095
+ if (options.items.length === 0) throw new ValidationError("No items specified.", "Use 'kira-kit view button' to inspect an item before installing.");
1096
+ return runShadcnChecked(["view", ...options.items.map(toItemAddress)]);
1097
+ }
1098
+ // src/commands/search.ts
1099
+ async function searchItems(options) {
1100
+ const args = ["search", "@kira-kit"];
1101
+ if (options.query.length > 0) args.push("--query", options.query.join(" "));
1102
+ if (options.json) args.push("--json");
1103
+ return runShadcnChecked(args);
1104
+ }
1105
+ // src/core/checks/suppressions.ts
1106
+ const LINE_SUPPRESSION = /\/\/\s*kira-kit-ignore\s+([a-z0-9-]+)\s*:\s*(.+)$/i;
1107
+ const FILE_SUPPRESSION = /\/\*\s*kira-kit-ignore-file\s+([a-z0-9-]+)\s*:\s*([^*]+)\*\//i;
1108
+ /** Suppression comment without a reason is itself an error. */
1109
+ const LINE_SUPPRESSION_NO_REASON = /\/\/\s*kira-kit-ignore\s+([a-z0-9-]+)\s*$/i;
1110
+ const FILE_SUPPRESSION_NO_REASON = /\/\*\s*kira-kit-ignore-file\s+([a-z0-9-]+)\s*\*\//i;
1111
+ function parseSuppressions(source, file) {
1112
+ const suppressions = {
1113
+ line: [],
1114
+ file: []
1115
+ };
1116
+ const errors = [];
1117
+ source.split("\n").forEach((text, index) => {
1118
+ const match = LINE_SUPPRESSION.exec(text.trim());
1119
+ if (match) {
1120
+ suppressions.line.push({
1121
+ checkId: match[1],
1122
+ line: index + 1,
1123
+ reason: match[2].trim()
1124
+ });
1125
+ return;
1126
+ }
1127
+ if (LINE_SUPPRESSION_NO_REASON.exec(text.trim())) errors.push({
1128
+ checkId: "suppression",
1129
+ severity: "error",
1130
+ file,
1131
+ line: index + 1,
1132
+ message: "kira-kit-ignore without a reason — add `: <why this is intentional>`."
1133
+ });
1134
+ });
1135
+ const fileMatch = FILE_SUPPRESSION.exec(source);
1136
+ if (fileMatch) suppressions.file.push({
1137
+ checkId: fileMatch[1],
1138
+ line: 0,
1139
+ reason: fileMatch[2].trim()
1140
+ });
1141
+ else if (FILE_SUPPRESSION_NO_REASON.exec(source)) errors.push({
1142
+ checkId: "suppression",
1143
+ severity: "error",
1144
+ file,
1145
+ message: "kira-kit-ignore-file without a reason — add `: <why this is intentional>`."
1146
+ });
1147
+ return {
1148
+ errors,
1149
+ suppressions
1150
+ };
1151
+ }
1152
+ function isSuppressed(finding, suppressions) {
1153
+ if (suppressions.file.some((s) => s.checkId === finding.checkId)) return true;
1154
+ if (finding.line === void 0) return false;
1155
+ return suppressions.line.some((s) => s.checkId === finding.checkId && s.line + 1 === finding.line);
1156
+ }
1157
+ function unusedSuppressions(findings, suppressions, file) {
1158
+ const used = /* @__PURE__ */ new Set();
1159
+ for (const suppression of suppressions.file) {
1160
+ const key = `file:${suppression.checkId}`;
1161
+ if (findings.some((f) => f.checkId === suppression.checkId)) used.add(key);
1162
+ }
1163
+ for (const suppression of suppressions.line) {
1164
+ const key = `line:${suppression.line}:${suppression.checkId}`;
1165
+ if (findings.some((f) => f.checkId === suppression.checkId && f.line === suppression.line + 1)) used.add(key);
1166
+ }
1167
+ const unused = [];
1168
+ for (const suppression of suppressions.file) if (!used.has(`file:${suppression.checkId}`)) unused.push({
1169
+ checkId: "suppression",
1170
+ severity: "warning",
1171
+ file,
1172
+ message: `file-level kira-kit-ignore for "${suppression.checkId}" suppresses nothing.`
1173
+ });
1174
+ for (const suppression of suppressions.line) if (!used.has(`line:${suppression.line}:${suppression.checkId}`)) unused.push({
1175
+ checkId: "suppression",
1176
+ severity: "warning",
1177
+ file,
1178
+ line: suppression.line,
1179
+ message: `kira-kit-ignore for "${suppression.checkId}" suppresses nothing.`
1180
+ });
1181
+ return unused;
1182
+ }
1183
+ // src/core/registry/extract.ts
1184
+ /**
1185
+ * Parse a TS/TSX module with the TypeScript compiler API and extract imports.
1186
+ * Handles `import "pkg"`, `import type`, dynamic `import()`, `export … from`,
1187
+ * and scoped/deep subpaths. `node:*` builtins are exempt. Reusable by check 1.
1188
+ */
1189
+ function extractImports(source, fileName = "file.tsx") {
1190
+ const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, fileName.endsWith(".ts") ? ts.ScriptKind.TS : ts.ScriptKind.TSX);
1191
+ const external = /* @__PURE__ */ new Map();
1192
+ const internal = /* @__PURE__ */ new Map();
1193
+ const lineOf = (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
1194
+ const add = (target, specifier, node, key) => {
1195
+ const line = lineOf(node);
1196
+ const existing = target.get(key);
1197
+ if (!existing || line < existing.line) target.set(key, {
1198
+ specifier,
1199
+ line
1200
+ });
1201
+ };
1202
+ const visit = (node) => {
1203
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) classify(node.moduleSpecifier.text, external, internal, node, add);
1204
+ else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== void 0 && ts.isStringLiteral(node.moduleSpecifier)) classify(node.moduleSpecifier.text, external, internal, node, add);
1205
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) classify(node.arguments[0].text, external, internal, node, add);
1206
+ ts.forEachChild(node, visit);
1207
+ };
1208
+ visit(sourceFile);
1209
+ return {
1210
+ external: [...external.values()].sort((a, b) => a.line - b.line),
1211
+ internal: [...internal.values()].sort((a, b) => a.line - b.line)
1212
+ };
1213
+ }
1214
+ function classify(specifier, external, internal, node, add) {
1215
+ if (specifier.startsWith("node:")) return "";
1216
+ if (specifier.startsWith("@/components/ui/")) {
1217
+ const name = specifier.replace("@/components/ui/", "").replace(/\.(tsx|ts)$/, "");
1218
+ if (name && !name.includes("/")) add(internal, specifier, node, name);
1219
+ return "";
1220
+ }
1221
+ if (specifier.startsWith("@/hooks/")) {
1222
+ const name = specifier.replace("@/hooks/", "").replace(/\.(tsx|ts)$/, "");
1223
+ if (name && !name.includes("/")) add(internal, specifier, node, name);
1224
+ return "";
1225
+ }
1226
+ if (specifier.startsWith("@/")) return "";
1227
+ if (specifier.startsWith(".")) return "";
1228
+ add(external, specifier, node, packageNameOf(specifier));
1229
+ return "";
1230
+ }
1231
+ /** Trim deep subpaths and peer-style suffixes to the package name. */
1232
+ function packageNameOf(specifier) {
1233
+ const parts = specifier.split("/");
1234
+ if (specifier.startsWith("@")) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : specifier;
1235
+ return parts[0];
1236
+ }
1237
+ // src/core/checks/types.ts
1238
+ const BUILTIN_IMPORTS = /* @__PURE__ */ new Set([
1239
+ "react",
1240
+ "react-dom",
1241
+ "react/jsx-runtime",
1242
+ "react/jsx-dev-runtime"
1243
+ ]);
1244
+ // src/core/checks/imports-deps.ts
1245
+ /** Support modules embedded as files rather than registry items. */
1246
+ const SUPPORT_MODULES = /* @__PURE__ */ new Set(["prop-guards", "content-keys"]);
1247
+ function itemNameOf(specifier) {
1248
+ return specifier.replace(/^@\/(components\/ui|hooks)\//, "").replace(/\.(tsx|ts)$/, "");
1249
+ }
1250
+ function undeclaredImports(fileName, meta, external, internal) {
1251
+ const findings = [];
1252
+ const declared = new Set(meta.dependencies);
1253
+ const declaredRegistry = new Set(meta.registryDependencies);
1254
+ for (const entry of external) {
1255
+ const pkg = packageNameOf(entry.specifier);
1256
+ if (BUILTIN_IMPORTS.has(pkg) || declared.has(pkg)) continue;
1257
+ findings.push({
1258
+ checkId: "imports-deps",
1259
+ severity: "error",
1260
+ file: fileName,
1261
+ line: entry.line,
1262
+ message: `imports "${pkg}" but the registry item does not declare it in dependencies.`
1263
+ });
1264
+ }
1265
+ for (const entry of internal) {
1266
+ const name = itemNameOf(entry.specifier);
1267
+ if (SUPPORT_MODULES.has(name)) continue;
1268
+ if (declaredRegistry.has(`@kira-kit/${name}`)) continue;
1269
+ findings.push({
1270
+ checkId: "imports-deps",
1271
+ severity: "error",
1272
+ file: fileName,
1273
+ line: entry.line,
1274
+ message: `imports "@kira-kit/${name}" but the registry item does not declare it in registryDependencies.`
1275
+ });
1276
+ }
1277
+ return findings;
1278
+ }
1279
+ function unusedDeclarations(fileName, meta, external, internal) {
1280
+ const findings = [];
1281
+ const imported = new Set(external.map((e) => packageNameOf(e.specifier)));
1282
+ const importedRegistry = new Set(internal.flatMap((e) => {
1283
+ const name = itemNameOf(e.specifier);
1284
+ return SUPPORT_MODULES.has(name) ? [] : [name];
1285
+ }));
1286
+ for (const dep of meta.dependencies) {
1287
+ if (BUILTIN_IMPORTS.has(dep) || imported.has(dep)) continue;
1288
+ findings.push({
1289
+ checkId: "imports-deps",
1290
+ severity: "error",
1291
+ file: fileName,
1292
+ message: `declares dependency "${dep}" but no file of this item imports it.`
1293
+ });
1294
+ }
1295
+ for (const dep of meta.registryDependencies) {
1296
+ const name = dep.replace("@kira-kit/", "");
1297
+ if (importedRegistry.has(name)) continue;
1298
+ findings.push({
1299
+ checkId: "imports-deps",
1300
+ severity: "error",
1301
+ file: fileName,
1302
+ message: `declares registry dependency "${dep}" but no file of this item imports it.`
1303
+ });
1304
+ }
1305
+ return findings;
1306
+ }
1307
+ /**
1308
+ * Check 1: imports vs declared dependencies — bidirectional.
1309
+ * Every bare npm import must be declared in the item's `dependencies`
1310
+ * (or be a React builtin), every internal import must be declared as
1311
+ * `@kira-kit/<name>`, and every declared dependency must actually be used.
1312
+ */
1313
+ const importsMatchDeps = (file, ctx) => {
1314
+ const meta = ctx.items.get(file.name);
1315
+ if (!meta) return [];
1316
+ const { external, internal } = extractImports(file.content, file.path);
1317
+ return [...undeclaredImports(file.name, meta, external, internal), ...unusedDeclarations(file.name, meta, external, internal)];
1318
+ };
1319
+ // src/core/checks/dead-animate.ts
1320
+ const ANIMATE_BUILTINS = /* @__PURE__ */ new Set([
1321
+ "in",
1322
+ "out",
1323
+ "spin",
1324
+ "ping",
1325
+ "pulse",
1326
+ "bounce",
1327
+ "none"
1328
+ ]);
1329
+ const ANIMATE_REGEX = /animate-([a-z0-9-]+)/g;
1330
+ /**
1331
+ * Check 3: `animate-*` utility without a matching `--animate-*` token AND
1332
+ * `@keyframes` in the global CSS (dead animation). Builtin Tailwind
1333
+ * animations are exempt.
1334
+ */
1335
+ const deadAnimate = (file, ctx) => {
1336
+ const findings = [];
1337
+ const names = /* @__PURE__ */ new Set();
1338
+ let match;
1339
+ while ((match = ANIMATE_REGEX.exec(file.content)) !== null) names.add(match[1]);
1340
+ for (const name of names) {
1341
+ if (ANIMATE_BUILTINS.has(name)) continue;
1342
+ const hasToken = ctx.indexCss.includes(`--animate-${name}`);
1343
+ const hasKeyframes = new RegExp(`@keyframes\\s+${name}\\s*\\{`).test(ctx.indexCss);
1344
+ if (!hasToken || !hasKeyframes) findings.push({
1345
+ checkId: "dead-animate",
1346
+ severity: "error",
1347
+ file: file.name,
1348
+ message: `uses \`animate-${name}\` but the global CSS is missing ${hasToken ? `@keyframes ${name}` : `--animate-${name}`} (dead animation).`
1349
+ });
1350
+ }
1351
+ return findings;
1352
+ };
1353
+ function animateNames(content) {
1354
+ const names = /* @__PURE__ */ new Set();
1355
+ let match;
1356
+ while ((match = ANIMATE_REGEX.exec(content)) !== null) names.add(match[1]);
1357
+ return names;
1358
+ }
1359
+ // src/core/checks/data-slot-cva.ts
1360
+ /**
1361
+ * Check 4: `data-slot` on the root of every component, and cva users export
1362
+ * their `*Variants`.
1363
+ */
1364
+ const dataSlotAndCva = (file) => {
1365
+ const findings = [];
1366
+ const content = file.content;
1367
+ if (!file.name.startsWith("hooks/") && !content.includes("data-slot=") && !/["']data-slot["']\s*:/.test(content)) findings.push({
1368
+ checkId: "data-slot-cva",
1369
+ severity: "warning",
1370
+ file: file.name,
1371
+ message: "no `data-slot=` found in component file."
1372
+ });
1373
+ const usesCva = content.includes("class-variance-authority") || /\bcva\s*\(/.test(content);
1374
+ const exportsVariants = /export\s+(?:const|function|var)\s+\w*Variants/.test(content) || /export\s*\{[^}]*Variants/.test(content);
1375
+ if (usesCva && !exportsVariants) findings.push({
1376
+ checkId: "data-slot-cva",
1377
+ severity: "warning",
1378
+ file: file.name,
1379
+ message: "uses cva but exports no `*Variants`."
1380
+ });
1381
+ return findings;
1382
+ };
1383
+ // src/core/checks/reduced-motion.ts
1384
+ /**
1385
+ * Check 5: motion (gsap or animate-*) without reduced-motion gating.
1386
+ * JS-driven motion (gsap) needs a JS gate in the file; CSS animation
1387
+ * utilities are also covered by `motion-reduce:` variants or the kit-wide
1388
+ * `prefers-reduced-motion` gate in src/index.css.
1389
+ */
1390
+ const reducedMotion = (file, ctx) => {
1391
+ const content = file.content;
1392
+ const usesGsap = /from\s+["']gsap/.test(content);
1393
+ const usesAnimate = animateNames(content).size > 0;
1394
+ const jsGated = content.includes("useReducedMotion") || content.includes("gsap.matchMedia") || content.includes("prefersReducedMotion");
1395
+ const cssGated = jsGated || /motion-reduce:/.test(content);
1396
+ const globalCssGate = /@media\s*\(prefers-reduced-motion:\s*reduce\)/.test(ctx.indexCss) && /animation-duration:\s*0/.test(ctx.indexCss);
1397
+ if (usesGsap && !jsGated) return [{
1398
+ checkId: "reduced-motion",
1399
+ severity: "warning",
1400
+ file: file.name,
1401
+ message: "imports gsap but has no useReducedMotion / prefersReducedMotion / gsap.matchMedia gate."
1402
+ }];
1403
+ if (usesAnimate && !cssGated && !globalCssGate) return [{
1404
+ checkId: "reduced-motion",
1405
+ severity: "warning",
1406
+ file: file.name,
1407
+ message: "uses animate-* but has no motion-reduce variant, JS gate, or global reduced-motion gate in index.css."
1408
+ }];
1409
+ return [];
1410
+ };
1411
+ // src/core/checks/target-size.ts
1412
+ /**
1413
+ * Check 6: interactive targets below 24px (WCAG 2.5.8). Flags a bare
1414
+ * `h-*`/`size-*` below 6 on interactive elements: class strings with
1415
+ * interactive affordances (pointer cursor, focus ring, hover/active state)
1416
+ * or className strings on interactive JSX tags. Small icons and decoration
1417
+ * inside a properly sized target are not findings.
1418
+ */
1419
+ const SMALL_SIZE = /^(?:h|size)-(\d+(?:\.\d+)?)$/;
1420
+ const STRING_LITERAL = /"([^"\\\n]*)"|'([^'\\\n]*)'/g;
1421
+ const INTERACTIVE_TAG = /<(?:button|input|select|textarea|a|summary)\b[^>]*>/g;
1422
+ function isInteractiveToken(token) {
1423
+ return token === "cursor-pointer" || token === "cursor-grab" || token.startsWith("focus-visible:") || token.startsWith("focus:") || token.startsWith("hover:bg-") || token.startsWith("active:");
1424
+ }
1425
+ const targetSize = (file) => {
1426
+ const findings = [];
1427
+ const flaggedLines = /* @__PURE__ */ new Set();
1428
+ const scan = (text, offset, requireMarker) => {
1429
+ for (const match of text.matchAll(STRING_LITERAL)) {
1430
+ const tokens = (match[1] ?? match[2] ?? "").split(/\s+/);
1431
+ if (requireMarker && !tokens.some(isInteractiveToken)) continue;
1432
+ const small = tokens.filter((token) => {
1433
+ const m = SMALL_SIZE.exec(token);
1434
+ return m !== null && Number(m[1]) < 6;
1435
+ });
1436
+ if (small.length === 0) continue;
1437
+ const line = file.content.slice(0, offset + match.index).split("\n").length;
1438
+ if (flaggedLines.has(line)) continue;
1439
+ flaggedLines.add(line);
1440
+ findings.push({
1441
+ checkId: "target-size",
1442
+ severity: "warning",
1443
+ file: file.name,
1444
+ line,
1445
+ message: `interactive element with ${small.join("/")} below 24px — check target size (WCAG 2.5.8).`
1446
+ });
1447
+ }
1448
+ };
1449
+ scan(file.content, 0, true);
1450
+ for (const tag of file.content.matchAll(INTERACTIVE_TAG)) scan(tag[0], tag.index, false);
1451
+ return findings;
1452
+ };
1453
+ // src/core/checks/raw-colors.ts
1454
+ /** Check 7: raw hex/rgb color literals — use semantic tokens instead. */
1455
+ const RAW_COLOR = /#[0-9a-fA-F]{3,8}\b|\brgba?\(/g;
1456
+ const rawColors = (file) => {
1457
+ const findings = [];
1458
+ for (const match of file.content.matchAll(RAW_COLOR)) {
1459
+ const line = file.content.slice(0, match.index).split("\n").length;
1460
+ findings.push({
1461
+ checkId: "raw-colors",
1462
+ severity: "warning",
1463
+ file: file.name,
1464
+ line,
1465
+ message: `raw colour literal (${match[0]}) — use semantic tokens.`
1466
+ });
1467
+ }
1468
+ return findings;
1469
+ };
1470
+ // src/core/checks/layout-transitions.ts
1471
+ /**
1472
+ * Check 8: `transition-all` or width/height/top/left transitions —
1473
+ * animate transform/opacity instead.
1474
+ */
1475
+ const LAYOUT_TRANSITION = /\btransition-all\b|transition-\[(width|height|top|left)[^\]]*\]/g;
1476
+ const layoutTransitions = (file) => {
1477
+ const findings = [];
1478
+ for (const match of file.content.matchAll(LAYOUT_TRANSITION)) {
1479
+ const line = file.content.slice(0, match.index).split("\n").length;
1480
+ findings.push({
1481
+ checkId: "layout-transitions",
1482
+ severity: "warning",
1483
+ file: file.name,
1484
+ line,
1485
+ message: `${match[0]} — use transform/opacity.`
1486
+ });
1487
+ }
1488
+ return findings;
1489
+ };
1490
+ // src/core/checks/arbitrary-values.ts
1491
+ /**
1492
+ * Check 9: one-off arbitrary z-/shadow-/rounded- values outside token scales.
1493
+ * `inherit` and values derived from design tokens (`var(--…)`) stay inside
1494
+ * the token system and are not findings.
1495
+ */
1496
+ const ARBITRARY = /\b(z|shadow|rounded)-\[([^\]]*)\]/g;
1497
+ const arbitraryValues = (file) => {
1498
+ const findings = [];
1499
+ for (const match of file.content.matchAll(ARBITRARY)) {
1500
+ const value = match[2];
1501
+ if (value === "inherit" || value.includes("var(--")) continue;
1502
+ const line = file.content.slice(0, match.index).split("\n").length;
1503
+ findings.push({
1504
+ checkId: "arbitrary-values",
1505
+ severity: "warning",
1506
+ file: file.name,
1507
+ line,
1508
+ message: `arbitrary ${match[1]}-[${value}] outside the token scales.`
1509
+ });
1510
+ }
1511
+ return findings;
1512
+ };
1513
+ // src/core/checks/registry-metadata.ts
1514
+ const BOILERPLATE_PATTERNS = [
1515
+ /^component from kira kit/i,
1516
+ /^todo:/i,
1517
+ /^\s*$/,
1518
+ /^(a |an |the )?[\w-]+ component\.?$/i
1519
+ ];
1520
+ /**
1521
+ * Check 10: registry item metadata — description present, not boilerplate,
1522
+ * at least one category.
1523
+ */
1524
+ const registryMetadata = (file, ctx) => {
1525
+ const meta = ctx.items.get(file.name);
1526
+ if (!meta) return [];
1527
+ const findings = [];
1528
+ const description = meta.description.trim();
1529
+ if (description.length === 0) findings.push({
1530
+ checkId: "registry-metadata",
1531
+ severity: "error",
1532
+ file: file.name,
1533
+ message: "registry item has an empty description."
1534
+ });
1535
+ else if (description.length < 20 || BOILERPLATE_PATTERNS.some((p) => p.test(description))) findings.push({
1536
+ checkId: "registry-metadata",
1537
+ severity: "error",
1538
+ file: file.name,
1539
+ message: `boilerplate description "${description.slice(0, 60)}" — describe what makes this item distinct.`
1540
+ });
1541
+ if (meta.categories.length === 0) findings.push({
1542
+ checkId: "registry-metadata",
1543
+ severity: "error",
1544
+ file: file.name,
1545
+ message: "registry item declares no category."
1546
+ });
1547
+ return findings;
1548
+ };
1549
+ // src/core/checks/base-ui-only.ts
1550
+ const FORBIDDEN$1 = /^(radix-ui|@radix-ui\/|react-aria)/;
1551
+ /** Check 11: Base UI only — flag Radix and React Aria imports. */
1552
+ const baseUiOnly = (file) => {
1553
+ const { external } = extractImports(file.content, file.path);
1554
+ const findings = [];
1555
+ for (const entry of external) if (FORBIDDEN$1.test(entry.specifier)) findings.push({
1556
+ checkId: "base-ui-only",
1557
+ severity: "error",
1558
+ file: file.name,
1559
+ line: entry.line,
1560
+ message: `imports "${entry.specifier}" — Kira Kit is Base UI only (@base-ui/react).`
1561
+ });
1562
+ return findings;
1563
+ };
1564
+ // src/core/checks/cn-source.ts
1565
+ const FORBIDDEN = /^(clsx|tailwind-merge)(\/|$)/;
1566
+ const LOCAL_CN = /from\s+["']@\/lib\/(cn|utils)["']/;
1567
+ /** Check 12: `cn` source — components must use the `cn` package. */
1568
+ const cnSource = (file) => {
1569
+ const { external } = extractImports(file.content, file.path);
1570
+ const findings = [];
1571
+ for (const entry of external) if (FORBIDDEN.test(entry.specifier)) findings.push({
1572
+ checkId: "cn-source",
1573
+ severity: "error",
1574
+ file: file.name,
1575
+ line: entry.line,
1576
+ message: `imports "${entry.specifier}" — use the \`cn\` package instead.`
1577
+ });
1578
+ const localMatch = LOCAL_CN.exec(file.content);
1579
+ if (localMatch) {
1580
+ const line = file.content.slice(0, localMatch.index).split("\n").length;
1581
+ findings.push({
1582
+ checkId: "cn-source",
1583
+ severity: "error",
1584
+ file: file.name,
1585
+ line,
1586
+ message: `imports cn from "${localMatch[1] === "cn" ? "@/lib/cn" : "@/lib/utils"}" — use the \`cn\` package instead.`
1587
+ });
1588
+ }
1589
+ return findings;
1590
+ };
1591
+ // src/core/checks/runner.ts
1592
+ const CHECKS = [
1593
+ importsMatchDeps,
1594
+ deadAnimate,
1595
+ dataSlotAndCva,
1596
+ reducedMotion,
1597
+ targetSize,
1598
+ rawColors,
1599
+ layoutTransitions,
1600
+ arbitraryValues,
1601
+ registryMetadata,
1602
+ baseUiOnly,
1603
+ cnSource
1604
+ ];
1605
+ const SKIP_FILES = /* @__PURE__ */ new Set([
1606
+ "registry",
1607
+ "content-keys",
1608
+ "index",
1609
+ "prop-guards"
1610
+ ]);
1611
+ function sourceDirs(repoRoot, paths) {
1612
+ if (paths.length === 0) return [[join(repoRoot, "src/components/ui"), "ui/"], [join(repoRoot, "src/hooks"), "hooks/"]];
1613
+ return paths.map((path) => {
1614
+ const abs = join(repoRoot, path);
1615
+ return [abs, abs.includes(join("src", "components", "ui")) ? "ui/" : "hooks/"];
1616
+ });
1617
+ }
1618
+ function collectSourceFiles$1(repoRoot, paths) {
1619
+ const files = [];
1620
+ for (const [dir, prefix] of sourceDirs(repoRoot, paths)) {
1621
+ if (!existsSync(dir)) continue;
1622
+ for (const entry of readdirSync(dir)) {
1623
+ if (!/\.(tsx|ts)$/.test(entry)) continue;
1624
+ const name = entry.replace(/\.(tsx|ts)$/, "");
1625
+ if (SKIP_FILES.has(name)) continue;
1626
+ files.push({
1627
+ name: `${prefix}${name}`,
1628
+ path: join(dir, entry),
1629
+ content: readFileSync(join(dir, entry), "utf-8")
1630
+ });
1631
+ }
1632
+ }
1633
+ return files;
1634
+ }
1635
+ function checkFile(file, ctx) {
1636
+ const fileFindings = CHECKS.flatMap((check) => check(file, ctx));
1637
+ const { errors, suppressions } = parseSuppressions(file.content, file.name);
1638
+ const valid = errors.filter((e) => e.checkId === "suppression" && e.severity === "error");
1639
+ const kept = fileFindings.filter((finding) => !isSuppressed(finding, suppressions));
1640
+ return {
1641
+ findings: [
1642
+ ...kept,
1643
+ ...valid,
1644
+ ...unusedSuppressions(fileFindings, suppressions, file.name)
1645
+ ],
1646
+ suppressed: fileFindings.length - kept.length
1647
+ };
1648
+ }
1649
+ function runChecks(options) {
1650
+ const { repoRoot } = options;
1651
+ const indexCssPath = join(repoRoot, "src/index.css");
1652
+ const ctx = {
1653
+ indexCss: existsSync(indexCssPath) ? readFileSync(indexCssPath, "utf-8") : "",
1654
+ items: loadItemMeta(repoRoot)
1655
+ };
1656
+ const files = collectSourceFiles$1(repoRoot, options.paths);
1657
+ const allFindings = [];
1658
+ let suppressed = 0;
1659
+ for (const file of files) {
1660
+ const result = checkFile(file, ctx);
1661
+ suppressed += result.suppressed;
1662
+ allFindings.push(...result.findings);
1663
+ }
1664
+ const failing = options.ci ? allFindings.length : allFindings.filter((f) => f.severity === "error").length;
1665
+ return {
1666
+ findings: allFindings,
1667
+ suppressed,
1668
+ ci: options.ci,
1669
+ failing,
1670
+ filesChecked: files.length
1671
+ };
1672
+ }
1673
+ function readRegistryItems(registryFile) {
1674
+ if (!existsSync(registryFile)) return [];
1675
+ try {
1676
+ return JSON.parse(readFileSync(registryFile, "utf-8")).items ?? [];
1677
+ } catch {
1678
+ return [];
1679
+ }
1680
+ }
1681
+ function toItemMeta(item) {
1682
+ return {
1683
+ dependencies: item.dependencies ?? [],
1684
+ registryDependencies: item.registryDependencies ?? [],
1685
+ files: (item.files ?? []).map((f) => typeof f === "string" ? f : f.path),
1686
+ description: item.description ?? "",
1687
+ categories: item.categories ?? []
1688
+ };
1689
+ }
1690
+ function loadItemMeta(repoRoot) {
1691
+ const metaByKey = /* @__PURE__ */ new Map();
1692
+ const registryFiles = [
1693
+ [join(repoRoot, "src/components/ui/registry.json"), "ui"],
1694
+ [join(repoRoot, "src/hooks/registry.json"), "hooks"],
1695
+ [join(repoRoot, "src/themes/registry.json"), "theme"]
1696
+ ];
1697
+ for (const [registryFile, prefix] of registryFiles) for (const item of readRegistryItems(registryFile)) {
1698
+ const meta = toItemMeta(item);
1699
+ metaByKey.set(item.name, meta);
1700
+ metaByKey.set(`${prefix}/${item.name}`, meta);
1701
+ }
1702
+ return metaByKey;
1703
+ }
1704
+ function githubAnnotation(f) {
1705
+ const level = f.severity === "error" ? "error" : "warning";
1706
+ const lineProp = f.line ? `,line=${f.line}` : "";
1707
+ return `::${level} ${[`file=${f.file.replace(/^ui\//, "src/components/ui/").replace(/^hooks\//, "src/hooks/")}${lineProp}`, `title=${f.checkId}`].join(",")}::${f.message}`;
1708
+ }
1709
+ function formatFindings(result, format) {
1710
+ if (format === "json") return JSON.stringify(result, null, 2);
1711
+ if (format === "github") return result.findings.map(githubAnnotation).join("\n");
1712
+ const lines = [];
1713
+ for (const finding of result.findings) {
1714
+ const at = finding.line ? `:${finding.line}` : "";
1715
+ lines.push(` ${finding.severity === "error" ? "✖" : "⚠"} [${finding.checkId}] ${finding.file}${at} — ${finding.message}`);
1716
+ }
1717
+ if (result.suppressed > 0) lines.push(` (${result.suppressed} finding(s) suppressed)`);
1718
+ return lines.join("\n");
1719
+ }
1720
+ // src/commands/check.ts
1721
+ async function check(options) {
1722
+ const ci = Boolean(options.ci);
1723
+ const format = options.json ? "json" : options.format ?? "pretty";
1724
+ const result = runChecks({
1725
+ repoRoot: process.cwd(),
1726
+ paths: options.paths ?? [],
1727
+ ci
1728
+ });
1729
+ if (format === "json") console.log(formatFindings(result, "json"));
1730
+ else if (format === "github") console.log(formatFindings(result, "github"));
1731
+ else {
1732
+ if (result.findings.length > 0) console.log(`\n${formatFindings(result, "pretty")}\n`);
1733
+ info(`${result.filesChecked} files checked — ${result.findings.length} finding(s)` + (ci ? " (CI mode: every unsuppressed finding fails)" : ""));
1734
+ }
1735
+ if (result.failing > 0) {
1736
+ error(ci ? `${result.failing} finding(s) must be fixed or suppressed with a reason (kira-kit check --ci).` : `${result.failing} error(s) found.`);
1737
+ return 3;
1738
+ }
1739
+ return 0;
1740
+ }
1741
+ // src/commands/theme.ts
1742
+ function reportContrast(generated) {
1743
+ for (const adjustment of generated.adjustments) info(`adjusted ${adjustment.scheme}.${adjustment.token} lightness ${adjustment.fromL} → ${adjustment.toL} for contrast`);
1744
+ const weakest = [...generated.apca].sort((a, b) => a.lc - b.lc)[0];
1745
+ if (weakest) info(`APCA (informational): weakest text pair ${weakest.pair} at Lc ${weakest.lc.toFixed(1)}`);
1746
+ }
1747
+ async function theme(options) {
1748
+ const cwd = options.cwd || process.cwd();
1749
+ if (!options.primary) throw new ValidationError("No primary color provided.", "Pass one, e.g. kira-kit theme --primary #e2694a --base-color stone, or use a preset via 'kira-kit add @kira-kit/theme-<name>'.");
1750
+ const name = "custom";
1751
+ let generated;
1752
+ try {
1753
+ generated = generateTheme({
1754
+ name,
1755
+ title: "Custom Kira Kit theme",
1756
+ description: `Custom OKLCH theme generated from primary ${options.primary}.`,
1757
+ primary: options.primary,
1758
+ baseColor: options.baseColor ?? "neutral"
1759
+ });
1760
+ } catch (error) {
1761
+ if (error instanceof ThemeContrastError) {
1762
+ console.error(`error: ${error.message}`);
1763
+ return 1;
1764
+ }
1765
+ throw error;
1766
+ }
1767
+ reportContrast(generated);
1768
+ const outPath = options.out ? join(cwd, options.out) : join(cwd, "kira-theme.json");
1769
+ writeFileSync(outPath, JSON.stringify(generated.item, null, 2) + "\n", "utf-8");
1770
+ success(`Wrote theme registry item to ${outPath}`);
1771
+ if (options.apply) {
1772
+ const code = await runShadcnChecked([
1773
+ "add",
1774
+ outPath,
1775
+ "--yes",
1776
+ "--overwrite",
1777
+ "--cwd",
1778
+ cwd
1779
+ ], cwd);
1780
+ if (code === 0) success("Theme applied.");
1781
+ else {
1782
+ warning("shadcn could not apply the theme automatically.");
1783
+ info(`Apply it manually: shadcn add ${outPath}`);
1784
+ }
1785
+ return code;
1786
+ }
1787
+ info(`Apply it with: kira-kit theme --primary ${options.primary} --apply`);
1788
+ return 0;
1789
+ }
1790
+ // src/core/theme/presets.ts
1791
+ /**
1792
+ * Curated theme presets, designed in three families (warm/editorial,
1793
+ * cool/technical, bold/expressive). Each is run through the same generator as
1794
+ * `kira-kit theme`, so CLI-generated and preset themes are identical for the
1795
+ * same input. Every preset is verified against WCAG 2.2 AA at build time.
1796
+ */
1797
+ const PRESETS = [
1798
+ {
1799
+ name: "ember-press",
1800
+ title: "Ember Press",
1801
+ description: "A burnished terracotta theme for editorial platforms, independent publications, and content-rich products with a confident point of view.",
1802
+ primary: "#A54932",
1803
+ baseColor: "stone",
1804
+ chartHues: [
1805
+ 30,
1806
+ 70,
1807
+ 165,
1808
+ 220
1809
+ ]
1810
+ },
1811
+ {
1812
+ name: "oxblood-atelier",
1813
+ title: "Oxblood Atelier",
1814
+ description: "A deep wine-red theme for luxury services, cultural institutions, and membership products that need drama in measured doses.",
1815
+ primary: "#7E3548",
1816
+ baseColor: "neutral",
1817
+ chartHues: [
1818
+ 32,
1819
+ 78,
1820
+ 155,
1821
+ 215
1822
+ ]
1823
+ },
1824
+ {
1825
+ name: "olive-ledger",
1826
+ title: "Olive Ledger",
1827
+ description: "A cultivated olive theme for research tools, financial workspaces, and sustainability products that value credibility over corporate polish.",
1828
+ primary: "#5F6738",
1829
+ baseColor: "stone",
1830
+ chartHues: [
1831
+ -55,
1832
+ -15,
1833
+ 115,
1834
+ 180
1835
+ ]
1836
+ },
1837
+ {
1838
+ name: "laurel-study",
1839
+ title: "Laurel Study",
1840
+ description: "A shaded laurel-green theme for wellness, hospitality, and knowledge products that should feel composed, discreet, and quietly restorative.",
1841
+ primary: "#315C4E",
1842
+ baseColor: "neutral",
1843
+ chartHues: [
1844
+ -155,
1845
+ -120,
1846
+ 35,
1847
+ 100
1848
+ ]
1849
+ },
1850
+ {
1851
+ name: "phase-line",
1852
+ title: "Phase Line",
1853
+ description: "A locked-in teal accent for operations consoles where live signals must remain readable through dense, quiet interfaces.",
1854
+ primary: "#0B7F79",
1855
+ baseColor: "slate",
1856
+ chartHues: [
1857
+ 34,
1858
+ 88,
1859
+ 154,
1860
+ 214
1861
+ ]
1862
+ },
1863
+ {
1864
+ name: "cryostat",
1865
+ title: "Cryostat",
1866
+ description: "A chilled petrol-cyan theme for data platforms that need the visual discipline of laboratory equipment.",
1867
+ primary: "#007C91",
1868
+ baseColor: "zinc",
1869
+ chartHues: [
1870
+ 42,
1871
+ 106,
1872
+ 178,
1873
+ 238
1874
+ ]
1875
+ },
1876
+ {
1877
+ name: "low-orbit",
1878
+ title: "Low Orbit",
1879
+ description: "A steel-indigo instrument palette for geospatial, aviation, and infrastructure tools built around exact coordinates and layered evidence.",
1880
+ primary: "#3B5F82",
1881
+ baseColor: "slate",
1882
+ chartHues: [
1883
+ 52,
1884
+ 116,
1885
+ 178,
1886
+ 238
1887
+ ]
1888
+ },
1889
+ {
1890
+ name: "coral-circuit",
1891
+ title: "Coral Circuit",
1892
+ description: "A hot coral accent on warm stone that makes collaborative canvases and campaign workspaces feel quick, tactile, and optimistic.",
1893
+ primary: "#F2555A",
1894
+ baseColor: "stone",
1895
+ chartHues: [
1896
+ 38,
1897
+ 128,
1898
+ 198,
1899
+ 272
1900
+ ]
1901
+ },
1902
+ {
1903
+ name: "magenta-riot",
1904
+ title: "Magenta Riot",
1905
+ description: "A deep magenta against cool zinc that brings editorial confidence to community platforms, music products, and launch dashboards.",
1906
+ primary: "#B91668",
1907
+ baseColor: "zinc",
1908
+ chartHues: [
1909
+ 42,
1910
+ 137,
1911
+ 197,
1912
+ 247
1913
+ ]
1914
+ }
1915
+ ];
1916
+ // src/core/theme/generate-presets.ts
1917
+ /**
1918
+ * Generate every curated preset with the same engine the `theme` command
1919
+ * uses, producing registry:theme items for src/themes/registry.json.
1920
+ */
1921
+ function generatePresetItems() {
1922
+ const items = [];
1923
+ const adjustments = [];
1924
+ for (const preset of PRESETS) {
1925
+ const generated = generateTheme({
1926
+ name: preset.name,
1927
+ title: preset.title,
1928
+ description: preset.description,
1929
+ primary: preset.primary,
1930
+ baseColor: preset.baseColor,
1931
+ chartHues: preset.chartHues
1932
+ });
1933
+ for (const adjustment of generated.adjustments) adjustments.push({
1934
+ preset: preset.name,
1935
+ token: `${adjustment.scheme}.${adjustment.token}`,
1936
+ fromL: adjustment.fromL,
1937
+ toL: adjustment.toL
1938
+ });
1939
+ items.push(generated.item);
1940
+ }
1941
+ return {
1942
+ items,
1943
+ adjustments
1944
+ };
1945
+ }
1946
+ // src/core/registry/loader.ts
1947
+ function parseRegistryFile(filePath, label, hint) {
1948
+ try {
1949
+ return sourceRegistrySchema.parse(JSON.parse(readFileSync(filePath, "utf-8")));
1950
+ } catch (error) {
1951
+ throw new ValidationError(`Could not read ${label}: ${error instanceof Error ? error.message : String(error)}`, hint);
1952
+ }
1953
+ }
1954
+ function collectItems(root, rootPath) {
1955
+ const items = [];
1956
+ const seen = /* @__PURE__ */ new Set();
1957
+ for (const include of root.include ?? []) {
1958
+ const included = parseRegistryFile(join(dirname(rootPath), include), `included registry ${include}`, "Every include must be a valid registry file with an items array.");
1959
+ for (const item of included.items ?? []) {
1960
+ if (seen.has(item.name)) throw new ValidationError(`Duplicate registry item "${item.name}" (from ${include}).`, "Item names must be unique across all included registries.");
1961
+ seen.add(item.name);
1962
+ items.push(item);
1963
+ }
1964
+ }
1965
+ for (const item of root.items ?? []) if (!seen.has(item.name)) {
1966
+ seen.add(item.name);
1967
+ items.push(item);
1968
+ }
1969
+ return items;
1970
+ }
1971
+ /**
1972
+ * Load the root source registry and resolve its `include` list. The root
1973
+ * registry.json is the source of truth for metadata; shadcn build consumes
1974
+ * the same files.
1975
+ */
1976
+ function loadSourceRegistry(rootDir) {
1977
+ const rootPath = resolve(rootDir, "registry.json");
1978
+ const root = parseRegistryFile(rootPath, `source registry at ${rootPath}`, "Fix registry.json (and any included files) so it matches the shadcn registry schema.");
1979
+ return {
1980
+ root,
1981
+ items: collectItems(root, rootPath)
1982
+ };
1983
+ }
1984
+ // src/core/docs/generate.ts
1985
+ const HOMEPAGE = "https://kira-kit.vercel.app";
1986
+ /** Generate public/llms.txt and public/docs/<item>.md from registry items. */
1987
+ function generateDocs(items, _options) {
1988
+ const perItem = items.map((item) => ({
1989
+ name: item.name,
1990
+ content: renderMarkdown(item)
1991
+ }));
1992
+ return {
1993
+ llmsTxt: renderLlmsTxt(items),
1994
+ perItem
1995
+ };
1996
+ }
1997
+ function renderLlmsTxt(items) {
1998
+ const lines = [
1999
+ "# Kira Kit",
2000
+ "",
2001
+ `> Enterprise UI kit built on Base UI primitives, ${items.length} components and hooks.`,
2002
+ "",
2003
+ "Kira Kit is a shadcn-compatible component registry. Install items with the shadcn CLI:",
2004
+ "`shadcn add @kira-kit/<name>`, or register the registry once with `shadcn registry add`.",
2005
+ "",
2006
+ "Conventions:",
2007
+ "- Primitives: @base-ui/react (Base UI only — no Radix, no React Aria)",
2008
+ "- Class merging: the `cn` npm package",
2009
+ "- Styling: Tailwind CSS v4 with semantic CSS variables (never raw hex colors)",
2010
+ "- Slots: every component root carries data-slot",
2011
+ "- Variants: class-variance-authority, exported as `<name>Variants`",
2012
+ "- Motion: GSAP and CSS animations, always gated by useReducedMotion / gsap.matchMedia",
2013
+ "- Icons: @tabler/icons-react",
2014
+ "",
2015
+ "Items:"
2016
+ ];
2017
+ for (const item of items) lines.push(`- [${item.title ?? item.name}](${HOMEPAGE}/docs/${item.name}.md): ${item.description}`);
2018
+ return lines.join("\n") + "\n";
2019
+ }
2020
+ function usageLines(item) {
2021
+ if (item.type === "registry:hook") return [`import { ${camelCase(item.name)} } from "@/hooks/${item.name}";`];
2022
+ const component = pascalCase(item.name);
2023
+ const importLine = `import { ${component} } from "@/components/ui/${item.name}";`;
2024
+ if (item.type === "registry:theme") return [importLine, "/* Applied as CSS variables by shadcn. */"];
2025
+ return [importLine, `<${component}> text</${component}>`];
2026
+ }
2027
+ function renderMarkdown(item) {
2028
+ const deps = item.dependencies ?? [];
2029
+ const registryDeps = item.registryDependencies ?? [];
2030
+ const lines = [
2031
+ `# ${item.title ?? item.name}`,
2032
+ "",
2033
+ item.description,
2034
+ "",
2035
+ "## Install",
2036
+ "",
2037
+ "```bash",
2038
+ `npx shadcn add @kira-kit/${item.name}`,
2039
+ "```",
2040
+ ""
2041
+ ];
2042
+ if (deps.length > 0) lines.push("## Dependencies", "", ...deps.map((d) => `- ${d}`), "");
2043
+ if (registryDeps.length > 0) lines.push("## Registry dependencies", "", ...registryDeps.map((d) => `- ${d}`), "");
2044
+ lines.push("## Usage", "", "```tsx", ...usageLines(item), "```", "");
2045
+ if (item.type !== "registry:hook" && item.type !== "registry:theme") lines.push("## Accessibility", "", "Built on Base UI primitives: keyboard navigation, focus management, and ARIA wiring", "come from the primitive layer. Animations are gated by `useReducedMotion`.", "");
2046
+ return lines.join("\n");
2047
+ }
2048
+ function pascalCase(name) {
2049
+ return name.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2050
+ }
2051
+ function camelCase(name) {
2052
+ const pascal = pascalCase(name);
2053
+ return pascal.charAt(0).toLowerCase() + pascal.slice(1);
2054
+ }
2055
+ function docsOutputPaths(repoRoot) {
2056
+ return {
2057
+ llms: join(repoRoot, "public", "llms.txt"),
2058
+ docsDir: join(repoRoot, "public", "docs")
2059
+ };
2060
+ }
2061
+ // src/commands/build.ts
2062
+ /** Quality gate: errors block the build; warnings are advisory per §8. */
2063
+ function qualityGate(repoRoot) {
2064
+ const result = runChecks({
2065
+ repoRoot,
2066
+ paths: [],
2067
+ ci: false
2068
+ });
2069
+ if (result.findings.length > 0) console.log(formatFindings(result, "pretty"));
2070
+ if (result.failing > 0) {
2071
+ warning(`Quality checks failed (${result.failing} error(s)).`);
2072
+ return 3;
2073
+ }
2074
+ success(`Quality checks passed (${result.filesChecked} files, ${result.findings.length} warning(s)).`);
2075
+ return 0;
2076
+ }
2077
+ function writeThemePresets(repoRoot) {
2078
+ const { items: themeItems, adjustments } = generatePresetItems();
2079
+ const themesPath = join(repoRoot, "src/themes/registry.json");
2080
+ mkdirSync(join(repoRoot, "src/themes"), { recursive: true });
2081
+ writeFileSync(themesPath, JSON.stringify({ items: themeItems }, null, 2) + "\n", "utf-8");
2082
+ for (const adjustment of adjustments) info(`theme ${adjustment.preset}: adjusted ${adjustment.token} lightness ${adjustment.fromL} → ${adjustment.toL} for contrast`);
2083
+ success(`Generated ${themeItems.length} theme presets into src/themes/registry.json.`);
2084
+ }
2085
+ function pruneStaleOutputs(repoRoot, items) {
2086
+ const expected = /* @__PURE__ */ new Set([
2087
+ ...items.map((item) => item.name),
2088
+ "registry",
2089
+ "index"
2090
+ ]);
2091
+ const outputDir = join(repoRoot, "public/r");
2092
+ if (!existsSync(outputDir)) return;
2093
+ for (const entry of readdirSync(outputDir)) {
2094
+ if (!entry.endsWith(".json")) continue;
2095
+ const base = entry.replace(/\.json$/, "");
2096
+ if (!expected.has(base)) {
2097
+ rmSync(join(outputDir, entry));
2098
+ info(`Pruned stale registry output: ${entry}`);
2099
+ }
2100
+ }
2101
+ }
2102
+ function writeDocs(repoRoot, items) {
2103
+ const { llmsTxt, perItem } = generateDocs(items, { repoRoot });
2104
+ const paths = docsOutputPaths(repoRoot);
2105
+ mkdirSync(paths.docsDir, { recursive: true });
2106
+ writeFileSync(paths.llms, llmsTxt, "utf-8");
2107
+ for (const doc of perItem) writeFileSync(join(paths.docsDir, `${doc.name}.md`), doc.content, "utf-8");
2108
+ success(`Generated ${paths.llms} and ${perItem.length} per-item docs.`);
2109
+ }
2110
+ async function buildRegistry(options) {
2111
+ const repoRoot = options.cwd && existsSync(join(options.cwd, "registry.json")) ? options.cwd : process.cwd();
2112
+ if (!options.skipChecks) {
2113
+ const gate = qualityGate(repoRoot);
2114
+ if (gate !== 0) return gate;
2115
+ }
2116
+ writeThemePresets(repoRoot);
2117
+ let code = await runShadcnChecked([
2118
+ "registry",
2119
+ "validate",
2120
+ join(repoRoot, "registry.json")
2121
+ ], repoRoot);
2122
+ if (code !== 0) return code;
2123
+ success("shadcn registry validate passed.");
2124
+ code = await runShadcnChecked([
2125
+ "build",
2126
+ join(repoRoot, "registry.json"),
2127
+ "--output",
2128
+ join(repoRoot, "public/r")
2129
+ ], repoRoot);
2130
+ if (code !== 0) return code;
2131
+ success("Built registry JSON into public/r/.");
2132
+ const { items } = loadSourceRegistry(repoRoot);
2133
+ pruneStaleOutputs(repoRoot, items);
2134
+ writeDocs(repoRoot, items);
2135
+ return 0;
2136
+ }
2137
+ // src/commands/create.ts
2138
+ const TEMPLATE_NAMES = [
2139
+ "vite",
2140
+ "next",
2141
+ "tanstack-start",
2142
+ "monorepo"
2143
+ ];
2144
+ /** Resolve the bundled templates dir, both from dist/ and src/ layouts. */
2145
+ function resolveTemplatesRoot() {
2146
+ const here = fileURLToPath(new URL(".", import.meta.url));
2147
+ const candidates = [resolve(here, "..", "templates"), resolve(here, "..", "..", "templates")];
2148
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
2149
+ throw new ValidationError("Could not locate the bundled templates directory.", "Reinstall kira-kit — the published package ships its templates.");
2150
+ }
2151
+ async function install(cwd, pm) {
2152
+ const child = spawn(pm, ["install"], {
2153
+ cwd,
2154
+ stdio: "inherit",
2155
+ shell: true
2156
+ });
2157
+ await new Promise((resolvePromise, reject) => {
2158
+ child.on("error", reject);
2159
+ child.on("exit", (code) => code === 0 ? resolvePromise() : reject(/* @__PURE__ */ new Error(`${pm} install exited with ${code}`)));
2160
+ });
2161
+ }
2162
+ async function resolveTemplate(options) {
2163
+ let template = options.template;
2164
+ if (!template) {
2165
+ if (!options.yes && process.stdin.isTTY) template = await select({ yes: options.yes }, "Which template should be scaffolded?", TEMPLATE_NAMES.map((name) => ({
2166
+ value: name,
2167
+ label: name
2168
+ })), "vite");
2169
+ else throw new ValidationError("No template specified.", `Pass one of: ${TEMPLATE_NAMES.join(", ")} — e.g. kira-kit create my-app --template vite`);
2170
+ }
2171
+ if (!TEMPLATE_NAMES.includes(template)) throw new ValidationError(`Unknown template "${template}".`, `Available templates: ${TEMPLATE_NAMES.join(", ")}`);
2172
+ return template;
2173
+ }
2174
+ function scaffoldTemplate(template, dir) {
2175
+ const targetDir = resolve(process.cwd(), dir ?? `kira-${template}-app`);
2176
+ if (existsSync(targetDir) && readdirSync(targetDir).length > 0) throw new ValidationError(`Target directory "${targetDir}" is not empty.`, "Choose a different directory or clean it first.");
2177
+ const sourceDir = join(resolveTemplatesRoot(), template);
2178
+ if (!existsSync(sourceDir)) throw new ValidationError(`Template "${template}" is missing from this kira-kit installation.`, "Reinstall kira-kit and retry.");
2179
+ cpSync(sourceDir, targetDir, { recursive: true });
2180
+ const pkgPath = join(targetDir, "package.json");
2181
+ if (existsSync(pkgPath)) {
2182
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2183
+ pkg.name = targetDir.split(/[\\/]/).pop() ?? "kira-app";
2184
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf-8");
2185
+ }
2186
+ success(`Scaffolded "${template}" template into ${targetDir}`);
2187
+ return targetDir;
2188
+ }
2189
+ async function initGit(targetDir) {
2190
+ const git = spawn("git", ["init"], {
2191
+ cwd: targetDir,
2192
+ stdio: "ignore",
2193
+ shell: true
2194
+ });
2195
+ await new Promise((resolvePromise) => {
2196
+ git.on("error", () => resolvePromise());
2197
+ git.on("exit", () => resolvePromise());
2198
+ });
2199
+ }
2200
+ async function installDependencies(targetDir) {
2201
+ const pm = (await detect({ cwd: targetDir }))?.name ?? "npm";
2202
+ info(`Installing dependencies with ${pm}…`);
2203
+ try {
2204
+ await install(targetDir, pm);
2205
+ success("Dependencies installed.");
2206
+ } catch (error) {
2207
+ warning(`Dependency install failed: ${error instanceof Error ? error.message : String(error)}`);
2208
+ info(`Install manually: cd ${targetDir} && ${pm} install`);
2209
+ }
2210
+ }
2211
+ function printNextSteps(targetDir, installed) {
2212
+ console.log("\nNext steps:");
2213
+ console.log(` cd ${targetDir}`);
2214
+ if (!installed) console.log(" npm install # or bun install / pnpm install");
2215
+ console.log(" kira-kit init --preset terracotta # apply a theme (optional)");
2216
+ console.log(" kira-kit add button # add your first component");
2217
+ console.log();
2218
+ }
2219
+ async function createProject(options) {
2220
+ const targetDir = scaffoldTemplate(await resolveTemplate(options), options.dir);
2221
+ if (options.git) await initGit(targetDir);
2222
+ if (options.install) await installDependencies(targetDir);
2223
+ printNextSteps(targetDir, Boolean(options.install));
2224
+ return 0;
2225
+ }
2226
+ // src/commands/migrate.ts
2227
+ const LEGACY_CN_SPECIFIERS = [
2228
+ "@/lib/cn",
2229
+ "@/lib/cn.ts",
2230
+ "@/utils/cn",
2231
+ "@/helpers/cn",
2232
+ "clsx",
2233
+ "tailwind-merge"
2234
+ ];
2235
+ async function collectSourceFiles(dir, out) {
2236
+ let entries;
2237
+ try {
2238
+ entries = await readdir(dir, { withFileTypes: true });
2239
+ } catch {
2240
+ return;
2241
+ }
2242
+ for (const entry of entries) {
2243
+ if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist") continue;
2244
+ const full = join(dir, entry.name);
2245
+ if (entry.isDirectory()) await collectSourceFiles(full, out);
2246
+ else if (/\.(tsx?|jsx?)$/.test(entry.name)) out.push(full);
2247
+ }
2248
+ }
2249
+ /**
2250
+ * Rewrite legacy `cn` imports (clsx / tailwind-merge / @/lib/cn) to the
2251
+ * single `@/lib/utils` alias. Returns the planned rewrites.
2252
+ */
2253
+ async function planCnRewrites(sourceDir, utilsAlias) {
2254
+ const files = [];
2255
+ await collectSourceFiles(sourceDir, files);
2256
+ const rewrites = [];
2257
+ for (const file of files) {
2258
+ const content = await readFile(file, "utf-8");
2259
+ for (const specifier of LEGACY_CN_SPECIFIERS) if (content.includes(`from "${specifier}"`) || content.includes(`from '${specifier}'`)) rewrites.push({
2260
+ file: relative(process.cwd(), file),
2261
+ from: specifier,
2262
+ to: utilsAlias
2263
+ });
2264
+ }
2265
+ return rewrites;
2266
+ }
2267
+ /** Best-effort: fetch a registry item JSON. Returns null on any failure. */
2268
+ async function fetchRegistryItem(url) {
2269
+ try {
2270
+ const response = await fetch(url);
2271
+ if (!response.ok) return null;
2272
+ return await response.json();
2273
+ } catch {
2274
+ return null;
2275
+ }
2276
+ }
2277
+ async function countChangedFiles(componentsDir, item) {
2278
+ let changed = 0;
2279
+ for (const registryFile of item.files ?? []) {
2280
+ if (!registryFile.path.endsWith(".tsx") && !registryFile.path.endsWith(".ts")) continue;
2281
+ const localPath = resolve(componentsDir, registryFile.path);
2282
+ let localContent;
2283
+ try {
2284
+ localContent = await readFile(localPath, "utf-8");
2285
+ } catch {
2286
+ continue;
2287
+ }
2288
+ if (localContent.trim() !== registryFile.content.trim()) changed += 1;
2289
+ }
2290
+ return changed;
2291
+ }
2292
+ /** Compare local component copies with the published registry. Never modifies anything. */
2293
+ async function findDivergentComponents(options) {
2294
+ const registryUrl = getRegistryUrl(options.cwd) ?? "https://kira-kit.vercel.app/r/{name}.json";
2295
+ const componentsDir = resolve(options.cwd, "src", "components", "ui");
2296
+ let localNames;
2297
+ try {
2298
+ localNames = (await readdir(componentsDir)).filter((n) => n.endsWith(".tsx"));
2299
+ } catch {
2300
+ return [];
2301
+ }
2302
+ const divergent = [];
2303
+ for (const file of localNames) {
2304
+ const name = file.replace(/\.tsx$/, "");
2305
+ if (name === "index" || name === "registry") continue;
2306
+ const item = await fetchRegistryItem(registryUrl.replace("{name}", name));
2307
+ if (!item?.files?.length) continue;
2308
+ const changed = await countChangedFiles(componentsDir, item);
2309
+ if (changed > 0) divergent.push({
2310
+ name,
2311
+ changedFiles: changed
2312
+ });
2313
+ }
2314
+ return divergent;
2315
+ }
2316
+ function configFacts(raw) {
2317
+ const aliases = raw?.aliases ?? {};
2318
+ return {
2319
+ utilsAlias: typeof aliases.utils === "string" ? aliases.utils : "@/lib/utils",
2320
+ hadLegacyRegistryUrl: typeof raw?.registryUrl === "string",
2321
+ alreadyHasNamespace: "@kira-kit" in (raw?.registries ?? {}),
2322
+ legacyAlias: aliases.lib === "@/lib/cn" || aliases.lib === "@/lib"
2323
+ };
2324
+ }
2325
+ async function planMigration(options) {
2326
+ const configPath = findConfigFile(options.cwd);
2327
+ if (!configPath) throw new ValidationError("No components.json found.", "Run `kira-kit init` first to generate one.");
2328
+ const raw = await readRawConfig(options.cwd);
2329
+ const facts = configFacts(raw);
2330
+ const sourceDir = resolve(options.cwd, "src");
2331
+ let sourceDirExists = true;
2332
+ try {
2333
+ await stat(sourceDir);
2334
+ } catch {
2335
+ sourceDirExists = false;
2336
+ }
2337
+ return {
2338
+ configPath,
2339
+ raw,
2340
+ facts,
2341
+ cnRewrites: sourceDirExists ? await planCnRewrites(sourceDir, facts.utilsAlias) : []
2342
+ };
2343
+ }
2344
+ function printDryRun(facts, cnRewrites) {
2345
+ console.log("Dry run — no files will be modified:\n");
2346
+ if (facts.hadLegacyRegistryUrl) console.log(` components.json: remove "registryUrl" (legacy), add "registries['@kira-kit']"`);
2347
+ else if (facts.alreadyHasNamespace) console.log(" components.json: already up to date");
2348
+ else console.log(` components.json: add "registries['@kira-kit']"`);
2349
+ if (facts.legacyAlias) console.log(` components.json: update aliases.lib to "${facts.utilsAlias}"`);
2350
+ console.log(` run \`shadcn migrate cn\` (clsx + tailwind-merge → cn)`);
2351
+ for (const rewrite of cnRewrites) console.log(` ${rewrite.file}: "${rewrite.from}" → "${rewrite.to}"`);
2352
+ console.log("\nApply with `kira-kit migrate` (no --dry-run).");
2353
+ }
2354
+ /** components.json: legacy registryUrl → registries map (idempotent). */
2355
+ async function updateRegistryConfig(options, configPath, raw, facts) {
2356
+ if (!facts.hadLegacyRegistryUrl && facts.alreadyHasNamespace) {
2357
+ info("components.json already has the @kira-kit registry (nothing to do)");
2358
+ return;
2359
+ }
2360
+ const url = facts.hadLegacyRegistryUrl ? raw?.registryUrl : getRegistryUrl(options.cwd) ?? "https://kira-kit.vercel.app/r/{name}.json";
2361
+ upsertKiraRegistry(options.cwd, url.endsWith("/{name}.json") ? url : `${url.replace(/\/$/, "")}/{name}.json`);
2362
+ if (facts.hadLegacyRegistryUrl) {
2363
+ const updated = JSON.parse(await readFile(resolve(configPath), "utf-8"));
2364
+ delete updated.registryUrl;
2365
+ await writeFile(resolve(configPath), JSON.stringify(updated, null, 2) + "\n", "utf-8");
2366
+ }
2367
+ success("components.json updated (@kira-kit registry namespace)");
2368
+ }
2369
+ /** clsx / tailwind-merge → cn via shadcn, then rewrite remaining legacy imports. */
2370
+ async function applyCnMigration(options, cnRewrites, facts) {
2371
+ if (cnRewrites.length > 0 || facts.legacyAlias) {
2372
+ info("Running `shadcn migrate cn`…");
2373
+ const { code } = await runShadcn([
2374
+ "migrate",
2375
+ "cn",
2376
+ "--yes"
2377
+ ], options.cwd);
2378
+ if (code !== 0) warning("`shadcn migrate cn` failed — continuing with import rewrites.");
2379
+ }
2380
+ let rewritten = 0;
2381
+ for (const rewrite of cnRewrites) {
2382
+ const fullPath = resolve(process.cwd(), rewrite.file);
2383
+ const updated = (await readFile(fullPath, "utf-8")).replaceAll(`from "${rewrite.from}"`, `from "${rewrite.to}"`).replaceAll(`from '${rewrite.from}'`, `from '${rewrite.to}'`);
2384
+ await writeFile(fullPath, updated, "utf-8");
2385
+ rewritten += 1;
2386
+ }
2387
+ if (rewritten > 0) success(`Rewrote ${rewritten} file${rewritten === 1 ? "" : "s"} to import cn from ${facts.utilsAlias}`);
2388
+ else info("No legacy cn imports found");
2389
+ }
2390
+ /** Report divergent components (never auto-modify). */
2391
+ async function reportDivergence(options) {
2392
+ if (options.yes) return;
2393
+ info("Checking local components against the registry…");
2394
+ const divergent = await findDivergentComponents(options);
2395
+ if (divergent.length === 0) {
2396
+ success("All local components match the registry");
2397
+ return;
2398
+ }
2399
+ warning(`${divergent.length} component${divergent.length === 1 ? "" : "s"} differ from the registry:`);
2400
+ for (const item of divergent) console.log(` ${item.name} (${item.changedFiles} file${item.changedFiles === 1 ? "" : "s"})`);
2401
+ console.log("\nReview and update individually with:");
2402
+ console.log(` kira-kit add <name> --diff # e.g. kira-kit add ${divergent[0].name} --diff`);
2403
+ }
2404
+ async function migrateProject(options) {
2405
+ const { configPath, raw, facts, cnRewrites } = await planMigration(options);
2406
+ if (options.dryRun) {
2407
+ printDryRun(facts, cnRewrites);
2408
+ return 0;
2409
+ }
2410
+ await updateRegistryConfig(options, configPath, raw, facts);
2411
+ await applyCnMigration(options, cnRewrites, facts);
2412
+ await reportDivergence(options);
2413
+ return 0;
2414
+ }
2415
+ // src/index.ts
2416
+ const program = new Command();
2417
+ program.name("kira-kit").description("Kira Kit — shadcn-compatible Base UI component registry, OKLCH themes, and quality checks").version(getVersion());
2418
+ program.command("init").description("Initialize Kira Kit in your project (delegates base setup to shadcn)").option("-c, --cwd <directory>", "Working directory", process.cwd()).option("--base <base>", "Component library base (base, radix, aria)").option("--preset <name>", "Install a theme preset (e.g. terracotta)").option("--primary <color>", "Generate a custom theme from this primary color").option("--base-color <name>", "Base color (neutral, stone, zinc, slate, gray)").option("--force", "Re-apply the theme even if one already exists").option("-y, --yes", "Skip prompts, use defaults").action(async (options) => {
2419
+ process.exit(await run(() => init(options)));
2420
+ });
2421
+ program.command("add [items...]").description("Add component(s) via the pinned shadcn CLI").option("-c, --cwd <directory>", "Working directory", process.cwd()).option("-o, --overwrite", "Overwrite existing files").option("-y, --yes", "Skip confirmation prompts").option("-a, --all", "Add every item in the registry").option("-p, --path <path>", "Path to add the component to").option("--dry-run", "Preview changes without writing files").option("--diff", "Show diff for files that would change").option("--view", "Show file contents instead of writing").action(async (items, options) => {
2422
+ process.exit(await run(() => addComponents({
2423
+ ...options,
2424
+ items
2425
+ })));
2426
+ });
2427
+ program.command("list").description("List available registry items").option("--json", "Print machine-readable JSON").action(async (options) => {
2428
+ process.exit(await run(() => listComponents(options)));
2429
+ });
2430
+ program.command("view [items...]").description("View registry item contents").action(async (items, options) => {
2431
+ process.exit(await run(() => viewItems({
2432
+ ...options,
2433
+ items
2434
+ })));
2435
+ });
2436
+ program.command("search [query...]").description("Search the registry").option("--json", "Print machine-readable JSON").action(async (query, options) => {
2437
+ process.exit(await run(() => searchItems({
2438
+ ...options,
2439
+ query
2440
+ })));
2441
+ });
2442
+ program.command("theme").description("Generate an OKLCH theme palette from a primary color").option("--primary <color>", "Primary color (hex or any CSS color)").option("--base-color <name>", "Base color (neutral, stone, zinc, slate, gray)").option("--out <file>", "Write the registry item to this file").option("--apply", "Install the generated theme via shadcn").option("-c, --cwd <directory>", "Working directory", process.cwd()).action(async (options) => {
2443
+ process.exit(await run(() => theme(options)));
2444
+ });
2445
+ program.command("check [paths...]").description("Run quality checks on component sources").option("--ci", "Fail on every finding unless suppressed (auto when CI is set)").option("--format <format>", "Output format: pretty, json, github").option("--json", "Shorthand for --format json").action(async (paths, options) => {
2446
+ process.exit(await run(() => check({
2447
+ ...options,
2448
+ paths
2449
+ })));
2450
+ });
2451
+ program.command("build").description("Maintainer: validate, build, and emit the registry + docs").option("-c, --cwd <directory>", "Working directory", process.cwd()).option("--skip-checks", "Skip quality checks").action(async (options) => {
2452
+ process.exit(await run(() => buildRegistry(options)));
2453
+ });
2454
+ program.command("create [dir]").description("Scaffold a new project pre-wired for Kira Kit").option("-t, --template <template>", "Template: vite, next, tanstack-start, monorepo").option("--install", "Install dependencies after scaffolding").option("--no-install", "Skip dependency installation").option("--git", "Initialize a git repository").option("--no-git", "Skip git initialization").option("-y, --yes", "Skip prompts, use defaults").action(async (dir, options) => {
2455
+ process.exit(await run(() => createProject({
2456
+ dir,
2457
+ ...options
2458
+ })));
2459
+ });
2460
+ program.command("migrate").description("Migrate a v0.2.x project to the shadcn-native setup").option("-c, --cwd <directory>", "Working directory", process.cwd()).option("--dry-run", "Print changes without writing files").option("-y, --yes", "Skip prompts, apply automatically").action(async (options) => {
2461
+ process.exit(await run(() => migrateProject(options)));
2462
+ });
2463
+ async function run(action) {
2464
+ try {
2465
+ const code = await action();
2466
+ return typeof code === "number" ? code : 0;
2467
+ } catch (error) {
2468
+ return printError(error);
2469
+ }
2470
+ }
2471
+ program.parse();
2472
+ export {};