bitboss-ui 3.0.0-beta.72 → 3.0.0-beta.74

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 (185) hide show
  1. package/README.md +4 -2
  2. package/bin/bitboss-ui-mcp.mjs +101 -3
  3. package/bin/bitboss-ui.mjs +6 -1
  4. package/bin/cli.mjs +34 -7
  5. package/dist/ai/BbBadge.md +4 -4
  6. package/dist/ai/BbCalendar.md +4 -3
  7. package/dist/ai/BbColorPalette.md +8 -9
  8. package/dist/ai/BbConfirmPortal.md +1 -1
  9. package/dist/ai/BbDatePicker.md +4 -3
  10. package/dist/ai/BbDialog.md +17 -4
  11. package/dist/ai/BbDropdown.md +23 -10
  12. package/dist/ai/BbDropdownButton.md +2 -2
  13. package/dist/ai/BbForm.md +11 -7
  14. package/dist/ai/BbHoverCardPortal.md +1 -1
  15. package/dist/ai/BbNumberInput.md +5 -3
  16. package/dist/ai/BbPopoverPortal.md +1 -1
  17. package/dist/ai/BbTable.md +43 -19
  18. package/dist/ai/BbTimePicker.md +4 -3
  19. package/dist/ai/BbToastPortal.md +1 -1
  20. package/dist/ai/changelog.json +60 -4
  21. package/dist/ai/components.json +56 -20
  22. package/dist/ai/guides/design-tokens.md +20 -0
  23. package/dist/ai/guides/eslint-rules.md +1 -1
  24. package/dist/ai/guides/inertia-helpers.md +613 -53
  25. package/dist/ai/guides/migration/adoption-checklist.md +5 -5
  26. package/dist/ai/guides/migration/components/use-confirm.md +4 -1
  27. package/dist/ai/guides/migration/v2-to-v3.md +24 -0
  28. package/dist/ai/guides/migration/v3-beta-tooling.md +3 -0
  29. package/dist/ai/guides/preset-components.md +15 -2
  30. package/dist/ai/guides/reporting.md +49 -0
  31. package/dist/ai/helpers/inertia/manifest.json +33 -38
  32. package/dist/ai/helpers/inertia/useHasChanged.ts +25 -37
  33. package/dist/ai/helpers/inertia/useQuery.ts +24 -6
  34. package/dist/ai/helpers/inertia/utils.ts +552 -3
  35. package/dist/ai/index.md +1 -0
  36. package/dist/ai/manifest/components/BbAlert.tree.json +1 -1
  37. package/dist/ai/manifest/components/BbCalendar.json +2 -2
  38. package/dist/ai/manifest/components/BbColorPalette.json +3 -3
  39. package/dist/ai/manifest/components/BbConfirm.removed.json +4 -4
  40. package/dist/ai/manifest/components/BbConfirmPortal.json +1 -1
  41. package/dist/ai/manifest/components/BbConfirmPortal.removed.json +2 -2
  42. package/dist/ai/manifest/components/BbDatePicker.json +3 -3
  43. package/dist/ai/manifest/components/BbDialog.tree.json +5 -1
  44. package/dist/ai/manifest/components/BbDropdown.json +3 -3
  45. package/dist/ai/manifest/components/BbDropdown.tree.json +3 -2
  46. package/dist/ai/manifest/components/BbDropdownButton.json +2 -2
  47. package/dist/ai/manifest/components/BbForm.json +1 -1
  48. package/dist/ai/manifest/components/BbHoverCard.json +1 -1
  49. package/dist/ai/manifest/components/BbHoverCardPortal.json +1 -1
  50. package/dist/ai/manifest/components/BbNumberInput.json +1 -1
  51. package/dist/ai/manifest/components/BbPopover.json +1 -1
  52. package/dist/ai/manifest/components/BbPopoverPortal.json +1 -1
  53. package/dist/ai/manifest/components/BbSelectPopover.json +1 -1
  54. package/dist/ai/manifest/components/BbTable.tree.json +12 -6
  55. package/dist/ai/manifest/components/BbTimePicker.json +3 -3
  56. package/dist/ai/manifest/components/BbToast.removed.json +1 -1
  57. package/dist/ai/manifest/components/BbToastPortal.json +1 -1
  58. package/dist/ai/manifest/components/CommonPopover.json +1 -1
  59. package/dist/ai/manifest/index.json +2 -2
  60. package/dist/ai/manifest/meta.json +36 -0
  61. package/dist/ai/manifest/types.advanced.json +81 -80
  62. package/dist/ai/manifest/types.api.json +66 -65
  63. package/dist/ai/manifest/types.wrapper.json +155 -118
  64. package/dist/ai/recipes/inertia/layout-scaffold.md +3 -1
  65. package/dist/ai/recipes/nuxt/layout-scaffold.md +3 -1
  66. package/dist/ai/recipes/vue/layout-scaffold.md +3 -1
  67. package/dist/ai/source/BbAlert.md +16 -4
  68. package/dist/ai/source/BbAvatar.md +2 -0
  69. package/dist/ai/source/BbBreadcrumbs.md +4 -1
  70. package/dist/ai/source/BbCalendar.md +22 -12
  71. package/dist/ai/source/BbColorPalette.md +41 -12
  72. package/dist/ai/source/BbConfirm.md +7 -0
  73. package/dist/ai/source/BbConfirmPortal.md +9 -4
  74. package/dist/ai/source/BbDatePicker.md +53 -22
  75. package/dist/ai/source/BbDatePickerInput.md +32 -8
  76. package/dist/ai/source/BbDialog.md +31 -1
  77. package/dist/ai/source/BbDropdown.md +52 -24
  78. package/dist/ai/source/BbDropdownGroup.md +17 -21
  79. package/dist/ai/source/BbForm.md +80 -6
  80. package/dist/ai/source/BbHoverCard.md +7 -0
  81. package/dist/ai/source/BbHoverCardPortal.md +9 -5
  82. package/dist/ai/source/BbNumberInput.md +5 -6
  83. package/dist/ai/source/BbOffCanvas.md +34 -1
  84. package/dist/ai/source/BbPopover.md +7 -0
  85. package/dist/ai/source/BbPopoverPortal.md +9 -5
  86. package/dist/ai/source/BbRadio.md +4 -3
  87. package/dist/ai/source/BbRadioGroup.md +7 -5
  88. package/dist/ai/source/BbTable.md +54 -6
  89. package/dist/ai/source/BbTag.md +10 -3
  90. package/dist/ai/source/BbTimePicker.md +50 -15
  91. package/dist/ai/source/BbTimePickerInput.md +30 -7
  92. package/dist/ai/source/BbToast.md +14 -0
  93. package/dist/ai/source/BbToastPortal.md +16 -4
  94. package/dist/ai/source/CommonFieldInput.md +11 -5
  95. package/dist/ai/source/CommonPopover.md +4 -1
  96. package/dist/components/BbAlert/BbAlert.vue_vue_type_script_setup_true_lang.js +31 -26
  97. package/dist/components/BbBreadcrumbs/BbBreadcrumbs.vue_vue_type_script_setup_true_lang.js +1 -1
  98. package/dist/components/BbCalendar/BbCalendar.vue.d.ts +1 -1
  99. package/dist/components/BbCalendar/BbCalendar.vue_vue_type_script_setup_true_lang.js +235 -234
  100. package/dist/components/BbCalendar/types.d.ts +2 -2
  101. package/dist/components/BbCalendar/useDayjsLocale.js +11 -8
  102. package/dist/components/BbColorPalette/BbColorPalette.vue_vue_type_script_setup_true_lang.js +197 -192
  103. package/dist/components/BbColorPalette/types.d.ts +1 -1
  104. package/dist/components/BbConfirm/BbConfirmPortal.vue.d.ts +2 -4
  105. package/dist/components/BbConfirm/types.d.ts +5 -0
  106. package/dist/components/BbDatePicker/BbDatePicker.vue.d.ts +1 -1
  107. package/dist/components/BbDatePicker/BbDatePicker.vue_vue_type_script_setup_true_lang.js +145 -139
  108. package/dist/components/BbDatePicker/types.d.ts +2 -2
  109. package/dist/components/BbDatePickerInput/BbDatePickerInput.vue_vue_type_script_setup_true_lang.js +337 -335
  110. package/dist/components/BbDialog/BbDialog.vue_vue_type_script_setup_true_lang.js +253 -245
  111. package/dist/components/BbDialog/leaveGhost.js +33 -0
  112. package/dist/components/BbDialog/overlayActions.js +34 -20
  113. package/dist/components/BbDropdown/BbDropdown.vue_vue_type_script_setup_true_lang.js +11 -3
  114. package/dist/components/BbDropdown/BbDropdownList.vue_vue_type_script_setup_true_lang.js +4 -4
  115. package/dist/components/BbDropdown/DropdownPipelineResolver.vue_vue_type_script_setup_true_lang.js +119 -120
  116. package/dist/components/BbDropdown/types.d.ts +8 -17
  117. package/dist/components/BbForm/BbForm.vue.d.ts +2 -21
  118. package/dist/components/BbForm/BbForm.vue_vue_type_script_setup_true_lang.js +229 -227
  119. package/dist/components/BbForm/types.d.ts +31 -0
  120. package/dist/components/BbHoverCard/BbHoverCardPortal.vue.d.ts +2 -5
  121. package/dist/components/BbHoverCard/types.d.ts +5 -0
  122. package/dist/components/BbNumberInput/BbNumberInput.vue_vue_type_script_setup_true_lang.js +1 -1
  123. package/dist/components/BbNumberInput/numberDisplay.js +102 -106
  124. package/dist/components/BbNumberInput/types.d.ts +4 -3
  125. package/dist/components/BbOffCanvas/BbOffCanvas.vue_vue_type_script_setup_true_lang.js +385 -377
  126. package/dist/components/BbPopover/BbPopoverPortal.vue.d.ts +2 -5
  127. package/dist/components/BbPopover/types.d.ts +5 -0
  128. package/dist/components/BbRadio/types.d.ts +4 -3
  129. package/dist/components/BbRadioGroup/BbRadioGroup.vue_vue_type_script_setup_true_lang.js +10 -12
  130. package/dist/components/BbTable/BbTable.vue_vue_type_script_setup_true_lang.js +231 -231
  131. package/dist/components/BbTable/BbTableDataRow.js +96 -96
  132. package/dist/components/BbTag/BbTag.vue_vue_type_script_setup_true_lang.js +9 -3
  133. package/dist/components/BbTimePicker/BbTimePicker.vue.d.ts +1 -1
  134. package/dist/components/BbTimePicker/BbTimePicker.vue_vue_type_script_setup_true_lang.js +106 -100
  135. package/dist/components/BbTimePicker/types.d.ts +2 -2
  136. package/dist/components/BbTimePickerInput/BbTimePickerInput.vue_vue_type_script_setup_true_lang.js +214 -213
  137. package/dist/components/BbToast/BbToastPortal.vue.d.ts +2 -4
  138. package/dist/components/BbToast/types.d.ts +5 -0
  139. package/dist/components/CommonFieldInput/CommonFieldInput.vue_vue_type_script_setup_true_lang.js +36 -36
  140. package/dist/components/CommonPopover/CommonPopover.vue_vue_type_script_setup_true_lang.js +1 -1
  141. package/dist/components/CommonTimeSelector/useMeridiem.js +6 -6
  142. package/dist/composables/formSubmitLock.js +2 -1
  143. package/dist/composables/overlayRegistry.js +52 -42
  144. package/dist/composables/useActiveInactiveState.js +8 -4
  145. package/dist/composables/useBbDialog.js +5 -5
  146. package/dist/composables/useOwnModel.js +16 -0
  147. package/dist/composables/useSegmentedFields.js +31 -20
  148. package/dist/deprecation/ai-deprecations.json.js +1 -1
  149. package/dist/i18n/currencyDigits.js +58 -0
  150. package/dist/i18n/regionDates.js +250 -0
  151. package/dist/i18n/regionHints.js +30 -41
  152. package/dist/index.d.ts +34 -30
  153. package/dist/llms-full.txt +874 -136
  154. package/dist/llms.txt +3 -1
  155. package/dist/styles.css +2 -2
  156. package/dist/types/ActionButton.d.ts +3 -1
  157. package/dist/types/CommonProps.d.ts +8 -0
  158. package/dist/utilities/functions/hash.js +123 -3
  159. package/dist/utilities/functions/isEqual.js +69 -3
  160. package/dist/utils/versionCheck.js +1 -1
  161. package/dist/vite-plugin.d.ts +2 -1
  162. package/dist/vite.js +8 -5
  163. package/llms.txt +3 -1
  164. package/package.json +2 -3
  165. package/scripts/README.md +43 -43
  166. package/scripts/lib/adoption-checklist.json +6 -5
  167. package/scripts/lib/agent-manifest.mjs +33 -6
  168. package/scripts/lib/agent-setup.mjs +54 -6
  169. package/scripts/lib/cldr-pins.ts +182 -0
  170. package/scripts/lib/engines-include.d.mts +5 -0
  171. package/scripts/lib/engines-include.mjs +40 -0
  172. package/scripts/lib/eslint-plugin.mjs +8 -2
  173. package/scripts/lib/helpers-add.mjs +21 -2
  174. package/scripts/lib/hidden-label-placeholder.mjs +25 -5
  175. package/scripts/lib/idiom-scan.mjs +30 -3
  176. package/scripts/lib/legacy-agent-files.json +152 -0
  177. package/scripts/lib/mcp-config.mjs +74 -7
  178. package/scripts/lib/portal-names.mjs +78 -8
  179. package/scripts/lib/release-results.mjs +153 -6
  180. package/scripts/lib/report.mjs +340 -0
  181. package/scripts/lib/run-beat.mjs +14 -0
  182. package/scripts/lib/run-records.mjs +313 -0
  183. package/scripts/lib/selector-log.mjs +98 -0
  184. package/scripts/lib/ticket-beat.mjs +30 -0
  185. package/scripts/lib/validate-bb-markup.mjs +17 -2
@@ -0,0 +1,340 @@
1
+ /**
2
+ * The report inbox client: `npx bitboss-ui report` and the MCP `report_issue`
3
+ * tool both send through `sendReport`. Zero dependencies (Node's fetch and
4
+ * crypto), so `report` runs on the CLI's slim path with nothing else
5
+ * installed.
6
+ *
7
+ * The inbox is the docs site's `/api/report`: `GET` on it returns the
8
+ * contract as JSON. A bare POST is accepted; the optional proof of work
9
+ * (`x-bitboss-pow`) marks the report verified, which lifts it out of the
10
+ * smaller unverified daily ceiling.
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { readFileSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+ import { parseArgs } from 'node:util';
16
+
17
+ /**
18
+ * Whether the app at `root` reports to the maintainers. On by default; an
19
+ * app turns it off with `"bitboss-ui": { "report": false }` in its
20
+ * package.json, read like the key's other entries
21
+ * (`dialogIdsWhitelist`, `registeredRules`). Only a literal `false` turns it
22
+ * off; a missing or broken package.json leaves it on.
23
+ * @param {string} [root] the project root (default: the working directory)
24
+ */
25
+ export function reportingEnabled(root = process.cwd()) {
26
+ try {
27
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8'));
28
+ return pkg?.['bitboss-ui']?.report !== false;
29
+ } catch {
30
+ return true;
31
+ }
32
+ }
33
+
34
+ /** What `report` prints when the app turned reporting off. */
35
+ export const REPORTING_OFF =
36
+ '[bitboss-ui] report: reporting is off in this project: package.json bitboss-ui.report';
37
+
38
+ export const REPORT_URL = 'https://ui-components.bitboss.it/api/report';
39
+
40
+ /** One line per kind, the same words the inbox serves on `GET /api/report`. */
41
+ export const KIND_DEFINITIONS = {
42
+ bug: 'The library does the wrong thing.',
43
+ friction:
44
+ 'It works, but getting there took trial and error, or the docs or types misled you.',
45
+ glue: 'Code you had to write around the library for a common need (a wrapper, an adapter, wiring you repeat across screens). Put the glue in `snippet`.',
46
+ smell:
47
+ 'It works, but something feels wrong: an inconsistent API, an odd name, a surprising default.',
48
+ feature: "Something the library doesn't do and should.",
49
+ docs: 'Docs that are wrong, missing or unfindable.',
50
+ };
51
+ export const REPORT_KINDS = Object.keys(KIND_DEFINITIONS);
52
+
53
+ /** The no-install way to report, as the agent docs print it. */
54
+ export const REPORT_CURL = `curl -sS ${REPORT_URL} -H 'content-type: application/json' -d '{"kind":"bug","component":"BbSelect","version":"<installed bitboss-ui version>","expected":"…","actual":"…"}'`;
55
+
56
+ /** The body's fields, in contract order. Unknown keys are refused by the inbox. */
57
+ export const REPORT_FIELDS = [
58
+ 'component',
59
+ 'kind',
60
+ 'version',
61
+ 'expected',
62
+ 'actual',
63
+ 'workaround',
64
+ 'snippet',
65
+ 'page',
66
+ 'reporter',
67
+ ];
68
+ const REQUIRED = ['component', 'kind', 'version', 'expected', 'actual'];
69
+
70
+ /** The inbox's default difficulty; a 401 names the current one. */
71
+ const POW_BITS = 20;
72
+
73
+ function leadingZeroBits(buffer) {
74
+ let bits = 0;
75
+ for (const byte of buffer) {
76
+ if (byte === 0) {
77
+ bits += 8;
78
+ continue;
79
+ }
80
+ return bits + Math.clz32(byte) - 24;
81
+ }
82
+ return bits;
83
+ }
84
+
85
+ /**
86
+ * The inbox's proof of work, copied from its reference solver: a nonce such
87
+ * that `sha256("<ts>.<nonce>.<sha256 hex of the exact body>")` starts with
88
+ * `bits` zero bits. About a second of CPU at 20 bits.
89
+ * @param {string} rawBody the exact string that will be POSTed
90
+ * @param {number} bits
91
+ * @param {number} [nowSeconds]
92
+ * @returns {string} the `x-bitboss-pow` header value
93
+ */
94
+ export function solvePow(
95
+ rawBody,
96
+ bits,
97
+ nowSeconds = Math.floor(Date.now() / 1000)
98
+ ) {
99
+ const digest = createHash('sha256').update(rawBody).digest('hex');
100
+ for (let nonce = 0; ; nonce++) {
101
+ const n = nonce.toString(36);
102
+ const hash = createHash('sha256')
103
+ .update(`${nowSeconds}.${n}.${digest}`)
104
+ .digest();
105
+ if (leadingZeroBits(hash) >= bits) return `${nowSeconds}.${n}`;
106
+ }
107
+ }
108
+
109
+ /** Whether `header` solves `rawBody` at `bits` (for tests). */
110
+ export function powSolves(header, rawBody, bits) {
111
+ const [ts, nonce] = header.split('.');
112
+ const digest = createHash('sha256').update(rawBody).digest('hex');
113
+ const hash = createHash('sha256').update(`${ts}.${nonce}.${digest}`).digest();
114
+ return leadingZeroBits(hash) >= bits;
115
+ }
116
+
117
+ /**
118
+ * The body to send: known fields only, empty strings dropped, `version`
119
+ * filled with the installed one when the caller left it out.
120
+ * @returns {{ body: Record<string, string>, problems: string[] }}
121
+ */
122
+ export function buildReport(input, { version }) {
123
+ const body = {};
124
+ const problems = [];
125
+ for (const key of Object.keys(input ?? {})) {
126
+ if (!REPORT_FIELDS.includes(key)) problems.push(`unknown field \`${key}\``);
127
+ }
128
+ for (const field of REPORT_FIELDS) {
129
+ const value = input?.[field];
130
+ if (value === undefined || value === null) continue;
131
+ if (typeof value !== 'string') {
132
+ problems.push(`\`${field}\` must be a string`);
133
+ continue;
134
+ }
135
+ if (value.trim() !== '') body[field] = value;
136
+ }
137
+ body.version ??= version || 'unknown';
138
+ for (const field of REQUIRED) {
139
+ if (!(field in body)) problems.push(`\`${field}\` is required`);
140
+ }
141
+ if (body.kind && !REPORT_KINDS.includes(body.kind))
142
+ problems.push(`\`kind\` is one of ${REPORT_KINDS.join(', ')}`);
143
+ // Contract order, so the bytes are stable for the proof of work.
144
+ const ordered = {};
145
+ for (const field of REPORT_FIELDS)
146
+ if (field in body) ordered[field] = body[field];
147
+ return { body: ordered, problems };
148
+ }
149
+
150
+ /**
151
+ * POST a report. Solves the proof of work unless `pow: false`; on a 401
152
+ * that names another difficulty it solves once more at that one, and
153
+ * otherwise resends without the proof (an unverified report still lands).
154
+ * @param {Record<string, string>} body from {@link buildReport}
155
+ * @param {{ client: string, fetch?: typeof fetch, url?: string, pow?: boolean, bits?: number }} options
156
+ * @returns {Promise<{ status: number, body: any }>}
157
+ */
158
+ export async function sendReport(
159
+ body,
160
+ {
161
+ client,
162
+ fetch: fetchImpl = globalThis.fetch,
163
+ url = process.env.BITBOSS_UI_REPORT_URL || REPORT_URL,
164
+ pow = true,
165
+ bits = POW_BITS,
166
+ }
167
+ ) {
168
+ const raw = JSON.stringify(body);
169
+ const post = async (proof) => {
170
+ const headers = {
171
+ 'content-type': 'application/json',
172
+ 'x-bitboss-client': client,
173
+ };
174
+ if (proof) headers['x-bitboss-pow'] = proof;
175
+ const response = await fetchImpl(url, {
176
+ method: 'POST',
177
+ headers,
178
+ body: raw,
179
+ });
180
+ let json;
181
+ try {
182
+ json = await response.json();
183
+ } catch {
184
+ json = { error: `HTTP ${response.status}` };
185
+ }
186
+ return { status: response.status, body: json };
187
+ };
188
+ let result = await post(pow && bits > 0 ? solvePow(raw, bits) : undefined);
189
+ if (result.status === 401 && result.body?.error === 'proof_of_work_invalid') {
190
+ const next = Number(result.body.bits);
191
+ result = await post(
192
+ Number.isInteger(next) && next > 0 && next <= 32 && next !== bits
193
+ ? solvePow(raw, next)
194
+ : undefined
195
+ );
196
+ }
197
+ return result;
198
+ }
199
+
200
+ /** One human line per outcome; `ok` says whether the report landed. */
201
+ export function describeResult({ status, body }) {
202
+ if ((status === 200 || status === 201) && body?.id) {
203
+ const where = body.duplicate ? 'Added to an open report' : 'Report filed';
204
+ return {
205
+ ok: true,
206
+ lines: [
207
+ `${where}: ${body.id}${body.verified === false ? ' (unverified)' : ''}`,
208
+ `Status: ${body.statusUrl}`,
209
+ ],
210
+ };
211
+ }
212
+ if (status === 400 && Array.isArray(body?.issues))
213
+ return {
214
+ ok: false,
215
+ lines: [
216
+ 'The inbox refused the report:',
217
+ ...body.issues.map((i) => ` ${i.field || '(body)'}: ${i.message}`),
218
+ ],
219
+ };
220
+ if (status === 429 || status === 503)
221
+ return {
222
+ ok: false,
223
+ lines: [
224
+ `The inbox is busy (${body?.error ?? status}); retry in ${body?.retryAfter ?? 60} s.`,
225
+ ],
226
+ };
227
+ return {
228
+ ok: false,
229
+ lines: [
230
+ `The inbox answered ${status}: ${body?.error ?? 'unknown error'}${body?.hint ? ` (${body.hint})` : ''}`,
231
+ ],
232
+ };
233
+ }
234
+
235
+ export const REPORT_HELP = `Usage:
236
+ npx bitboss-ui report --kind <kind> --component <name> --expected <text> --actual <text>
237
+ [--workaround <text>] [--snippet <text>] [--page <path>]
238
+ [--reporter <contact>] [--version <v>] [--json]
239
+ npx bitboss-ui report --stdin [--json] < report.json
240
+
241
+ Kinds:
242
+ ${REPORT_KINDS.map((k) => ` ${k.padEnd(9)}${KIND_DEFINITIONS[k]}`).join('\n')}
243
+
244
+ --component is a Bb* name, or the surface (cli, mcp, vite-plugin, nuxt-module,
245
+ docs, other). --version defaults to the installed bitboss-ui. --stdin reads one
246
+ JSON object with the same field names; flags override it. Send a minimal repro
247
+ only: never app data, customer data, secrets or proprietary code. Keep your
248
+ workaround in place: a report never waits on a fix.`;
249
+
250
+ function readStdin() {
251
+ return readFileSync(0, 'utf-8');
252
+ }
253
+
254
+ /**
255
+ * `npx bitboss-ui report`. Exit 0 when the report landed, 1 otherwise.
256
+ * @param {string[]} argv
257
+ * @param {{ version?: string, fetch?: typeof fetch, bits?: number, stdin?: () => string, log?: (s: string) => void, error?: (s: string) => void, root?: string }} [io] test seams
258
+ */
259
+ export async function reportCli(argv, io = {}) {
260
+ const log = io.log ?? ((s) => console.log(s));
261
+ const error = io.error ?? ((s) => console.error(s));
262
+ if (!reportingEnabled(io.root)) {
263
+ error(REPORTING_OFF);
264
+ return 1;
265
+ }
266
+ const version = io.version ?? installedVersion();
267
+ let values;
268
+ try {
269
+ ({ values } = parseArgs({
270
+ args: argv,
271
+ allowPositionals: false,
272
+ options: {
273
+ ...Object.fromEntries(
274
+ REPORT_FIELDS.map((f) => [f, { type: 'string' }])
275
+ ),
276
+ stdin: { type: 'boolean' },
277
+ json: { type: 'boolean' },
278
+ help: { type: 'boolean', short: 'h' },
279
+ },
280
+ }));
281
+ } catch (e) {
282
+ error(`[bitboss-ui] report: ${e instanceof Error ? e.message : String(e)}`);
283
+ error(REPORT_HELP);
284
+ return 1;
285
+ }
286
+ if (values.help) {
287
+ log(REPORT_HELP);
288
+ return 0;
289
+ }
290
+ let input = {};
291
+ if (values.stdin) {
292
+ try {
293
+ input = JSON.parse((io.stdin ?? readStdin)());
294
+ } catch (e) {
295
+ error(
296
+ `[bitboss-ui] report: --stdin needs one JSON object (${e instanceof Error ? e.message : String(e)})`
297
+ );
298
+ return 1;
299
+ }
300
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
301
+ error('[bitboss-ui] report: --stdin needs one JSON object');
302
+ return 1;
303
+ }
304
+ }
305
+ for (const field of REPORT_FIELDS)
306
+ if (values[field] !== undefined) input[field] = values[field];
307
+ const { body, problems } = buildReport(input, { version });
308
+ if (problems.length) {
309
+ error(`[bitboss-ui] report: ${problems.join('; ')}`);
310
+ error(REPORT_HELP);
311
+ return 1;
312
+ }
313
+ let result;
314
+ try {
315
+ result = await sendReport(body, {
316
+ client: `bitboss-ui-cli/${version}`,
317
+ fetch: io.fetch,
318
+ bits: io.bits,
319
+ });
320
+ } catch (e) {
321
+ error(
322
+ `[bitboss-ui] report: could not reach the inbox (${e instanceof Error ? e.message : String(e)})`
323
+ );
324
+ return 1;
325
+ }
326
+ const { ok, lines } = describeResult(result);
327
+ if (values.json) log(JSON.stringify(result.body));
328
+ else (ok ? log : error)(lines.join('\n'));
329
+ return ok ? 0 : 1;
330
+ }
331
+
332
+ export function installedVersion() {
333
+ try {
334
+ return JSON.parse(
335
+ readFileSync(new URL('../../package.json', import.meta.url), 'utf-8')
336
+ ).version;
337
+ } catch {
338
+ return 'unknown';
339
+ }
340
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The heartbeat of a recorded run (run-records.mjs startRun), as its own
3
+ * detached process: the gates run their steps with spawnSync, which blocks
4
+ * the parent's timers. Every BEAT_MS it appends a `beat` line with a load
5
+ * and memory sample; when the parent is gone without having stopped it (a
6
+ * kill, a crash: the run writes no history), it appends `gone` and exits.
7
+ *
8
+ * Usage: node scripts/lib/run-beat.mjs <run log> <runId> <parent pid>
9
+ */
10
+ import { beatLoop } from './run-records.mjs';
11
+
12
+ const [log, runId, parent] = process.argv.slice(2);
13
+ beatLoop({ env: { BB_RUN_LOG: log, BB_RUN_ID: runId }, pid: Number(parent) });
14
+ process.on('SIGTERM', () => process.exit(0));
@@ -0,0 +1,313 @@
1
+ /**
2
+ * The run log: what every gate, wall and release run spent its time on,
3
+ * written as it happens, for the measurement that prices the test suite.
4
+ * Nothing here changes what a run does; every write is best-effort and never
5
+ * throws into the run it records.
6
+ *
7
+ * ONE FILE, beside the wall histories:
8
+ * <git-common-dir>/bb-gate/results/runs.jsonl (BB_RESULTS_DIR moves it)
9
+ * one JSON line per event, each with `runId` and `at` (ISO). The history
10
+ * record a run writes at its end carries the same `runId`. Lines:
11
+ * start { kind, mode, sha, pid, cwd, load1, memMB }
12
+ * the run began. A start without its history record (or without an
13
+ * `end`) is a run that was killed: those write no history.
14
+ * beat { load1, memMB } every BEAT_MS while the run lives
15
+ * gone { } the run's process died without writing `end`
16
+ * end { ok, seconds }
17
+ * files { step, where, attempt, exit, killed?, ms, before, after, files }
18
+ * one vitest invocation: `files` is [path, ms, status] per test
19
+ * file, from Vitest's JSON report (`ms` = endTime − startTime);
20
+ * `before` / `after` are { load1, memMB } samples around it
21
+ * wait { step?, lock, label, ms, reason } time spent waiting for a
22
+ * machine-wide lock: 'browser-tier', 'memory', 'memory-pause',
23
+ * 'timing-window' (another run's timing files hold it), 'timing-claim'
24
+ * (taking it), 'browser-drain' (other browser runs finishing)
25
+ *
26
+ * HOW IT REACHES THE RUNNERS: the top-level run (gate.mjs, release-check.mjs,
27
+ * release-local.mjs) calls startRun(), which exports BB_RUN_ID and
28
+ * BB_RUN_LOG; each step's environment adds BB_RUN_STEP (its name, nested
29
+ * with ` › ` under release:local). Every vitest runner and every Vitest
30
+ * process below inherits them and appends with recordRun(). A run started
31
+ * inside another (release:check under release:local) joins the outer run.
32
+ * Without BB_RUN_LOG (CI, a direct `npx vitest`), nothing is written.
33
+ *
34
+ * THE HEARTBEAT is a small detached process (run-beat.mjs): the gates run
35
+ * their steps with spawnSync, which blocks the parent's own timers.
36
+ */
37
+ import { spawn } from 'node:child_process';
38
+ import { randomBytes } from 'node:crypto';
39
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
40
+ import os from 'node:os';
41
+ import path from 'node:path';
42
+ import { fileURLToPath } from 'node:url';
43
+ import { memorySignal } from './heavy-admission.mjs';
44
+
45
+ export const RUN_ID_ENV = 'BB_RUN_ID';
46
+ export const RUN_LOG_ENV = 'BB_RUN_LOG';
47
+ export const RUN_STEP_ENV = 'BB_RUN_STEP';
48
+ export const RUN_LOG_NAME = 'runs.jsonl';
49
+ export const BEAT_MS = 30_000;
50
+
51
+ /** { load1, memMB }: the 1-minute load average and the memory available. */
52
+ export function machineSample({
53
+ loadavg = os.loadavg,
54
+ signal = () => memorySignal(),
55
+ } = {}) {
56
+ let memMB = null;
57
+ try {
58
+ memMB = signal()?.availableMB ?? null;
59
+ } catch {
60
+ memMB = null;
61
+ }
62
+ return { load1: Math.round(loadavg()[0] * 100) / 100, memMB };
63
+ }
64
+
65
+ /**
66
+ * Append one line to the run log (no-op outside a recorded run). The step
67
+ * comes from BB_RUN_STEP unless the line names one.
68
+ */
69
+ export function recordRun(line, env = process.env) {
70
+ const log = env[RUN_LOG_ENV];
71
+ const runId = env[RUN_ID_ENV];
72
+ if (!log || !runId) return;
73
+ const step = env[RUN_STEP_ENV];
74
+ try {
75
+ appendFileSync(
76
+ log,
77
+ `${JSON.stringify({
78
+ runId,
79
+ at: new Date().toISOString(),
80
+ ...(step ? { step } : {}),
81
+ ...line,
82
+ })}\n`
83
+ );
84
+ } catch {
85
+ // recording never fails a run
86
+ }
87
+ }
88
+
89
+ /** A nested step name: `outer › inner`, or `inner` at the top. */
90
+ export const stepName = (name, env = process.env) =>
91
+ env[RUN_STEP_ENV] ? `${env[RUN_STEP_ENV]} › ${name}` : name;
92
+
93
+ /**
94
+ * Per-file [path, ms, status] from a Vitest JSON report, paths relative to
95
+ * `cwd`; [] when there is no readable report (a crash, a kill).
96
+ */
97
+ export function fileTimes(jsonPath, cwd = process.cwd()) {
98
+ if (!jsonPath || !existsSync(jsonPath)) return [];
99
+ try {
100
+ const report = JSON.parse(readFileSync(jsonPath, 'utf8'));
101
+ return (report?.testResults ?? []).map((r) => [
102
+ path.relative(cwd, r.name),
103
+ Number.isFinite(r.endTime - r.startTime)
104
+ ? Math.round(r.endTime - r.startTime)
105
+ : null,
106
+ r.status,
107
+ ]);
108
+ } catch {
109
+ return [];
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Record one vitest invocation: call `begin()` before it and the returned
115
+ * function after it, with its report.
116
+ */
117
+ export function recordFiles({
118
+ where,
119
+ attempt = 1,
120
+ env = process.env,
121
+ sample = machineSample,
122
+ now = Date.now,
123
+ }) {
124
+ if (!env[RUN_LOG_ENV]) return () => {};
125
+ const before = sample();
126
+ const start = now();
127
+ return ({ report, exit = null, killed = false, cwd = process.cwd() }) =>
128
+ recordRun(
129
+ {
130
+ type: 'files',
131
+ where,
132
+ attempt,
133
+ exit,
134
+ ...(killed ? { killed: true } : {}),
135
+ ms: now() - start,
136
+ before,
137
+ after: sample(),
138
+ files: fileTimes(report, cwd),
139
+ },
140
+ env
141
+ );
142
+ }
143
+
144
+ /**
145
+ * Record a wait for a machine-wide lock, from what the waiting function
146
+ * returned. Nothing for a lock that was skipped (off, CI) or already held
147
+ * by the run; `always: false` drops a zero wait (the per-chunk pause).
148
+ */
149
+ export function recordWait(
150
+ lock,
151
+ label,
152
+ result,
153
+ { env = process.env, always = true } = {}
154
+ ) {
155
+ if (!result || result.skipped || result.nested || result.inside) return;
156
+ const ms = result.waitedMs ?? 0;
157
+ if (!always && ms <= 0) return;
158
+ recordRun(
159
+ {
160
+ type: 'wait',
161
+ lock,
162
+ label,
163
+ ms,
164
+ reason: result.reason ?? null,
165
+ ...(result.gaveUp ? { gaveUp: true } : {}),
166
+ },
167
+ env
168
+ );
169
+ }
170
+
171
+ /** The run log's path in a results directory. */
172
+ export const runLogPath = (dir) => path.join(dir, RUN_LOG_NAME);
173
+
174
+ const BEAT_SCRIPT = path.join(
175
+ path.dirname(fileURLToPath(import.meta.url)),
176
+ 'run-beat.mjs'
177
+ );
178
+
179
+ /**
180
+ * Open a recorded run: write its `start` line, export BB_RUN_ID / BB_RUN_LOG
181
+ * into `env` (its children inherit them) and start the heartbeat. Inside a
182
+ * run that is already recorded (BB_RUN_ID set), joins it: no new start line.
183
+ * Returns { runId, nested, end({ ok, seconds }) }.
184
+ */
185
+ export function startRun({
186
+ kind,
187
+ mode = null,
188
+ sha = null,
189
+ dir,
190
+ env = process.env,
191
+ pid = process.pid,
192
+ cwd = process.cwd(),
193
+ beat = (log, runId) => {
194
+ const child = spawn(
195
+ process.execPath,
196
+ [BEAT_SCRIPT, log, runId, String(pid)],
197
+ { detached: true, stdio: 'ignore' }
198
+ );
199
+ child.unref();
200
+ return () => {
201
+ try {
202
+ child.kill();
203
+ } catch {
204
+ // already gone
205
+ }
206
+ };
207
+ },
208
+ sample = machineSample,
209
+ }) {
210
+ if (env[RUN_ID_ENV] && env[RUN_LOG_ENV])
211
+ return { runId: env[RUN_ID_ENV], nested: true, end() {} };
212
+ const runId = `${kind}-${Date.now().toString(36)}-${randomBytes(3).toString('hex')}`;
213
+ let log;
214
+ try {
215
+ mkdirSync(dir, { recursive: true });
216
+ log = runLogPath(dir);
217
+ } catch {
218
+ return { runId, nested: false, end() {} };
219
+ }
220
+ env[RUN_ID_ENV] = runId;
221
+ env[RUN_LOG_ENV] = log;
222
+ const top = { ...env, [RUN_STEP_ENV]: '' };
223
+ recordRun({ type: 'start', kind, mode, sha, pid, cwd, ...sample() }, top);
224
+ let stop = () => {};
225
+ try {
226
+ stop = beat(log, runId);
227
+ } catch {
228
+ // no heartbeat: the start and end lines still bound the run
229
+ }
230
+ let ended = false;
231
+ return {
232
+ runId,
233
+ nested: false,
234
+ end({ ok, seconds }) {
235
+ if (ended) return;
236
+ ended = true;
237
+ stop();
238
+ recordRun({ type: 'end', ok, seconds }, top);
239
+ },
240
+ };
241
+ }
242
+
243
+ const parentAlive = (pid) => {
244
+ try {
245
+ process.kill(pid, 0);
246
+ return true;
247
+ } catch (e) {
248
+ return e.code === 'EPERM';
249
+ }
250
+ };
251
+
252
+ /**
253
+ * The heartbeat loop (run-beat.mjs): every `checkMs` look at the parent;
254
+ * every `beatMs` append a `beat` sample; once the parent is gone append
255
+ * `gone` and stop. Returns the stop function.
256
+ */
257
+ export function beatLoop({
258
+ env,
259
+ pid,
260
+ alive = parentAlive,
261
+ sample = machineSample,
262
+ checkMs = 5_000,
263
+ beatMs = BEAT_MS,
264
+ every = setInterval,
265
+ cancel = clearInterval,
266
+ }) {
267
+ let since = 0;
268
+ const timer = every(() => {
269
+ if (!alive(pid)) {
270
+ recordRun({ type: 'gone' }, env);
271
+ cancel(timer);
272
+ return;
273
+ }
274
+ since += checkMs;
275
+ if (since < beatMs) return;
276
+ since = 0;
277
+ recordRun({ type: 'beat', ...sample() }, env);
278
+ }, checkMs);
279
+ return () => cancel(timer);
280
+ }
281
+
282
+ /** Every line of a run log, oldest first (torn lines skipped). */
283
+ export function readRunLog(dir) {
284
+ const file = runLogPath(dir);
285
+ if (!existsSync(file)) return [];
286
+ return readFileSync(file, 'utf8')
287
+ .split('\n')
288
+ .filter(Boolean)
289
+ .flatMap((line) => {
290
+ try {
291
+ return [JSON.parse(line)];
292
+ } catch {
293
+ return [];
294
+ }
295
+ });
296
+ }
297
+
298
+ /**
299
+ * Waits by lock over `lines` (from readRunLog) at or after `since`:
300
+ * [{ lock, count, ms, max }], the most waited first.
301
+ */
302
+ export function waitsByLock(lines, { since } = {}) {
303
+ const by = new Map();
304
+ for (const l of lines) {
305
+ if (l.type !== 'wait' || (since && l.at < since)) continue;
306
+ const e = by.get(l.lock) ?? { lock: l.lock, count: 0, ms: 0, max: 0 };
307
+ e.count += 1;
308
+ e.ms += l.ms ?? 0;
309
+ e.max = Math.max(e.max, l.ms ?? 0);
310
+ by.set(l.lock, e);
311
+ }
312
+ return [...by.values()].sort((a, b) => b.ms - a.ms);
313
+ }