banhaten 0.5.0 → 0.6.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 (290) hide show
  1. package/CHANGELOG.md +177 -139
  2. package/CONTRIBUTING.md +46 -46
  3. package/README.md +192 -192
  4. package/SECURITY.md +15 -15
  5. package/banhaten.config.example.json +11 -11
  6. package/docs/design-spacing.md +13 -13
  7. package/docs/design-system/README.md +22 -22
  8. package/docs/design-system/adoption-quality-remediation.md +87 -87
  9. package/docs/design-system/agent-usage.md +13 -13
  10. package/docs/design-system/appearance-presets.md +189 -189
  11. package/docs/design-system/appearances/default.md +94 -94
  12. package/docs/design-system/appearances/rounded.md +95 -95
  13. package/docs/design-system/appearances/sharp.md +95 -95
  14. package/docs/design-system/component-docs-pattern.md +81 -81
  15. package/docs/design-system/component-implementation-ownership-audit.md +245 -245
  16. package/docs/design-system/component-quality-audit-2026-08-20.md +225 -225
  17. package/docs/design-system/component-showcase-consistency-report.md +219 -219
  18. package/docs/design-system/component-token-consistency-audit.md +173 -173
  19. package/docs/design-system/components/README.md +91 -90
  20. package/docs/design-system/components/accordion.md +52 -52
  21. package/docs/design-system/components/activity-feed.md +93 -93
  22. package/docs/design-system/components/activity-heatmap.md +56 -56
  23. package/docs/design-system/components/alert-dialog.md +71 -71
  24. package/docs/design-system/components/alert.md +103 -97
  25. package/docs/design-system/components/app-header.md +97 -0
  26. package/docs/design-system/components/aspect-ratio.md +45 -45
  27. package/docs/design-system/components/attribute.md +101 -89
  28. package/docs/design-system/components/autocomplete.md +75 -75
  29. package/docs/design-system/components/avatar.md +53 -53
  30. package/docs/design-system/components/badge.md +55 -55
  31. package/docs/design-system/components/banner.md +86 -86
  32. package/docs/design-system/components/breadcrumbs.md +181 -177
  33. package/docs/design-system/components/button-group.md +97 -97
  34. package/docs/design-system/components/button.md +80 -80
  35. package/docs/design-system/components/card.md +102 -88
  36. package/docs/design-system/components/carousel.md +46 -46
  37. package/docs/design-system/components/catalog-components.md +46 -46
  38. package/docs/design-system/components/checkbox.md +53 -53
  39. package/docs/design-system/components/collapsible.md +63 -63
  40. package/docs/design-system/components/command.md +61 -61
  41. package/docs/design-system/components/context-menu.md +45 -45
  42. package/docs/design-system/components/date-picker.md +80 -80
  43. package/docs/design-system/components/divider.md +102 -102
  44. package/docs/design-system/components/empty-state.md +56 -56
  45. package/docs/design-system/components/field.md +70 -70
  46. package/docs/design-system/components/file-upload.md +186 -186
  47. package/docs/design-system/components/hover-card.md +47 -47
  48. package/docs/design-system/components/icons.md +48 -48
  49. package/docs/design-system/components/input-group.md +57 -57
  50. package/docs/design-system/components/input-otp.md +56 -56
  51. package/docs/design-system/components/input.md +111 -109
  52. package/docs/design-system/components/item.md +58 -58
  53. package/docs/design-system/components/kbd.md +49 -49
  54. package/docs/design-system/components/label.md +49 -49
  55. package/docs/design-system/components/menu.md +94 -73
  56. package/docs/design-system/components/menubar.md +46 -46
  57. package/docs/design-system/components/modal.md +104 -104
  58. package/docs/design-system/components/native-select.md +53 -53
  59. package/docs/design-system/components/navigation-menu.md +49 -49
  60. package/docs/design-system/components/onboarding-step-list-item.md +81 -81
  61. package/docs/design-system/components/page-header.md +127 -93
  62. package/docs/design-system/components/pagination.md +56 -56
  63. package/docs/design-system/components/popover.md +59 -59
  64. package/docs/design-system/components/progress-slider.md +49 -49
  65. package/docs/design-system/components/progress.md +76 -76
  66. package/docs/design-system/components/radio-card.md +50 -50
  67. package/docs/design-system/components/radio-group.md +56 -56
  68. package/docs/design-system/components/resizable.md +43 -43
  69. package/docs/design-system/components/scroll-area.md +50 -50
  70. package/docs/design-system/components/segmented-control.md +54 -54
  71. package/docs/design-system/components/select.md +68 -64
  72. package/docs/design-system/components/sheet.md +66 -66
  73. package/docs/design-system/components/sidebar.md +167 -111
  74. package/docs/design-system/components/skeleton.md +74 -74
  75. package/docs/design-system/components/slideout.md +64 -64
  76. package/docs/design-system/components/slider.md +62 -62
  77. package/docs/design-system/components/social-button.md +49 -49
  78. package/docs/design-system/components/spinner.md +62 -62
  79. package/docs/design-system/components/steps.md +65 -65
  80. package/docs/design-system/components/table.md +499 -422
  81. package/docs/design-system/components/tabs.md +74 -59
  82. package/docs/design-system/components/tag.md +79 -79
  83. package/docs/design-system/components/textarea.md +49 -49
  84. package/docs/design-system/components/timeline.md +82 -82
  85. package/docs/design-system/components/toast.md +57 -57
  86. package/docs/design-system/components/toggle.md +80 -80
  87. package/docs/design-system/components/toolbar.md +89 -89
  88. package/docs/design-system/components/tooltip.md +92 -92
  89. package/docs/design-system/components/typography.md +18 -18
  90. package/docs/design-system/density-and-elevation.md +65 -65
  91. package/docs/design-system/design-system-test-missing-items.md +368 -368
  92. package/docs/design-system/direction-and-localization.md +23 -23
  93. package/docs/design-system/form-recipes.md +73 -73
  94. package/docs/design-system/gap-promotion-policy.md +21 -21
  95. package/docs/design-system/icons.md +74 -74
  96. package/docs/design-system/installation.md +70 -70
  97. package/docs/design-system/launch-comparison-shadcn.md +98 -98
  98. package/docs/design-system/registry-and-cli.md +64 -64
  99. package/docs/design-system/release-policy.md +30 -30
  100. package/docs/design-system/roadmap.md +14 -14
  101. package/docs/design-system/support-matrix.md +23 -23
  102. package/docs/design-system/tabs.md +54 -54
  103. package/docs/design-system/template-gap-audit.md +32 -32
  104. package/docs/design-system/templates.md +59 -59
  105. package/docs/design-system/token-governance.md +72 -72
  106. package/package.json +98 -98
  107. package/registry/component-contract.json +40 -40
  108. package/registry/components/accordion.tsx +155 -155
  109. package/registry/components/alert-dialog.tsx +297 -297
  110. package/registry/components/alert.tsx +309 -293
  111. package/registry/components/app-header.tsx +151 -0
  112. package/registry/components/aspect-ratio.tsx +30 -30
  113. package/registry/components/attribute.tsx +489 -454
  114. package/registry/components/autocomplete.tsx +598 -598
  115. package/registry/components/avatar.tsx +385 -385
  116. package/registry/components/badge.tsx +630 -629
  117. package/registry/components/button-group.tsx +565 -565
  118. package/registry/components/button.tsx +128 -127
  119. package/registry/components/card.tsx +651 -638
  120. package/registry/components/carousel.tsx +296 -296
  121. package/registry/components/chart.tsx +203 -203
  122. package/registry/components/checkbox.tsx +247 -247
  123. package/registry/components/collapsible.tsx +109 -109
  124. package/registry/components/command.tsx +208 -208
  125. package/registry/components/context-menu.tsx +236 -236
  126. package/registry/components/date-picker.tsx +1289 -1289
  127. package/registry/components/expanded/ActivityFeed.tsx +227 -227
  128. package/registry/components/expanded/ActivityHeatmap.tsx +64 -64
  129. package/registry/components/expanded/Banner.tsx +179 -179
  130. package/registry/components/expanded/Breadcrumbs.tsx +135 -131
  131. package/registry/components/expanded/CatalogComponentsShowcase.tsx +205 -205
  132. package/registry/components/expanded/CatalogDivider.tsx +49 -49
  133. package/registry/components/expanded/EmptyState.tsx +155 -155
  134. package/registry/components/expanded/FileUpload.tsx +543 -543
  135. package/registry/components/expanded/OnboardingStepListItem.tsx +60 -60
  136. package/registry/components/expanded/PageHeader.tsx +209 -179
  137. package/registry/components/expanded/Slideout.tsx +108 -108
  138. package/registry/components/expanded/Steps.tsx +402 -402
  139. package/registry/components/expanded/Table.tsx +1109 -1092
  140. package/registry/components/expanded/Timeline.tsx +203 -203
  141. package/registry/components/expanded/activityFeed.css +248 -248
  142. package/registry/components/expanded/activityHeatmap.css +66 -66
  143. package/registry/components/expanded/banner.css +260 -260
  144. package/registry/components/expanded/breadcrumbs.css +157 -140
  145. package/registry/components/expanded/catalogComponentsShowcase.css +87 -87
  146. package/registry/components/expanded/divider.css +75 -75
  147. package/registry/components/expanded/emptyState.css +111 -111
  148. package/registry/components/expanded/fileUpload.css +457 -457
  149. package/registry/components/expanded/onboardingStepListItem.css +135 -135
  150. package/registry/components/expanded/pageHeader.css +284 -248
  151. package/registry/components/expanded/slideout.css +276 -276
  152. package/registry/components/expanded/steps.css +356 -356
  153. package/registry/components/expanded/table.css +655 -606
  154. package/registry/components/expanded/timeline.css +286 -286
  155. package/registry/components/field.tsx +283 -283
  156. package/registry/components/hover-card.tsx +48 -48
  157. package/registry/components/input-content.ts +107 -107
  158. package/registry/components/input-group.tsx +130 -130
  159. package/registry/components/input-otp.tsx +584 -584
  160. package/registry/components/input.tsx +992 -990
  161. package/registry/components/item.tsx +189 -189
  162. package/registry/components/kbd.tsx +246 -246
  163. package/registry/components/label.tsx +78 -78
  164. package/registry/components/menu.tsx +1091 -978
  165. package/registry/components/menubar.tsx +226 -226
  166. package/registry/components/modal.tsx +872 -872
  167. package/registry/components/native-select.tsx +205 -205
  168. package/registry/components/navigation-menu.tsx +171 -171
  169. package/registry/components/pagination.css +36 -36
  170. package/registry/components/pagination.tsx +560 -560
  171. package/registry/components/popover.tsx +338 -338
  172. package/registry/components/progress-slider.tsx +216 -216
  173. package/registry/components/radio-card.tsx +676 -676
  174. package/registry/components/radio-group.tsx +570 -570
  175. package/registry/components/resizable.tsx +108 -108
  176. package/registry/components/scroll-area.tsx +91 -91
  177. package/registry/components/segmented-control.tsx +87 -87
  178. package/registry/components/select-content.tsx +218 -218
  179. package/registry/components/select.tsx +937 -937
  180. package/registry/components/sheet.tsx +305 -305
  181. package/registry/components/sidebar.tsx +1535 -1433
  182. package/registry/components/skeleton.css +54 -54
  183. package/registry/components/skeleton.tsx +482 -482
  184. package/registry/components/slider.tsx +380 -380
  185. package/registry/components/social-button.tsx +387 -387
  186. package/registry/components/spinner.tsx +78 -78
  187. package/registry/components/table-elements.tsx +287 -128
  188. package/registry/components/tabs.css +246 -222
  189. package/registry/components/tabs.tsx +245 -241
  190. package/registry/components/tag.tsx +423 -423
  191. package/registry/components/textarea.tsx +610 -610
  192. package/registry/components/toast.tsx +136 -136
  193. package/registry/components/toggle.tsx +256 -256
  194. package/registry/components/toolbar.tsx +539 -539
  195. package/registry/components/tooltip.tsx +433 -433
  196. package/registry/examples/alert-demo.tsx +34 -34
  197. package/registry/examples/alert-dialog-demo.tsx +42 -42
  198. package/registry/examples/app-header-demo.tsx +40 -0
  199. package/registry/examples/aspect-ratio-demo.tsx +11 -11
  200. package/registry/examples/attribute-demo.tsx +65 -65
  201. package/registry/examples/autocomplete-demo.tsx +109 -109
  202. package/registry/examples/avatar-demo.tsx +132 -132
  203. package/registry/examples/badge-demo.tsx +69 -69
  204. package/registry/examples/button-demo.tsx +86 -86
  205. package/registry/examples/button-group-demo.tsx +63 -63
  206. package/registry/examples/card-demo.tsx +86 -86
  207. package/registry/examples/carousel-demo.tsx +43 -43
  208. package/registry/examples/chart-demo.tsx +18 -18
  209. package/registry/examples/checkbox-demo.tsx +62 -62
  210. package/registry/examples/collapsible-demo.tsx +16 -16
  211. package/registry/examples/collection-filter-bar-demo.tsx +135 -135
  212. package/registry/examples/command-demo.tsx +42 -42
  213. package/registry/examples/command-palette-demo.tsx +235 -235
  214. package/registry/examples/context-menu-demo.tsx +29 -29
  215. package/registry/examples/control-density-contract-demo.tsx +65 -65
  216. package/registry/examples/date-picker-demo.tsx +127 -127
  217. package/registry/examples/divider-demo.tsx +17 -17
  218. package/registry/examples/expanded/activity-heatmap-demo.tsx +29 -29
  219. package/registry/examples/expanded/banner-demo.tsx +48 -48
  220. package/registry/examples/expanded/breadcrumbs-demo.tsx +59 -59
  221. package/registry/examples/expanded/empty-state-demo.tsx +39 -39
  222. package/registry/examples/expanded/file-upload-demo.tsx +60 -60
  223. package/registry/examples/expanded/onboarding-step-demo.tsx +11 -11
  224. package/registry/examples/expanded/slideout-demo.tsx +15 -15
  225. package/registry/examples/expanded/steps-demo.tsx +29 -29
  226. package/registry/examples/expanded/tabs-demo.tsx +13 -13
  227. package/registry/examples/expanded/timeline-demo.tsx +18 -18
  228. package/registry/examples/field-demo.tsx +51 -51
  229. package/registry/examples/hover-card-demo.tsx +23 -23
  230. package/registry/examples/input-actions-demo.tsx +36 -36
  231. package/registry/examples/input-demo.tsx +87 -87
  232. package/registry/examples/input-group-demo.tsx +16 -16
  233. package/registry/examples/input-otp-demo.tsx +72 -72
  234. package/registry/examples/item-demo.tsx +46 -46
  235. package/registry/examples/kbd-demo.tsx +12 -12
  236. package/registry/examples/label-demo.tsx +20 -20
  237. package/registry/examples/menu-demo.tsx +122 -122
  238. package/registry/examples/menubar-demo.tsx +34 -34
  239. package/registry/examples/modal-demo.tsx +74 -74
  240. package/registry/examples/native-select-demo.tsx +16 -16
  241. package/registry/examples/navigation-menu-demo.tsx +29 -29
  242. package/registry/examples/pagination-demo.tsx +20 -20
  243. package/registry/examples/popover-demo.tsx +547 -547
  244. package/registry/examples/progress-demo.tsx +37 -37
  245. package/registry/examples/progress-slider-demo.tsx +29 -29
  246. package/registry/examples/radio-card-demo.tsx +51 -51
  247. package/registry/examples/radio-group-demo.tsx +62 -62
  248. package/registry/examples/resizable-demo.tsx +22 -22
  249. package/registry/examples/results-toolbar-demo.tsx +44 -44
  250. package/registry/examples/scroll-area-demo.tsx +15 -15
  251. package/registry/examples/segmented-control-demo.tsx +39 -39
  252. package/registry/examples/select-demo.tsx +87 -87
  253. package/registry/examples/sheet-demo.tsx +47 -47
  254. package/registry/examples/sidebar-demo.tsx +101 -101
  255. package/registry/examples/slider-demo.tsx +31 -31
  256. package/registry/examples/social-button-demo.tsx +61 -61
  257. package/registry/examples/spinner-demo.tsx +59 -59
  258. package/registry/examples/tabs-demo.tsx +13 -13
  259. package/registry/examples/tag-demo.tsx +29 -29
  260. package/registry/examples/textarea-demo.tsx +79 -79
  261. package/registry/examples/toast-demo.tsx +35 -35
  262. package/registry/examples/toggle-demo.tsx +59 -59
  263. package/registry/examples/tooltip-demo.tsx +115 -115
  264. package/registry/guidance/USAGE.md +27 -27
  265. package/registry/hooks/use-direction.ts +207 -207
  266. package/registry/index.json +387 -17
  267. package/registry/styles/globals.css +46 -0
  268. package/registry.json +24 -2
  269. package/schema/config.schema.json +51 -51
  270. package/schema/registry.schema.json +194 -194
  271. package/schema/tokens.schema.json +167 -167
  272. package/src/cli/command-line.js +194 -194
  273. package/src/cli/config-editors.js +9 -9
  274. package/src/cli/doctor.js +399 -399
  275. package/src/cli/file-transaction.js +302 -302
  276. package/src/cli/global-css.js +153 -153
  277. package/src/cli/index.js +1002 -1002
  278. package/src/cli/install-plan.js +592 -592
  279. package/src/cli/install-receipt.js +171 -171
  280. package/src/cli/jsonc.js +203 -203
  281. package/src/cli/package-install-state.js +254 -254
  282. package/src/cli/package-manager.js +238 -238
  283. package/src/cli/package-plan.js +185 -185
  284. package/src/cli/package-version.js +97 -97
  285. package/src/cli/registry-query.js +207 -207
  286. package/src/cli/reporting.js +55 -55
  287. package/src/cli/schema-validation.js +19 -19
  288. package/src/cli/source-scanner.js +686 -686
  289. package/src/cli/vite-config.js +478 -478
  290. package/tokens/banhaten.tokens.json +184 -0
package/src/cli/index.js CHANGED
@@ -1,1002 +1,1002 @@
1
- #!/usr/bin/env node
2
-
3
- import { createHash } from "node:crypto"
4
- import fs from "node:fs/promises"
5
- import path from "node:path"
6
- import process from "node:process"
7
- import { fileURLToPath } from "node:url"
8
- import { parseCommandLine } from "./command-line.js"
9
- import {
10
- inspectBanhatenProject,
11
- printBanhatenDoctor,
12
- } from "./doctor.js"
13
- import {
14
- assertFileUnchanged,
15
- deferUntilApplied,
16
- formatUnifiedDiff,
17
- readFileForUpdate,
18
- runFileTransaction,
19
- writeFile,
20
- } from "./file-transaction.js"
21
- import {
22
- applyPackageDependencyPlan,
23
- createPackageDependencyPlan,
24
- mergeDependencyRequirements,
25
- } from "./package-plan.js"
26
- import { inspectPackageInstallState } from "./package-install-state.js"
27
- import {
28
- createInstallPlan,
29
- resolveInstallTarget,
30
- } from "./install-plan.js"
31
- import {
32
- createInstallPlanReceipt,
33
- normalizeReceiptComponents,
34
- normalizeReceiptTarget,
35
- validateReceiptDestinations,
36
- } from "./install-receipt.js"
37
- import {
38
- ensureGlobalCssImports,
39
- removeExistingTokenBlock,
40
- } from "./global-css.js"
41
- import {
42
- printInstallHint,
43
- printResult,
44
- resolveInstallAction,
45
- } from "./reporting.js"
46
- import { assertSchema } from "./schema-validation.js"
47
- import {
48
- listComponents,
49
- searchComponents,
50
- showComponentDocs,
51
- viewComponent,
52
- } from "./registry-query.js"
53
-
54
- const packageRoot = path.resolve(
55
- path.dirname(fileURLToPath(import.meta.url)),
56
- "..",
57
- ".."
58
- )
59
- const registryRoot = path.join(packageRoot, "registry")
60
- const registryIndexPath = path.join(registryRoot, "index.json")
61
- const packageJsonPath = path.join(packageRoot, "package.json")
62
- const schemaRoot = path.join(packageRoot, "schema")
63
-
64
- const CONFIG_FILE = "banhaten.config.json"
65
- const INSTALL_RECEIPT_FILE = ".banhaten/installed.json"
66
- const SETUP_DEV_DEPENDENCIES = {
67
- tailwindcss: "^4.0.0",
68
- }
69
- const VITE_DEV_DEPENDENCIES = {
70
- "@tailwindcss/vite": "^4.0.0",
71
- }
72
- let runtimeOptions = {
73
- json: false,
74
- silent: false,
75
- }
76
-
77
- const DEFAULT_CONFIG = {
78
- $schema: ".banhaten/schema/config.schema.json",
79
- tailwind: {
80
- css: "app/globals.css",
81
- },
82
- aliases: {
83
- ui: "@/components/ui",
84
- utils: "@/lib/utils",
85
- hooks: "@/hooks",
86
- },
87
- }
88
-
89
- // Top-level keys from the shadcn-shaped config this CLI grew out of. They are
90
- // deliberately migrated away rather than rejected, so an existing project can
91
- // upgrade in place. Every *other* unknown key is a real error: without this
92
- // list, dropping unknown keys wholesale is indistinguishable from silently
93
- // destroying a setting the user meant to keep.
94
- const LEGACY_CONFIG_KEYS = Object.freeze(["style", "tsx", "rsc", "iconLibrary"])
95
-
96
- function stripLegacyConfigKeys(config) {
97
- const next = { ...config }
98
- for (const key of LEGACY_CONFIG_KEYS) delete next[key]
99
- return next
100
- }
101
-
102
- function findLegacyConfigKeys(config) {
103
- return LEGACY_CONFIG_KEYS.filter((key) => key in config)
104
- }
105
-
106
- const registry = await readJson(registryIndexPath)
107
- const packageManifest = await readJson(packageJsonPath)
108
- const registrySchema = await readJson(path.join(schemaRoot, "registry.schema.json"))
109
- const configSchema = await readJson(path.join(schemaRoot, "config.schema.json"))
110
- assertSchema(registry, registrySchema, "registry/index.json")
111
-
112
- main().catch((error) => {
113
- console.error(`banhaten: ${error.message}`)
114
- process.exitCode = 1
115
- })
116
-
117
- async function main() {
118
- const { command, positionals, flags } = parseCommandLine(process.argv.slice(2))
119
- runtimeOptions = {
120
- json: Boolean(flags.json),
121
- silent: Boolean(flags.silent),
122
- }
123
-
124
- if (command === "version" || flags.version) {
125
- console.log(packageManifest.version)
126
- return
127
- }
128
-
129
- if (!command || command === "help" || flags.help) {
130
- printHelp()
131
- return
132
- }
133
-
134
- if (command === "list") {
135
- listComponents(registry, runtimeOptions)
136
- return
137
- }
138
-
139
- if (command === "search") {
140
- searchComponents(registry, positionals, runtimeOptions)
141
- return
142
- }
143
-
144
- if (command === "docs") {
145
- await showComponentDocs(registry, packageRoot, positionals, runtimeOptions)
146
- return
147
- }
148
-
149
- if (command === "view") {
150
- await viewComponent(
151
- registry,
152
- registryRoot,
153
- positionals,
154
- flags,
155
- runtimeOptions
156
- )
157
- return
158
- }
159
-
160
- if (command === "doctor") {
161
- const report = await inspectBanhatenProject({
162
- cwd: path.resolve(flags.cwd || process.cwd()),
163
- registryVersion: packageManifest.version,
164
- })
165
- printBanhatenDoctor(report, runtimeOptions)
166
- if (report.summary.errors > 0) process.exitCode = 1
167
- return
168
- }
169
-
170
- if (command === "init") {
171
- await runFileTransaction(() => initProject(flags))
172
- return
173
- }
174
-
175
- if (command === "add") {
176
- await runFileTransaction(() => addComponents(positionals, flags))
177
- return
178
- }
179
-
180
- if (command === "diff") {
181
- await runFileTransaction(() => diffComponents(positionals, flags))
182
- return
183
- }
184
-
185
- if (command === "update") {
186
- await runFileTransaction(() => updateComponents(positionals, flags))
187
- return
188
- }
189
-
190
- throw new Error(`unknown command "${command}"`)
191
- }
192
-
193
- function printHelp() {
194
- console.log(`Banhaten design system
195
-
196
- Usage:
197
- banhaten init [--cwd <path>] [--force] [--dry-run] [--json]
198
- banhaten add <component...> [--cwd <path>] [--force] [--dry-run] [--json]
199
- banhaten diff [component...] [--cwd <path>] [--json]
200
- banhaten update [component...] [--cwd <path>] [--force] [--dry-run] [--json]
201
- banhaten list [--json]
202
- banhaten search <query> [--json]
203
- banhaten docs <component> [--json]
204
- banhaten view <component> [--file <registry-source>] [--json]
205
- banhaten doctor [--cwd <path>] [--json]
206
- banhaten version
207
-
208
- Examples:
209
- npx banhaten init
210
- npx banhaten add button
211
- npx banhaten diff
212
- npx banhaten update button
213
- npx banhaten search input
214
- npx banhaten docs button
215
- npx banhaten view button
216
- npx banhaten doctor
217
-
218
- Command flags:
219
- --cwd <path> Run project-aware commands against a project directory.
220
- --dry-run Preview init, add, or update writes.
221
- --force Replace locally modified generated files after review.
222
- --json Print machine-readable output where shown above.
223
-
224
- Global flags:
225
- --help, -h Print help.
226
- --silent, -s Suppress normal command output.
227
- --yes, -y Accepted for non-interactive scripts.
228
- --version, -v Print the installed CLI version.
229
- `)
230
- }
231
-
232
- async function initProject(flags) {
233
- const cwd = path.resolve(flags.cwd || process.cwd())
234
- const dryRun = Boolean(flags["dry-run"])
235
- const force = Boolean(flags.force)
236
- const config = await loadConfig(cwd)
237
- const installPlan = await createInstallPlan(cwd, config)
238
- const receipt = await readInstallReceipt(cwd)
239
- validateReceiptDestinations(installPlan, receipt, registry)
240
- const managedOptions = { dryRun, force, receipt }
241
- const writes = []
242
-
243
- writes.push(
244
- ...(await writeConfig(cwd, config, { dryRun, force })),
245
- ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
246
- ...(await writeBaseFiles(installPlan, managedOptions)),
247
- ...(await writeGlobalCss(installPlan, managedOptions)),
248
- ...(await writeAliasConfig(installPlan, { dryRun, force }))
249
- )
250
-
251
- const packageResult = await updatePackageJson(
252
- cwd,
253
- getPackageChanges(installPlan, registry.base.dependencies || {}),
254
- { dryRun }
255
- )
256
- writes.push(...packageResult.writes)
257
- writes.push(...(await writeInstallReceipt(installPlan, [], { dryRun })))
258
- const installResolution = await resolveInstallAction(
259
- cwd,
260
- packageResult.installRequired
261
- )
262
- for (const evidence of installResolution.evidence) {
263
- await assertFileUnchanged(evidence.path, evidence.source)
264
- }
265
- const { install } = installResolution
266
-
267
- deferUntilApplied(() => {
268
- printResult(
269
- "Initialized Banhaten design system",
270
- writes,
271
- dryRun,
272
- runtimeOptions,
273
- install
274
- )
275
- printInstallHint(install, dryRun, runtimeOptions)
276
- })
277
- }
278
-
279
- async function addComponents(names, flags) {
280
- if (names.length === 0) {
281
- throw new Error("missing component name. Try `banhaten add button`.")
282
- }
283
-
284
- await writeComponents(names, flags, {
285
- inferInstalled: false,
286
- title: `Added ${names.join(", ")}`,
287
- })
288
- }
289
-
290
- async function diffComponents(names, flags) {
291
- await writeComponents(names, { ...flags, "dry-run": true, "show-diff": true }, {
292
- inferInstalled: true,
293
- title: names.length
294
- ? `Checked ${names.join(", ")} for updates`
295
- : "Checked installed components for updates",
296
- })
297
- }
298
-
299
- async function updateComponents(names, flags) {
300
- await writeComponents(names, flags, {
301
- inferInstalled: true,
302
- title: names.length
303
- ? `Updated ${names.join(", ")}`
304
- : "Updated installed components",
305
- })
306
- }
307
-
308
- async function writeComponents(requestedNames, flags, options) {
309
- const cwd = path.resolve(flags.cwd || process.cwd())
310
- const dryRun = Boolean(flags["dry-run"])
311
- const force = Boolean(flags.force)
312
- const showDiff = Boolean(flags["show-diff"])
313
- const config = await loadConfig(cwd)
314
- const installPlan = await createInstallPlan(cwd, config)
315
- const receipt = await readInstallReceipt(cwd)
316
- validateReceiptDestinations(installPlan, receipt, registry)
317
- const managedOptions = { dryRun, force, receipt, showDiff }
318
- const selectedNames =
319
- requestedNames.length > 0
320
- ? requestedNames
321
- : options.inferInstalled
322
- ? await findInstalledComponents(installPlan)
323
- : requestedNames
324
-
325
- if (selectedNames.length === 0) {
326
- throw new Error(
327
- "no installed components found. Run `banhaten add button` first, or pass component names."
328
- )
329
- }
330
-
331
- const names = resolveRegistryDependencies(selectedNames)
332
-
333
- const writes = []
334
- const deps = {}
335
- const components = []
336
-
337
- mergeDependencyRequirements(
338
- deps,
339
- registry.base.dependencies || {},
340
- "registry base"
341
- )
342
-
343
- for (const name of names) {
344
- const component = registry.components[name]
345
- if (!component) {
346
- throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
347
- }
348
-
349
- mergeDependencyRequirements(
350
- deps,
351
- component.dependencies || {},
352
- `registry component "${name}"`
353
- )
354
- components.push({ component, name })
355
- }
356
-
357
- writes.push(
358
- ...(await writeConfig(cwd, config, { dryRun, force })),
359
- ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
360
- ...(await writeBaseFiles(installPlan, managedOptions)),
361
- ...(await writeGlobalCss(installPlan, managedOptions)),
362
- ...(await writeAliasConfig(installPlan, { dryRun, force }))
363
- )
364
-
365
- for (const { component, name } of components) {
366
- writes.push(
367
- ...(await writeRegistryFiles(installPlan, component.files || [], {
368
- ...managedOptions,
369
- owner: name,
370
- }))
371
- )
372
- }
373
-
374
- const packageResult = await updatePackageJson(
375
- cwd,
376
- getPackageChanges(installPlan, deps),
377
- { dryRun }
378
- )
379
- writes.push(...packageResult.writes)
380
- writes.push(...(await writeInstallReceipt(installPlan, names, { dryRun })))
381
- const installResolution = await resolveInstallAction(
382
- cwd,
383
- packageResult.installRequired
384
- )
385
- for (const evidence of installResolution.evidence) {
386
- await assertFileUnchanged(evidence.path, evidence.source)
387
- }
388
- const { install } = installResolution
389
-
390
- deferUntilApplied(() => {
391
- printResult(options.title, writes, dryRun, runtimeOptions, install)
392
- printInstallHint(install, dryRun, runtimeOptions)
393
- })
394
- }
395
-
396
- async function readInstallReceipt(cwd) {
397
- const receipt = await readJsonForUpdate(path.join(cwd, INSTALL_RECEIPT_FILE))
398
- if (!receipt) return null
399
- if (receipt.schemaVersion !== 1 || !receipt.components) {
400
- throw new Error(
401
- `${INSTALL_RECEIPT_FILE} is invalid. Re-run an explicit \`banhaten add <component> --force\` command to rebuild it.`
402
- )
403
- }
404
- return receipt
405
- }
406
-
407
- async function findInstalledComponents(installPlan) {
408
- const { cwd } = installPlan
409
- const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
410
- const receipt = await readInstallReceipt(cwd)
411
- if (receipt) {
412
- const installed = []
413
- for (const [name, record] of Object.entries(receipt.components)) {
414
- if (!registry.components[name] || !Array.isArray(record.files)) continue
415
- if (
416
- record.files.length > 0 &&
417
- (await allPathsExist(
418
- record.files.map((file) =>
419
- path.join(cwd, normalizeReceiptTarget(file.target))
420
- )
421
- ))
422
- ) {
423
- installed.push(name)
424
- }
425
- }
426
-
427
- return installed
428
- }
429
-
430
- const installed = []
431
-
432
- for (const [name, component] of Object.entries(registry.components)) {
433
- const files = component.files || []
434
- if (files.length === 0) continue
435
-
436
- const targetPaths = files.map((file) =>
437
- path.join(cwd, resolveInstallTarget(installPlan, file.target))
438
- )
439
- if (await allPathsExist(targetPaths)) {
440
- installed.push(name)
441
- }
442
- }
443
-
444
- return installed
445
- }
446
-
447
- async function writeInstallReceipt(installPlan, names, options) {
448
- const { cwd } = installPlan
449
- const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
450
- const current = (await readJsonForUpdate(receiptPath)) || {
451
- schemaVersion: 1,
452
- components: {},
453
- }
454
- const components = normalizeReceiptComponents(current.components || {})
455
- const managedFiles = Object.fromEntries(
456
- Object.entries(current.managedFiles || {}).map(([target, record]) => [
457
- normalizeReceiptTarget(target),
458
- record,
459
- ])
460
- )
461
-
462
- await addManagedFileRecords(
463
- managedFiles,
464
- installPlan,
465
- registry.base.files || [],
466
- "base"
467
- )
468
-
469
- for (const name of names) {
470
- const component = registry.components[name]
471
- await addManagedFileRecords(
472
- managedFiles,
473
- installPlan,
474
- component.files || [],
475
- name
476
- )
477
- components[name] = {
478
- files: await Promise.all(
479
- (component.files || []).map(async (file) => {
480
- const sourcePath = path.join(registryRoot, file.source)
481
- const source = await fs.readFile(sourcePath)
482
- const target = resolveInstallTarget(installPlan, file.target)
483
- const content = isTextRegistryFile(file.source)
484
- ? applyTemplate(source.toString("utf8"), installPlan, target)
485
- : source
486
-
487
- return {
488
- target,
489
- sha256: createHash("sha256").update(content).digest("hex"),
490
- }
491
- })
492
- ),
493
- }
494
- }
495
-
496
- const next = {
497
- schemaVersion: 1,
498
- registryVersion: packageManifest.version,
499
- installPlan: createInstallPlanReceipt(installPlan),
500
- components: sortObject(components),
501
- managedFiles: sortObject(managedFiles),
502
- tokenCss: await createTokenCssReceipt(installPlan),
503
- }
504
- const status = await writeFile(
505
- receiptPath,
506
- `${JSON.stringify(next, null, 2)}\n`,
507
- { dryRun: options.dryRun, force: true }
508
- )
509
-
510
- return [`${status} ${INSTALL_RECEIPT_FILE}`]
511
- }
512
-
513
- async function addManagedFileRecords(records, installPlan, files, owner) {
514
- for (const file of files) {
515
- const source = await fs.readFile(path.join(registryRoot, file.source))
516
- const target = resolveInstallTarget(installPlan, file.target)
517
- const content = isTextRegistryFile(file.source)
518
- ? applyTemplate(source.toString("utf8"), installPlan, target)
519
- : source
520
- records[target] = {
521
- owner,
522
- sha256: hashContent(content),
523
- }
524
- }
525
- }
526
-
527
- async function createTokenCssReceipt(installPlan) {
528
- const tokenCss = await fs.readFile(
529
- path.join(registryRoot, "styles", "globals.css"),
530
- "utf8"
531
- )
532
- return {
533
- target: installPlan.destinations.css,
534
- sha256: hashNormalizedText(tokenCss),
535
- }
536
- }
537
-
538
- async function allPathsExist(paths) {
539
- const results = await Promise.all(paths.map((targetPath) => exists(targetPath)))
540
- return results.every(Boolean)
541
- }
542
-
543
- function resolveRegistryDependencies(names) {
544
- const resolved = []
545
- const seen = new Set()
546
- const visiting = new Set()
547
-
548
- for (const name of names) {
549
- visit(name)
550
- }
551
-
552
- return resolved
553
-
554
- function visit(name) {
555
- const component = registry.components[name]
556
- if (!component) {
557
- throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
558
- }
559
-
560
- if (seen.has(name)) return
561
- if (visiting.has(name)) {
562
- throw new Error(`circular registry dependency detected at "${name}".`)
563
- }
564
-
565
- visiting.add(name)
566
- for (const dependency of component.registryDependencies || []) {
567
- visit(dependency)
568
- }
569
- visiting.delete(name)
570
-
571
- seen.add(name)
572
- resolved.push(name)
573
- }
574
- }
575
-
576
- async function loadConfig(cwd) {
577
- const configPath = path.join(cwd, CONFIG_FILE)
578
- const componentsPath = path.join(cwd, "components.json")
579
- const config = structuredClone(DEFAULT_CONFIG)
580
-
581
- const componentsConfig = await readJsonForUpdate(componentsPath)
582
- let hasExplicitCssPath = false
583
- if (componentsConfig) {
584
- if (componentsConfig.tailwind?.css) {
585
- config.tailwind.css = componentsConfig.tailwind.css
586
- hasExplicitCssPath = true
587
- }
588
- config.aliases.utils = componentsConfig.aliases?.utils || config.aliases.utils
589
- config.aliases.hooks = componentsConfig.aliases?.hooks || config.aliases.hooks
590
- config.aliases.ui =
591
- componentsConfig.aliases?.ui ||
592
- appendAliasSegment(componentsConfig.aliases?.components, "ui") ||
593
- config.aliases.ui
594
- }
595
-
596
- const localConfig = await readJsonForUpdate(configPath)
597
- if (localConfig) {
598
- // Validate what the user actually wrote, before it is merged onto the
599
- // defaults. Validating the merged object instead would apply
600
- // `additionalProperties: false` to something that structurally cannot carry
601
- // an unknown top-level key, so a stray key would pass here and then be
602
- // silently dropped by writeConfig. Known legacy keys are stripped first so
603
- // they migrate instead of failing.
604
- assertSchema(stripLegacyConfigKeys(localConfig), configSchema, CONFIG_FILE)
605
-
606
- if (localConfig.tailwind?.css) hasExplicitCssPath = true
607
- config.tailwind = { ...config.tailwind, ...(localConfig.tailwind || {}) }
608
- config.aliases = { ...config.aliases, ...(localConfig.aliases || {}) }
609
- }
610
-
611
- if (!hasExplicitCssPath) {
612
- config.tailwind.css = await detectCssPath(cwd, config.tailwind.css)
613
- }
614
-
615
- assertSchema(config, configSchema, CONFIG_FILE)
616
-
617
- return config
618
- }
619
-
620
- async function detectCssPath(cwd, fallback) {
621
- const candidates = [
622
- "app/globals.css",
623
- "src/app/globals.css",
624
- "src/index.css",
625
- "src/globals.css",
626
- "styles/globals.css",
627
- ]
628
-
629
- for (const candidate of candidates) {
630
- if (await exists(path.join(cwd, candidate))) return candidate
631
- }
632
-
633
- if (await exists(path.join(cwd, "src", "app"))) return "src/app/globals.css"
634
-
635
- return fallback
636
- }
637
-
638
- async function writeConfig(cwd, config, options) {
639
- const configPath = path.join(cwd, CONFIG_FILE)
640
- if ((await exists(configPath)) && !options.force) {
641
- const current = await fs.readFile(configPath, "utf8")
642
- const currentConfig = JSON.parse(current)
643
- // Spread the existing file first so any key this version does not manage
644
- // survives the rewrite. Rebuilding from a fixed whitelist would delete it
645
- // and still report the write as a plain "updated". Legacy keys are the one
646
- // intentional exception, and the removal is reported rather than silent.
647
- const legacyKeys = findLegacyConfigKeys(currentConfig)
648
- const nextConfig = {
649
- ...stripLegacyConfigKeys(currentConfig),
650
- $schema: DEFAULT_CONFIG.$schema,
651
- tailwind: config.tailwind,
652
- aliases: config.aliases,
653
- }
654
-
655
- if (JSON.stringify(currentConfig) !== JSON.stringify(nextConfig)) {
656
- const status = await writeFile(
657
- configPath,
658
- `${JSON.stringify(nextConfig, null, 2)}\n`,
659
- { dryRun: options.dryRun }
660
- )
661
-
662
- const notes = [`${status} ${relative(cwd, configPath)}`]
663
- if (legacyKeys.length > 0) {
664
- notes.push(
665
- `removed legacy config ${legacyKeys.length === 1 ? "key" : "keys"} ` +
666
- `${legacyKeys.map((key) => JSON.stringify(key)).join(", ")} from ` +
667
- `${relative(cwd, configPath)}`
668
- )
669
- }
670
- return notes
671
- }
672
-
673
- return [`kept ${relative(cwd, configPath)}`]
674
- }
675
-
676
- const status = await writeFile(
677
- configPath,
678
- `${JSON.stringify(config, null, 2)}\n`,
679
- options
680
- )
681
- return [`${status} ${relative(cwd, configPath)}`]
682
- }
683
-
684
- async function writeProjectSchemaFiles(cwd, options) {
685
- const schemaFiles = [
686
- "config.schema.json",
687
- "registry.schema.json",
688
- "tokens.schema.json",
689
- ]
690
- const writes = []
691
-
692
- for (const schemaFile of schemaFiles) {
693
- const sourcePath = path.join(schemaRoot, schemaFile)
694
- const targetPath = path.join(cwd, ".banhaten", "schema", schemaFile)
695
- const source = await fs.readFile(sourcePath, "utf8")
696
- const status = await writeFile(targetPath, source, options)
697
-
698
- writes.push(`${status} ${relative(cwd, targetPath)}`)
699
- }
700
-
701
- return writes
702
- }
703
-
704
- async function writeBaseFiles(installPlan, options) {
705
- return writeRegistryFiles(installPlan, registry.base.files || [], {
706
- ...options,
707
- owner: "base",
708
- })
709
- }
710
-
711
- async function writeRegistryFiles(installPlan, files, options) {
712
- const { cwd } = installPlan
713
- const writes = []
714
-
715
- for (const file of files) {
716
- const sourcePath = path.join(registryRoot, file.source)
717
- const targetPath = path.join(
718
- cwd,
719
- resolveInstallTarget(installPlan, file.target)
720
- )
721
- const source = await fs.readFile(sourcePath)
722
- const content = isTextRegistryFile(file.source)
723
- ? applyTemplate(
724
- source.toString("utf8"),
725
- installPlan,
726
- relative(cwd, targetPath)
727
- )
728
- : source
729
- const target = relative(cwd, targetPath)
730
-
731
- const current = await readFileForUpdate(targetPath)
732
- assertManagedFileSafe(current, content, target, options)
733
-
734
- const status = await writeFile(targetPath, content, options)
735
- writes.push(`${status} ${target}`)
736
- if (options.showDiff && status === "would update") {
737
- writes.push(formatUnifiedDiff(
738
- target,
739
- isTextRegistryFile(file.source) ? current.toString("utf8") : current,
740
- content
741
- ))
742
- }
743
- }
744
-
745
- return writes
746
- }
747
-
748
- async function writeGlobalCss(installPlan, options) {
749
- const { cwd } = installPlan
750
- const cssPath = path.join(cwd, installPlan.destinations.css)
751
- const sourcePath = path.join(registryRoot, "styles", "globals.css")
752
- const tokenCss = await fs.readFile(sourcePath, "utf8")
753
- const current = await readTextForUpdate(cssPath)
754
- const tokenBlock = current
755
- ? removeExistingTokenBlock(current, relative(cwd, cssPath))
756
- : { content: "", found: false }
757
-
758
- const nextCss = current
759
- ? `${tokenBlock.content.trimEnd()}\n\n${tokenCss}\n`
760
- : `${tokenCss}\n`
761
- const next = ensureGlobalCssImports(nextCss)
762
-
763
- if (
764
- current &&
765
- tokenBlock.found &&
766
- next !== current &&
767
- !options.dryRun &&
768
- !options.force
769
- ) {
770
- const expectedHash = options.receipt?.tokenCss?.sha256
771
- const currentHash = hashNormalizedText(tokenBlock.block)
772
- if (!expectedHash || currentHash !== expectedHash) {
773
- throw new Error(
774
- `${relative(cwd, cssPath)} contains local changes inside the generated Banhaten token block. ` +
775
- "Run `banhaten diff` to inspect them, move intentional overrides outside the generated block, or re-run with `--force`."
776
- )
777
- }
778
- }
779
-
780
- const status = await writeFile(cssPath, next, options)
781
- const writes = [`${status} ${relative(cwd, cssPath)}`]
782
- if (options.showDiff && status === "would update" && current !== null) {
783
- writes.push(formatUnifiedDiff(relative(cwd, cssPath), current, next))
784
- }
785
- return writes
786
- }
787
-
788
- async function writeAliasConfig(installPlan, options) {
789
- const writes = []
790
-
791
- for (const plannedConfig of [installPlan.typescript, installPlan.vite]) {
792
- if (!plannedConfig) continue
793
- const status = await writeFile(
794
- plannedConfig.targetPath,
795
- plannedConfig.nextSource,
796
- {
797
- dryRun: options.dryRun,
798
- expectedCurrent: plannedConfig.currentSource,
799
- force: true,
800
- }
801
- )
802
- writes.push(
803
- `${status} ${relative(installPlan.cwd, plannedConfig.targetPath)}`
804
- )
805
- }
806
-
807
- return writes
808
- }
809
-
810
- function getPackageChanges(installPlan, dependencies) {
811
- const devDependencies = { ...SETUP_DEV_DEPENDENCIES }
812
- if (installPlan.vite) {
813
- Object.assign(devDependencies, VITE_DEV_DEPENDENCIES)
814
- }
815
-
816
- return {
817
- dependencies,
818
- devDependencies,
819
- }
820
- }
821
-
822
- async function updatePackageJson(cwd, changes, options) {
823
- const packagePath = path.join(cwd, "package.json")
824
- const currentSource = await readTextForUpdate(packagePath)
825
- const packageExists = currentSource !== null
826
- const packageJson = currentSource !== null ? JSON.parse(currentSource) : {
827
- name: path.basename(cwd).toLowerCase(),
828
- version: "0.0.0",
829
- private: true,
830
- }
831
- const packagePlan = createPackageDependencyPlan(packageJson, changes)
832
-
833
- if (packagePlan.operations.length === 0 && packageExists) {
834
- await assertFileUnchanged(packagePath, currentSource)
835
- const installState = await inspectPackageInstallState({
836
- cwd,
837
- packageJson,
838
- requirements: packagePlan.requirements,
839
- })
840
- for (const evidence of installState.evidence) {
841
- await assertFileUnchanged(evidence.path, evidence.source)
842
- }
843
- return {
844
- installRequired: installState.required,
845
- writes: [`kept ${relative(cwd, packagePath)}`],
846
- }
847
- }
848
-
849
- applyPackageDependencyPlan(packageJson, packagePlan.operations)
850
-
851
- const status = await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, {
852
- dryRun: options.dryRun,
853
- expectedCurrent: currentSource,
854
- force: true,
855
- })
856
-
857
- return {
858
- installRequired: packagePlan.operations.length > 0,
859
- writes: [`${status} ${relative(cwd, packagePath)}`],
860
- }
861
- }
862
-
863
- function applyTemplate(source, installPlan, target) {
864
- const replacements = {
865
- "@/components/ui": resolveTemplateImport(
866
- installPlan,
867
- target,
868
- "ui"
869
- ),
870
- "@/lib/utils": resolveTemplateImport(
871
- installPlan,
872
- target,
873
- "utils"
874
- ),
875
- "@/hooks": resolveTemplateImport(
876
- installPlan,
877
- target,
878
- "hooks"
879
- ),
880
- }
881
-
882
- return source.replace(
883
- /@\/components\/ui|@\/lib\/utils|@\/hooks/g,
884
- (match) => replacements[match]
885
- )
886
- }
887
-
888
- function resolveTemplateImport(installPlan, target, destinationName) {
889
- const configuredAlias = installPlan.config.aliases[destinationName]
890
- if (
891
- configuredAlias === "@" ||
892
- configuredAlias === "~" ||
893
- configuredAlias.startsWith("@/") ||
894
- configuredAlias.startsWith("~/")
895
- ) {
896
- return configuredAlias.replace(/\/$/, "")
897
- }
898
-
899
- const targetDirectory = path.posix.dirname(
900
- normalizeReceiptTarget(target)
901
- )
902
- const destination = installPlan.destinations[destinationName]
903
- const relativeImport = path.posix.relative(targetDirectory, destination)
904
-
905
- if (!relativeImport) return "."
906
- return relativeImport.startsWith(".")
907
- ? relativeImport
908
- : `./${relativeImport}`
909
- }
910
-
911
- function isTextRegistryFile(source) {
912
- return !/\.(avif|eot|gif|ico|jpe?g|otf|png|ttf|webp|woff2?)$/i.test(source)
913
- }
914
-
915
- async function readJson(filePath) {
916
- return JSON.parse(await fs.readFile(filePath, "utf8"))
917
- }
918
-
919
- async function readJsonForUpdate(filePath) {
920
- const source = await readTextForUpdate(filePath)
921
- return source === null ? null : JSON.parse(source)
922
- }
923
-
924
- async function readTextForUpdate(filePath) {
925
- const source = await readFileForUpdate(filePath)
926
- return source === null ? null : source.toString("utf8")
927
- }
928
-
929
- function assertManagedFileSafe(current, nextContent, target, options) {
930
- if (options.dryRun || options.force || current === null) return
931
-
932
- const next = Buffer.isBuffer(nextContent)
933
- ? nextContent
934
- : Buffer.from(nextContent, "utf8")
935
- if (current.equals(next)) return
936
-
937
- const expectedHash = findManagedFileHash(options.receipt, target)
938
- const currentHash = hashContent(current)
939
- if (expectedHash && currentHash === expectedHash) return
940
-
941
- const owner = options.owner ? ` (${options.owner})` : ""
942
- const reason = expectedHash
943
- ? "has local changes since Banhaten installed it"
944
- : "already exists without a Banhaten ownership receipt"
945
- const diffCommand = ["banhaten", "diff", options.owner === "base" ? "" : options.owner]
946
- .filter(Boolean)
947
- .join(" ")
948
- throw new Error(
949
- `${target}${owner} ${reason}. Run \`${diffCommand}\` to inspect the registry version, ` +
950
- "or re-run the command with `--force` to replace the file."
951
- )
952
- }
953
-
954
- function findManagedFileHash(receipt, target) {
955
- const normalizedTarget = normalizeReceiptTarget(target)
956
- const direct = Object.entries(receipt?.managedFiles || {}).find(
957
- ([recordedTarget]) =>
958
- normalizeReceiptTarget(recordedTarget) === normalizedTarget
959
- )?.[1]?.sha256
960
- if (direct) return direct
961
-
962
- for (const component of Object.values(receipt?.components || {})) {
963
- const match = component.files?.find(
964
- (file) => normalizeReceiptTarget(file.target) === normalizedTarget
965
- )
966
- if (match?.sha256) return match.sha256
967
- }
968
-
969
- return null
970
- }
971
-
972
- function hashContent(content) {
973
- return createHash("sha256").update(content).digest("hex")
974
- }
975
-
976
- function hashNormalizedText(content) {
977
- return hashContent(String(content).replace(/\r\n/g, "\n").trim())
978
- }
979
-
980
- async function exists(filePath) {
981
- try {
982
- await fs.access(filePath)
983
- return true
984
- } catch {
985
- return false
986
- }
987
- }
988
-
989
- function appendAliasSegment(alias, segment) {
990
- if (!alias) return null
991
- return `${alias.replace(/\/$/, "")}/${segment}`
992
- }
993
-
994
- function sortObject(value) {
995
- return Object.fromEntries(
996
- Object.entries(value).sort(([left], [right]) => left.localeCompare(right))
997
- )
998
- }
999
-
1000
- function relative(cwd, targetPath) {
1001
- return path.relative(cwd, targetPath).replaceAll("\\", "/")
1002
- }
1
+ #!/usr/bin/env node
2
+
3
+ import { createHash } from "node:crypto"
4
+ import fs from "node:fs/promises"
5
+ import path from "node:path"
6
+ import process from "node:process"
7
+ import { fileURLToPath } from "node:url"
8
+ import { parseCommandLine } from "./command-line.js"
9
+ import {
10
+ inspectBanhatenProject,
11
+ printBanhatenDoctor,
12
+ } from "./doctor.js"
13
+ import {
14
+ assertFileUnchanged,
15
+ deferUntilApplied,
16
+ formatUnifiedDiff,
17
+ readFileForUpdate,
18
+ runFileTransaction,
19
+ writeFile,
20
+ } from "./file-transaction.js"
21
+ import {
22
+ applyPackageDependencyPlan,
23
+ createPackageDependencyPlan,
24
+ mergeDependencyRequirements,
25
+ } from "./package-plan.js"
26
+ import { inspectPackageInstallState } from "./package-install-state.js"
27
+ import {
28
+ createInstallPlan,
29
+ resolveInstallTarget,
30
+ } from "./install-plan.js"
31
+ import {
32
+ createInstallPlanReceipt,
33
+ normalizeReceiptComponents,
34
+ normalizeReceiptTarget,
35
+ validateReceiptDestinations,
36
+ } from "./install-receipt.js"
37
+ import {
38
+ ensureGlobalCssImports,
39
+ removeExistingTokenBlock,
40
+ } from "./global-css.js"
41
+ import {
42
+ printInstallHint,
43
+ printResult,
44
+ resolveInstallAction,
45
+ } from "./reporting.js"
46
+ import { assertSchema } from "./schema-validation.js"
47
+ import {
48
+ listComponents,
49
+ searchComponents,
50
+ showComponentDocs,
51
+ viewComponent,
52
+ } from "./registry-query.js"
53
+
54
+ const packageRoot = path.resolve(
55
+ path.dirname(fileURLToPath(import.meta.url)),
56
+ "..",
57
+ ".."
58
+ )
59
+ const registryRoot = path.join(packageRoot, "registry")
60
+ const registryIndexPath = path.join(registryRoot, "index.json")
61
+ const packageJsonPath = path.join(packageRoot, "package.json")
62
+ const schemaRoot = path.join(packageRoot, "schema")
63
+
64
+ const CONFIG_FILE = "banhaten.config.json"
65
+ const INSTALL_RECEIPT_FILE = ".banhaten/installed.json"
66
+ const SETUP_DEV_DEPENDENCIES = {
67
+ tailwindcss: "^4.0.0",
68
+ }
69
+ const VITE_DEV_DEPENDENCIES = {
70
+ "@tailwindcss/vite": "^4.0.0",
71
+ }
72
+ let runtimeOptions = {
73
+ json: false,
74
+ silent: false,
75
+ }
76
+
77
+ const DEFAULT_CONFIG = {
78
+ $schema: ".banhaten/schema/config.schema.json",
79
+ tailwind: {
80
+ css: "app/globals.css",
81
+ },
82
+ aliases: {
83
+ ui: "@/components/ui",
84
+ utils: "@/lib/utils",
85
+ hooks: "@/hooks",
86
+ },
87
+ }
88
+
89
+ // Top-level keys from the shadcn-shaped config this CLI grew out of. They are
90
+ // deliberately migrated away rather than rejected, so an existing project can
91
+ // upgrade in place. Every *other* unknown key is a real error: without this
92
+ // list, dropping unknown keys wholesale is indistinguishable from silently
93
+ // destroying a setting the user meant to keep.
94
+ const LEGACY_CONFIG_KEYS = Object.freeze(["style", "tsx", "rsc", "iconLibrary"])
95
+
96
+ function stripLegacyConfigKeys(config) {
97
+ const next = { ...config }
98
+ for (const key of LEGACY_CONFIG_KEYS) delete next[key]
99
+ return next
100
+ }
101
+
102
+ function findLegacyConfigKeys(config) {
103
+ return LEGACY_CONFIG_KEYS.filter((key) => key in config)
104
+ }
105
+
106
+ const registry = await readJson(registryIndexPath)
107
+ const packageManifest = await readJson(packageJsonPath)
108
+ const registrySchema = await readJson(path.join(schemaRoot, "registry.schema.json"))
109
+ const configSchema = await readJson(path.join(schemaRoot, "config.schema.json"))
110
+ assertSchema(registry, registrySchema, "registry/index.json")
111
+
112
+ main().catch((error) => {
113
+ console.error(`banhaten: ${error.message}`)
114
+ process.exitCode = 1
115
+ })
116
+
117
+ async function main() {
118
+ const { command, positionals, flags } = parseCommandLine(process.argv.slice(2))
119
+ runtimeOptions = {
120
+ json: Boolean(flags.json),
121
+ silent: Boolean(flags.silent),
122
+ }
123
+
124
+ if (command === "version" || flags.version) {
125
+ console.log(packageManifest.version)
126
+ return
127
+ }
128
+
129
+ if (!command || command === "help" || flags.help) {
130
+ printHelp()
131
+ return
132
+ }
133
+
134
+ if (command === "list") {
135
+ listComponents(registry, runtimeOptions)
136
+ return
137
+ }
138
+
139
+ if (command === "search") {
140
+ searchComponents(registry, positionals, runtimeOptions)
141
+ return
142
+ }
143
+
144
+ if (command === "docs") {
145
+ await showComponentDocs(registry, packageRoot, positionals, runtimeOptions)
146
+ return
147
+ }
148
+
149
+ if (command === "view") {
150
+ await viewComponent(
151
+ registry,
152
+ registryRoot,
153
+ positionals,
154
+ flags,
155
+ runtimeOptions
156
+ )
157
+ return
158
+ }
159
+
160
+ if (command === "doctor") {
161
+ const report = await inspectBanhatenProject({
162
+ cwd: path.resolve(flags.cwd || process.cwd()),
163
+ registryVersion: packageManifest.version,
164
+ })
165
+ printBanhatenDoctor(report, runtimeOptions)
166
+ if (report.summary.errors > 0) process.exitCode = 1
167
+ return
168
+ }
169
+
170
+ if (command === "init") {
171
+ await runFileTransaction(() => initProject(flags))
172
+ return
173
+ }
174
+
175
+ if (command === "add") {
176
+ await runFileTransaction(() => addComponents(positionals, flags))
177
+ return
178
+ }
179
+
180
+ if (command === "diff") {
181
+ await runFileTransaction(() => diffComponents(positionals, flags))
182
+ return
183
+ }
184
+
185
+ if (command === "update") {
186
+ await runFileTransaction(() => updateComponents(positionals, flags))
187
+ return
188
+ }
189
+
190
+ throw new Error(`unknown command "${command}"`)
191
+ }
192
+
193
+ function printHelp() {
194
+ console.log(`Banhaten design system
195
+
196
+ Usage:
197
+ banhaten init [--cwd <path>] [--force] [--dry-run] [--json]
198
+ banhaten add <component...> [--cwd <path>] [--force] [--dry-run] [--json]
199
+ banhaten diff [component...] [--cwd <path>] [--json]
200
+ banhaten update [component...] [--cwd <path>] [--force] [--dry-run] [--json]
201
+ banhaten list [--json]
202
+ banhaten search <query> [--json]
203
+ banhaten docs <component> [--json]
204
+ banhaten view <component> [--file <registry-source>] [--json]
205
+ banhaten doctor [--cwd <path>] [--json]
206
+ banhaten version
207
+
208
+ Examples:
209
+ npx banhaten init
210
+ npx banhaten add button
211
+ npx banhaten diff
212
+ npx banhaten update button
213
+ npx banhaten search input
214
+ npx banhaten docs button
215
+ npx banhaten view button
216
+ npx banhaten doctor
217
+
218
+ Command flags:
219
+ --cwd <path> Run project-aware commands against a project directory.
220
+ --dry-run Preview init, add, or update writes.
221
+ --force Replace locally modified generated files after review.
222
+ --json Print machine-readable output where shown above.
223
+
224
+ Global flags:
225
+ --help, -h Print help.
226
+ --silent, -s Suppress normal command output.
227
+ --yes, -y Accepted for non-interactive scripts.
228
+ --version, -v Print the installed CLI version.
229
+ `)
230
+ }
231
+
232
+ async function initProject(flags) {
233
+ const cwd = path.resolve(flags.cwd || process.cwd())
234
+ const dryRun = Boolean(flags["dry-run"])
235
+ const force = Boolean(flags.force)
236
+ const config = await loadConfig(cwd)
237
+ const installPlan = await createInstallPlan(cwd, config)
238
+ const receipt = await readInstallReceipt(cwd)
239
+ validateReceiptDestinations(installPlan, receipt, registry)
240
+ const managedOptions = { dryRun, force, receipt }
241
+ const writes = []
242
+
243
+ writes.push(
244
+ ...(await writeConfig(cwd, config, { dryRun, force })),
245
+ ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
246
+ ...(await writeBaseFiles(installPlan, managedOptions)),
247
+ ...(await writeGlobalCss(installPlan, managedOptions)),
248
+ ...(await writeAliasConfig(installPlan, { dryRun, force }))
249
+ )
250
+
251
+ const packageResult = await updatePackageJson(
252
+ cwd,
253
+ getPackageChanges(installPlan, registry.base.dependencies || {}),
254
+ { dryRun }
255
+ )
256
+ writes.push(...packageResult.writes)
257
+ writes.push(...(await writeInstallReceipt(installPlan, [], { dryRun })))
258
+ const installResolution = await resolveInstallAction(
259
+ cwd,
260
+ packageResult.installRequired
261
+ )
262
+ for (const evidence of installResolution.evidence) {
263
+ await assertFileUnchanged(evidence.path, evidence.source)
264
+ }
265
+ const { install } = installResolution
266
+
267
+ deferUntilApplied(() => {
268
+ printResult(
269
+ "Initialized Banhaten design system",
270
+ writes,
271
+ dryRun,
272
+ runtimeOptions,
273
+ install
274
+ )
275
+ printInstallHint(install, dryRun, runtimeOptions)
276
+ })
277
+ }
278
+
279
+ async function addComponents(names, flags) {
280
+ if (names.length === 0) {
281
+ throw new Error("missing component name. Try `banhaten add button`.")
282
+ }
283
+
284
+ await writeComponents(names, flags, {
285
+ inferInstalled: false,
286
+ title: `Added ${names.join(", ")}`,
287
+ })
288
+ }
289
+
290
+ async function diffComponents(names, flags) {
291
+ await writeComponents(names, { ...flags, "dry-run": true, "show-diff": true }, {
292
+ inferInstalled: true,
293
+ title: names.length
294
+ ? `Checked ${names.join(", ")} for updates`
295
+ : "Checked installed components for updates",
296
+ })
297
+ }
298
+
299
+ async function updateComponents(names, flags) {
300
+ await writeComponents(names, flags, {
301
+ inferInstalled: true,
302
+ title: names.length
303
+ ? `Updated ${names.join(", ")}`
304
+ : "Updated installed components",
305
+ })
306
+ }
307
+
308
+ async function writeComponents(requestedNames, flags, options) {
309
+ const cwd = path.resolve(flags.cwd || process.cwd())
310
+ const dryRun = Boolean(flags["dry-run"])
311
+ const force = Boolean(flags.force)
312
+ const showDiff = Boolean(flags["show-diff"])
313
+ const config = await loadConfig(cwd)
314
+ const installPlan = await createInstallPlan(cwd, config)
315
+ const receipt = await readInstallReceipt(cwd)
316
+ validateReceiptDestinations(installPlan, receipt, registry)
317
+ const managedOptions = { dryRun, force, receipt, showDiff }
318
+ const selectedNames =
319
+ requestedNames.length > 0
320
+ ? requestedNames
321
+ : options.inferInstalled
322
+ ? await findInstalledComponents(installPlan)
323
+ : requestedNames
324
+
325
+ if (selectedNames.length === 0) {
326
+ throw new Error(
327
+ "no installed components found. Run `banhaten add button` first, or pass component names."
328
+ )
329
+ }
330
+
331
+ const names = resolveRegistryDependencies(selectedNames)
332
+
333
+ const writes = []
334
+ const deps = {}
335
+ const components = []
336
+
337
+ mergeDependencyRequirements(
338
+ deps,
339
+ registry.base.dependencies || {},
340
+ "registry base"
341
+ )
342
+
343
+ for (const name of names) {
344
+ const component = registry.components[name]
345
+ if (!component) {
346
+ throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
347
+ }
348
+
349
+ mergeDependencyRequirements(
350
+ deps,
351
+ component.dependencies || {},
352
+ `registry component "${name}"`
353
+ )
354
+ components.push({ component, name })
355
+ }
356
+
357
+ writes.push(
358
+ ...(await writeConfig(cwd, config, { dryRun, force })),
359
+ ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
360
+ ...(await writeBaseFiles(installPlan, managedOptions)),
361
+ ...(await writeGlobalCss(installPlan, managedOptions)),
362
+ ...(await writeAliasConfig(installPlan, { dryRun, force }))
363
+ )
364
+
365
+ for (const { component, name } of components) {
366
+ writes.push(
367
+ ...(await writeRegistryFiles(installPlan, component.files || [], {
368
+ ...managedOptions,
369
+ owner: name,
370
+ }))
371
+ )
372
+ }
373
+
374
+ const packageResult = await updatePackageJson(
375
+ cwd,
376
+ getPackageChanges(installPlan, deps),
377
+ { dryRun }
378
+ )
379
+ writes.push(...packageResult.writes)
380
+ writes.push(...(await writeInstallReceipt(installPlan, names, { dryRun })))
381
+ const installResolution = await resolveInstallAction(
382
+ cwd,
383
+ packageResult.installRequired
384
+ )
385
+ for (const evidence of installResolution.evidence) {
386
+ await assertFileUnchanged(evidence.path, evidence.source)
387
+ }
388
+ const { install } = installResolution
389
+
390
+ deferUntilApplied(() => {
391
+ printResult(options.title, writes, dryRun, runtimeOptions, install)
392
+ printInstallHint(install, dryRun, runtimeOptions)
393
+ })
394
+ }
395
+
396
+ async function readInstallReceipt(cwd) {
397
+ const receipt = await readJsonForUpdate(path.join(cwd, INSTALL_RECEIPT_FILE))
398
+ if (!receipt) return null
399
+ if (receipt.schemaVersion !== 1 || !receipt.components) {
400
+ throw new Error(
401
+ `${INSTALL_RECEIPT_FILE} is invalid. Re-run an explicit \`banhaten add <component> --force\` command to rebuild it.`
402
+ )
403
+ }
404
+ return receipt
405
+ }
406
+
407
+ async function findInstalledComponents(installPlan) {
408
+ const { cwd } = installPlan
409
+ const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
410
+ const receipt = await readInstallReceipt(cwd)
411
+ if (receipt) {
412
+ const installed = []
413
+ for (const [name, record] of Object.entries(receipt.components)) {
414
+ if (!registry.components[name] || !Array.isArray(record.files)) continue
415
+ if (
416
+ record.files.length > 0 &&
417
+ (await allPathsExist(
418
+ record.files.map((file) =>
419
+ path.join(cwd, normalizeReceiptTarget(file.target))
420
+ )
421
+ ))
422
+ ) {
423
+ installed.push(name)
424
+ }
425
+ }
426
+
427
+ return installed
428
+ }
429
+
430
+ const installed = []
431
+
432
+ for (const [name, component] of Object.entries(registry.components)) {
433
+ const files = component.files || []
434
+ if (files.length === 0) continue
435
+
436
+ const targetPaths = files.map((file) =>
437
+ path.join(cwd, resolveInstallTarget(installPlan, file.target))
438
+ )
439
+ if (await allPathsExist(targetPaths)) {
440
+ installed.push(name)
441
+ }
442
+ }
443
+
444
+ return installed
445
+ }
446
+
447
+ async function writeInstallReceipt(installPlan, names, options) {
448
+ const { cwd } = installPlan
449
+ const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
450
+ const current = (await readJsonForUpdate(receiptPath)) || {
451
+ schemaVersion: 1,
452
+ components: {},
453
+ }
454
+ const components = normalizeReceiptComponents(current.components || {})
455
+ const managedFiles = Object.fromEntries(
456
+ Object.entries(current.managedFiles || {}).map(([target, record]) => [
457
+ normalizeReceiptTarget(target),
458
+ record,
459
+ ])
460
+ )
461
+
462
+ await addManagedFileRecords(
463
+ managedFiles,
464
+ installPlan,
465
+ registry.base.files || [],
466
+ "base"
467
+ )
468
+
469
+ for (const name of names) {
470
+ const component = registry.components[name]
471
+ await addManagedFileRecords(
472
+ managedFiles,
473
+ installPlan,
474
+ component.files || [],
475
+ name
476
+ )
477
+ components[name] = {
478
+ files: await Promise.all(
479
+ (component.files || []).map(async (file) => {
480
+ const sourcePath = path.join(registryRoot, file.source)
481
+ const source = await fs.readFile(sourcePath)
482
+ const target = resolveInstallTarget(installPlan, file.target)
483
+ const content = isTextRegistryFile(file.source)
484
+ ? applyTemplate(source.toString("utf8"), installPlan, target)
485
+ : source
486
+
487
+ return {
488
+ target,
489
+ sha256: createHash("sha256").update(content).digest("hex"),
490
+ }
491
+ })
492
+ ),
493
+ }
494
+ }
495
+
496
+ const next = {
497
+ schemaVersion: 1,
498
+ registryVersion: packageManifest.version,
499
+ installPlan: createInstallPlanReceipt(installPlan),
500
+ components: sortObject(components),
501
+ managedFiles: sortObject(managedFiles),
502
+ tokenCss: await createTokenCssReceipt(installPlan),
503
+ }
504
+ const status = await writeFile(
505
+ receiptPath,
506
+ `${JSON.stringify(next, null, 2)}\n`,
507
+ { dryRun: options.dryRun, force: true }
508
+ )
509
+
510
+ return [`${status} ${INSTALL_RECEIPT_FILE}`]
511
+ }
512
+
513
+ async function addManagedFileRecords(records, installPlan, files, owner) {
514
+ for (const file of files) {
515
+ const source = await fs.readFile(path.join(registryRoot, file.source))
516
+ const target = resolveInstallTarget(installPlan, file.target)
517
+ const content = isTextRegistryFile(file.source)
518
+ ? applyTemplate(source.toString("utf8"), installPlan, target)
519
+ : source
520
+ records[target] = {
521
+ owner,
522
+ sha256: hashContent(content),
523
+ }
524
+ }
525
+ }
526
+
527
+ async function createTokenCssReceipt(installPlan) {
528
+ const tokenCss = await fs.readFile(
529
+ path.join(registryRoot, "styles", "globals.css"),
530
+ "utf8"
531
+ )
532
+ return {
533
+ target: installPlan.destinations.css,
534
+ sha256: hashNormalizedText(tokenCss),
535
+ }
536
+ }
537
+
538
+ async function allPathsExist(paths) {
539
+ const results = await Promise.all(paths.map((targetPath) => exists(targetPath)))
540
+ return results.every(Boolean)
541
+ }
542
+
543
+ function resolveRegistryDependencies(names) {
544
+ const resolved = []
545
+ const seen = new Set()
546
+ const visiting = new Set()
547
+
548
+ for (const name of names) {
549
+ visit(name)
550
+ }
551
+
552
+ return resolved
553
+
554
+ function visit(name) {
555
+ const component = registry.components[name]
556
+ if (!component) {
557
+ throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
558
+ }
559
+
560
+ if (seen.has(name)) return
561
+ if (visiting.has(name)) {
562
+ throw new Error(`circular registry dependency detected at "${name}".`)
563
+ }
564
+
565
+ visiting.add(name)
566
+ for (const dependency of component.registryDependencies || []) {
567
+ visit(dependency)
568
+ }
569
+ visiting.delete(name)
570
+
571
+ seen.add(name)
572
+ resolved.push(name)
573
+ }
574
+ }
575
+
576
+ async function loadConfig(cwd) {
577
+ const configPath = path.join(cwd, CONFIG_FILE)
578
+ const componentsPath = path.join(cwd, "components.json")
579
+ const config = structuredClone(DEFAULT_CONFIG)
580
+
581
+ const componentsConfig = await readJsonForUpdate(componentsPath)
582
+ let hasExplicitCssPath = false
583
+ if (componentsConfig) {
584
+ if (componentsConfig.tailwind?.css) {
585
+ config.tailwind.css = componentsConfig.tailwind.css
586
+ hasExplicitCssPath = true
587
+ }
588
+ config.aliases.utils = componentsConfig.aliases?.utils || config.aliases.utils
589
+ config.aliases.hooks = componentsConfig.aliases?.hooks || config.aliases.hooks
590
+ config.aliases.ui =
591
+ componentsConfig.aliases?.ui ||
592
+ appendAliasSegment(componentsConfig.aliases?.components, "ui") ||
593
+ config.aliases.ui
594
+ }
595
+
596
+ const localConfig = await readJsonForUpdate(configPath)
597
+ if (localConfig) {
598
+ // Validate what the user actually wrote, before it is merged onto the
599
+ // defaults. Validating the merged object instead would apply
600
+ // `additionalProperties: false` to something that structurally cannot carry
601
+ // an unknown top-level key, so a stray key would pass here and then be
602
+ // silently dropped by writeConfig. Known legacy keys are stripped first so
603
+ // they migrate instead of failing.
604
+ assertSchema(stripLegacyConfigKeys(localConfig), configSchema, CONFIG_FILE)
605
+
606
+ if (localConfig.tailwind?.css) hasExplicitCssPath = true
607
+ config.tailwind = { ...config.tailwind, ...(localConfig.tailwind || {}) }
608
+ config.aliases = { ...config.aliases, ...(localConfig.aliases || {}) }
609
+ }
610
+
611
+ if (!hasExplicitCssPath) {
612
+ config.tailwind.css = await detectCssPath(cwd, config.tailwind.css)
613
+ }
614
+
615
+ assertSchema(config, configSchema, CONFIG_FILE)
616
+
617
+ return config
618
+ }
619
+
620
+ async function detectCssPath(cwd, fallback) {
621
+ const candidates = [
622
+ "app/globals.css",
623
+ "src/app/globals.css",
624
+ "src/index.css",
625
+ "src/globals.css",
626
+ "styles/globals.css",
627
+ ]
628
+
629
+ for (const candidate of candidates) {
630
+ if (await exists(path.join(cwd, candidate))) return candidate
631
+ }
632
+
633
+ if (await exists(path.join(cwd, "src", "app"))) return "src/app/globals.css"
634
+
635
+ return fallback
636
+ }
637
+
638
+ async function writeConfig(cwd, config, options) {
639
+ const configPath = path.join(cwd, CONFIG_FILE)
640
+ if ((await exists(configPath)) && !options.force) {
641
+ const current = await fs.readFile(configPath, "utf8")
642
+ const currentConfig = JSON.parse(current)
643
+ // Spread the existing file first so any key this version does not manage
644
+ // survives the rewrite. Rebuilding from a fixed whitelist would delete it
645
+ // and still report the write as a plain "updated". Legacy keys are the one
646
+ // intentional exception, and the removal is reported rather than silent.
647
+ const legacyKeys = findLegacyConfigKeys(currentConfig)
648
+ const nextConfig = {
649
+ ...stripLegacyConfigKeys(currentConfig),
650
+ $schema: DEFAULT_CONFIG.$schema,
651
+ tailwind: config.tailwind,
652
+ aliases: config.aliases,
653
+ }
654
+
655
+ if (JSON.stringify(currentConfig) !== JSON.stringify(nextConfig)) {
656
+ const status = await writeFile(
657
+ configPath,
658
+ `${JSON.stringify(nextConfig, null, 2)}\n`,
659
+ { dryRun: options.dryRun }
660
+ )
661
+
662
+ const notes = [`${status} ${relative(cwd, configPath)}`]
663
+ if (legacyKeys.length > 0) {
664
+ notes.push(
665
+ `removed legacy config ${legacyKeys.length === 1 ? "key" : "keys"} ` +
666
+ `${legacyKeys.map((key) => JSON.stringify(key)).join(", ")} from ` +
667
+ `${relative(cwd, configPath)}`
668
+ )
669
+ }
670
+ return notes
671
+ }
672
+
673
+ return [`kept ${relative(cwd, configPath)}`]
674
+ }
675
+
676
+ const status = await writeFile(
677
+ configPath,
678
+ `${JSON.stringify(config, null, 2)}\n`,
679
+ options
680
+ )
681
+ return [`${status} ${relative(cwd, configPath)}`]
682
+ }
683
+
684
+ async function writeProjectSchemaFiles(cwd, options) {
685
+ const schemaFiles = [
686
+ "config.schema.json",
687
+ "registry.schema.json",
688
+ "tokens.schema.json",
689
+ ]
690
+ const writes = []
691
+
692
+ for (const schemaFile of schemaFiles) {
693
+ const sourcePath = path.join(schemaRoot, schemaFile)
694
+ const targetPath = path.join(cwd, ".banhaten", "schema", schemaFile)
695
+ const source = await fs.readFile(sourcePath, "utf8")
696
+ const status = await writeFile(targetPath, source, options)
697
+
698
+ writes.push(`${status} ${relative(cwd, targetPath)}`)
699
+ }
700
+
701
+ return writes
702
+ }
703
+
704
+ async function writeBaseFiles(installPlan, options) {
705
+ return writeRegistryFiles(installPlan, registry.base.files || [], {
706
+ ...options,
707
+ owner: "base",
708
+ })
709
+ }
710
+
711
+ async function writeRegistryFiles(installPlan, files, options) {
712
+ const { cwd } = installPlan
713
+ const writes = []
714
+
715
+ for (const file of files) {
716
+ const sourcePath = path.join(registryRoot, file.source)
717
+ const targetPath = path.join(
718
+ cwd,
719
+ resolveInstallTarget(installPlan, file.target)
720
+ )
721
+ const source = await fs.readFile(sourcePath)
722
+ const content = isTextRegistryFile(file.source)
723
+ ? applyTemplate(
724
+ source.toString("utf8"),
725
+ installPlan,
726
+ relative(cwd, targetPath)
727
+ )
728
+ : source
729
+ const target = relative(cwd, targetPath)
730
+
731
+ const current = await readFileForUpdate(targetPath)
732
+ assertManagedFileSafe(current, content, target, options)
733
+
734
+ const status = await writeFile(targetPath, content, options)
735
+ writes.push(`${status} ${target}`)
736
+ if (options.showDiff && status === "would update") {
737
+ writes.push(formatUnifiedDiff(
738
+ target,
739
+ isTextRegistryFile(file.source) ? current.toString("utf8") : current,
740
+ content
741
+ ))
742
+ }
743
+ }
744
+
745
+ return writes
746
+ }
747
+
748
+ async function writeGlobalCss(installPlan, options) {
749
+ const { cwd } = installPlan
750
+ const cssPath = path.join(cwd, installPlan.destinations.css)
751
+ const sourcePath = path.join(registryRoot, "styles", "globals.css")
752
+ const tokenCss = await fs.readFile(sourcePath, "utf8")
753
+ const current = await readTextForUpdate(cssPath)
754
+ const tokenBlock = current
755
+ ? removeExistingTokenBlock(current, relative(cwd, cssPath))
756
+ : { content: "", found: false }
757
+
758
+ const nextCss = current
759
+ ? `${tokenBlock.content.trimEnd()}\n\n${tokenCss}\n`
760
+ : `${tokenCss}\n`
761
+ const next = ensureGlobalCssImports(nextCss)
762
+
763
+ if (
764
+ current &&
765
+ tokenBlock.found &&
766
+ next !== current &&
767
+ !options.dryRun &&
768
+ !options.force
769
+ ) {
770
+ const expectedHash = options.receipt?.tokenCss?.sha256
771
+ const currentHash = hashNormalizedText(tokenBlock.block)
772
+ if (!expectedHash || currentHash !== expectedHash) {
773
+ throw new Error(
774
+ `${relative(cwd, cssPath)} contains local changes inside the generated Banhaten token block. ` +
775
+ "Run `banhaten diff` to inspect them, move intentional overrides outside the generated block, or re-run with `--force`."
776
+ )
777
+ }
778
+ }
779
+
780
+ const status = await writeFile(cssPath, next, options)
781
+ const writes = [`${status} ${relative(cwd, cssPath)}`]
782
+ if (options.showDiff && status === "would update" && current !== null) {
783
+ writes.push(formatUnifiedDiff(relative(cwd, cssPath), current, next))
784
+ }
785
+ return writes
786
+ }
787
+
788
+ async function writeAliasConfig(installPlan, options) {
789
+ const writes = []
790
+
791
+ for (const plannedConfig of [installPlan.typescript, installPlan.vite]) {
792
+ if (!plannedConfig) continue
793
+ const status = await writeFile(
794
+ plannedConfig.targetPath,
795
+ plannedConfig.nextSource,
796
+ {
797
+ dryRun: options.dryRun,
798
+ expectedCurrent: plannedConfig.currentSource,
799
+ force: true,
800
+ }
801
+ )
802
+ writes.push(
803
+ `${status} ${relative(installPlan.cwd, plannedConfig.targetPath)}`
804
+ )
805
+ }
806
+
807
+ return writes
808
+ }
809
+
810
+ function getPackageChanges(installPlan, dependencies) {
811
+ const devDependencies = { ...SETUP_DEV_DEPENDENCIES }
812
+ if (installPlan.vite) {
813
+ Object.assign(devDependencies, VITE_DEV_DEPENDENCIES)
814
+ }
815
+
816
+ return {
817
+ dependencies,
818
+ devDependencies,
819
+ }
820
+ }
821
+
822
+ async function updatePackageJson(cwd, changes, options) {
823
+ const packagePath = path.join(cwd, "package.json")
824
+ const currentSource = await readTextForUpdate(packagePath)
825
+ const packageExists = currentSource !== null
826
+ const packageJson = currentSource !== null ? JSON.parse(currentSource) : {
827
+ name: path.basename(cwd).toLowerCase(),
828
+ version: "0.0.0",
829
+ private: true,
830
+ }
831
+ const packagePlan = createPackageDependencyPlan(packageJson, changes)
832
+
833
+ if (packagePlan.operations.length === 0 && packageExists) {
834
+ await assertFileUnchanged(packagePath, currentSource)
835
+ const installState = await inspectPackageInstallState({
836
+ cwd,
837
+ packageJson,
838
+ requirements: packagePlan.requirements,
839
+ })
840
+ for (const evidence of installState.evidence) {
841
+ await assertFileUnchanged(evidence.path, evidence.source)
842
+ }
843
+ return {
844
+ installRequired: installState.required,
845
+ writes: [`kept ${relative(cwd, packagePath)}`],
846
+ }
847
+ }
848
+
849
+ applyPackageDependencyPlan(packageJson, packagePlan.operations)
850
+
851
+ const status = await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, {
852
+ dryRun: options.dryRun,
853
+ expectedCurrent: currentSource,
854
+ force: true,
855
+ })
856
+
857
+ return {
858
+ installRequired: packagePlan.operations.length > 0,
859
+ writes: [`${status} ${relative(cwd, packagePath)}`],
860
+ }
861
+ }
862
+
863
+ function applyTemplate(source, installPlan, target) {
864
+ const replacements = {
865
+ "@/components/ui": resolveTemplateImport(
866
+ installPlan,
867
+ target,
868
+ "ui"
869
+ ),
870
+ "@/lib/utils": resolveTemplateImport(
871
+ installPlan,
872
+ target,
873
+ "utils"
874
+ ),
875
+ "@/hooks": resolveTemplateImport(
876
+ installPlan,
877
+ target,
878
+ "hooks"
879
+ ),
880
+ }
881
+
882
+ return source.replace(
883
+ /@\/components\/ui|@\/lib\/utils|@\/hooks/g,
884
+ (match) => replacements[match]
885
+ )
886
+ }
887
+
888
+ function resolveTemplateImport(installPlan, target, destinationName) {
889
+ const configuredAlias = installPlan.config.aliases[destinationName]
890
+ if (
891
+ configuredAlias === "@" ||
892
+ configuredAlias === "~" ||
893
+ configuredAlias.startsWith("@/") ||
894
+ configuredAlias.startsWith("~/")
895
+ ) {
896
+ return configuredAlias.replace(/\/$/, "")
897
+ }
898
+
899
+ const targetDirectory = path.posix.dirname(
900
+ normalizeReceiptTarget(target)
901
+ )
902
+ const destination = installPlan.destinations[destinationName]
903
+ const relativeImport = path.posix.relative(targetDirectory, destination)
904
+
905
+ if (!relativeImport) return "."
906
+ return relativeImport.startsWith(".")
907
+ ? relativeImport
908
+ : `./${relativeImport}`
909
+ }
910
+
911
+ function isTextRegistryFile(source) {
912
+ return !/\.(avif|eot|gif|ico|jpe?g|otf|png|ttf|webp|woff2?)$/i.test(source)
913
+ }
914
+
915
+ async function readJson(filePath) {
916
+ return JSON.parse(await fs.readFile(filePath, "utf8"))
917
+ }
918
+
919
+ async function readJsonForUpdate(filePath) {
920
+ const source = await readTextForUpdate(filePath)
921
+ return source === null ? null : JSON.parse(source)
922
+ }
923
+
924
+ async function readTextForUpdate(filePath) {
925
+ const source = await readFileForUpdate(filePath)
926
+ return source === null ? null : source.toString("utf8")
927
+ }
928
+
929
+ function assertManagedFileSafe(current, nextContent, target, options) {
930
+ if (options.dryRun || options.force || current === null) return
931
+
932
+ const next = Buffer.isBuffer(nextContent)
933
+ ? nextContent
934
+ : Buffer.from(nextContent, "utf8")
935
+ if (current.equals(next)) return
936
+
937
+ const expectedHash = findManagedFileHash(options.receipt, target)
938
+ const currentHash = hashContent(current)
939
+ if (expectedHash && currentHash === expectedHash) return
940
+
941
+ const owner = options.owner ? ` (${options.owner})` : ""
942
+ const reason = expectedHash
943
+ ? "has local changes since Banhaten installed it"
944
+ : "already exists without a Banhaten ownership receipt"
945
+ const diffCommand = ["banhaten", "diff", options.owner === "base" ? "" : options.owner]
946
+ .filter(Boolean)
947
+ .join(" ")
948
+ throw new Error(
949
+ `${target}${owner} ${reason}. Run \`${diffCommand}\` to inspect the registry version, ` +
950
+ "or re-run the command with `--force` to replace the file."
951
+ )
952
+ }
953
+
954
+ function findManagedFileHash(receipt, target) {
955
+ const normalizedTarget = normalizeReceiptTarget(target)
956
+ const direct = Object.entries(receipt?.managedFiles || {}).find(
957
+ ([recordedTarget]) =>
958
+ normalizeReceiptTarget(recordedTarget) === normalizedTarget
959
+ )?.[1]?.sha256
960
+ if (direct) return direct
961
+
962
+ for (const component of Object.values(receipt?.components || {})) {
963
+ const match = component.files?.find(
964
+ (file) => normalizeReceiptTarget(file.target) === normalizedTarget
965
+ )
966
+ if (match?.sha256) return match.sha256
967
+ }
968
+
969
+ return null
970
+ }
971
+
972
+ function hashContent(content) {
973
+ return createHash("sha256").update(content).digest("hex")
974
+ }
975
+
976
+ function hashNormalizedText(content) {
977
+ return hashContent(String(content).replace(/\r\n/g, "\n").trim())
978
+ }
979
+
980
+ async function exists(filePath) {
981
+ try {
982
+ await fs.access(filePath)
983
+ return true
984
+ } catch {
985
+ return false
986
+ }
987
+ }
988
+
989
+ function appendAliasSegment(alias, segment) {
990
+ if (!alias) return null
991
+ return `${alias.replace(/\/$/, "")}/${segment}`
992
+ }
993
+
994
+ function sortObject(value) {
995
+ return Object.fromEntries(
996
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right))
997
+ )
998
+ }
999
+
1000
+ function relative(cwd, targetPath) {
1001
+ return path.relative(cwd, targetPath).replaceAll("\\", "/")
1002
+ }