strata-react 1.1.0 → 1.1.2

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.
package/README.md CHANGED
@@ -156,7 +156,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
156
156
  | Compare | `Compare`, `PairVote`, `PairJudge`, `CompareAudio`, `CompareText`, `CompareGrid`, `CompareVideoGrid`, `ViewportFrame`, `useViewport`, `FullscreenFrame`, `useDifference`, `differences` | Two pictures judged together: side by side, swipe (a divider that moves from the keyboard), fade, blink (`x` flips) and difference (a live difference blend with amplify, or pixelmatch's changed pixels with a tolerance and the share that differ; pixels are read only when that view is open, at most 2048 px on the long side, and a picture the browser will not let the page read says so in words); `maxHeight="fit"` measures the window for the pair and its surroundings instead of the `"viewport"` guess; `CompareGrid` is every candidate at once with the same zoom and full screen, and `actions` for what a tile offers; one zoom and pan for both sides (buttons, `+` `-` `0`, Ctrl-wheel or trackpad pinch, drag, arrow keys, double click, `1:1`), and full screen (the browser's Fullscreen API, a modal where there is none). `blind` is required: a blind comparison names pictures by `label` only and never writes the variant `id`, `note` or `alt`. A picture that fails shows the required `missing` words in its place; the keys come from one `Shortcut[]` shared with `KeysLegend`, and `keys={false}` leaves them to a surrounding screen. `PairVote` wraps `Compare` for a blind pairwise judgment: answer keys `a` `b` `t` `s` in Compare's one legend, a vote bar with no filled button, `pending`, a flag menu, a progress line, preload and Undo, and click to choose (a click on the picture you prefer, not a drag or double click; in swipe the side of the divider, in blink the side showing, none in fade or difference; `onPick` on `Compare` and `CompareVideo`, `pick={false}` turns it off). `CompareAudio` is one transport for two clips with an A/B switch that keeps the playhead (same time, or the same share when the lengths differ), a loop range and loudness matching (the louder clip turned down to the quieter, by RMS); `CompareText` is two texts scrolled together with a word diff and an optional reference; `PairJudge` is the answering around any of them; `CompareVideo` is two videos on one clock (play, pause, seek and speed drive both, the follower kept within a frame, both held while either waits for data) in side by side, swipe, fade and blink, with zoom and pan locked and nearest-neighbour pixels past 1:1, candidates of different sizes drawn in one box, one soundtrack (`audio`), and the same slots as the rest. `autoPlay` starts the pair once both can play (muted; not with reduced motion unless `"always"`) and `loopWhole` loops the whole clip when no range is set (also on `CompareVideoGrid`). Frame by frame (`,` `.`), a loop range the app can hold (`i` `o` `c`), speeds down to 0.1 and named `moments` are in it; `CompareVideoGrid` is every candidate's video at once on that one clock (one transport, one zoom, regions, a loop, stepping), light on the browser (metadata only until the first play, cells out of sight paused and left out of the sync, sound off unless `audio` names a cell, a cell that falls behind marked "Catching up"), with an optional `reference` drawn first, never blind and nearest-neighbour. `regions` (on `Compare`, `CompareVideo` and `CompareGrid`) names boxes in the source's coordinates to look at enlarged: chips, keys `q` `w` `e` `r` `y` `u`, nearest-neighbour drawing, the box outlined while its chip is pointed at, and Shift-drag to make another |
157
157
  | Selection | `useSelection`, `useChoices`, `BulkBar`, `SelectableGrid`, `DataTable`'s `selection` (`RowSelection<T>`) | Opt-in checkbox column with "Select all shown" that respects `isSelectable`; Shift-click or Shift+Space chooses or clears the run from the last row clicked, in the order shown; `initial` (keys or a test on the row) chooses a row the first time it appears, so it applies to data that loads later; the selection drops rows that are gone; `BulkBar` announces the count politely, and while it is up its one filled action is the view's only one (the screen's primary goes to `outline`); `SelectableGrid` is the same selection as a grid of pictures (`renderImage`), each tile one labelled target, virtualised from 100 tiles; as a photo grid it takes a pixel `tileSize` zoomed by Ctrl/Cmd+wheel, `+` and `-` and two-finger pinch (`onTileSizeChange`), `aspect="natural"` (rows of equal height, each picture at its `naturalAspect`), a marquee from between tiles, `selectionMode` and `selectionBehavior` (`replace` is the Finder's rules; `onAction` opens), `groupBy` (sticky headings with a group box and a fold), a corner `badge`, `unselectableReason`, and counts what a filter hides ("3 chosen are hidden by the filter"); `ViewOptions` with `useViewOptions` is the one toolbar for how it is looked at: sort (natural order, direction named for the key), group, size slider, aspect, grid or list and a filter with its count, kept in `localStorage` and optionally `?sort=…&group=…&size=…`, a "View" popover on a phone. A choice can imply others: `implies(key)` (on `useSelection`, and `useChoices` for a lazy tree) keeps what the person chose apart from what that brings in, follows it through, locks the implied keys (they only clear with what implied them), and gives `implied`, `because(key)`, `counts`, a `note` for the live region and `summary(noun, then)`, the line a destructive confirm can carry ("12 results will be forgotten: 8 chosen, 4 that depend on them") |
158
158
  | Expansion | `Disclosure`, `useExpanded`, `DataTable`'s `expansion` (`RowExpansion<T>`) | Show more of one row in place. The toggle is a button with `aria-expanded`; the body is mounted only while open, so a request inside it runs on first open (unlike `<details>`, which mounts every closed body); `useExpanded({ param })` shares the open keys across a list or table and keeps them in the URL; a table's detail row spans the data columns and is measured when virtualised |
159
- | Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `useInfiniteLoad`, `useJob`, `toLoad`, `staleOf`, `fetchJson`, `HttpError`, `readErrorBody`, `fieldErrorsOf` | TanStack Query in, `Load<T>` out; a refetch that fails after a good read stays `ready` with `stale` set, never an error panel; `useInfiniteLoad` works out the cursor itself (after the last item held), merges pages by key and can `dismiss` an item at once; `useJob` polls a job's status only while it runs and invalidates the queries it changes once, when it ends; `fetchJson` reads an error response's body onto the `HttpError` (`body`, `reason`, `fieldErrors`, read by `readErrorBody` or the API's own `readError`) |
159
+ | Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `useInfiniteLoad`, `useJob`, `toLoad`, `staleOf`, `fetchJson`, `HttpError`, `readErrorBody`, `fieldErrorsOf` | TanStack Query in, `Load<T>` out; a refetch that fails after a good read stays `ready` with `stale` set, never an error panel; `useInfiniteLoad` works out the cursor itself (after the last item held), merges pages by key and can `dismiss` an item at once; `useJob` polls a job's status only while it runs and invalidates the queries it changes once, when it ends; `fetchJson` reads an error response's body onto the `HttpError` (`body`, `reason`, `fieldErrors`, read by `readErrorBody` or the API's own `readError`); the strata apps' shared server shapes (`strata_python.contracts`): `apiPage<T>()` gives `useInfiniteLoad` the `Page<T>` items and its own `next` cursor (nothing held or dismissed changes it), `isTaskRunning(task, FINISHED)` is `useJob`'s `isRunning` for a `Task`, and an error body's `payload` (what is already running, on a 409) is on `HttpError.payload`, read typed with `errorPayload<T>(error)` |
160
160
  | Page and navigation | `AppShell`, `SideNav`, `Breadcrumb`, `Tabs`, `PageHeader`, `LinkCard`, `LinkCardList` | React Router; tab and sort state in the URL; a `LinkCard` is one link named by its title, described by its text and `Status` marks, with the whole card as the target (`to` a route, `href` elsewhere, marked with an arrow) |
161
161
  | Keyboard | `useHotkeys`, `KeysLegend`, `Shortcut`, `useActiveItem`, `ActiveList`, `isTypingTarget` | For queues worked from the keyboard; one shortcut list drives the handler and the legend; keys never fire while typing; answering moves focus to the next item |
162
162
  | Theme | `ThemeProvider`, `useColorScheme`, `useSystemColorScheme`, `ColorSchemeChoice`, `colorSchemeScript` | System, light or dark; sets `.dark`, persists in localStorage when it can; `ColorSchemeChoice` is a radio list for a settings page, or `compact` icon segments named "Appearance" for an app with no settings page |
@@ -168,7 +168,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
168
168
  | Overlays | `Dialog`, `DialogProps`, `AlertDialog`, `Popover`, `Tooltip` | React Aria underneath. A dialog always has a title and, via `actions`'s close render prop, a way out; `closable={false}` while work cannot stop; `placement="end"` is a sheet. `AlertDialog` is the only confirm: required verb on the confirm button, Cancel focused first, no outside dismiss, stays open with the reason when an async confirm fails. `Popover` needs a `label`. `Tooltip` opens on hover and focus and `IconButton` uses it. All portal onto the `layer-*` stacking utilities |
169
169
  | Value controls | `NumberField`, `Slider`, `ColorField`, `SecretField` | Set a number or colour precisely, inside `Field`. `NumberField` and `Slider` are React Aria's; the number field runs with `commitBehavior="validate"`, so a typed value outside `min`/`max` is kept on screen, explained in the `Field` ("Enter a value from 0% to 500%.") and never passed to `onChange`. A value that is not known is `null` and shows an en dash, never 0 or NaN. Digits and decimal mark follow `locale`. The unit sits inside the control, and in the slider's spoken value when `Intl` has it (%, °, ms, s, kB, MB, GB, kbps, Mbps). Arrows step, Home/End jump to the limits; `Slider editable` adds a number field. `ColorField`: platform picker, typed hex that is normalised, app suggestions, and a contrast note against `against`. No motion on value changes. `NumberField` options for a value set a little at a time or that costs work to change: `nudge={[0.1, 1, 10]}` (a toolbar of named step buttons that repeat when held and stop at the limits), `suggestion={{ value, label, reason }}` (a row with the reason in words and Use this value, never applied by itself) and `preview` (changes wait behind Apply and Revert; `onChange` is Apply's). `SecretField` is a credential the server keeps and never shows again: not set, set (no characters, no length, no input in the DOM), a masked entry with a Show toggle named for what it reveals, `onSave` through `AsyncButton`, Replace, a confirmed Remove that says what stops working, and a Test whose result is text beside it; a set, untouched field reports nothing |
170
170
  | Notices and progress | `Alert`, `toast`, `StrataToastRegion`, `useClientWork`, `JobStatus` | Three weights. A `toast` confirms finished work and goes by itself (5 s plus 40 ms a character, 8 s minimum with an action, paused under the pointer or focus, always dismissable); it has no danger tone, because an error a person must act on is an inline `Alert` with its recovery as `action` (`announce` makes it `role="alert"` only when it answers something the person just did). `StrataToastRegion` goes once at the app root. `useClientWork` runs browser work with progress, cancel (aborts its `signal`, ends `cancelled`, never `failed`) and a double-start guard; `JobStatus` shows it exactly as it shows a server job, with `onCancel`, `cancelled` and `onDismiss` |
171
- | Media player | `MediaPlayer`, `useMediaElement`, `SPEECH_RATES`, `useMediaSpans`, `SpanActions` | Play a file or a sequence of chapters without the event glue: the element, its state, Strata's controls (or the browser's own on a touch device, `controls="auto"`), a load error with Try again, `navigator.mediaSession` metadata, the seek bar spanning the whole sequence. `useMediaElement(ref)` alone follows an element drawn with the browser's controls `spans` and `spanKinds` mark stretches (an intro, a recap, a sponsor read) on the seek bar as named ranges in a status role's tone and act on them as playback reaches them: `auto` skips (or mutes, for `action: "mute"`) with "Skipped intro" and Undo, `ask` offers a Skip button over the picture and on the `s` key, `off` only draws; each is acted on once, `onSpan` reports `skipped`, `muted`, `undone` or `played`, and `SeekBar` takes `spans` too. `mediaRef` hands out the player's state and requests (an object ref holds the latest, no render of its own), `overlay` draws the app's own thing over the picture only, and a video keeps a 16:9 (or `aspect`) box before its metadata loads. The HLS attacher starts a `growing` source at its beginning, honours `config.startPosition` and takes `words` for its failures. |
171
+ | Media player | `MediaPlayer`, `useMediaElement`, `SPEECH_RATES`, `useMediaSpans`, `SpanActions` | Play a file or a sequence of chapters without the event glue: the element, its state, Strata's controls (or the browser's own on a touch device, `controls="auto"`), a load error with Try again, `navigator.mediaSession` metadata, the seek bar spanning the whole sequence. `useMediaElement(ref)` alone follows an element drawn with the browser's controls `spans` and `spanKinds` mark stretches (an intro, a recap, a sponsor read) on the seek bar as named ranges in a status role's tone and act on them as playback reaches them: `auto` skips (or mutes, for `action: "mute"`) with "Skipped intro" and Undo, `ask` offers a Skip button over the picture and on the `s` key, `off` only draws; each is acted on once, `onSpan` reports `skipped`, `muted`, `undone` or `played`, and `SeekBar` takes `spans` too. `mediaRef` hands out the player's state and requests (an object ref holds the latest, no render of its own), `overlay` draws the app's own thing over the picture only, and a video keeps a 16:9 (or `aspect`) box before its metadata loads. A video has a Full screen button and the `f` key by default (`fullscreen={false}` removes them); on the picture a click plays or pauses, a double click toggles full screen and the wheel sets the volume while the player has focus. The HLS attacher starts a `growing` source at its beginning, honours `config.startPosition` and takes `words` for its failures. |
172
172
  | Media playback | `Transport`, `SeekBar`, `TimeReadout`, `VolumeControl`, `RateChoice`, `MediaStage`, `StageGuides`, `transportShortcuts`, `format.timecode` | The controls around anything that plays, wired to a player the app owns (HTML media, Web Audio, a canvas, a data replay). Every control is a named icon button in one toolbar; the play button's name is "Play" or "Pause". `SeekBar` has the formatted time as its accessible value, arrows step 5 s and Page keys 30 s by default, and optional marks. `VolumeControl` shows its percent, and muting remembers the level. `transportShortcuts` is the one list for `useHotkeys` and `KeysLegend` (Space and K, J and L, the arrows by a frame, Home and End). `format.timecode` prints m:ss, m:ss.mmm or m:ss:ff. `MediaStage` fits a picture of any aspect ratio into the pane with a letterbox on the sunken surface role, and takes overlays such as `StageGuides` |
173
173
  | Listening and reading | `Waveform`, `TranscriptView`, `PlayWindowButton`, `MediaGroup`; `resamplePeaks`, `peaksFromAudio`, `phraseAt`, `wordAt` | Timed media: a waveform from peaks or a decoded file (one slider, marks by line style, named spans, zoom, a keyboard-made range, a spectrogram underlay); timed text that marks the heard word and plays from any word (modes, speakers, follow and Jump to now, virtualised), with doubtful words (dotted, named, counted, "Only doubtful"), a mark per phrase set from a row menu (`states`, `onPhraseState`), correction in place (Enter or F2, `onEdit`) and a hover and focus card (`renderCard`); `MediaPlayer window` plays one stretch of a file, `MediaGroup` lets one player play at a time, `PlayWindowButton` is a row's play control on a shared element; a review transcript needs no player (`time` and `onSeek` are optional), takes `marking` (words become `MarkableText` marks with ids `wordId(phraseId, index)`, selected across rows that are not mounted) and shows a corrected word (`word.correction`) dotted with the original on hover and `onCorrectionPress` to open it |
174
174
  | Streams | `MediaPlayer attach`/`growing`, `useAttachedSource`, `attachHls` (`strata-react/hls`) | A source the element cannot play is attached by an engine; a source still being made says so, shows what exists as ready, and waits at its end without ending |
@@ -186,11 +186,26 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
186
186
  | Feedback | `UndoBar`, `useUndoable`, `Done` | Undo before confirm; the hook owns which rows are out of view (`isRemoved`), a failed commit brings the row back with Try again in the same bar, and `flush()` commits before a dependent action; `Done` is the one celebration, and it must say what happens next |
187
187
  | Helpers | `cn`, `format`, `createFormat`, `NBSP` | `cn` knows `type-*`; all numbers and dates through `Intl`; `format.integer(n)`, `.decimal(n)`, `.percent(n)` are callable and keep Intl's methods; `format.bytes(n, unit?)` writes sizes in decimal units (`byteUnit` shares one unit across figures); `format.date(at)` ("8 Nov 2026") and `format.dateTime(at)` ("8 Nov 2026, 06:05"), like `clock`, `day` and `shortDay`, take a Date, ISO string or epoch ms; `format.ago(at, now?)` ("3 weeks ago"), `format.compact(n)` ("1.2k", and `count(n, one, many, { compact: true })`), `format.runningTime(seconds)` ("1:02:09") and `format.share(n)` ("<1%" for a part that rounds to 0); every number and date formatter prints the placeholder (`format.missing`, an en dash) for `null` or `undefined`; `createFormat(locale, { timeZone, missing })` fixes the zone and the placeholder; units and counts join with a non-breaking space |
188
188
  | Testing | `strata-react/testing`: `renderWithStrata`, `renderRoutes`, `createTestQueryClient`, `installLayoutShims`, `installFakeIntersectionObserver`, `filledButtons`, `expectOneFilledButton`, `asyncButtonPhase` | Router + query client around Testing Library's `render`; `renderRoutes(routes, { route, basename })` renders the app's own `RouteObject[]` in a memory data router, so layout routes, redirects, loaders and error elements run, and returns the `router` (where a redirect landed is `router.state.location`) and an act-wrapped `navigate`; a fixed box and ResizeObserver so measuring components render in jsdom; an IntersectionObserver the test fires with `scrollToEnd()` or `intersect(el)`; `filledButtons()` and `expectOneFilledButton()` check "one filled button per view" from `data-variant`, and `asyncButtonPhase(el)` reads an `AsyncButton`'s phase. Role names keep the non-breaking space from `format.count`, so match them with the same call or a `\s` regex |
189
+ | API types | `strata-react/api-types` and the `strata-api-types` command | See "API types from the server" below |
189
190
  | Visual regression | `strata-react/visual` and the `strata-visual` command | Screenshots an app's Storybook and its routes in each MSW state, light and dark, against baselines in the app's repo |
190
191
 
191
192
  Specs for the components not built yet (menus, toasts, command menu, prose)
192
193
  are in ux-research `ui-library/components.md`.
193
194
 
195
+ ## API types from the server
196
+
197
+ An app's FastAPI server publishes its routes, the shared contracts (`strata_python.contracts`: `Health`, `Task`, `Page`, `ErrorBody`…) and its typed settings at `/api/openapi.json`. `strata-api-types` writes the TypeScript types from that schema, so they follow the Python ones instead of being written again by hand:
198
+
199
+ ```sh
200
+ npm install --save-dev openapi-typescript # once; see the TypeScript note below
201
+ npx strata-api-types http://localhost:8360/api/openapi.json -o src/api.generated.ts
202
+ npx strata-api-types openapi.json -o src/api.generated.ts --check # CI: exits 1 when the file is stale
203
+ ```
204
+
205
+ The schema is a URL (a running server) or a JSON file the server's CLI wrote, so CI needs no server. Commit the output and never edit it, as with `theme.generated.css`; it holds nothing of the machine (no URL, no date), so `--check` is exact. The file exports `paths`, `components` and `Schema<"Task">`. Then use the shared shapes with the hooks made for them: `useInfiniteLoad({ …, ...apiPage<Item>() })` pages by `Page<T>`'s own `next` cursor, `useJob({ isRunning: (t) => isTaskRunning(t, FINISHED) })` ends when a `Task`'s state is a finished one, and `errorPayload<T>(error)` reads an error body's `payload` (what is already running, on a 409).
206
+
207
+ `openapi-typescript` does the reading (types only, nothing in the app's bundle) and is an optional peer, so an app that never runs the command installs nothing. It declares `typescript@^5` as a peer; an app on another TypeScript (7, or the TypeScript 6 package) points it at its own with an `overrides` entry, `"openapi-typescript": { "typescript": "$typescript" }`, as this repository does (the generator uses the TypeScript 6 API and is tested on it).
208
+
194
209
  ## Visual regression for apps
195
210
 
196
211
  `strata-visual` is the runner strata-react tests itself with: Playwright Chromium screenshots,
package/UPGRADING.md CHANGED
@@ -11,6 +11,16 @@ time. While the version is 0.x, any release may break.
11
11
 
12
12
  Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
13
13
 
14
+ ## 2026-11-15
15
+
16
+ - `MediaPlayer` (video, Strata's controls) now has a Full screen button after the volume and an `f` key (where the browser has the Fullscreen API); pass `fullscreen={false}` to remove them. The player is wrapped in `FullscreenFrame`, so a test that counts buttons or a baseline of a video player changes.
17
+ - `MediaPlayer` video: click plays or pauses, double click toggles full screen, and the wheel sets the volume while the player has focus. A test that clicks the video now changes playback.
18
+ - `useAsyncAction` no longer sets state or starts its settle timer after unmount; nothing to change.
19
+
20
+ ## After v1.0.47 (2026-11-14)
21
+
22
+ - New, optional: the `strata-api-types` command (`strata-react/api-types`) generates API types from a server's OpenAPI schema. It needs `openapi-typescript` installed in the app (an optional peer) and, on a TypeScript other than 5, an `overrides` entry for its `typescript@^5` peer; see the README. Apps that do not run it change nothing.
23
+
14
24
  ## After v1.0.46 (2026-11-14)
15
25
 
16
26
  - `MarkableText` now acts on arrow, Home, End and Escape keys only while its own region has focus; keys from something focusable inside it (a list of rows) are that thing's. Words drawn as `Mark`s with nothing focusable around them behave as before.
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // strata-api-types: generate an app's TypeScript API types from its OpenAPI schema (src/api-types/cli.ts, built into dist/).
3
+ import { main } from "../dist/api-types-cli.js";
4
+
5
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,2 @@
1
+ /** Runs the command; the exit code. */
2
+ export declare function main(argv: readonly string[], out?: (text: string) => void, fetcher?: typeof fetch): Promise<number>;
@@ -0,0 +1,9 @@
1
+ /** The OpenAPI document as the generator takes it: a parsed JSON object. */
2
+ export type OpenApiDocument = Record<string, unknown>;
3
+ /** Reads an OpenAPI document from an `http(s)` URL (a running server) or a JSON file path. */
4
+ export declare function loadSchema(source: string, fetcher?: typeof fetch): Promise<OpenApiDocument>;
5
+ /**
6
+ * The TypeScript types for an OpenAPI document, as the text of the generated file. `source` is where the
7
+ * document was read from (a URL or file path): relative `$ref`s to other files resolve against it.
8
+ */
9
+ export declare function generateApiTypes(schema: OpenApiDocument, source?: string): Promise<string>;
@@ -0,0 +1 @@
1
+ export { generateApiTypes, loadSchema, type OpenApiDocument } from './generate';
@@ -0,0 +1,67 @@
1
+ import { n as loadSchema, t as generateApiTypes } from "./generate-DCRYZPJs.js";
2
+ import { existsSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { readFile, writeFile } from "node:fs/promises";
5
+ // src/api-types/cli.ts
6
+ var usage = `Usage: strata-api-types <schema> [options]
7
+
8
+ Writes TypeScript types for an app's API from its OpenAPI schema, so they follow the Python
9
+ server's instead of being written again by hand. <schema> is a URL (a running server, for example
10
+ http://localhost:8360/api/openapi.json) or a JSON file the server's CLI wrote, so CI needs no server.
11
+
12
+ -o, --output <file> the generated file (default src/api.generated.ts); commit it, never edit it
13
+ --check write nothing; exit 1 if the file is missing or differs from the schema (for CI)
14
+ --help show this
15
+ `;
16
+ /** Runs the command; the exit code. */
17
+ async function main(argv, out = (t) => console.log(t), fetcher = fetch) {
18
+ let parsed;
19
+ try {
20
+ parsed = parseArgs({
21
+ args: [...argv],
22
+ options: {
23
+ output: {
24
+ type: "string",
25
+ short: "o"
26
+ },
27
+ check: { type: "boolean" },
28
+ help: { type: "boolean" }
29
+ },
30
+ allowPositionals: true
31
+ });
32
+ } catch (e) {
33
+ out(`${e.message}\n\n${usage}`);
34
+ return 2;
35
+ }
36
+ const { values, positionals } = parsed;
37
+ if (values.help) {
38
+ out(usage);
39
+ return 0;
40
+ }
41
+ if (positionals.length !== 1) {
42
+ out(`Give the schema to read: a URL or a JSON file.\n\n${usage}`);
43
+ return 2;
44
+ }
45
+ const output = values.output ?? "src/api.generated.ts";
46
+ try {
47
+ const next = await generateApiTypes(await loadSchema(positionals[0], fetcher), positionals[0]);
48
+ if (values.check) {
49
+ const current = existsSync(output) ? (await readFile(output, "utf8")).replace(/\r\n/g, "\n") : null;
50
+ if (current === next) {
51
+ out(`${output} matches the schema.`);
52
+ return 0;
53
+ }
54
+ out(`${output} ${current === null ? "does not exist" : "no longer matches the schema"}. Regenerate it: strata-api-types ${positionals[0]} -o ${output}`);
55
+ return 1;
56
+ }
57
+ await writeFile(output, next);
58
+ out(`Wrote ${output}.`);
59
+ return 0;
60
+ } catch (e) {
61
+ out(e.message);
62
+ return 1;
63
+ }
64
+ }
65
+ export { main };
66
+
67
+ //# sourceMappingURL=api-types-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-types-cli.js","names":[],"sources":["../src/api-types/cli.ts"],"sourcesContent":["// The strata-api-types command: generate an app's TypeScript API types from its OpenAPI schema (see generate.ts).\nimport { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { parseArgs } from \"node:util\";\nimport { generateApiTypes, loadSchema } from \"./generate\";\n\nconst usage = `Usage: strata-api-types <schema> [options]\n\nWrites TypeScript types for an app's API from its OpenAPI schema, so they follow the Python\nserver's instead of being written again by hand. <schema> is a URL (a running server, for example\nhttp://localhost:8360/api/openapi.json) or a JSON file the server's CLI wrote, so CI needs no server.\n\n -o, --output <file> the generated file (default src/api.generated.ts); commit it, never edit it\n --check write nothing; exit 1 if the file is missing or differs from the schema (for CI)\n --help show this\n`;\n\n/** Runs the command; the exit code. */\nexport async function main(argv: readonly string[], out: (text: string) => void = (t) => console.log(t), fetcher: typeof fetch = fetch): Promise<number> {\n let parsed;\n try {\n parsed = parseArgs({ args: [...argv], options: { output: { type: \"string\", short: \"o\" }, check: { type: \"boolean\" }, help: { type: \"boolean\" } }, allowPositionals: true });\n } catch (e) {\n out(`${(e as Error).message}\\n\\n${usage}`);\n return 2;\n }\n const { values, positionals } = parsed;\n if (values.help) {\n out(usage);\n return 0;\n }\n if (positionals.length !== 1) {\n out(`Give the schema to read: a URL or a JSON file.\\n\\n${usage}`);\n return 2;\n }\n const output = values.output ?? \"src/api.generated.ts\";\n try {\n const next = await generateApiTypes(await loadSchema(positionals[0]!, fetcher), positionals[0]!);\n if (values.check) {\n const current = existsSync(output) ? (await readFile(output, \"utf8\")).replace(/\\r\\n/g, \"\\n\") : null;\n if (current === next) {\n out(`${output} matches the schema.`);\n return 0;\n }\n out(`${output} ${current === null ? \"does not exist\" : \"no longer matches the schema\"}. Regenerate it: strata-api-types ${positionals[0]} -o ${output}`);\n return 1;\n }\n await writeFile(output, next);\n out(`Wrote ${output}.`);\n return 0;\n } catch (e) {\n out((e as Error).message);\n return 1;\n }\n}\n"],"mappings":";;;;;AAMA,IAAM,QAAQ;;;;;;;;;;;AAYd,eAAsB,KAAK,MAAyB,OAA+B,MAAM,QAAQ,IAAI,CAAC,GAAG,UAAwB,OAAwB;CACvJ,IAAI;CACJ,IAAI;EACF,SAAS,UAAU;GAAE,MAAM,CAAC,GAAG,IAAI;GAAG,SAAS;IAAE,QAAQ;KAAE,MAAM;KAAU,OAAO;IAAI;IAAG,OAAO,EAAE,MAAM,UAAU;IAAG,MAAM,EAAE,MAAM,UAAU;GAAE;GAAG,kBAAkB;EAAK,CAAC;CAC5K,SAAS,GAAG;EACV,IAAI,GAAI,EAAY,QAAQ,MAAM,OAAO;EACzC,OAAO;CACT;CACA,MAAM,EAAE,QAAQ,gBAAgB;CAChC,IAAI,OAAO,MAAM;EACf,IAAI,KAAK;EACT,OAAO;CACT;CACA,IAAI,YAAY,WAAW,GAAG;EAC5B,IAAI,qDAAqD,OAAO;EAChE,OAAO;CACT;CACA,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI;EACF,MAAM,OAAO,MAAM,iBAAiB,MAAM,WAAW,YAAY,IAAK,OAAO,GAAG,YAAY,EAAG;EAC/F,IAAI,OAAO,OAAO;GAChB,MAAM,UAAU,WAAW,MAAM,KAAK,MAAM,SAAS,QAAQ,MAAM,EAAA,CAAG,QAAQ,SAAS,IAAI,IAAI;GAC/F,IAAI,YAAY,MAAM;IACpB,IAAI,GAAG,OAAO,qBAAqB;IACnC,OAAO;GACT;GACA,IAAI,GAAG,OAAO,GAAG,YAAY,OAAO,mBAAmB,+BAA+B,oCAAoC,YAAY,GAAG,MAAM,QAAQ;GACvJ,OAAO;EACT;EACA,MAAM,UAAU,QAAQ,IAAI;EAC5B,IAAI,SAAS,OAAO,EAAE;EACtB,OAAO;CACT,SAAS,GAAG;EACV,IAAK,EAAY,OAAO;EACxB,OAAO;CACT;AACF"}
@@ -0,0 +1 @@
1
+ export { t as generateApiTypes, n as loadSchema } from "./generate-DCRYZPJs.js";
@@ -7,10 +7,12 @@ export type FullscreenFrameProps = {
7
7
  active: boolean;
8
8
  /** Called with `false` when the person leaves with Escape or the browser's own control. */
9
9
  onActiveChange: (active: boolean) => void;
10
+ /** Open a window-filling modal where the browser has no Fullscreen API or refuses. Default true. `false` for content that must not be mounted again (a playing video): where the browser cannot or will not, `onActiveChange(false)` is called instead. */
11
+ modal?: boolean;
10
12
  children: React.ReactNode;
11
13
  className?: string;
12
14
  };
13
15
  /** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */
14
16
  export declare function canFullscreen(): boolean;
15
17
  /** Shows its children full screen while `active`: the browser's Fullscreen API where there is one, a window-filling modal where there is not. */
16
- export declare function FullscreenFrame({ label, active, onActiveChange, children, className }: FullscreenFrameProps): React.JSX.Element;
18
+ export declare function FullscreenFrame({ label, active, onActiveChange, modal: allowModal, children, className }: FullscreenFrameProps): React.JSX.Element;
@@ -173,6 +173,8 @@ export type MediaPlayerProps = {
173
173
  overlay?: (media: MediaElementState) => React.ReactNode;
174
174
  /** The picture's shape before its metadata loads (and after, when given): a width over a height, or "16/9". Default "16/9" until the video says its own. */
175
175
  aspect?: number | `${number}/${number}`;
176
+ /** A video has a Full screen button (and the `f` key) beside the speed and volume. Default true; `false` for a picture that must stay in its place. Only where the browser has the Fullscreen API (the window-filling fallback would mount the video again and lose its place). Not drawn with the browser's own controls (`controls="native"`, or `"auto"` on a touch device), which have their own. */
177
+ fullscreen?: boolean;
176
178
  className?: string;
177
179
  };
178
180
  /** Playback speeds an audiobook or lecture listener expects. */
@@ -182,4 +184,4 @@ export declare const SPEECH_RATES: readonly number[];
182
184
  * a touch device), with the failure to load shown and retried. For an editor or a replay, use the
183
185
  * parts and `useMediaElement` directly.
184
186
  */
185
- export declare function MediaPlayer({ label, kind, src, sources, index: controlledIndex, onIndexChange, autoAdvance, controls, autoPlay, poster, session, rates, shortcuts, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, onSpan, spanWords, mediaRef, overlay, aspect, className, }: MediaPlayerProps): React.JSX.Element;
187
+ export declare function MediaPlayer({ label, kind, src, sources, index: controlledIndex, onIndexChange, autoAdvance, controls, autoPlay, poster, session, rates, shortcuts, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, onSpan, spanWords, mediaRef, overlay, aspect, fullscreen, className, }: MediaPlayerProps): React.JSX.Element;
@@ -115,6 +115,8 @@ var HttpError = class extends Error {
115
115
  reason;
116
116
  /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */
117
117
  fieldErrors;
118
+ /** The body's `payload`, when it has one (`{ detail, payload }`): data for the app, not words for the person. Read it typed with `errorPayload`. */
119
+ payload;
118
120
  constructor(status, statusText, url, body, found = readErrorBody(body)) {
119
121
  super(`${status} ${statusText} from ${url}`);
120
122
  this.status = status;
@@ -124,6 +126,7 @@ var HttpError = class extends Error {
124
126
  this.name = "HttpError";
125
127
  this.reason = found.reason;
126
128
  this.fieldErrors = found.fields ?? {};
129
+ this.payload = found.payload;
127
130
  }
128
131
  };
129
132
  var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
@@ -154,6 +157,7 @@ function readErrorBody(body) {
154
157
  }
155
158
  if (!body || typeof body !== "object") return {};
156
159
  const b = body;
160
+ const payload = b.payload !== void 0 && b.payload !== null ? { payload: b.payload } : {};
157
161
  if (Array.isArray(b.detail)) {
158
162
  const fields = {};
159
163
  for (const item of b.detail) {
@@ -162,10 +166,16 @@ function readErrorBody(body) {
162
166
  const msg = text(entry?.msg);
163
167
  if (name && msg && !fields[name]) fields[name] = msg;
164
168
  }
165
- return { fields };
169
+ return {
170
+ fields,
171
+ ...payload
172
+ };
166
173
  }
167
174
  const nested = b.error && typeof b.error === "object" ? text(b.error.message) : void 0;
168
- return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested };
175
+ return {
176
+ reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested,
177
+ ...payload
178
+ };
169
179
  }
170
180
  /** A sentence ends once: "…absolute path" and "…absolute path." both end in one full stop. */
171
181
  var sentence = (s) => /[.!?…]$/.test(s) ? s : `${s}.`;
@@ -182,6 +192,10 @@ var describeActionError = (error) => error instanceof HttpError ? error.status >
182
192
  function fieldErrorsOf(error) {
183
193
  return error instanceof HttpError ? error.fieldErrors : {};
184
194
  }
185
- export { readErrorBody as a, RowAction as c, fieldErrorsOf as i, buttonVariants as l, describeActionError as n, Button$1 as o, describeHttpError as r, IconButton as s, HttpError as t, isDev as u };
195
+ /** The payload of an error from the server as the type the app expects (`errorPayload<{ running: string }>(error)`), or `undefined` when it is not an `HttpError` or carries none. The type is the caller's claim: check it against the API's schema. */
196
+ function errorPayload(error) {
197
+ return error instanceof HttpError ? error.payload : void 0;
198
+ }
199
+ export { fieldErrorsOf as a, IconButton as c, isDev as d, errorPayload as i, RowAction as l, describeActionError as n, readErrorBody as o, describeHttpError as r, Button$1 as s, HttpError as t, buttonVariants as u };
186
200
 
187
- //# sourceMappingURL=errors-BXSbhx2s.js.map
201
+ //# sourceMappingURL=errors-Dt--eHgK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BXSbhx2s.js","names":["Button","AriaButton","Tooltip"],"sources":["../src/lib/dev.ts","../src/components/button.tsx","../src/lib/errors.ts"],"sourcesContent":["// Development-only checks (a warning for a mistake a type cannot catch). `import.meta.env.DEV` is\n// replaced by the library build itself, so in the published package it is always false and the check\n// never runs in an app's development. `process.env.NODE_ENV` is left for the app's bundler to replace\n// (Vite, webpack and the rest do, in dependencies too), so the app decides. Where nothing replaces it\n// `process` does not exist, and the check is off.\n\n/** Whether the app is running in development, decided by the app's bundler. */\nexport function isDev(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return false;\n }\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { ControlSize } from \"../lib/control\";\nimport { Tooltip } from \"./tooltip\";\nimport { isDev } from \"../lib/dev\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\n// 5. `title` is refused, not passed through (issue #231). React Aria's `Button` does not forward it,\n// so a tip moved over from a native button vanished with nothing said. Passing it through would\n// give a tip that has no keyboard focus, no touch and a long, unstyled delay; the answer is a\n// `Tooltip` (and `IconButton`'s `label` and `hint`). The type says so (`title?: never`) and, for\n// an untyped caller, so does a development warning. A button whose only child is one symbol\n// (`✕`, `−`, `+`) has no accessible name from its text and gets a development warning too.\nexport const buttonVariants = cva(\n \"inline-flex max-w-full shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-(--control-icon) [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-(--control-px)\",\n sm: \"h-(--control-h-sm) px-(--control-px-sm)\",\n icon: \"size-(--control-h)\",\n \"icon-sm\": \"size-(--control-h-sm)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\" | \"title\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** Not accepted: a `title` is a poor tooltip (no keyboard focus, no touch) and React Aria's button drops it. Wrap the button in a `Tooltip`, or use `IconButton`'s `label` and `hint`. */\n title?: never;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n /** When a press begins and ends: for a control that acts while held (a nudge that repeats). */\n onPressStart?: (event: PressEvent) => void;\n onPressEnd?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, children, \"aria-busy\": ariaBusy, ...props }: ButtonProps) {\n // React Aria's button drops `aria-busy` (it forwards only the aria props it knows), so it is set\n // on the element here; a pending row action says it is busy to a screen reader (issue #248).\n const ref = React.useRef<HTMLButtonElement>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (ariaBusy) el.setAttribute(\"aria-busy\", String(ariaBusy));\n else el.removeAttribute(\"aria-busy\");\n }, [ariaBusy]);\n if (isDev()) warnOnLoss(props as Record<string, unknown>, children);\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n ref={ref}\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n >\n {/* A text label that cannot fit its column is cut with an ellipsis, not drawn past the button (issue #116). */}\n {typeof children === \"string\" ? <span className=\"min-w-0 truncate\">{children}</span> : children}\n </AriaButton>\n );\n}\n\n/** Development only: what a native button had that this one loses or cannot name (issue #231). */\nfunction warnOnLoss(props: Record<string, unknown>, children: React.ReactNode) {\n if (props.title !== undefined && !warned.has(\"title\")) {\n warned.add(\"title\");\n console.warn(\"strata-react: Button does not pass `title` through (React Aria's button drops it, and a title has no keyboard or touch). Wrap the button in a `Tooltip`, or use IconButton's `label` and `hint`.\");\n }\n const glyph = typeof children === \"string\" ? children.trim() : \"\";\n if (glyph && Array.from(glyph).length === 1 && !/[\\p{L}\\p{N}]/u.test(glyph) && !props[\"aria-label\"] && !props[\"aria-labelledby\"] && !warned.has(\"glyph\")) {\n warned.add(\"glyph\");\n console.warn(`strata-react: a Button whose only content is \"${glyph}\" has no accessible name. Give it an aria-label, or use an IconButton with a label.`);\n }\n}\nconst warned = new Set<string>();\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `Button`, for a toolbar or property row. Default --control-h. */\n size?: ControlSize;\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", size = \"default\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size={size === \"sm\" ? \"icon-sm\" : \"icon\"} variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\n}\n","// Errors, described for a person. Anything that fails in front of someone (a load in DataView, an\n// action in AsyncButton) says what happened in a sentence, in the product's words, not the\n// developer's: `HttpError`'s own message (\"409 Conflict from /api/bookings\") is for logs. Loads\n// and actions share HttpError's status sentences, so the same failure reads the same everywhere,\n// and differ only in what is true afterwards: a failed load changed nothing, while a failed action\n// may have reached the server, so its sentence does not promise that.\n//\n// A server's own reason beats the status text (strata-react issue #42, from python-app-template).\n// FastAPI and most JSON APIs say why a 4xx happened in the body (`{\"detail\": \"the data folder must\n// be an absolute path\"}`), and a client that drops it has to repeat every server rule to show the\n// person anything better than \"Bad Request\", which drifts and cannot cover rules only the server\n// can check. So `fetchJson` reads an error response's body, `HttpError` keeps it with the reason\n// and any per-field messages found in it, and the sentences below use the reason for a 4xx.\n// Per-field messages (FastAPI's 422 `detail: [{loc, msg}]`) are keyed by field name, so\n// `useAsyncAction`'s `fieldErrors` can put each under its `Field`, never in a toast. A 5xx body is\n// not shown: it is usually a stack trace or a proxy's HTML page, and is kept on `body` for logs.\n\n/** What `readErrorBody` finds in an error response: the server's sentence, and messages per field. */\nexport type ErrorBody = {\n /** Why the server refused, in its own words. */\n reason?: string;\n /** Messages for individual fields, keyed by field name (`\"name\"`, `\"address.city\"`). */\n fields?: Record<string, string>;\n};\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */\n readonly reason?: string;\n /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */\n readonly fieldErrors: Readonly<Record<string, string>>;\n\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n /** The response body: parsed JSON when it was JSON, else its text; undefined when empty. */\n readonly body?: unknown,\n found: ErrorBody = readErrorBody(body),\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n this.reason = found.reason;\n this.fieldErrors = found.fields ?? {};\n }\n}\n\nconst text = (value: unknown) => (typeof value === \"string\" && value.trim() ? value.trim() : undefined);\n\n/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`[\"body\", \"address\", \"city\"]` is `\"address.city\"`). */\nfunction fieldName(loc: unknown) {\n if (!Array.isArray(loc)) return undefined;\n const path = loc.map(String);\n if ([\"body\", \"query\", \"path\", \"header\", \"cookie\", \"form\"].includes(path[0]) && path.length > 1) path.shift();\n return path.join(\".\") || undefined;\n}\n\n/**\n * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: \"…\" }`\n * (FastAPI), `{ message: \"…\" }`, `{ error: \"…\" }` or `{ error: { message: \"…\" } }` for the reason,\n * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short\n * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.\n */\nexport function readErrorBody(body: unknown): ErrorBody {\n if (typeof body === \"string\") {\n const t = text(body);\n return t && t.length <= 300 && !t.startsWith(\"<\") ? { reason: t } : {};\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n if (Array.isArray(b.detail)) {\n const fields: Record<string, string> = {};\n for (const item of b.detail as unknown[]) {\n const entry = item as { loc?: unknown; msg?: unknown } | null;\n const name = fieldName(entry?.loc);\n const msg = text(entry?.msg);\n if (name && msg && !fields[name]) fields[name] = msg;\n }\n return { fields };\n }\n const nested = b.error && typeof b.error === \"object\" ? text((b.error as Record<string, unknown>).message) : undefined;\n return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested };\n}\n\n/** Writes an error for a person: what happened, in a sentence. A product passes its own words. */\nexport type DescribeError = (error: unknown) => string;\n\n/** A sentence ends once: \"…absolute path\" and \"…absolute path.\" both end in one full stop. */\nconst sentence = (s: string) => (/[.!?…]$/.test(s) ? s : `${s}.`);\n\nfunction refused(error: HttpError) {\n if (error.reason) return `The request was refused: ${sentence(error.reason)}`;\n if (Object.keys(error.fieldErrors).length) return \"The request was refused: check the fields marked.\";\n return `The request was refused (${error.status}): ${error.statusText || \"no reason given\"}.`;\n}\n\n/** The default `DescribeError` for loads: the HTTP status in a sentence (with the server's reason for a 4xx), else the error's message, else a plain fallback. */\nexport const describeHttpError: DescribeError = (error) =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}). Nothing was changed.`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : \"The data could not be loaded. Nothing was changed.\";\n\n/** The default for `useAsyncAction`: the HTTP status in a sentence (with the server's reason for a 4xx), else the thrown Error's message, else undefined (the retry label alone). */\nexport const describeActionError = (error: unknown): string | undefined =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}).`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : undefined;\n\n/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */\nexport function fieldErrorsOf(error: unknown): Readonly<Record<string, string>> {\n return error instanceof HttpError ? error.fieldErrors : {};\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,QAAiB;CAC/B,IAAI;EACF,OAAA,QAAA,IAAA,aAAgC;CAClC,QAAQ;EACN,OAAO;CACT;AACF;;ACaA,IAAa,iBAAiB,IAC5B,oRACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SAAS;GACT,WAAW;GACX,OAAO;GACP,aAAa;GACb,MAAM;EACR;E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;;AAGR,IAAa,uBAAuB,UAClC,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,MAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN,KAAA;;AAGR,SAAgB,cAAc,OAAkD;CAC9E,OAAO,iBAAiB,YAAY,MAAM,cAAc,CAAC;AAC3D"}
1
+ {"version":3,"file":"errors-Dt--eHgK.js","names":["Button","AriaButton","Tooltip"],"sources":["../src/lib/dev.ts","../src/components/button.tsx","../src/lib/errors.ts"],"sourcesContent":["// Development-only checks (a warning for a mistake a type cannot catch). `import.meta.env.DEV` is\n// replaced by the library build itself, so in the published package it is always false and the check\n// never runs in an app's development. `process.env.NODE_ENV` is left for the app's bundler to replace\n// (Vite, webpack and the rest do, in dependencies too), so the app decides. Where nothing replaces it\n// `process` does not exist, and the check is off.\n\n/** Whether the app is running in development, decided by the app's bundler. */\nexport function isDev(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return false;\n }\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { ControlSize } from \"../lib/control\";\nimport { Tooltip } from \"./tooltip\";\nimport { isDev } from \"../lib/dev\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\n// 5. `title` is refused, not passed through (issue #231). React Aria's `Button` does not forward it,\n// so a tip moved over from a native button vanished with nothing said. Passing it through would\n// give a tip that has no keyboard focus, no touch and a long, unstyled delay; the answer is a\n// `Tooltip` (and `IconButton`'s `label` and `hint`). The type says so (`title?: never`) and, for\n// an untyped caller, so does a development warning. A button whose only child is one symbol\n// (`✕`, `−`, `+`) has no accessible name from its text and gets a development warning too.\nexport const buttonVariants = cva(\n \"inline-flex max-w-full shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-(--control-icon) [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-(--control-px)\",\n sm: \"h-(--control-h-sm) px-(--control-px-sm)\",\n icon: \"size-(--control-h)\",\n \"icon-sm\": \"size-(--control-h-sm)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\" | \"title\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** Not accepted: a `title` is a poor tooltip (no keyboard focus, no touch) and React Aria's button drops it. Wrap the button in a `Tooltip`, or use `IconButton`'s `label` and `hint`. */\n title?: never;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n /** When a press begins and ends: for a control that acts while held (a nudge that repeats). */\n onPressStart?: (event: PressEvent) => void;\n onPressEnd?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, children, \"aria-busy\": ariaBusy, ...props }: ButtonProps) {\n // React Aria's button drops `aria-busy` (it forwards only the aria props it knows), so it is set\n // on the element here; a pending row action says it is busy to a screen reader (issue #248).\n const ref = React.useRef<HTMLButtonElement>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (ariaBusy) el.setAttribute(\"aria-busy\", String(ariaBusy));\n else el.removeAttribute(\"aria-busy\");\n }, [ariaBusy]);\n if (isDev()) warnOnLoss(props as Record<string, unknown>, children);\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n ref={ref}\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n >\n {/* A text label that cannot fit its column is cut with an ellipsis, not drawn past the button (issue #116). */}\n {typeof children === \"string\" ? <span className=\"min-w-0 truncate\">{children}</span> : children}\n </AriaButton>\n );\n}\n\n/** Development only: what a native button had that this one loses or cannot name (issue #231). */\nfunction warnOnLoss(props: Record<string, unknown>, children: React.ReactNode) {\n if (props.title !== undefined && !warned.has(\"title\")) {\n warned.add(\"title\");\n console.warn(\"strata-react: Button does not pass `title` through (React Aria's button drops it, and a title has no keyboard or touch). Wrap the button in a `Tooltip`, or use IconButton's `label` and `hint`.\");\n }\n const glyph = typeof children === \"string\" ? children.trim() : \"\";\n if (glyph && Array.from(glyph).length === 1 && !/[\\p{L}\\p{N}]/u.test(glyph) && !props[\"aria-label\"] && !props[\"aria-labelledby\"] && !warned.has(\"glyph\")) {\n warned.add(\"glyph\");\n console.warn(`strata-react: a Button whose only content is \"${glyph}\" has no accessible name. Give it an aria-label, or use an IconButton with a label.`);\n }\n}\nconst warned = new Set<string>();\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `Button`, for a toolbar or property row. Default --control-h. */\n size?: ControlSize;\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", size = \"default\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size={size === \"sm\" ? \"icon-sm\" : \"icon\"} variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\n}\n","// Errors, described for a person. Anything that fails in front of someone (a load in DataView, an\n// action in AsyncButton) says what happened in a sentence, in the product's words, not the\n// developer's: `HttpError`'s own message (\"409 Conflict from /api/bookings\") is for logs. Loads\n// and actions share HttpError's status sentences, so the same failure reads the same everywhere,\n// and differ only in what is true afterwards: a failed load changed nothing, while a failed action\n// may have reached the server, so its sentence does not promise that.\n//\n// A server's own reason beats the status text (strata-react issue #42, from python-app-template).\n// FastAPI and most JSON APIs say why a 4xx happened in the body (`{\"detail\": \"the data folder must\n// be an absolute path\"}`), and a client that drops it has to repeat every server rule to show the\n// person anything better than \"Bad Request\", which drifts and cannot cover rules only the server\n// can check. So `fetchJson` reads an error response's body, `HttpError` keeps it with the reason\n// and any per-field messages found in it, and the sentences below use the reason for a 4xx.\n// Per-field messages (FastAPI's 422 `detail: [{loc, msg}]`) are keyed by field name, so\n// `useAsyncAction`'s `fieldErrors` can put each under its `Field`, never in a toast. A 5xx body is\n// not shown: it is usually a stack trace or a proxy's HTML page, and is kept on `body` for logs.\n\n/** What `readErrorBody` finds in an error response: the server's sentence, and messages per field. */\nexport type ErrorBody = {\n /** Why the server refused, in its own words. */\n reason?: string;\n /** Messages for individual fields, keyed by field name (`\"name\"`, `\"address.city\"`). */\n fields?: Record<string, string>;\n /** The structured part of the body (`ErrorBody.payload` of the shared contract): what the app can act on, such as what is already running on a 409. Typed by the caller with `errorPayload`. */\n payload?: unknown;\n};\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */\n readonly reason?: string;\n /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */\n readonly fieldErrors: Readonly<Record<string, string>>;\n /** The body's `payload`, when it has one (`{ detail, payload }`): data for the app, not words for the person. Read it typed with `errorPayload`. */\n readonly payload?: unknown;\n\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n /** The response body: parsed JSON when it was JSON, else its text; undefined when empty. */\n readonly body?: unknown,\n found: ErrorBody = readErrorBody(body),\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n this.reason = found.reason;\n this.fieldErrors = found.fields ?? {};\n this.payload = found.payload;\n }\n}\n\nconst text = (value: unknown) => (typeof value === \"string\" && value.trim() ? value.trim() : undefined);\n\n/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`[\"body\", \"address\", \"city\"]` is `\"address.city\"`). */\nfunction fieldName(loc: unknown) {\n if (!Array.isArray(loc)) return undefined;\n const path = loc.map(String);\n if ([\"body\", \"query\", \"path\", \"header\", \"cookie\", \"form\"].includes(path[0]) && path.length > 1) path.shift();\n return path.join(\".\") || undefined;\n}\n\n/**\n * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: \"…\" }`\n * (FastAPI), `{ message: \"…\" }`, `{ error: \"…\" }` or `{ error: { message: \"…\" } }` for the reason,\n * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short\n * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.\n */\nexport function readErrorBody(body: unknown): ErrorBody {\n if (typeof body === \"string\") {\n const t = text(body);\n return t && t.length <= 300 && !t.startsWith(\"<\") ? { reason: t } : {};\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n const payload = b.payload !== undefined && b.payload !== null ? { payload: b.payload } : {};\n if (Array.isArray(b.detail)) {\n const fields: Record<string, string> = {};\n for (const item of b.detail as unknown[]) {\n const entry = item as { loc?: unknown; msg?: unknown } | null;\n const name = fieldName(entry?.loc);\n const msg = text(entry?.msg);\n if (name && msg && !fields[name]) fields[name] = msg;\n }\n return { fields, ...payload };\n }\n const nested = b.error && typeof b.error === \"object\" ? text((b.error as Record<string, unknown>).message) : undefined;\n return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested, ...payload };\n}\n\n/** Writes an error for a person: what happened, in a sentence. A product passes its own words. */\nexport type DescribeError = (error: unknown) => string;\n\n/** A sentence ends once: \"…absolute path\" and \"…absolute path.\" both end in one full stop. */\nconst sentence = (s: string) => (/[.!?…]$/.test(s) ? s : `${s}.`);\n\nfunction refused(error: HttpError) {\n if (error.reason) return `The request was refused: ${sentence(error.reason)}`;\n if (Object.keys(error.fieldErrors).length) return \"The request was refused: check the fields marked.\";\n return `The request was refused (${error.status}): ${error.statusText || \"no reason given\"}.`;\n}\n\n/** The default `DescribeError` for loads: the HTTP status in a sentence (with the server's reason for a 4xx), else the error's message, else a plain fallback. */\nexport const describeHttpError: DescribeError = (error) =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}). Nothing was changed.`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : \"The data could not be loaded. Nothing was changed.\";\n\n/** The default for `useAsyncAction`: the HTTP status in a sentence (with the server's reason for a 4xx), else the thrown Error's message, else undefined (the retry label alone). */\nexport const describeActionError = (error: unknown): string | undefined =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}).`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : undefined;\n\n/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */\nexport function fieldErrorsOf(error: unknown): Readonly<Record<string, string>> {\n return error instanceof HttpError ? error.fieldErrors : {};\n}\n\n/** The payload of an error from the server as the type the app expects (`errorPayload<{ running: string }>(error)`), or `undefined` when it is not an `HttpError` or carries none. The type is the caller's claim: check it against the API's schema. */\nexport function errorPayload<T>(error: unknown): T | undefined {\n return error instanceof HttpError ? (error.payload as T | undefined) : undefined;\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,QAAiB;CAC/B,IAAI;EACF,OAAA,QAAA,IAAA,aAAgC;CAClC,QAAQ;EACN,OAAO;CACT;AACF;;ACaA,IAAa,iBAAiB,IAC5B,oRACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SAAS;GACT,WAAW;GACX,OAAO;GACP,aAAa;GACb,MAAM;EACR;EACA,MAAM;GACJ,SAAS;GACT,IAAI;GACJ,MAAM;GACN,WAAW;EACb;CACF;CACA,iBAAiB;EAAE,SAAS;EAAW,MAAM;CAAU;AACzD,CACF;;;;;;;AAoBA,SAAgBA,SAAO,EAAE,WAAW,SAAS,MAAM,OAAO,UAAU,UAAU,UAAU,aAAa,UAAU,GAAG,SAAsB;CAGtI,MAAM,MAAM,MAAM,OAA0B,IAAI;CAChD,MAAM,gBAAgB;EACpB,MAAM,KAAK,IAAI;EACf,IAAI,CAAC,IAAI;EACT,IAAI,UAAU,GAAG,aAAa,aAAa,OAAO,QAAQ,CAAC;OACtD,GAAG,gBAAgB,WAAW;CACrC,GAAG,CAAC,QAAQ,CAAC;CACb,IAAI,MAAM,GAAG,WAAW,OAAkC,QAAQ;CAGlE,OACE,oBAACC,QAAD;EACO;EACC;EACN,YAAY;EACZ,gBAAc,WAAW;EACzB,WAAW,GAAG,eAAe;GAAE;GAAS;EAAK,CAAC,GAAG,SAAS;EAC1D,GAAK;EAGJ,UAAA,OAAO,aAAa,WAAW,oBAAC,QAAD;GAAM,WAAU;GAAoB;EAAe,CAAA,IAAI;CAC7E,CAAA;AAEhB;;AAGA,SAAS,WAAW,OAAgC,UAA2B;CAC7E,IAAI,MAAM,UAAU,KAAA,KAAa,CAAC,OAAO,IAAI,OAAO,GAAG;EACrD,OAAO,IAAI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;CAC7G,OAAO;EAAE,QAAQ,KAAK,EAAE,MAAM,KAAK,KAAK,EAAE,OAAO,KAAK,KAAK,EAAE,KAAK,KAAK;EAAQ,GAAG;CAAQ;AAC5F;;AAMA,IAAM,YAAY,MAAe,UAAU,KAAK,CAAC,IAAI,IAAI,GAAG,EAAE;AAE9D,SAAS,QAAQ,OAAkB;CACjC,IAAI,MAAM,QAAQ,OAAO,4BAA4B,SAAS,MAAM,MAAM;CAC1E,IAAI,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,QAAQ,OAAO;CAClD,OAAO,4BAA4B,MAAM,OAAO,KAAK,MAAM,cAAc,kBAAkB;AAC7F;;AAGA,IAAa,qBAAoC,UAC/C,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,2BAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN;;AAGR,IAAa,uBAAuB,UAClC,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,MAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN,KAAA;;AAGR,SAAgB,cAAc,OAAkD;CAC9E,OAAO,iBAAiB,YAAY,MAAM,cAAc,CAAC;AAC3D;;AAGA,SAAgB,aAAgB,OAA+B;CAC7D,OAAO,iBAAiB,YAAa,MAAM,UAA4B,KAAA;AACzE"}
@@ -0,0 +1,46 @@
1
+ import { resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { readFile } from "node:fs/promises";
4
+ // src/api-types/generate.ts
5
+ /** Reads an OpenAPI document from an `http(s)` URL (a running server) or a JSON file path. */
6
+ async function loadSchema(source, fetcher = fetch) {
7
+ let text;
8
+ if (/^https?:\/\//i.test(source)) {
9
+ const response = await fetcher(source, { headers: { accept: "application/json" } });
10
+ if (!response.ok) throw new Error(`${source} answered ${response.status} ${response.statusText}`);
11
+ text = await response.text();
12
+ } else text = await readFile(source, "utf8");
13
+ let parsed;
14
+ try {
15
+ parsed = JSON.parse(text);
16
+ } catch {
17
+ throw new Error(`${source} is not JSON. Give the OpenAPI document (/api/openapi.json), not the docs page.`);
18
+ }
19
+ if (!parsed || typeof parsed !== "object" || !("openapi" in parsed)) throw new Error(`${source} is JSON but not an OpenAPI document (no "openapi" field).`);
20
+ return parsed;
21
+ }
22
+ var header = `/* eslint-disable */
23
+ // Generated by strata-api-types from the app's OpenAPI schema. Do not edit by hand:
24
+ // regenerate with \`strata-api-types <schema> -o <this file>\`; CI runs it with --check.
25
+ `;
26
+ var footer = `
27
+ /** A named schema of the API: \`Schema<"Task">\`. */
28
+ export type Schema<K extends keyof components["schemas"]> = components["schemas"][K];
29
+ `;
30
+ /** The URL relative references resolve against: the document's own URL, or its file's location. */
31
+ function baseOf(source) {
32
+ return /^https?:\/\//i.test(source) ? new URL(source) : pathToFileURL(resolve(source));
33
+ }
34
+ /**
35
+ * The TypeScript types for an OpenAPI document, as the text of the generated file. `source` is where the
36
+ * document was read from (a URL or file path): relative `$ref`s to other files resolve against it.
37
+ */
38
+ async function generateApiTypes(schema, source) {
39
+ const { default: openapiTS, astToString } = await import("openapi-typescript").catch(() => {
40
+ throw new Error("strata-api-types needs openapi-typescript: npm install --save-dev openapi-typescript (it also wants TypeScript 5 or an override that points it at yours).");
41
+ });
42
+ return `${header}\n${astToString(await openapiTS(schema, source ? { cwd: baseOf(source) } : void 0)).trimEnd()}\n${footer}`;
43
+ }
44
+ export { loadSchema as n, generateApiTypes as t };
45
+
46
+ //# sourceMappingURL=generate-DCRYZPJs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-DCRYZPJs.js","names":[],"sources":["../src/api-types/generate.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n// The types behind `strata-api-types` (strata-react issue #263). A strata app's FastAPI server\n// publishes its routes, the shared contracts (`strata_python.contracts`: Health, Task, Page, ErrorBody…)\n// and its typed settings at `/api/openapi.json`; the TypeScript types follow that schema instead of\n// being written again by hand and drifting. The work of reading OpenAPI is `openapi-typescript`\n// (Jonathan, 2026-11-14: types only, nothing in the app's bundle); this file adds where the schema\n// comes from (a running server, or a file the server's own CLI wrote, so CI needs no server) and what\n// the committed file looks like. It lives behind its own entry (`strata-react/api-types`), like\n// `strata-react/visual`, and `openapi-typescript` is an optional peer, so an app that never runs the\n// command installs nothing and the main entry's peer contract is unchanged.\n//\n// The output is deterministic, so `--check` can compare it with the committed file and fail CI when\n// the Python side moved and the file did not. Nothing about the machine (the URL it was read from, a\n// date) goes into it, for the same reason.\n\n/** The OpenAPI document as the generator takes it: a parsed JSON object. */\nexport type OpenApiDocument = Record<string, unknown>;\n\n/** Reads an OpenAPI document from an `http(s)` URL (a running server) or a JSON file path. */\nexport async function loadSchema(source: string, fetcher: typeof fetch = fetch): Promise<OpenApiDocument> {\n let text: string;\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetcher(source, { headers: { accept: \"application/json\" } });\n if (!response.ok) throw new Error(`${source} answered ${response.status} ${response.statusText}`);\n text = await response.text();\n } else {\n text = await readFile(source, \"utf8\");\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(`${source} is not JSON. Give the OpenAPI document (/api/openapi.json), not the docs page.`);\n }\n if (!parsed || typeof parsed !== \"object\" || !(\"openapi\" in parsed)) throw new Error(`${source} is JSON but not an OpenAPI document (no \"openapi\" field).`);\n return parsed as OpenApiDocument;\n}\n\nconst header = `/* eslint-disable */\n// Generated by strata-api-types from the app's OpenAPI schema. Do not edit by hand:\n// regenerate with \\`strata-api-types <schema> -o <this file>\\`; CI runs it with --check.\n`;\n\n// Short names for the schemas, so a screen writes \\`Schema<\"Task\">\\` and not the whole path.\nconst footer = `\n/** A named schema of the API: \\`Schema<\"Task\">\\`. */\nexport type Schema<K extends keyof components[\"schemas\"]> = components[\"schemas\"][K];\n`;\n\n/** The URL relative references resolve against: the document's own URL, or its file's location. */\nfunction baseOf(source: string): URL {\n return /^https?:\\/\\//i.test(source) ? new URL(source) : pathToFileURL(resolve(source));\n}\n\n/**\n * The TypeScript types for an OpenAPI document, as the text of the generated file. `source` is where the\n * document was read from (a URL or file path): relative `$ref`s to other files resolve against it.\n */\nexport async function generateApiTypes(schema: OpenApiDocument, source?: string): Promise<string> {\n const mod = await import(\"openapi-typescript\").catch(() => {\n throw new Error(\"strata-api-types needs openapi-typescript: npm install --save-dev openapi-typescript (it also wants TypeScript 5 or an override that points it at yours).\");\n });\n const { default: openapiTS, astToString } = mod;\n const ast = await openapiTS(schema as never, source ? { cwd: baseOf(source) } : undefined);\n return `${header}\\n${astToString(ast).trimEnd()}\\n${footer}`;\n}\n"],"mappings":";;;;;AAsBA,eAAsB,WAAW,QAAgB,UAAwB,OAAiC;CACxG,IAAI;CACJ,IAAI,gBAAgB,KAAK,MAAM,GAAG;EAChC,MAAM,WAAW,MAAM,QAAQ,QAAQ,EAAE,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC;EAClF,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,GAAG,OAAO,YAAY,SAAS,OAAO,GAAG,SAAS,YAAY;EAChG,OAAO,MAAM,SAAS,KAAK;CAC7B,OACE,OAAO,MAAM,SAAS,QAAQ,MAAM;CAEtC,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN,MAAM,IAAI,MAAM,GAAG,OAAO,gFAAgF;CAC5G;CACA,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,EAAE,aAAa,SAAS,MAAM,IAAI,MAAM,GAAG,OAAO,2DAA2D;CAC1J,OAAO;AACT;AAEA,IAAM,SAAS;;;;AAMf,IAAM,SAAS;;;;;AAMf,SAAS,OAAO,QAAqB;CACnC,OAAO,gBAAgB,KAAK,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,cAAc,QAAQ,MAAM,CAAC;AACvF;;;;;AAMA,eAAsB,iBAAiB,QAAyB,QAAkC;CAIhG,MAAM,EAAE,SAAS,WAAW,gBAAgB,MAH1B,OAAO,qBAAqB,CAAC,YAAY;EACzD,MAAM,IAAI,MAAM,2JAA2J;CAC7K,CAAC;CAGD,OAAO,GAAG,OAAO,IAAI,YAAY,MADf,UAAU,QAAiB,SAAS,EAAE,KAAK,OAAO,MAAM,EAAE,IAAI,KAAA,CAAS,CACrD,CAAC,CAAC,QAAQ,EAAE,IAAI;AACtD"}
package/dist/index.d.ts CHANGED
@@ -71,7 +71,7 @@ export type { ControlSize } from './lib/control';
71
71
  export { useHotkeys, KeysLegend, isTypingTarget, type Shortcut } from './components/hotkeys';
72
72
  export { useActiveItem, ActiveList, type ActiveItem } from './components/active-list';
73
73
  export { ThemeProvider, useColorScheme, useSystemColorScheme, ColorSchemeChoice, colorSchemeScript, COLOR_SCHEME_STORAGE_KEY, type ColorScheme, type ColorSchemePreference, type ColorSchemeLabels, type ColorSchemeState, } from './components/theme';
74
- export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, fetchJson, HttpError, describeHttpError, readErrorBody, type DescribeError, type ErrorBody, type FetchJsonOptions, type InfiniteLoad, type InfiniteLoadOptions, type Job, type JobOptions, type More, } from './query';
74
+ export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, isTaskRunning, apiPage, fetchJson, HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody, type FetchJsonOptions, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type Job, type JobOptions, type More, } from './query';
75
75
  export { describeActionError, fieldErrorsOf } from './lib/errors';
76
76
  export { Compare, type CompareProps, type CompareMode, type Candidate, type ImageMedia, type AudioMedia, type TextMedia, type VideoMedia } from './components/compare';
77
77
  export { ViewportFrame, useViewport, type ViewportFrameProps, type ViewportState } from './components/viewport';