@behavioral-agentic-design-system/core 0.42.0 → 0.47.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 (314) hide show
  1. package/package.json +38 -8
  2. package/scripts/a11y-lint.cjs +101 -14
  3. package/scripts/bads-sync.mjs +1 -1
  4. package/scripts/build-tokens.cjs +122 -7
  5. package/scripts/check-dark-contrast.mjs +204 -0
  6. package/scripts/check-flush-edges.mjs +245 -0
  7. package/scripts/check-spec.mjs +73 -0
  8. package/scripts/deal-directions.mjs +186 -0
  9. package/scripts/design-system-advisory/README.md +239 -0
  10. package/scripts/design-system-advisory/check-copy-punctuation.mjs +44 -0
  11. package/scripts/design-system-advisory/check-even-padding.mjs +35 -0
  12. package/scripts/design-system-advisory/check-hand-built-button.mjs +46 -0
  13. package/scripts/design-system-advisory/check-html-nesting.mjs +51 -0
  14. package/scripts/design-system-advisory/check-icon-sizing.mjs +79 -0
  15. package/scripts/design-system-advisory/check-label-case.mjs +92 -0
  16. package/scripts/design-system-advisory/check-native-form-controls.mjs +53 -0
  17. package/scripts/design-system-advisory/check-radius.mjs +56 -0
  18. package/scripts/design-system-advisory/check-raw-values.mjs +61 -0
  19. package/scripts/design-system-advisory/check-small-text.mjs +72 -0
  20. package/scripts/design-system-advisory/check-tap-target.mjs +70 -0
  21. package/scripts/design-system-advisory/defaults.mjs +90 -0
  22. package/scripts/design-system-advisory/fixtures/clean.tsx.fixture +12 -0
  23. package/scripts/design-system-advisory/fixtures/violations.tsx.fixture +19 -0
  24. package/scripts/design-system-advisory/lib.mjs +255 -0
  25. package/scripts/design-system-advisory/run.mjs +189 -0
  26. package/scripts/design-system-advisory/workflow.yml +82 -0
  27. package/scripts/health-report.mjs +20 -14
  28. package/scripts/lib/copy-strings.mjs +146 -0
  29. package/scripts/lib/counted-lint.mjs +100 -0
  30. package/scripts/lib/dark-contrast.mjs +120 -0
  31. package/scripts/lib/flush-edges.mjs +294 -0
  32. package/scripts/lib/lab-lint.mjs +62 -0
  33. package/scripts/lib/marketing-library.mjs +129 -0
  34. package/scripts/lib/mount-page.mjs +25 -0
  35. package/scripts/lib/on-system.mjs +249 -0
  36. package/scripts/lib/random.mjs +22 -0
  37. package/scripts/lib/source-scan.mjs +173 -0
  38. package/scripts/lib/spec-parse.d.mts +25 -0
  39. package/scripts/lib/spec-parse.mjs +188 -0
  40. package/scripts/lib/tells.mjs +366 -0
  41. package/scripts/lint-arbitrary-tokens.mjs +47 -0
  42. package/scripts/lint-component-token-refs.mjs +63 -0
  43. package/scripts/lint-content-hierarchy.mjs +114 -0
  44. package/scripts/lint-control-baseline.mjs +72 -0
  45. package/scripts/lint-copy-punctuation.mjs +60 -0
  46. package/scripts/lint-css-vars.mjs +175 -0
  47. package/scripts/lint-even-padding.mjs +58 -0
  48. package/scripts/lint-html-nesting.mjs +116 -0
  49. package/scripts/lint-label-case.mjs +219 -0
  50. package/scripts/lint-live-ctas.mjs +138 -0
  51. package/scripts/lint-microanimation.mjs +2 -2
  52. package/scripts/lint-proximity.mjs +181 -0
  53. package/scripts/lint-slop.mjs +1 -1
  54. package/scripts/lint-spacing-scale.mjs +78 -0
  55. package/scripts/lint-target-size.cjs +132 -0
  56. package/scripts/lint-token-primitives.mjs +307 -0
  57. package/scripts/on-system-score.mjs +95 -0
  58. package/scripts/size-audit.cjs +2 -2
  59. package/scripts/slop-rules.mjs +1 -1
  60. package/scripts/source-images.mjs +180 -0
  61. package/scripts/ux-tells.mjs +80 -0
  62. package/scripts/wcag-audit.cjs +25 -4
  63. package/src/api/brand-colors.ts +3 -0
  64. package/src/api/brand-fonts.ts +3 -0
  65. package/src/api/brand-mark.ts +6 -1
  66. package/src/api/dev-write-guard.ts +53 -0
  67. package/src/api/layers/file.ts +9 -4
  68. package/src/api/onboarding-extract.ts +85 -30
  69. package/src/api/onboarding.ts +3 -0
  70. package/src/api/save-tokens.ts +3 -0
  71. package/src/api/site-auth.ts +14 -2
  72. package/src/app/layout.tsx +6 -0
  73. package/src/app/preview/canvas/page.tsx +12 -0
  74. package/src/app/preview/components/page.tsx +828 -14
  75. package/src/app/preview/sticker-sheet/page.tsx +329 -0
  76. package/src/app/preview/sticker-sheet/specimens.tsx +296 -0
  77. package/src/app/preview/studio/blank-screen.tsx +143 -0
  78. package/src/app/preview/studio/page.tsx +7 -0
  79. package/src/app/shell.tsx +164 -47
  80. package/src/components/Foundations/Colors.stories.tsx +119 -8
  81. package/src/components/canvas/canvas.tsx +458 -0
  82. package/src/components/canvas/layout.ts +72 -0
  83. package/src/components/canvas/parse-canvas.ts +32 -0
  84. package/src/components/canvas/sample.ts +90 -0
  85. package/src/components/canvas/spec-frame.tsx +43 -0
  86. package/src/components/canvas/types.ts +33 -0
  87. package/src/components/docs-tab.tsx +7 -7
  88. package/src/components/home-recent.tsx +73 -0
  89. package/src/components/home-tab.tsx +19 -14
  90. package/src/components/layers-tab.tsx +2 -2
  91. package/src/components/markdown-preview.tsx +60 -12
  92. package/src/components/onboarding-wizard.tsx +1 -1
  93. package/src/components/studio/control-panel.tsx +299 -0
  94. package/src/components/studio/control-row.tsx +77 -0
  95. package/src/components/studio/preview-frame.tsx +165 -0
  96. package/src/components/studio/preview-pane.tsx +247 -0
  97. package/src/components/studio/studio.tsx +133 -128
  98. package/src/components/studio/types.ts +218 -0
  99. package/src/components/studio/use-studio-tweaks.ts +128 -0
  100. package/src/components/studio/use-studio-view-state.ts +72 -0
  101. package/src/components/ui/autocomplete.tsx +1 -1
  102. package/src/components/ui/avatar.tsx +4 -0
  103. package/src/components/ui/chart.tsx +134 -42
  104. package/src/components/ui/checkbox-group.tsx +1 -1
  105. package/src/components/ui/checkbox.tsx +1 -1
  106. package/src/components/ui/color-picker.tsx +20 -4
  107. package/src/components/ui/combobox.tsx +1 -0
  108. package/src/components/ui/command.tsx +1 -1
  109. package/src/components/ui/data-table.tsx +64 -3
  110. package/src/components/ui/date-field.tsx +1 -1
  111. package/src/components/ui/date-picker.tsx +2 -0
  112. package/src/components/ui/date-range-picker.tsx +4 -0
  113. package/src/components/ui/editable.tsx +1 -0
  114. package/src/components/ui/faceted-filter.tsx +187 -0
  115. package/src/components/ui/file-upload.tsx +21 -2
  116. package/src/components/ui/gauge-chart.tsx +18 -4
  117. package/src/components/ui/heatmap.tsx +3 -1
  118. package/src/components/ui/inline-edit.tsx +175 -0
  119. package/src/components/ui/input-group.tsx +5 -2
  120. package/src/components/ui/month-picker.tsx +1 -1
  121. package/src/components/ui/multi-select.tsx +1 -0
  122. package/src/components/ui/number-input.tsx +28 -5
  123. package/src/components/ui/otp-input.tsx +208 -0
  124. package/src/components/ui/phone-input.tsx +274 -0
  125. package/src/components/ui/radio-group.tsx +2 -2
  126. package/src/components/ui/search-input.tsx +1 -1
  127. package/src/components/ui/sparkline.tsx +33 -4
  128. package/src/components/ui/spinner.tsx +23 -4
  129. package/src/components/ui/table.tsx +9 -0
  130. package/src/components/ui/tags-input.tsx +1 -1
  131. package/src/components/ui/timer.tsx +1 -0
  132. package/src/components/ui/transfer-list.tsx +13 -26
  133. package/src/components/ui/week-picker.tsx +1 -13
  134. package/src/components/ui/year-picker.tsx +1 -1
  135. package/src/data/component-added.json +966 -0
  136. package/src/data/docs-index.ts +35 -2
  137. package/src/data/history.json +161 -161
  138. package/src/data/sticker-sheet.json +9244 -0
  139. package/src/docs-trace-globs.json +1 -0
  140. package/src/hooks/use-global-mono-font.ts +1 -0
  141. package/src/hooks/use-global-primary-color.ts +1 -0
  142. package/src/hooks/use-global-sans-font.ts +1 -0
  143. package/src/hooks/use-global-serif-font.ts +1 -0
  144. package/src/hooks/use-global-type-scale.ts +17 -2
  145. package/src/hooks/use-mobile.ts +2 -0
  146. package/src/hooks/use-sync-type-scale.ts +7 -11
  147. package/src/lib/chart-motion.ts +41 -0
  148. package/src/lib/get-icon-color.ts +1 -1
  149. package/src/lib/spec-parse.ts +4 -0
  150. package/src/lib/svg-sanitize.ts +19 -9
  151. package/src/stories/Accordion.stories.tsx +7 -0
  152. package/src/stories/ActionBar.stories.tsx +5 -0
  153. package/src/stories/Affix.stories.tsx +4 -0
  154. package/src/stories/AiBadge.stories.tsx +9 -7
  155. package/src/stories/Alert.stories.tsx +13 -0
  156. package/src/stories/AlertDialog.stories.tsx +4 -0
  157. package/src/stories/Anchor.stories.tsx +5 -0
  158. package/src/stories/AngleSlider.stories.tsx +6 -3
  159. package/src/stories/AspectRatio.stories.tsx +4 -0
  160. package/src/stories/Autocomplete.stories.tsx +8 -0
  161. package/src/stories/Avatar.stories.tsx +10 -0
  162. package/src/stories/Badge.stories.tsx +14 -6
  163. package/src/stories/Blockquote.stories.tsx +6 -0
  164. package/src/stories/BottomNavigation.stories.tsx +4 -0
  165. package/src/stories/Breadcrumb.stories.tsx +3 -0
  166. package/src/stories/Burger.stories.tsx +1 -0
  167. package/src/stories/Button.stories.tsx +24 -0
  168. package/src/stories/ButtonGroup.stories.tsx +9 -0
  169. package/src/stories/Calendar.stories.tsx +3 -0
  170. package/src/stories/Canvas.stories.tsx +45 -0
  171. package/src/stories/Card.stories.tsx +4 -0
  172. package/src/stories/Carousel.stories.tsx +6 -0
  173. package/src/stories/Cascader.stories.tsx +4 -0
  174. package/src/stories/Chart.stories.tsx +46 -1
  175. package/src/stories/ChatBubble.stories.tsx +8 -2
  176. package/src/stories/ChatMarker.stories.tsx +1 -0
  177. package/src/stories/Checkbox.stories.tsx +40 -0
  178. package/src/stories/CheckboxCard.stories.tsx +8 -0
  179. package/src/stories/CheckboxGroup.stories.tsx +19 -0
  180. package/src/stories/Chip.stories.tsx +10 -19
  181. package/src/stories/CircularProgress.stories.tsx +13 -27
  182. package/src/stories/Clipboard.stories.tsx +6 -0
  183. package/src/stories/CloseButton.stories.tsx +6 -4
  184. package/src/stories/Code.stories.tsx +8 -1
  185. package/src/stories/Collapsible.stories.tsx +2 -0
  186. package/src/stories/ColorPicker.stories.tsx +46 -0
  187. package/src/stories/ColorSwatch.stories.tsx +1 -0
  188. package/src/stories/Combobox.stories.tsx +9 -0
  189. package/src/stories/Command.stories.tsx +2 -0
  190. package/src/stories/Container.stories.tsx +8 -0
  191. package/src/stories/ContextMenu.stories.tsx +9 -0
  192. package/src/stories/CopyButton.stories.tsx +12 -36
  193. package/src/stories/DataList.stories.tsx +8 -0
  194. package/src/stories/DataTable.stories.tsx +39 -0
  195. package/src/stories/DateField.stories.tsx +28 -0
  196. package/src/stories/DatePicker.stories.tsx +34 -0
  197. package/src/stories/DateRangePicker.stories.tsx +32 -0
  198. package/src/stories/Dialog.stories.tsx +8 -0
  199. package/src/stories/Drawer.stories.tsx +6 -0
  200. package/src/stories/DropdownMenu.stories.tsx +2 -0
  201. package/src/stories/Editable.stories.tsx +12 -0
  202. package/src/stories/EmptyState.stories.tsx +9 -0
  203. package/src/stories/FacetedFilter.stories.tsx +197 -0
  204. package/src/stories/Field.stories.tsx +7 -0
  205. package/src/stories/Fieldset.stories.tsx +8 -0
  206. package/src/stories/FileButton.stories.tsx +4 -0
  207. package/src/stories/FileUpload.stories.tsx +16 -17
  208. package/src/stories/FloatLabel.stories.tsx +3 -8
  209. package/src/stories/FloatingActionButton.stories.tsx +10 -0
  210. package/src/stories/FloatingIndicator.stories.tsx +4 -0
  211. package/src/stories/FloatingPanel.stories.tsx +6 -0
  212. package/src/stories/FocusTrap.stories.tsx +5 -0
  213. package/src/stories/FormatByte.stories.tsx +6 -0
  214. package/src/stories/FormatDate.stories.tsx +8 -0
  215. package/src/stories/FormatNumber.stories.tsx +9 -0
  216. package/src/stories/GaugeChart.stories.tsx +9 -3
  217. package/src/stories/Heatmap.stories.tsx +11 -0
  218. package/src/stories/Highlight.stories.tsx +6 -0
  219. package/src/stories/HoverCard.stories.tsx +4 -0
  220. package/src/stories/Image.stories.tsx +9 -0
  221. package/src/stories/Indicator.stories.tsx +19 -0
  222. package/src/stories/InlineEdit.stories.tsx +106 -0
  223. package/src/stories/Input.stories.tsx +7 -0
  224. package/src/stories/InputClearButton.stories.tsx +3 -0
  225. package/src/stories/InputGroup.stories.tsx +40 -0
  226. package/src/stories/Kbd.stories.tsx +7 -1
  227. package/src/stories/KeyboardShortcut.stories.tsx +2 -0
  228. package/src/stories/Label.stories.tsx +2 -0
  229. package/src/stories/Link.stories.tsx +9 -0
  230. package/src/stories/List.stories.tsx +8 -0
  231. package/src/stories/Listbox.stories.tsx +1 -0
  232. package/src/stories/LoadingDots.stories.tsx +5 -3
  233. package/src/stories/LoadingOverlay.stories.tsx +5 -1
  234. package/src/stories/Mark.stories.tsx +5 -0
  235. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  236. package/src/stories/Marquee.stories.tsx +4 -0
  237. package/src/stories/Masonry.stories.tsx +5 -0
  238. package/src/stories/Menubar.stories.tsx +3 -0
  239. package/src/stories/Meter.stories.tsx +11 -17
  240. package/src/stories/MonthPicker.stories.tsx +26 -1
  241. package/src/stories/MotionToggle.stories.tsx +1 -0
  242. package/src/stories/MultiSelect.stories.tsx +9 -0
  243. package/src/stories/NativeSelect.stories.tsx +1 -0
  244. package/src/stories/NavLink.stories.tsx +7 -0
  245. package/src/stories/NavigationMenu.stories.tsx +5 -0
  246. package/src/stories/NavigationRail.stories.tsx +10 -0
  247. package/src/stories/Notification.stories.tsx +13 -34
  248. package/src/stories/NumberInput.stories.tsx +33 -1
  249. package/src/stories/OtpInput.stories.tsx +110 -0
  250. package/src/stories/Overlay.stories.tsx +5 -1
  251. package/src/stories/Pagination.stories.tsx +8 -0
  252. package/src/stories/PasswordInput.stories.tsx +2 -0
  253. package/src/stories/PhoneInput.stories.tsx +127 -0
  254. package/src/stories/PinInput.stories.tsx +9 -2
  255. package/src/stories/Popover.stories.tsx +2 -0
  256. package/src/stories/Progress.stories.tsx +6 -1
  257. package/src/stories/Prose.stories.tsx +8 -0
  258. package/src/stories/QrCode.stories.tsx +2 -0
  259. package/src/stories/Questionnaire.stories.tsx +7 -0
  260. package/src/stories/RadioGroup.stories.tsx +40 -0
  261. package/src/stories/RatingGroup.stories.tsx +8 -4
  262. package/src/stories/Resizable.stories.tsx +4 -2
  263. package/src/stories/Result.stories.tsx +3 -0
  264. package/src/stories/Reveal.stories.tsx +2 -0
  265. package/src/stories/RollingNumber.stories.tsx +5 -0
  266. package/src/stories/ScrollArea.stories.tsx +3 -1
  267. package/src/stories/SearchInput.stories.tsx +10 -6
  268. package/src/stories/SegmentedControl.stories.tsx +11 -0
  269. package/src/stories/Select.stories.tsx +7 -0
  270. package/src/stories/Separator.stories.tsx +6 -0
  271. package/src/stories/Sheet.stories.tsx +5 -0
  272. package/src/stories/Sidebar.stories.tsx +40 -1
  273. package/src/stories/SimpleGrid.stories.tsx +5 -0
  274. package/src/stories/Skeleton.stories.tsx +8 -0
  275. package/src/stories/SkeletonTable.stories.tsx +6 -5
  276. package/src/stories/SkipLink.stories.tsx +3 -0
  277. package/src/stories/Slider.stories.tsx +2 -1
  278. package/src/stories/Sonner.stories.tsx +7 -0
  279. package/src/stories/Sparkline.stories.tsx +14 -1
  280. package/src/stories/Spinner.stories.tsx +20 -10
  281. package/src/stories/Spoiler.stories.tsx +5 -0
  282. package/src/stories/Squircle.stories.tsx +7 -0
  283. package/src/stories/Stack.stories.tsx +7 -0
  284. package/src/stories/StatusBadge.stories.tsx +12 -6
  285. package/src/stories/Stepper.stories.tsx +5 -0
  286. package/src/stories/Switch.stories.tsx +4 -0
  287. package/src/stories/Table.stories.tsx +10 -1
  288. package/src/stories/Tabs.stories.tsx +8 -0
  289. package/src/stories/Tag.stories.tsx +13 -5
  290. package/src/stories/TagsInput.stories.tsx +15 -0
  291. package/src/stories/Text.stories.tsx +12 -0
  292. package/src/stories/Textarea.stories.tsx +9 -0
  293. package/src/stories/ThemeIcon.stories.tsx +6 -3
  294. package/src/stories/TimePicker.stories.tsx +2 -0
  295. package/src/stories/Timeline.stories.tsx +12 -0
  296. package/src/stories/Timer.stories.tsx +30 -0
  297. package/src/stories/Toggle.stories.tsx +7 -5
  298. package/src/stories/ToggleGroup.stories.tsx +5 -0
  299. package/src/stories/ToggleTip.stories.tsx +4 -0
  300. package/src/stories/Toolbar.stories.tsx +6 -0
  301. package/src/stories/Tooltip.stories.tsx +3 -0
  302. package/src/stories/Tour.stories.tsx +3 -0
  303. package/src/stories/TransferList.stories.tsx +7 -0
  304. package/src/stories/TreeSelect.stories.tsx +4 -0
  305. package/src/stories/TreeView.stories.tsx +5 -0
  306. package/src/stories/TypingIndicator.stories.tsx +4 -0
  307. package/src/stories/VisuallyHidden.stories.tsx +3 -0
  308. package/src/stories/Watermark.stories.tsx +6 -0
  309. package/src/stories/WeekPicker.stories.tsx +25 -1
  310. package/src/stories/WordRotate.stories.tsx +5 -0
  311. package/src/stories/YearPicker.stories.tsx +26 -11
  312. package/src/stories/story-groups.json +22 -16
  313. package/src/styles.css +50 -2
  314. package/src/tokens.json +86 -58
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check:dark-contrast (bin: bads-check-dark-contrast) — every page, in dark mode, measured in a real browser: text that
4
+ * cannot be read on what is actually painted behind it fails.
5
+ *
6
+ * WHY THIS EXISTS
7
+ *
8
+ * In a client's prototypes, with dark mode on, a whole sign-up journey was near-white text on a white card, and a
9
+ * calendar had near-black names on its blue bars. Every gate passed: a token-pair audit checks the pairs the theme
10
+ * declares, and a static read of the built HTML sees light values only. The cause was a pair nobody declared, a
11
+ * hard-coded white fill under a theme-aware text token. Only the painted page shows it, so this measures the painted
12
+ * page, on every route, in dark. The in-page measure is lib/dark-contrast.mjs.
13
+ *
14
+ * WHAT IT DOES
15
+ *
16
+ * Opens each route on a running site in dark mode, at each viewport width, scrolls it so deferred blocks mount,
17
+ * proves the page really is dark, and measures every visible text node under the scope against its painted backdrop.
18
+ *
19
+ * SETTINGS. Each one is a flag, or a key under "darkContrast" in bads-checks.config.json (or the file --config names).
20
+ * A flag wins over the file, and the file wins over the default.
21
+ *
22
+ * base --base the running site http://localhost:3000
23
+ * routes --routes a,b the paths to open ["/"]
24
+ * scope --scope a CSS selector of what to measure the whole body
25
+ * viewports --viewports widths, in CSS px [1440, 393]
26
+ * darkQuery --dark-query a query added to each URL, as k=v none
27
+ * darkStorage localStorage entries set before load {}
28
+ * darkClass --dark-class a class put on <html> after load "dark"
29
+ * ("" leaves <html> alone, for a site that reads only the query or storage)
30
+ * darkProof --dark-proof a selector that must match once dark ".dark"
31
+ * normal --normal least ratio for normal text 4.5 (WCAG AA)
32
+ * large --large least ratio for large text 3
33
+ * largeSize, largeBoldSize when text is large, in px 24, and 18.66 at weight 700
34
+ * frameAttr --frame-attr the attribute naming a design "data-frame-id"
35
+ * lazySelector --lazy placeholders that must all mount "[data-lazy-skeleton]" ("" skips the scroll)
36
+ * known --known a JSON file of known findings none
37
+ *
38
+ * KNOWN FINDINGS. { "known": [{ "route": "/x", "frame": "(page)", "text": "Start of the text", "reason": "a sentence" }] }.
39
+ * An entry nothing matches any more fails a full run, so the list only shrinks.
40
+ *
41
+ * A route that will not load, a page that does not turn dark, or a page where nothing could be measured FAILS. A check
42
+ * that passes over nothing is how the defect it exists for ships.
43
+ *
44
+ * Usage:
45
+ * bads-check-dark-contrast --base http://localhost:3000 --routes /,/pricing
46
+ * bads-check-dark-contrast --route /pricing
47
+ */
48
+ import { existsSync, readFileSync } from "node:fs";
49
+ import { resolve } from "node:path";
50
+ import { DEFAULTS, measureTextContrast } from "./lib/dark-contrast.mjs";
51
+ import { mountEverything } from "./lib/mount-page.mjs";
52
+
53
+ const argv = process.argv.slice(2);
54
+ const flag = (name) => (argv.includes(name) ? argv[argv.indexOf(name) + 1] : undefined);
55
+ const list = (v) => (v === undefined ? undefined : String(v).split(",").map((s) => s.trim()).filter(Boolean));
56
+
57
+ const configPath = resolve(flag("--config") ?? "bads-checks.config.json");
58
+ let fileSettings = {};
59
+ if (existsSync(configPath)) {
60
+ try {
61
+ fileSettings = JSON.parse(readFileSync(configPath, "utf8")).darkContrast ?? {};
62
+ } catch (e) {
63
+ console.error(`✗ dark-contrast check: ${configPath} is not valid JSON (${e.message}).`);
64
+ process.exit(1);
65
+ }
66
+ } else if (flag("--config")) {
67
+ console.error(`✗ dark-contrast check: no settings file at ${configPath}.`);
68
+ process.exit(1);
69
+ }
70
+ const pick = (key, fromFlag, fallback) => fromFlag ?? fileSettings[key] ?? fallback;
71
+ const single = flag("--route");
72
+ const s = {
73
+ base: String(pick("base", flag("--base"), "http://localhost:3000")).replace(/\/$/, ""),
74
+ routes: single ? [single] : pick("routes", list(flag("--routes")), ["/"]),
75
+ scope: pick("scope", flag("--scope"), null),
76
+ viewports: pick("viewports", list(flag("--viewports"))?.map(Number), [1440, 393]),
77
+ darkQuery: pick("darkQuery", flag("--dark-query"), null),
78
+ darkStorage: pick("darkStorage", undefined, {}),
79
+ darkClass: pick("darkClass", flag("--dark-class"), "dark"),
80
+ darkProof: pick("darkProof", flag("--dark-proof"), ".dark"),
81
+ normal: Number(pick("normal", flag("--normal"), DEFAULTS.normal)),
82
+ large: Number(pick("large", flag("--large"), DEFAULTS.large)),
83
+ largeSize: Number(pick("largeSize", undefined, DEFAULTS.largeSize)),
84
+ largeBoldSize: Number(pick("largeBoldSize", undefined, DEFAULTS.largeBoldSize)),
85
+ frameAttr: pick("frameAttr", flag("--frame-attr"), DEFAULTS.frameAttr),
86
+ lazySelector: pick("lazySelector", flag("--lazy"), "[data-lazy-skeleton]"),
87
+ known: pick("known", flag("--known"), null),
88
+ };
89
+ const bad = [];
90
+ if (!Array.isArray(s.routes) || !s.routes.length) bad.push("routes must name at least one path");
91
+ for (const k of ["normal", "large", "largeSize", "largeBoldSize"]) if (!Number.isFinite(s[k]) || s[k] <= 0) bad.push(`${k} must be a positive number, not ${s[k]}`);
92
+ if (s.normal < 3 || s.large < 3) bad.push("normal and large must be 3:1 or more: under that no WCAG level is met");
93
+ if (!s.viewports.length || s.viewports.some((w) => !Number.isFinite(w) || w < 200)) bad.push(`viewports must be widths of 200px or more, not ${s.viewports}`);
94
+ if (!s.darkProof) bad.push("darkProof must be a selector: without it a light page would be measured and called dark");
95
+ if (s.darkQuery && !/^[^=&]+=[^&]*$/.test(s.darkQuery)) bad.push(`darkQuery must be one key=value pair, not ${s.darkQuery}`);
96
+ if (bad.length) {
97
+ console.error(`✗ dark-contrast check: bad settings.\n${bad.map((p) => ` ${p}`).join("\n")}`);
98
+ process.exit(1);
99
+ }
100
+
101
+ const failures = [];
102
+ let known = [];
103
+ if (s.known) {
104
+ try {
105
+ known = JSON.parse(readFileSync(resolve(s.known), "utf8")).known ?? [];
106
+ } catch (e) {
107
+ console.error(`✗ dark-contrast check: cannot read the known findings in ${s.known} (${e.message}).`);
108
+ process.exit(1);
109
+ }
110
+ for (const k of known) if (!k.route || !k.frame || !k.text || !k.reason || k.reason.length < 20) failures.push(`${s.known}: an entry needs route, frame, text and a reason of a sentence: ${JSON.stringify(k)}`);
111
+ }
112
+ const used = new Set();
113
+
114
+ let chromium;
115
+ try {
116
+ ({ chromium } = await import("playwright"));
117
+ } catch {
118
+ console.error("✗ dark-contrast check: playwright is not installed. Install it (pnpm add -D playwright).");
119
+ process.exit(1);
120
+ }
121
+ let browser;
122
+ try {
123
+ browser = await chromium.launch();
124
+ } catch (e) {
125
+ console.error("✗ dark-contrast check: no Chromium to drive. Run `pnpm exec playwright install chromium`.");
126
+ console.error(` ${String(e.message).split("\n")[0]}`);
127
+ process.exit(1);
128
+ }
129
+
130
+ const options = { scope: s.scope, normal: s.normal, large: s.large, largeSize: s.largeSize, largeBoldSize: s.largeBoldSize, frameAttr: s.frameAttr };
131
+ const totals = { measured: 0, onImage: 0, disabled: 0, pages: 0 };
132
+ const lines = new Set();
133
+ for (const width of s.viewports) {
134
+ const ctx = await browser.newContext({ viewport: { width, height: 900 }, colorScheme: "dark", reducedMotion: "reduce" });
135
+ await ctx.addInitScript((entries) => {
136
+ try {
137
+ for (const [k, v] of Object.entries(entries)) localStorage.setItem(k, v);
138
+ } catch {}
139
+ }, s.darkStorage);
140
+ const page = await ctx.newPage();
141
+ page.setDefaultTimeout(30000);
142
+ for (const route of s.routes) {
143
+ try {
144
+ const url = new URL(s.base + route);
145
+ if (s.darkQuery) {
146
+ const [k, v] = s.darkQuery.split("=");
147
+ url.searchParams.set(k, v);
148
+ }
149
+ const res = await page.goto(url.toString(), { waitUntil: "load", timeout: 120000 });
150
+ if (!res || res.status() >= 400) throw new Error(`HTTP ${res?.status() ?? "no response"}`);
151
+ await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
152
+ if (s.darkClass) await page.evaluate((c) => document.documentElement.classList.add(c), s.darkClass);
153
+ await page.waitForTimeout(1200);
154
+ if (s.lazySelector !== "") {
155
+ const unmounted = await mountEverything(page, { lazySelector: s.lazySelector });
156
+ if (unmounted > 0) throw new Error(`${unmounted} deferred block(s) never mounted (${s.lazySelector}), so they could not be measured`);
157
+ }
158
+ if (s.darkClass) await page.evaluate((c) => document.documentElement.classList.add(c), s.darkClass);
159
+ /* `content-visibility: auto` skips style for whatever is off screen, so a section below the fold can still hold
160
+ its light-mode colours, mid-way through the theme change, when the measure reads it. A person scrolling there
161
+ sees it finished. Every element is made visible to the renderer before measuring, so the measure reads what a
162
+ person would see on arriving. */
163
+ await page.addStyleTag({ content: "*, *::before, *::after { content-visibility: visible !important; }" });
164
+ await page.waitForTimeout(600);
165
+ /* Checked immediately before measuring: without it "no failures in dark" and "never entered dark" read the same. */
166
+ if (!(await page.evaluate((sel) => !!document.querySelector(sel), s.darkProof))) throw new Error(`the page did not turn dark (nothing matches ${s.darkProof})`);
167
+ const r = await page.evaluate(`(${measureTextContrast})(${JSON.stringify(options)})`);
168
+ if (r.measured === 0) throw new Error(`no text measured${s.scope ? ` inside ${s.scope}` : ""}`);
169
+ totals.pages++;
170
+ totals.measured += r.measured;
171
+ totals.onImage += r.onImage;
172
+ totals.disabled += r.disabled;
173
+ for (const f of r.fails) {
174
+ const k = known.find((x) => x.route === route && x.frame === f.frame && f.text.startsWith(x.text));
175
+ if (k) {
176
+ used.add(k);
177
+ continue;
178
+ }
179
+ const line = `${route} ${f.frame}: "${f.text}" ${f.fg} on ${f.bg} = ${f.ratio.toFixed(2)}:1 (needs ${f.floor}:1)`;
180
+ if (!lines.has(line)) failures.push(`${line} at ${width}px`);
181
+ lines.add(line);
182
+ }
183
+ } catch (e) {
184
+ failures.push(`${route} at ${width}px: could not measure: ${String(e.message).split("\n")[0]}`);
185
+ }
186
+ }
187
+ await ctx.close();
188
+ }
189
+ await browser.close();
190
+ if (!single) for (const k of known) if (!used.has(k)) failures.push(`${s.known}: nothing matches ${k.route} / ${k.frame} / "${k.text}" any more. Remove the entry.`);
191
+
192
+ if (failures.length) {
193
+ console.error(`\n✗ dark-contrast check: ${failures.length} problem(s) in dark mode across ${s.routes.length} route(s).\n`);
194
+ for (const f of failures.slice(0, 200)) console.error(` ${f}`);
195
+ if (failures.length > 200) console.error(` … and ${failures.length - 200} more`);
196
+ console.error(
197
+ "\n A surface and the text on it are a pair. A hard-coded fill (bg-white, a neutral step) stays light while theme" +
198
+ "\n tokens on it turn light too. Use a surface token, or give the fill a dark value.",
199
+ );
200
+ process.exit(1);
201
+ }
202
+ console.log(
203
+ `✓ dark-contrast check: ${totals.measured} text(s) on ${totals.pages} page(s) (${s.routes.length} route(s) at ${s.viewports.join(" and ")}px) in dark, all at ${s.normal}:1 (${s.large}:1 large) or more; ${totals.onImage} over an image and ${totals.disabled} disabled not measured.`,
204
+ );
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check:flush-edges (bin: bads-check-flush-edges) — text never sits right up against the edge of the shape that holds it.
4
+ *
5
+ * WHY THIS EXISTS
6
+ *
7
+ * A booking bar's label sat 6px from the start of a pill whose round end curves in by 22px, so the letters touched the
8
+ * curve. Every gate passed: an even-padding lint reads class pairs, and nothing measured where the text actually lands
9
+ * against the edge it is drawn in. This measures the laid-out page. First found in a client's prototypes, where it now
10
+ * runs over every prototype in every state; ported here so every fork gets the same measure.
11
+ *
12
+ * WHAT IT DOES
13
+ *
14
+ * Opens each route on a running site, at each viewport width, and measures every visible text node under the root
15
+ * selector against the inner edge of its nearest visually bounded ancestor (lib/flush-edges.mjs says exactly how).
16
+ * Closer than the floor on any bounded side fails.
17
+ *
18
+ * SETTINGS. Each one is a flag, or a key under "flushEdges" in bads-checks.config.json (or the file --config names).
19
+ * A flag wins over the file, and the file wins over the default.
20
+ *
21
+ * base --base the running site http://localhost:3000
22
+ * routes --routes a,b the paths to open ["/"]
23
+ * root --root the CSS selector of what to measure "body"
24
+ * viewports --viewports widths, in CSS px [390, 1280]
25
+ * floor --floor least distance from the edge, CSS px 6
26
+ * measure --measure "cap" (capitals to baseline) or "line" "cap"
27
+ * exceptAttr --except-attr the attribute that excuses a container "data-flush-ok"
28
+ * minReason --min-reason least length of that attribute's reason 12
29
+ * frameAttr --frame-attr the attribute naming a design "data-frame-id"
30
+ * probe --probe a window function naming shipped parts none
31
+ * known --known a JSON file of known findings none
32
+ * minMeasured --min-measured fewer text nodes than this fails 1
33
+ * lazySelector --lazy placeholders that must all mount "[data-lazy-skeleton]"
34
+ * (each page is scrolled to the bottom first, so deferred blocks are drawn; "" turns
35
+ * the scroll off, for a page that defers nothing)
36
+ * --report-json f also write every hit to f, as JSON
37
+ *
38
+ * KNOWN FINDINGS. A shipped component a page must not restyle can still fail, and a fork that adopts this check starts
39
+ * with findings nobody has fixed yet. Record them in the known file, { "known": [ ... ] }, each entry with a reason of a
40
+ * sentence, in one of three shapes:
41
+ * { "route": "/x", "text": "Label", "reason": "..." } one hit: that route, text starting with `text`
42
+ * { "shipped": "badge", "count": 12, "reason": "..." } a ratchet: up to `count` hits inside that shipped component
43
+ * (its data-slot, or what the probe names), on any route
44
+ * { "route": "/x", "count": 3, "reason": "..." } a ratchet: up to `count` hits in that route's own markup
45
+ * A ratchet that is exceeded fails, and lists every hit it covers. A ratchet with fewer hits than its count fails a full
46
+ * run and says the number to lower it to, and an exact entry nothing matches fails a full run, so the list only shrinks.
47
+ *
48
+ * A route that will not load, or a run that measures fewer than minMeasured text nodes, FAILS. A check that passes over
49
+ * nothing is how the defect it exists for ships.
50
+ *
51
+ * Usage:
52
+ * bads-check-flush-edges --base http://localhost:3000 --routes /,/pricing
53
+ * bads-check-flush-edges --route /pricing # one route; known entries for other routes are not called stale
54
+ */
55
+ import { existsSync, readFileSync } from "node:fs";
56
+ import { resolve } from "node:path";
57
+ import { DEFAULTS, measureFlushEdges } from "./lib/flush-edges.mjs";
58
+ import { mountEverything } from "./lib/mount-page.mjs";
59
+
60
+ const argv = process.argv.slice(2);
61
+ const flag = (name) => (argv.includes(name) ? argv[argv.indexOf(name) + 1] : undefined);
62
+ const list = (v) => (v === undefined ? undefined : String(v).split(",").map((s) => s.trim()).filter(Boolean));
63
+
64
+ const configPath = resolve(flag("--config") ?? "bads-checks.config.json");
65
+ let fileSettings = {};
66
+ if (existsSync(configPath)) {
67
+ try {
68
+ fileSettings = JSON.parse(readFileSync(configPath, "utf8")).flushEdges ?? {};
69
+ } catch (e) {
70
+ console.error(`✗ flush-edges check: ${configPath} is not valid JSON (${e.message}).`);
71
+ process.exit(1);
72
+ }
73
+ } else if (flag("--config")) {
74
+ console.error(`✗ flush-edges check: no settings file at ${configPath}.`);
75
+ process.exit(1);
76
+ }
77
+
78
+ const pick = (key, fromFlag, fallback) => fromFlag ?? fileSettings[key] ?? fallback;
79
+ const single = flag("--route");
80
+ const settings = {
81
+ base: String(pick("base", flag("--base"), "http://localhost:3000")).replace(/\/$/, ""),
82
+ routes: single ? [single] : pick("routes", list(flag("--routes")), ["/"]),
83
+ root: pick("root", flag("--root"), "body"),
84
+ viewports: pick("viewports", list(flag("--viewports"))?.map(Number), [390, 1280]),
85
+ floor: Number(pick("floor", flag("--floor"), DEFAULTS.floor)),
86
+ measure: pick("measure", flag("--measure"), DEFAULTS.measure),
87
+ exceptAttr: pick("exceptAttr", flag("--except-attr"), DEFAULTS.exceptAttr),
88
+ minReason: Number(pick("minReason", flag("--min-reason"), DEFAULTS.minReason)),
89
+ frameAttr: pick("frameAttr", flag("--frame-attr"), DEFAULTS.frameAttr),
90
+ probe: pick("probe", flag("--probe"), DEFAULTS.probe),
91
+ known: pick("known", flag("--known"), null),
92
+ minMeasured: Number(pick("minMeasured", flag("--min-measured"), 1)),
93
+ reportJson: flag("--report-json") ?? null,
94
+ lazySelector: pick("lazySelector", flag("--lazy"), "[data-lazy-skeleton]"),
95
+ };
96
+
97
+ const problems = [];
98
+ if (!Array.isArray(settings.routes) || !settings.routes.length) problems.push("routes must name at least one path");
99
+ if (!Number.isFinite(settings.floor) || settings.floor <= 0) problems.push(`floor must be a positive number of px, not ${settings.floor}`);
100
+ if (settings.measure !== "cap" && settings.measure !== "line") problems.push(`measure must be "cap" or "line", not ${JSON.stringify(settings.measure)}`);
101
+ if (!settings.viewports.length || settings.viewports.some((w) => !Number.isFinite(w) || w < 200)) problems.push(`viewports must be widths of 200px or more, not ${settings.viewports}`);
102
+ if (!Number.isFinite(settings.minMeasured) || settings.minMeasured < 1) problems.push("minMeasured must be 1 or more: a run that measures nothing is not a pass");
103
+ if (problems.length) {
104
+ console.error(`✗ flush-edges check: bad settings.\n${problems.map((p) => ` ${p}`).join("\n")}`);
105
+ process.exit(1);
106
+ }
107
+
108
+ const failures = [];
109
+ let known = [];
110
+ if (settings.known) {
111
+ try {
112
+ known = JSON.parse(readFileSync(resolve(settings.known), "utf8")).known ?? [];
113
+ } catch (e) {
114
+ console.error(`✗ flush-edges check: cannot read the known findings in ${settings.known} (${e.message}).`);
115
+ process.exit(1);
116
+ }
117
+ for (const k of known) {
118
+ const exact = k.route && k.text && k.count === undefined;
119
+ const ratchet = (k.shipped || k.route) && !k.text && Number.isInteger(k.count) && k.count > 0;
120
+ if (!(exact || ratchet) || !k.reason || k.reason.length < 20)
121
+ failures.push(`${settings.known}: an entry needs route and text, or shipped (or route) and a whole count, and a reason of a sentence: ${JSON.stringify(k)}`);
122
+ }
123
+ }
124
+ const used = new Set();
125
+
126
+ let chromium;
127
+ try {
128
+ ({ chromium } = await import("playwright"));
129
+ } catch {
130
+ console.error("✗ flush-edges check: playwright is not installed. Install it (pnpm add -D playwright).");
131
+ process.exit(1);
132
+ }
133
+ let browser;
134
+ try {
135
+ browser = await chromium.launch();
136
+ } catch (e) {
137
+ console.error("✗ flush-edges check: no Chromium to drive. Run `pnpm exec playwright install chromium`.");
138
+ console.error(` ${String(e.message).split("\n")[0]}`);
139
+ process.exit(1);
140
+ }
141
+
142
+ const options = {
143
+ rootSelector: settings.root,
144
+ floor: settings.floor,
145
+ measure: settings.measure,
146
+ exceptAttr: settings.exceptAttr,
147
+ minReason: settings.minReason,
148
+ frameAttr: settings.frameAttr,
149
+ probe: settings.probe,
150
+ };
151
+ const totals = { measured: 0, excused: 0, dots: 0, pages: 0 };
152
+ const hits = new Map();
153
+ for (const width of settings.viewports) {
154
+ const page = await browser.newPage({ viewport: { width, height: 900 } });
155
+ page.setDefaultTimeout(30000);
156
+ for (const route of settings.routes) {
157
+ try {
158
+ const res = await page.goto(settings.base + route, { waitUntil: "networkidle", timeout: 60000 });
159
+ if (!res || res.status() >= 400) throw new Error(`HTTP ${res?.status() ?? "no response"}`);
160
+ await page.locator(settings.root).first().waitFor({ state: "attached" });
161
+ if (settings.lazySelector !== "") {
162
+ const unmounted = await mountEverything(page, { lazySelector: settings.lazySelector });
163
+ if (unmounted > 0) throw new Error(`${unmounted} deferred block(s) never mounted (${settings.lazySelector}), so they could not be measured`);
164
+ }
165
+ await page.evaluate(() => document.fonts.ready);
166
+ await page.waitForTimeout(500);
167
+ const r = await page.evaluate(`(${measureFlushEdges})(${JSON.stringify(options)})`);
168
+ totals.pages++;
169
+ totals.measured += r.measured;
170
+ totals.excused += r.excused;
171
+ totals.dots += r.dots ?? 0;
172
+ for (const b of r.badReasons) failures.push(`${route}: ${settings.exceptAttr} on ${b.box} needs a reason of ${settings.minReason} characters or more ("${b.text}")`);
173
+ for (const h of r.hits) {
174
+ const key = `${route}|${h.box}|${h.text}`;
175
+ const seen = hits.get(key);
176
+ if (seen) seen.widths.add(width);
177
+ else hits.set(key, { ...h, route, widths: new Set([width]) });
178
+ }
179
+ } catch (e) {
180
+ failures.push(`${route} at ${width}px: stopped because ${String(e.message).split("\n")[0]}`);
181
+ }
182
+ }
183
+ await page.close();
184
+ }
185
+ await browser.close();
186
+
187
+ const describeHit = (h) => {
188
+ const where = `${[...h.widths].join(" and ")}px${h.frame ? `, design ${h.frame}` : ""}${h.shipped ? `, shipped ${h.shipped}` : ""}`;
189
+ return `${h.route}: "${h.text}" is ${h.sides.join(", ")} from the edge of ${h.box} (${where})${h.overflows ? "; the text runs past the box's own padding, so the content is too long for it" : ""}`;
190
+ };
191
+ let knownCount = 0;
192
+ const ratchetHits = new Map();
193
+ for (const h of hits.values()) {
194
+ const k = known.find((x) => x.text && x.route === h.route && h.text.startsWith(x.text));
195
+ if (k) {
196
+ used.add(k);
197
+ knownCount++;
198
+ continue;
199
+ }
200
+ const r = h.shipped ? known.find((x) => !x.text && x.shipped === h.shipped) : known.find((x) => !x.text && !x.shipped && x.route === h.route);
201
+ if (r) {
202
+ if (!ratchetHits.has(r)) ratchetHits.set(r, []);
203
+ ratchetHits.get(r).push(h);
204
+ continue;
205
+ }
206
+ failures.push(describeHit(h));
207
+ }
208
+ for (const k of known) {
209
+ if (k.text) {
210
+ if (!single && !used.has(k)) failures.push(`${settings.known}: nothing matches ${k.route} / "${k.text}" any more. Remove the entry.`);
211
+ continue;
212
+ }
213
+ const got = ratchetHits.get(k) ?? [];
214
+ const name = k.shipped ? `the shipped ${k.shipped}` : `${k.route}'s own markup`;
215
+ if (got.length > k.count) {
216
+ failures.push(`${settings.known}: ${got.length} hit(s) in ${name}, over the ${k.count} recorded. A new one is not grandfathered:`);
217
+ for (const h of got) failures.push(` ${describeHit(h)}`);
218
+ } else {
219
+ knownCount += got.length;
220
+ if (!single && got.length < k.count) failures.push(`${settings.known}: ${name} now has ${got.length} hit(s), fewer than the ${k.count} recorded. Lower the count to ${got.length}${got.length ? "" : " (remove the entry)"}.`);
221
+ }
222
+ }
223
+ if (settings.reportJson) {
224
+ const { writeFileSync } = await import("node:fs");
225
+ writeFileSync(resolve(settings.reportJson), JSON.stringify([...hits.values()].map((h) => ({ ...h, widths: [...h.widths] })), null, "\t"));
226
+ }
227
+
228
+ const wanted = settings.routes.length * settings.viewports.length;
229
+ if (totals.pages < wanted || totals.measured < settings.minMeasured) {
230
+ console.error(`✗ flush-edges check: measured ${totals.measured} text node(s) on ${totals.pages} of ${wanted} page(s). The site, the routes or the root selector are wrong.`);
231
+ for (const f of failures.slice(0, 20)) console.error(` ${f}`);
232
+ process.exit(1);
233
+ }
234
+ if (failures.length) {
235
+ console.error(`✗ flush-edges check: ${failures.length} problem(s). Text must sit at least ${settings.floor}px inside the edge that holds it.\n`);
236
+ for (const f of failures) console.error(` ${f}`);
237
+ console.error(
238
+ `\n Give the container a real inset (the 8px step or more, more again beside a round end). If the text is meant to touch the edge,\n` +
239
+ ` say why on the container: ${settings.exceptAttr}="<reason>". A shipped component you must not restyle goes in the known file.`,
240
+ );
241
+ process.exit(1);
242
+ }
243
+ console.log(
244
+ `✓ flush-edges check: ${totals.measured} text node(s) on ${totals.pages} page(s) (${settings.routes.length} route(s) at ${settings.viewports.join(" and ")}px), all ${settings.floor}px or more inside their edge (${settings.measure} measure); ${totals.excused} excused with ${settings.exceptAttr}, ${knownCount} known finding(s), ${totals.dots} centred mark(s) in a dot not measured.`,
245
+ );
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * bads-check-spec: gate a prototype's spec.md.
4
+ *
5
+ * Layout it reads (default root: ./prototypes):
6
+ * prototypes/<slug>/prototype.meta.ts status: "draft" | "review" | "approved" | "shipped"
7
+ * prototypes/<slug>/spec.md
8
+ *
9
+ * For a prototype at review, approved, or shipped, any spec problem is an error
10
+ * and the exit code is 1. A draft reports problems as warnings. The status comes
11
+ * from prototype.meta.ts, the single source, so the spec carries no status of
12
+ * its own.
13
+ *
14
+ * npx bads-check-spec [root] [--warn]
15
+ */
16
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"
17
+ import { join, resolve } from "node:path"
18
+ import { fileURLToPath } from "node:url"
19
+ import { analyzeSpec } from "./lib/spec-parse.mjs"
20
+
21
+ const GATED = new Set(["review", "approved", "shipped"])
22
+
23
+ export function readStatus(metaSource) {
24
+ const m = /status\s*:\s*["'](draft|review|approved|shipped)["']/.exec(metaSource)
25
+ return m ? m[1] : null
26
+ }
27
+
28
+ /** Check every prototype folder under `root`. Returns { errors, warnings }. */
29
+ export function checkPrototypes(root) {
30
+ const errors = []
31
+ const warnings = []
32
+ if (!existsSync(root)) return { errors, warnings, checked: 0 }
33
+ let checked = 0
34
+ for (const slug of readdirSync(root).sort()) {
35
+ const dir = join(root, slug)
36
+ if (!statSync(dir).isDirectory()) continue
37
+ const metaPath = join(dir, "prototype.meta.ts")
38
+ if (!existsSync(metaPath)) continue
39
+ checked += 1
40
+ const status = readStatus(readFileSync(metaPath, "utf8"))
41
+ const out = status && GATED.has(status) ? errors : warnings
42
+ if (!status) {
43
+ errors.push(`${slug}: prototype.meta.ts has no readable status`)
44
+ continue
45
+ }
46
+ const specPath = join(dir, "spec.md")
47
+ if (!existsSync(specPath)) {
48
+ out.push(`${slug} (${status}): no spec.md`)
49
+ continue
50
+ }
51
+ const { frontMatter, problems } = analyzeSpec(readFileSync(specPath, "utf8"))
52
+ if (frontMatter.prototype && frontMatter.prototype !== slug && !frontMatter.prototype.includes("<")) {
53
+ problems.push(`front matter \`prototype\` is "${frontMatter.prototype}" but the folder is "${slug}"`)
54
+ }
55
+ for (const p of problems) out.push(`${slug} (${status}): ${p}`)
56
+ }
57
+ return { errors, warnings, checked }
58
+ }
59
+
60
+ // A bin runs through a symlink, so compare real paths, not argv[1] as given.
61
+ const isMain = process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)
62
+
63
+ if (isMain) {
64
+ const args = process.argv.slice(2)
65
+ const warnOnly = args.includes("--warn")
66
+ const root = resolve(args.find((a) => !a.startsWith("--")) ?? "prototypes")
67
+ const { errors, warnings, checked } = checkPrototypes(root)
68
+ for (const w of warnings) console.log(`warn ${w}`)
69
+ for (const e of errors) console.log(`error ${e}`)
70
+ if (checked === 0) console.log(`bads-check-spec: no prototypes found under ${root}`)
71
+ else console.log(`bads-check-spec: ${checked} prototype(s), ${errors.length} error(s), ${warnings.length} warning(s)`)
72
+ process.exit(errors.length > 0 && !warnOnly ? 1 : 0)
73
+ }