basalt-ui 2.17.0 → 2.18.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 (69) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/MIGRATING.md +44 -12
  3. package/agent/skills/basalt-design/SKILL.md +1 -1
  4. package/dist/cli/help.d.ts +1 -0
  5. package/dist/cli/help.d.ts.map +1 -1
  6. package/dist/cli/help.js +8 -2
  7. package/dist/cli/shot/capture.d.ts +12 -1
  8. package/dist/cli/shot/capture.d.ts.map +1 -1
  9. package/dist/cli/shot/capture.js +72 -10
  10. package/dist/cli/shot/index.d.ts +10 -1
  11. package/dist/cli/shot/index.d.ts.map +1 -1
  12. package/dist/cli/shot/index.js +40 -5
  13. package/dist/cli/shot/real-data.d.ts +35 -0
  14. package/dist/cli/shot/real-data.d.ts.map +1 -0
  15. package/dist/cli/shot/real-data.js +120 -0
  16. package/dist/cli/shot/serve.d.ts +2 -2
  17. package/dist/cli/shot/serve.d.ts.map +1 -1
  18. package/dist/cli/shot/serve.js +16 -2
  19. package/dist/dashboard/bar-list.d.ts +29 -0
  20. package/dist/dashboard/bar-list.d.ts.map +1 -0
  21. package/dist/dashboard/bar-list.js +52 -0
  22. package/dist/dashboard/bar-list.module.css +73 -0
  23. package/dist/dashboard/bar-list.module.css.d.ts +16 -0
  24. package/dist/dashboard/index.d.ts +2 -0
  25. package/dist/dashboard/index.d.ts.map +1 -1
  26. package/dist/dashboard/index.js +4 -0
  27. package/dist/dashboard/meter-model.d.ts +78 -0
  28. package/dist/dashboard/meter-model.d.ts.map +1 -0
  29. package/dist/dashboard/meter-model.js +91 -0
  30. package/dist/dashboard/meter-parts.d.ts +42 -0
  31. package/dist/dashboard/meter-parts.d.ts.map +1 -0
  32. package/dist/dashboard/meter-parts.js +163 -0
  33. package/dist/dashboard/meter.d.ts +112 -0
  34. package/dist/dashboard/meter.d.ts.map +1 -0
  35. package/dist/dashboard/meter.js +43 -0
  36. package/dist/dashboard/meter.module.css +150 -0
  37. package/dist/dashboard/meter.module.css.d.ts +28 -0
  38. package/dist/dashboard/scale.d.ts +9 -0
  39. package/dist/dashboard/scale.d.ts.map +1 -0
  40. package/dist/dashboard/scale.js +10 -0
  41. package/dist/index.d.ts +1 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +5 -1
  44. package/dist/tokens/derive.d.ts +11 -1
  45. package/dist/tokens/derive.d.ts.map +1 -1
  46. package/dist/tokens/derive.js +9 -24
  47. package/dist/tokens/status-text.d.ts +26 -0
  48. package/dist/tokens/status-text.d.ts.map +1 -0
  49. package/dist/tokens/status-text.js +68 -0
  50. package/llms.txt +32 -3
  51. package/package.json +1 -1
  52. package/src/cli/help.ts +22 -2
  53. package/src/cli/shot/capture.ts +98 -9
  54. package/src/cli/shot/index.ts +50 -4
  55. package/src/cli/shot/real-data.ts +165 -0
  56. package/src/cli/shot/serve.ts +28 -3
  57. package/src/dashboard/bar-list.module.css +73 -0
  58. package/src/dashboard/bar-list.module.css.d.ts +16 -0
  59. package/src/dashboard/bar-list.tsx +112 -0
  60. package/src/dashboard/index.ts +2 -0
  61. package/src/dashboard/meter-model.ts +161 -0
  62. package/src/dashboard/meter-parts.tsx +223 -0
  63. package/src/dashboard/meter.module.css +150 -0
  64. package/src/dashboard/meter.module.css.d.ts +28 -0
  65. package/src/dashboard/meter.tsx +162 -0
  66. package/src/dashboard/scale.ts +13 -0
  67. package/src/index.ts +4 -0
  68. package/src/tokens/derive.ts +19 -31
  69. package/src/tokens/status-text.ts +85 -0
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Status text solver — the `--vx-status-good|warn|bad` solids are painted as TEXT (`DeltaBadge`,
3
+ * a toned breakdown row), so each must clear WCAG AA on every text surface of the palette it ships
4
+ * in. The calibrated stops below are kept unchanged when they already clear every surface (the
5
+ * default config); otherwise each walks along its lightness axis only — light darkens, dark
6
+ * lightens, hue preserved (chroma may clip at the gamut edge) — to the first tone that does.
7
+ */
8
+ import type { ColorPair } from './core.js';
9
+ import type { StatusKey, SurfaceKey } from './derive.js';
10
+ type Side = 'light' | 'dark';
11
+ type Stop = {
12
+ readonly tone: number;
13
+ readonly chroma: number;
14
+ };
15
+ export declare const STATUS_HUE: Readonly<Record<StatusKey, number>>;
16
+ export declare const STATUS_STOP: Readonly<Record<StatusKey, Readonly<Record<Side, Stop>>>>;
17
+ /** The surfaces status text is painted on — exhaustive, so a new `SurfaceKey` must pick a side. */
18
+ export declare const STATUS_TEXT_SURFACES: Readonly<Record<SurfaceKey, boolean>>;
19
+ export declare const STATUS_TEXT_CONTRAST_MIN = 4.5;
20
+ export declare const STATUS_TONE_STEP = 0.25;
21
+ /** The hex at the `step`-th tone from `stop` along the side's lightness axis (0 = the stop). */
22
+ export declare function statusHexAtStep(key: StatusKey, side: Side, step: number): string;
23
+ /** The three status solids for a derived palette's surfaces. */
24
+ export declare function deriveStatusHexes(surfaces: Record<SurfaceKey, ColorPair>): Record<StatusKey, ColorPair>;
25
+ export {};
26
+ //# sourceMappingURL=status-text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status-text.d.ts","sourceRoot":"","sources":["../../src/tokens/status-text.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AACvC,OAAO,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAGrD,KAAK,IAAI,GAAG,OAAO,GAAG,MAAM,CAAA;AAC5B,KAAK,IAAI,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAE9D,eAAO,MAAM,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAI1D,CAAA;AAED,eAAO,MAAM,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAIjF,CAAA;AAED,mGAAmG;AACnG,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAStE,CAAA;AAED,eAAO,MAAM,wBAAwB,MAAM,CAAA;AAC3C,eAAO,MAAM,gBAAgB,OAAO,CAAA;AAOpC,gGAAgG;AAChG,wBAAgB,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAQhF;AAoBD,gEAAgE;AAChE,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,CAAC,GACtC,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,CAM9B"}
@@ -0,0 +1,68 @@
1
+ import { contrastRatio, hctToHex } from "./hct.js";
2
+ const STATUS_HUE = {
3
+ good: 151.975,
4
+ warn: 76.64,
5
+ bad: 29.905
6
+ };
7
+ const STATUS_STOP = {
8
+ good: { light: { tone: 45.75, chroma: 37.75 }, dark: { tone: 70.23, chroma: 53.23 } },
9
+ warn: { light: { tone: 46, chroma: 61.12 }, dark: { tone: 72.34, chroma: 62.55 } },
10
+ bad: { light: { tone: 43.86, chroma: 54.46 }, dark: { tone: 66.5, chroma: 53.79 } }
11
+ };
12
+ const STATUS_TEXT_SURFACES = {
13
+ bg: true,
14
+ panel: true,
15
+ panelHover: true,
16
+ elevated: true,
17
+ subtle: true,
18
+ field: true,
19
+ border: false,
20
+ hairline: false
21
+ };
22
+ const STATUS_TEXT_CONTRAST_MIN = 4.5;
23
+ const STATUS_TONE_STEP = 0.25;
24
+ const TEXT_SURFACE_KEYS = Object.keys(STATUS_TEXT_SURFACES).filter(
25
+ (key) => STATUS_TEXT_SURFACES[key]
26
+ );
27
+ const STATUS_KEYS = Object.keys(STATUS_HUE);
28
+ function statusHexAtStep(key, side, step) {
29
+ const stop = STATUS_STOP[key][side];
30
+ const direction = side === "light" ? -1 : 1;
31
+ return hctToHex({
32
+ hue: STATUS_HUE[key],
33
+ chroma: stop.chroma,
34
+ tone: stop.tone + direction * step * STATUS_TONE_STEP
35
+ });
36
+ }
37
+ function clearsEverySurface(hex, side, surfaces) {
38
+ return TEXT_SURFACE_KEYS.every(
39
+ (key) => contrastRatio(hex, surfaces[key][side]) >= STATUS_TEXT_CONTRAST_MIN
40
+ );
41
+ }
42
+ function solve(key, side, surfaces) {
43
+ const { tone } = STATUS_STOP[key][side];
44
+ const maxSteps = Math.floor((side === "light" ? tone : 100 - tone) / STATUS_TONE_STEP);
45
+ for (let step = 0; step <= maxSteps; step++) {
46
+ const hex = statusHexAtStep(key, side, step);
47
+ if (clearsEverySurface(hex, side, surfaces)) return hex;
48
+ }
49
+ throw new Error(
50
+ `status text: no ${side} ${key} tone reaches ${STATUS_TEXT_CONTRAST_MIN}:1 on every surface`
51
+ );
52
+ }
53
+ function deriveStatusHexes(surfaces) {
54
+ const status = {};
55
+ for (const key of STATUS_KEYS) {
56
+ status[key] = { light: solve(key, "light", surfaces), dark: solve(key, "dark", surfaces) };
57
+ }
58
+ return status;
59
+ }
60
+ export {
61
+ STATUS_HUE,
62
+ STATUS_STOP,
63
+ STATUS_TEXT_CONTRAST_MIN,
64
+ STATUS_TEXT_SURFACES,
65
+ STATUS_TONE_STEP,
66
+ deriveStatusHexes,
67
+ statusHexAtStep
68
+ };
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v2.17.0
1
+ # basalt-ui v2.18.0
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets
3
3
  #
4
4
  # Entry points: use the exact import specifier below; do not guess.
@@ -13,13 +13,24 @@
13
13
  # A subpath's `Install:` line is its required peers; `OptionalPeers:` are import()-only, install on use.
14
14
 
15
15
  Package: basalt-ui
16
- Version: 2.17.0
16
+ Version: 2.18.0
17
17
 
18
18
  ## basalt-ui
19
19
  Import: import { ... } from 'basalt-ui'
20
20
  Description: Wiring (`BasaltProvider`, `createBasaltTheme`, `createBasaltRouter`, `unwrap`), shell + nav (`BasaltShell`, `PageBar`, `PageAside`, `PageTitle`, `ThemeToggle`, `defineNav`/`navGroup`/`navTarget`/`flattenNav`, `useBasaltNav`, `useSizeClass`, `useCoarsePointer`), dashboard (`Section`, `WidgetHeader`, `StatCard`, `StatGroup`, `DeltaBadge`, `EmptyState`, `SettingsSection`/`SettingsRow`/`DangerZone`). Reaches no subpath-required peer.
21
21
  Layer: mantine-coupled
22
22
  Rule: basalt-mantine
23
+ Signature: BarList(props: BarListProps): JSX.Element
24
+ className?: string
25
+ style?: CSSProperties
26
+ label: string
27
+ items: readonly BarListItem[]
28
+ format?: (value: number) => string
29
+ max?: number
30
+ accentLeader?: boolean
31
+ loading?: boolean
32
+ loadingRows?: number
33
+ emptyText?: string
23
34
  Signature: BasaltProvider(props: BasaltProviderProps): JSX.Element
24
35
  one of: router | children
25
36
  theme?: PartialObjectDeep<MantineTheme, { recurseIntoArrays: false;…
@@ -80,6 +91,24 @@ Signature: EmptyState(props: EmptyStateProps): JSX.Element
80
91
  description?: string
81
92
  action?: ReactNode
82
93
  tier?: "section" | "page"
94
+ Signature: Meter(props: MeterProps): JSX.Element
95
+ className?: string
96
+ style?: CSSProperties
97
+ label: string
98
+ min?: number
99
+ max?: number
100
+ format?: (value: number) => string
101
+ loading?: boolean
102
+ emptyText?: string
103
+ shape?: "bar" | "ring"
104
+ target?: number [with segments | zones]
105
+ startCaption?: ReactNode [with segments | zones]
106
+ endCaption?: ReactNode [with segments | zones]
107
+ value?: number | null [with zones]
108
+ color?: string
109
+ segments: readonly MeterSegment[]
110
+ zones: readonly MeterZone[]
111
+ forecastCaption?: string [with segments]
83
112
  Signature: PageAside(props: PageAsideProps): ReactNode
84
113
  className?: string
85
114
  style?: CSSProperties
@@ -426,7 +455,7 @@ Signature: Sparkline(props: SparklineProps): ReactElement<unknown, string | JSXE
426
455
  data: readonly number[]
427
456
  height: number
428
457
  width?: number
429
- mark?: "line" | "bar"
458
+ mark?: "bar" | "line"
430
459
  color?: string
431
460
  emphasizeLast?: boolean
432
461
  emphasisColor?: string
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "2.17.0",
3
+ "version": "2.18.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
package/src/cli/help.ts CHANGED
@@ -12,7 +12,10 @@
12
12
  */
13
13
  import { parseArgs } from 'node:util'
14
14
 
15
- export const COMMAND_OPTIONS: Record<string, Record<string, { type: 'string' | 'boolean' }>> = {
15
+ export const COMMAND_OPTIONS: Record<
16
+ string,
17
+ Record<string, { type: 'string' | 'boolean'; multiple?: boolean }>
18
+ > = {
16
19
  init: {
17
20
  'no-merge-lint': { type: 'boolean' },
18
21
  },
@@ -48,6 +51,12 @@ export const COMMAND_OPTIONS: Record<string, Record<string, { type: 'string' | '
48
51
  dist: { type: 'string' },
49
52
  out: { type: 'string' },
50
53
  states: { type: 'string' },
54
+ 'local-storage': { type: 'string', multiple: true },
55
+ api: { type: 'string', multiple: true },
56
+ header: { type: 'string', multiple: true },
57
+ wait: { type: 'string' },
58
+ 'auto-anchors': { type: 'boolean' },
59
+ 'api-allow-writes': { type: 'boolean' },
51
60
  },
52
61
  }
53
62
 
@@ -92,7 +101,18 @@ export const USAGE =
92
101
  ' Render routes in Chromium (Playwright from YOUR project: bun add -d playwright) and write\n' +
93
102
  ' board.html, metrics.json and png/* — every data-shot anchor × light/dark × desktop/mobile ×\n' +
94
103
  ' rest, hover, focus, tooltip, empty, loading, error. --dist serves a built SPA dir itself.\n' +
95
- ' Default --out .basalt/shots (emptied each run); .basalt/shots/last.json names the last out dir.\n\n' +
104
+ ' Default --out .basalt/shots (emptied each run); .basalt/shots/last.json names the last out dir.\n' +
105
+ ' A real, signed-in app: [--local-storage <key>=<@env:NAME|@file:path>]… seeds localStorage (app origin\n' +
106
+ ' only) before any page script; [--api <prefix>=<origin>]… (with --dist) proxies GET/HEAD under that\n' +
107
+ ' prefix to the origin (other methods get 405 unless --api-allow-writes); [--header <name>=@env:NAME]… is\n' +
108
+ ' added to every proxied request, to EVERY --api origin (never on a navigation; https required);\n' +
109
+ ' [--wait <ms|networkidle>] adds ms of settle AFTER networkidle (default none); [--auto-anchors] crops\n' +
110
+ ' each Card, Paper and table over 120×60 px on a page with no data-shot. Values are never printed or\n' +
111
+ ' written; a redirect, 401/403/404, 5xx or dead API fails every shot of that page. Shots of real data go to the\n' +
112
+ ' reviewer subagent and so to its model provider: point --api at staging or synthetic data when the\n' +
113
+ " app holds other people's data. Example:\n" +
114
+ ' basalt-ui shot /overview --dist dist --api /api=https://app.example.com \\\n' +
115
+ ' --local-storage auth-token=@env:APP_TOKEN --header authorization=@env:APP_BEARER --auto-anchors\n\n' +
96
116
  'doctor [--tokens-only|--framework]\n' +
97
117
  ' Checks THIS project only: the manifest exists, the oxlint preset is wired, the pre-commit\n' +
98
118
  ' hook runs check-theme (via `lefthook dump`), and the ai package major is consistent within\n' +
@@ -4,6 +4,8 @@ import { readFileSync } from 'node:fs'
4
4
  import { basename, join } from 'node:path'
5
5
 
6
6
  import { buildSheet } from './board'
7
+ import { SEED_FLAG, seedScript } from './real-data'
8
+ import type { Pair } from './real-data'
7
9
 
8
10
  import { finishMeasurement, measureAnchor } from './measure'
9
11
  import type { Box, PwBrowser, PwContext, PwLocator, PwPage, ShotOptions } from './playwright'
@@ -33,6 +35,14 @@ export type CaptureInput = {
33
35
  routes: readonly string[]
34
36
  states: readonly ShotState[]
35
37
  pngDir: string
38
+ /** Seeded before any page script runs (values may be secrets: never logged or written). */
39
+ localStorage?: readonly Pair[]
40
+ /** Extra settle in ms after `networkidle`; omitted: none. */
41
+ wait?: number
42
+ /** Drains the proxied calls that failed since the last read (401/403, no answer). */
43
+ apiProblems?: () => string[]
44
+ /** On a page with no `data-shot`, tag each large Card, Paper and table as an anchor. */
45
+ autoAnchors?: boolean
36
46
  /** Replaces the in-page measurer (tests). */
37
47
  measure?: (anchor: PwLocator) => Promise<Measurement>
38
48
  log: (line: string) => void
@@ -51,6 +61,8 @@ type Ctx = {
51
61
  anchors: AnchorMetrics[]
52
62
  shots: ShotRecord[]
53
63
  measured: Set<string>
64
+ /** What the last visit showed to be wrong about the data itself: a failed seed, a 401/403, no API answer. */
65
+ problems: string[]
54
66
  /** Read on the first page of a context that loads. */
55
67
  scale?: Steps | undefined
56
68
  scaleError?: string | undefined
@@ -124,9 +136,20 @@ function record(c: Ctx, { name, state, status, file, note }: Outcome): void {
124
136
  c.input.log(`[shot] ${route} ${name} ${scheme}/${viewport}/${state}: ${note}`)
125
137
  }
126
138
 
127
- async function load(page: PwPage, url: string): Promise<void> {
139
+ async function load(page: PwPage, url: string, settle = 0): Promise<void> {
128
140
  await page.goto(url, { waitUntil: 'networkidle' })
129
141
  await page.evaluate('document.fonts.ready.then(() => undefined)')
142
+ if (settle > 0) await new Promise((done) => setTimeout(done, settle))
143
+ }
144
+
145
+ /** Runs in the page: numbers every Card, Paper and table in DOM order, tagging those over 120×60 px as anchors. */
146
+ export function tagAutoAnchors(): void {
147
+ const found = document.querySelectorAll('.mantine-Card-root, .mantine-Paper-root, table')
148
+ Array.from(found).forEach((el, i) => {
149
+ const { width, height } = el.getBoundingClientRect()
150
+ if (width > 120 && height > 60)
151
+ el.setAttribute('data-shot', `auto-${String(i + 1).padStart(2, '0')}`)
152
+ })
130
153
  }
131
154
 
132
155
  const readFacts = (page: PwPage): Promise<PageFacts> =>
@@ -135,6 +158,54 @@ const readFacts = (page: PwPage): Promise<PageFacts> =>
135
158
  declared: [...document.querySelectorAll('[data-shot-states]')].flatMap((e) => (e.getAttribute('data-shot-states') ?? '').split(/\\s+/)).filter(Boolean),
136
159
  }))()`)
137
160
 
161
+ const addProblem = (c: Ctx, problem: string): void => {
162
+ if (!c.problems.includes(problem)) c.problems.push(problem)
163
+ }
164
+
165
+ /** Moves the proxied calls that failed since the last read into this page visit's problems. */
166
+ const collect = (c: Ctx): void => {
167
+ for (const problem of c.input.apiProblems?.() ?? []) addProblem(c, problem)
168
+ }
169
+
170
+ /**
171
+ * One load of `url`: settle, auto-anchor a page that declares none, read its facts, and collect
172
+ * what is wrong with the data (`c.problems`) so a board never looks fine over a failed login.
173
+ */
174
+ async function visit(c: Ctx, url: string): Promise<PageFacts> {
175
+ const { input, page } = c
176
+ await load(page, url, input.wait)
177
+ let facts = await readFacts(page)
178
+ if (input.autoAnchors && facts.anchors.length === 0) {
179
+ await page.evaluate(tagAutoAnchors, undefined)
180
+ facts = await readFacts(page)
181
+ }
182
+ collect(c)
183
+ if (input.localStorage?.length) {
184
+ const failed = await page.evaluate<unknown>(`globalThis.${SEED_FLAG} ?? ''`)
185
+ if (failed === 'origin') {
186
+ input.log(`[shot] ${c.route}: page left the app origin; not seeded`)
187
+ } else if (typeof failed === 'string' && failed !== '') {
188
+ addProblem(c, `localStorage seed failed (${failed})`)
189
+ input.log(`[shot] ${c.route}: localStorage seed failed (${failed})`)
190
+ }
191
+ }
192
+ return facts
193
+ }
194
+
195
+ /**
196
+ * When this page visit's data is untrustworthy, every shot of it (page and anchors, every state)
197
+ * becomes an error carrying the problem; a page shot is added when `rest` was not requested.
198
+ */
199
+ function flagProblems(c: Ctx): void {
200
+ if (c.problems.length === 0) return
201
+ const note = c.problems.join('; ')
202
+ for (const shot of c.shots)
203
+ if (shot.status === 'ok') Object.assign(shot, { status: 'error', note })
204
+ if (!c.shots.some((s) => s.name === PAGE_ANCHOR && s.state === 'rest'))
205
+ record(c, { name: PAGE_ANCHOR, state: 'rest', status: 'error', note })
206
+ c.input.log(`[shot] ${c.route} ${c.scheme}/${c.viewport}: ${note}`)
207
+ }
208
+
138
209
  /** Brings the anchor into view; throws when it is absent, hidden or off-screen at this viewport. */
139
210
  async function reveal(anchor: PwLocator): Promise<void> {
140
211
  if ((await anchor.count()) === 0) throw new Error('anchor not found')
@@ -398,8 +469,7 @@ async function captureUrlState(c: Ctx, state: ShotState): Promise<void> {
398
469
  }
399
470
  let here: PageFacts
400
471
  try {
401
- await load(c.page, c.input.base + withParam(c.route, state))
402
- here = await readFacts(c.page)
472
+ here = await visit(c, c.input.base + withParam(c.route, state))
403
473
  } catch (error) {
404
474
  for (const name of restNames)
405
475
  record(c, { name, state, status: 'error', note: `load failed: ${firstLine(error)}` })
@@ -501,7 +571,7 @@ export function groupScale({ mantine, vx }: ScaleRead): Steps {
501
571
  }
502
572
 
503
573
  async function capturePage(
504
- args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured'> & { wantScale: boolean },
574
+ args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured' | 'problems'> & { wantScale: boolean },
505
575
  ) {
506
576
  const { wantScale, ...rest } = args
507
577
  const c: Ctx = {
@@ -510,11 +580,12 @@ async function capturePage(
510
580
  anchors: [],
511
581
  shots: [],
512
582
  measured: new Set(),
583
+ problems: [],
513
584
  }
514
585
  const { input, route } = c
586
+ input.apiProblems?.() // calls still in flight from an earlier route are not this page's
515
587
  try {
516
- await load(c.page, input.base + route)
517
- c.facts = await readFacts(c.page)
588
+ c.facts = await visit(c, input.base + route)
518
589
  } catch (error) {
519
590
  record(c, {
520
591
  name: PAGE_ANCHOR,
@@ -544,12 +615,20 @@ async function capturePage(
544
615
  snap(c.page, path, { fullPage: true }).then(() => undefined),
545
616
  )
546
617
  }
618
+ flagProblems(c)
547
619
  for (const name of usable) {
548
620
  for (const [state, capture] of Object.entries(POINTER_STATES)) {
549
- if (input.states.includes(state as ShotState)) await capture(c, name)
621
+ if (!input.states.includes(state as ShotState)) continue
622
+ await capture(c, name)
623
+ collect(c)
550
624
  }
551
625
  }
552
- for (const state of URL_STATES) if (input.states.includes(state)) await captureUrlState(c, state)
626
+ for (const state of URL_STATES) {
627
+ if (!input.states.includes(state)) continue
628
+ await captureUrlState(c, state)
629
+ collect(c)
630
+ }
631
+ flagProblems(c)
553
632
  return c
554
633
  }
555
634
 
@@ -558,6 +637,8 @@ export async function openContext<C extends PwContext>(
558
637
  browser: PwBrowser<C>,
559
638
  scheme: Scheme,
560
639
  viewport: Viewport,
640
+ seeded: readonly Pair[] = [],
641
+ origin = '',
561
642
  ): Promise<C> {
562
643
  const spec = VIEWPORT_SPECS[viewport]
563
644
  const context = await browser.newContext({
@@ -569,6 +650,7 @@ export async function openContext<C extends PwContext>(
569
650
  reducedMotion: 'reduce',
570
651
  })
571
652
  await context.addInitScript(`localStorage.setItem('mantine-color-scheme-value', '${scheme}')`)
653
+ if (seeded.length > 0) await context.addInitScript(seedScript(seeded, origin))
572
654
  return context
573
655
  }
574
656
 
@@ -644,7 +726,14 @@ export async function capture(input: CaptureInput): Promise<{
644
726
  }
645
727
  for (const scheme of SCHEMES) {
646
728
  for (const viewport of VIEWPORTS) {
647
- const context = await openContext(input.browser, scheme, viewport)
729
+ input.apiProblems?.() // a new context starts with a clean queue
730
+ const context = await openContext(
731
+ input.browser,
732
+ scheme,
733
+ viewport,
734
+ input.localStorage,
735
+ new URL(input.base).origin,
736
+ )
648
737
  try {
649
738
  const page = await context.newPage()
650
739
  page.setDefaultTimeout(NAV_TIMEOUT_MS)
@@ -21,6 +21,8 @@ import { buildBoard } from './board'
21
21
  import { capture } from './capture'
22
22
  import { INSTALL_LINE, ShotError, resolvePlaywright, withBrowser } from './playwright'
23
23
  import type { Playwright, PlaywrightResolver } from './playwright'
24
+ import { apiProxy, parseApi, parseHeaders, parseStorage } from './real-data'
25
+ import type { ApiRoute, Pair, Source } from './real-data'
24
26
  import { serveDist } from './serve'
25
27
  import { SCHEMES, STATES, VIEWPORTS } from './types'
26
28
  import type { ShotMetrics, ShotState } from './types'
@@ -29,7 +31,7 @@ const HOME = '.basalt/shots'
29
31
  /** A run dir under the home, so `last.json` and a named run's dir never share the default out. */
30
32
  const DEFAULT_OUT = `${HOME}/latest`
31
33
  const USAGE_LINE =
32
- 'usage: basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>]'
34
+ 'usage: basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>] [--local-storage k=@env:X] [--api /p=origin] [--header n=@env:X] [--api-allow-writes] [--wait ms] [--auto-anchors]'
33
35
 
34
36
  export type ShotDeps = {
35
37
  resolve?: PlaywrightResolver
@@ -45,10 +47,21 @@ export type ShotArgs = {
45
47
  dist?: string
46
48
  out: string
47
49
  states: ShotState[]
50
+ /** Resolved secrets: held for the browser only, never written anywhere. */
51
+ localStorage: Pair[]
52
+ api: ApiRoute[]
53
+ headers: Pair[]
54
+ /** Extra settle in ms after networkidle. */
55
+ wait: number
56
+ allowWrites: boolean
57
+ autoAnchors: boolean
48
58
  }
49
59
 
50
60
  /** Parses argv; throws `ShotError` with the one-line reason. */
51
- export function parseShotArgs(flags: readonly string[]): ShotArgs {
61
+ export function parseShotArgs(
62
+ flags: readonly string[],
63
+ src: Source = { env: process.env, cwd: process.cwd() },
64
+ ): ShotArgs {
52
65
  let parsed
53
66
  try {
54
67
  parsed = parseArgs({
@@ -59,6 +72,12 @@ export function parseShotArgs(flags: readonly string[]): ShotArgs {
59
72
  dist: { type: 'string' },
60
73
  out: { type: 'string' },
61
74
  states: { type: 'string' },
75
+ 'local-storage': { type: 'string', multiple: true },
76
+ api: { type: 'string', multiple: true },
77
+ header: { type: 'string', multiple: true },
78
+ wait: { type: 'string' },
79
+ 'auto-anchors': { type: 'boolean' },
80
+ 'api-allow-writes': { type: 'boolean' },
62
81
  },
63
82
  })
64
83
  } catch (error) {
@@ -80,8 +99,27 @@ export function parseShotArgs(flags: readonly string[]): ShotArgs {
80
99
  : [...STATES]
81
100
  const unknown = states.find((s) => !(STATES as readonly string[]).includes(s))
82
101
  if (unknown) throw new ShotError(`unknown state '${unknown}'. Known: ${STATES.join(', ')}`)
102
+ const secrets = (values.header?.length ?? 0) + (values['local-storage']?.length ?? 0) > 0
103
+ const api = parseApi(values.api ?? [], secrets)
104
+ if (api.length > 0 && !values.dist)
105
+ throw new ShotError(`--api needs --dist (it proxies the static server).\n${USAGE_LINE}`)
106
+ if ((values.header?.length ?? 0) > 0 && new Set(api.map((r) => r.origin)).size > 1)
107
+ throw new ShotError(
108
+ `--header goes to every --api origin; it is refused when --api names more than one.\n${USAGE_LINE}`,
109
+ )
110
+ if ((values.header?.length ?? 0) > 0 && api.length === 0)
111
+ throw new ShotError(`--header is sent on --api requests only; pass --api.\n${USAGE_LINE}`)
112
+ const wait = values.wait ?? 'networkidle'
113
+ if (wait !== 'networkidle' && !/^\d+$/.test(wait))
114
+ throw new ShotError(`--wait takes milliseconds or 'networkidle'.\n${USAGE_LINE}`)
83
115
  return {
84
116
  routes: positionals,
117
+ localStorage: parseStorage(values['local-storage'] ?? [], src),
118
+ api,
119
+ headers: parseHeaders(values.header ?? [], src),
120
+ wait: wait === 'networkidle' ? 0 : Number(wait),
121
+ allowWrites: values['api-allow-writes'] ?? false,
122
+ autoAnchors: values['auto-anchors'] ?? false,
85
123
  ...(values.base ? { base: values.base.replace(/\/+$/, '') } : {}),
86
124
  ...(values.dist ? { dist: values.dist } : {}),
87
125
  out: values.out ?? DEFAULT_OUT,
@@ -284,14 +322,18 @@ export async function shot(
284
322
  const stops: (() => unknown)[] = []
285
323
  const uninstall = exitOnSignal(stops)
286
324
  try {
287
- const args = parseShotArgs(flags)
325
+ const args = parseShotArgs(flags, { env: process.env, cwd })
288
326
  const outDir = planOut(cwd, args.out)
289
327
  recoverOut(outDir)
290
328
  const pw: Playwright | null = (deps.resolve ?? resolvePlaywright)(cwd)
291
329
  if (!pw) throw new ShotError(INSTALL_LINE)
292
330
  const now = (deps.now ?? (() => new Date()))()
293
331
  sweepStaleTmp(join(cwd, HOME), now)
294
- const server = args.dist ? serveDist(resolve(cwd, args.dist)) : null
332
+ const proxy =
333
+ args.api.length > 0
334
+ ? apiProxy(args.api, args.headers, { log, allowWrites: args.allowWrites })
335
+ : null
336
+ const server = args.dist ? serveDist(resolve(cwd, args.dist), proxy?.handle) : null
295
337
  if (server) stops.push(server.stop)
296
338
  let tmp = ''
297
339
  stops.push(() => tmp && rmSync(tmp, { recursive: true, force: true }))
@@ -313,6 +355,10 @@ export async function shot(
313
355
  routes: args.routes,
314
356
  states: args.states,
315
357
  pngDir: join(tmp, 'png'),
358
+ localStorage: args.localStorage,
359
+ wait: args.wait,
360
+ autoAnchors: args.autoAnchors,
361
+ ...(proxy && { apiProblems: proxy.drain }),
316
362
  log,
317
363
  })
318
364
  },