# @plurid/uitive-core

The contract, the client, data and policy: everything that adapts an interface, in any JavaScript runtime, with no DOM or Node APIs.

Install: `pnpm add @plurid/uitive-core`, with `zod` ^4.2.0 as a peer. Guides: [Getting started](https://uitive.dev/docs/getting-started), [Contracts](https://uitive.dev/docs/contracts), [Data and actions](https://uitive.dev/docs/data-and-actions), [Pages](https://uitive.dev/docs/pages).

- [Contracts](https://uitive.dev/docs/api/core#contracts): [`action`](https://uitive.dev/docs/api/core#action), [`assertIds`](https://uitive.dev/docs/api/core#assertids), [`block`](https://uitive.dev/docs/api/core#block), [`canonicalizer`](https://uitive.dev/docs/api/core#canonicalizer), [`choice`](https://uitive.dev/docs/api/core#choice), [`collection`](https://uitive.dev/docs/api/core#collection), [`CONTRACT_FORMAT`](https://uitive.dev/docs/api/core#contract_format), [`defineApp`](https://uitive.dev/docs/api/core#defineapp), [`fieldsFromJson`](https://uitive.dev/docs/api/core#fieldsfromjson), [`fieldsToJson`](https://uitive.dev/docs/api/core#fieldstojson), [`FORMAT_VERSION`](https://uitive.dev/docs/api/core#format_version), [`fromJson`](https://uitive.dev/docs/api/core#fromjson), [`ID_PATTERN`](https://uitive.dev/docs/api/core#id_pattern), [`itemSchema`](https://uitive.dev/docs/api/core#itemschema), [`list`](https://uitive.dev/docs/api/core#list), [`page`](https://uitive.dev/docs/api/core#page), [`SURFACE_PATTERN`](https://uitive.dev/docs/api/core#surface_pattern), [`toJson`](https://uitive.dev/docs/api/core#tojson), [`ActionIdOf`](https://uitive.dev/docs/api/core#actionidof), [`ActionJson`](https://uitive.dev/docs/api/core#actionjson), [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec), [`ActionView`](https://uitive.dev/docs/api/core#actionview), [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`BlockOf`](https://uitive.dev/docs/api/core#blockof), [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`ChoiceSpec`](https://uitive.dev/docs/api/core#choicespec), [`CollectionEntry`](https://uitive.dev/docs/api/core#collectionentry), [`CollectionSpec`](https://uitive.dev/docs/api/core#collectionspec), [`CollectionValue`](https://uitive.dev/docs/api/core#collectionvalue), [`ContextOf`](https://uitive.dev/docs/api/core#contextof), [`Contract`](https://uitive.dev/docs/api/core#contract), [`ContractJson`](https://uitive.dev/docs/api/core#contractjson), [`ContractSpec`](https://uitive.dev/docs/api/core#contractspec), [`FieldJson`](https://uitive.dev/docs/api/core#fieldjson), [`FieldsJson`](https://uitive.dev/docs/api/core#fieldsjson), [`ListSpec`](https://uitive.dev/docs/api/core#listspec), [`ListValue`](https://uitive.dev/docs/api/core#listvalue), [`PageSection`](https://uitive.dev/docs/api/core#pagesection), [`PageSpec`](https://uitive.dev/docs/api/core#pagespec), [`PropsOf`](https://uitive.dev/docs/api/core#propsof), [`RegionSpec`](https://uitive.dev/docs/api/core#regionspec), [`RowOf`](https://uitive.dev/docs/api/core#rowof), [`Runtime`](https://uitive.dev/docs/api/core#runtime), [`SectionPage`](https://uitive.dev/docs/api/core#sectionpage), [`SourceIdOf`](https://uitive.dev/docs/api/core#sourceidof), [`SourceJson`](https://uitive.dev/docs/api/core#sourcejson), [`SurfaceIdOf`](https://uitive.dev/docs/api/core#surfaceidof), [`SurfaceJson`](https://uitive.dev/docs/api/core#surfacejson), [`SurfaceSpec`](https://uitive.dev/docs/api/core#surfacespec), [`SurfaceValue`](https://uitive.dev/docs/api/core#surfacevalue), [`SurfaceValueOf`](https://uitive.dev/docs/api/core#surfacevalueof)
- [Sources and fields](https://uitive.dev/docs/api/core#sources-and-fields): [`ARITY`](https://uitive.dev/docs/api/core#arity), [`currencyDigits`](https://uitive.dev/docs/api/core#currencydigits), [`describeFields`](https://uitive.dev/docs/api/core#describefields), [`field`](https://uitive.dev/docs/api/core#field), [`FIELD_META`](https://uitive.dev/docs/api/core#field_meta), [`FIELD_PATTERN`](https://uitive.dev/docs/api/core#field_pattern), [`FIELD_TYPES`](https://uitive.dev/docs/api/core#field_types), [`humanize`](https://uitive.dev/docs/api/core#humanize), [`MAX_LIMIT`](https://uitive.dev/docs/api/core#max_limit), [`OPS`](https://uitive.dev/docs/api/core#ops), [`OPS_BY_TYPE`](https://uitive.dev/docs/api/core#ops_by_type), [`qualifiedFields`](https://uitive.dev/docs/api/core#qualifiedfields), [`resolvePath`](https://uitive.dev/docs/api/core#resolvepath), [`resolveSources`](https://uitive.dev/docs/api/core#resolvesources), [`SCAN`](https://uitive.dev/docs/api/core#scan), [`source`](https://uitive.dev/docs/api/core#source), [`SOURCE_PATTERN`](https://uitive.dev/docs/api/core#source_pattern), [`TTL`](https://uitive.dev/docs/api/core#ttl), [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`Capabilities`](https://uitive.dev/docs/api/core#capabilities), [`Field`](https://uitive.dev/docs/api/core#field-type), [`FieldMeta`](https://uitive.dev/docs/api/core#fieldmeta), [`FieldNameOf`](https://uitive.dev/docs/api/core#fieldnameof), [`FieldOptions`](https://uitive.dev/docs/api/core#fieldoptions), [`FieldPath`](https://uitive.dev/docs/api/core#fieldpath), [`FieldType`](https://uitive.dev/docs/api/core#fieldtype), [`MoneyOptions`](https://uitive.dev/docs/api/core#moneyoptions), [`Op`](https://uitive.dev/docs/api/core#op), [`ResolvedSource`](https://uitive.dev/docs/api/core#resolvedsource), [`SourceSpec`](https://uitive.dev/docs/api/core#sourcespec), [`TimeUnit`](https://uitive.dev/docs/api/core#timeunit)
- [Queries and data](https://uitive.dev/docs/api/core#queries-and-data): [`BUCKETS`](https://uitive.dev/docs/api/core#buckets), [`bucketStart`](https://uitive.dev/docs/api/core#bucketstart), [`checkQuery`](https://uitive.dev/docs/api/core#checkquery), [`createData`](https://uitive.dev/docs/api/core#createdata), [`DEFAULT_LIMIT`](https://uitive.dev/docs/api/core#default_limit), [`DIRECTIONS`](https://uitive.dev/docs/api/core#directions), [`formatValue`](https://uitive.dev/docs/api/core#formatvalue), [`fromRows`](https://uitive.dev/docs/api/core#fromrows), [`isToken`](https://uitive.dev/docs/api/core#istoken), [`MAX_FIELDS`](https://uitive.dev/docs/api/core#max_fields), [`MAX_FILTERS`](https://uitive.dev/docs/api/core#max_filters), [`MAX_SORTS`](https://uitive.dev/docs/api/core#max_sorts), [`MEASURES`](https://uitive.dev/docs/api/core#measures), [`NO_AGGREGATE`](https://uitive.dev/docs/api/core#no_aggregate), [`NONE`](https://uitive.dev/docs/api/core#none), [`parseTime`](https://uitive.dev/docs/api/core#parsetime), [`parseValue`](https://uitive.dev/docs/api/core#parsevalue), [`partsIn`](https://uitive.dev/docs/api/core#partsin), [`PERIODS`](https://uitive.dev/docs/api/core#periods), [`query`](https://uitive.dev/docs/api/core#query), [`runQuery`](https://uitive.dev/docs/api/core#runquery), [`SEARCH_LENGTH`](https://uitive.dev/docs/api/core#search_length), [`startOf`](https://uitive.dev/docs/api/core#startof), [`timeOf`](https://uitive.dev/docs/api/core#timeof), [`TOKENS`](https://uitive.dev/docs/api/core#tokens), [`VALUE_LENGTH`](https://uitive.dev/docs/api/core#value_length), [`Aggregate`](https://uitive.dev/docs/api/core#aggregate), [`BindingContext`](https://uitive.dev/docs/api/core#bindingcontext), [`Bucket`](https://uitive.dev/docs/api/core#bucket), [`Clock`](https://uitive.dev/docs/api/core#clock), [`DataClient`](https://uitive.dev/docs/api/core#dataclient), [`DataEntry`](https://uitive.dev/docs/api/core#dataentry), [`DataOptions`](https://uitive.dev/docs/api/core#dataoptions), [`DataScope`](https://uitive.dev/docs/api/core#datascope), [`Direction`](https://uitive.dev/docs/api/core#direction), [`Fetch`](https://uitive.dev/docs/api/core#fetch), [`Fetchers`](https://uitive.dev/docs/api/core#fetchers), [`FetchFilter`](https://uitive.dev/docs/api/core#fetchfilter), [`FetchRequest`](https://uitive.dev/docs/api/core#fetchrequest), [`FetchResult`](https://uitive.dev/docs/api/core#fetchresult), [`Filter`](https://uitive.dev/docs/api/core#filter), [`Group`](https://uitive.dev/docs/api/core#group), [`LocalParts`](https://uitive.dev/docs/api/core#localparts), [`Measure`](https://uitive.dev/docs/api/core#measure), [`Parsed`](https://uitive.dev/docs/api/core#parsed), [`Period`](https://uitive.dev/docs/api/core#period), [`Query`](https://uitive.dev/docs/api/core#query-type), [`QueryCheck`](https://uitive.dev/docs/api/core#querycheck), [`QueryResult`](https://uitive.dev/docs/api/core#queryresult), [`QueryScope`](https://uitive.dev/docs/api/core#queryscope), [`Row`](https://uitive.dev/docs/api/core#row), [`RunOptions`](https://uitive.dev/docs/api/core#runoptions), [`Sort`](https://uitive.dev/docs/api/core#sort), [`Stored`](https://uitive.dev/docs/api/core#stored), [`Token`](https://uitive.dev/docs/api/core#token)
- [Actions and bindings](https://uitive.dev/docs/api/core#actions-and-bindings): [`EFFECTS`](https://uitive.dev/docs/api/core#effects), [`pointer`](https://uitive.dev/docs/api/core#pointer), [`restFetch`](https://uitive.dev/docs/api/core#restfetch), [`restPerform`](https://uitive.dev/docs/api/core#restperform), [`rowParam`](https://uitive.dev/docs/api/core#rowparam), [`Bindings`](https://uitive.dev/docs/api/core#bindings), [`Confirmation`](https://uitive.dev/docs/api/core#confirmation), [`DeclaredParams`](https://uitive.dev/docs/api/core#declaredparams), [`Effect`](https://uitive.dev/docs/api/core#effect), [`HttpFetch`](https://uitive.dev/docs/api/core#httpfetch), [`HttpResponse`](https://uitive.dev/docs/api/core#httpresponse), [`ParamsOf`](https://uitive.dev/docs/api/core#paramsof), [`Perform`](https://uitive.dev/docs/api/core#perform), [`PerformContext`](https://uitive.dev/docs/api/core#performcontext), [`Performers`](https://uitive.dev/docs/api/core#performers), [`PerformOptions`](https://uitive.dev/docs/api/core#performoptions), [`PerformOutcome`](https://uitive.dev/docs/api/core#performoutcome), [`PerformResult`](https://uitive.dev/docs/api/core#performresult), [`RestAction`](https://uitive.dev/docs/api/core#restaction), [`RestFetchConfig`](https://uitive.dev/docs/api/core#restfetchconfig), [`RestPerformConfig`](https://uitive.dev/docs/api/core#restperformconfig), [`RestSource`](https://uitive.dev/docs/api/core#restsource), [`Target`](https://uitive.dev/docs/api/core#target)
- [Pages and blocks](https://uitive.dev/docs/api/core#pages-and-blocks): [`BUILT_IN`](https://uitive.dev/docs/api/core#built_in), [`builtInBlocks`](https://uitive.dev/docs/api/core#builtinblocks), [`checkGeneric`](https://uitive.dev/docs/api/core#checkgeneric), [`DATA_BLOCKS`](https://uitive.dev/docs/api/core#data_blocks), [`DATA_PATTERN`](https://uitive.dev/docs/api/core#data_pattern), [`ELEMENT_PATTERN`](https://uitive.dev/docs/api/core#element_pattern), [`fromSections`](https://uitive.dev/docs/api/core#fromsections), [`GENERIC`](https://uitive.dev/docs/api/core#generic), [`genericBlocks`](https://uitive.dev/docs/api/core#genericblocks), [`genericFor`](https://uitive.dev/docs/api/core#genericfor), [`GenericProblem`](https://uitive.dev/docs/api/core#genericproblem), [`LAYOUTS`](https://uitive.dev/docs/api/core#layouts), [`MAX_DEPTH`](https://uitive.dev/docs/api/core#max_depth), [`MAX_ELEMENTS`](https://uitive.dev/docs/api/core#max_elements), [`MAX_QUERIES`](https://uitive.dev/docs/api/core#max_queries), [`PageProblem`](https://uitive.dev/docs/api/core#pageproblem), [`periodOf`](https://uitive.dev/docs/api/core#periodof), [`regionsFor`](https://uitive.dev/docs/api/core#regionsfor), [`toPage`](https://uitive.dev/docs/api/core#topage), [`ui`](https://uitive.dev/docs/api/core#ui), [`USER_PAGE_PATH`](https://uitive.dev/docs/api/core#user_page_path), [`userPagePath`](https://uitive.dev/docs/api/core#userpagepath), [`userPageSpec`](https://uitive.dev/docs/api/core#userpagespec), [`validatePage`](https://uitive.dev/docs/api/core#validatepage), [`walk`](https://uitive.dev/docs/api/core#walk), [`ActionsProps`](https://uitive.dev/docs/api/core#actionsprops), [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`BoardProps`](https://uitive.dev/docs/api/core#boardprops), [`BuiltIn`](https://uitive.dev/docs/api/core#builtin), [`BuiltInElement`](https://uitive.dev/docs/api/core#builtinelement), [`ChartProps`](https://uitive.dev/docs/api/core#chartprops), [`DetailProps`](https://uitive.dev/docs/api/core#detailprops), [`Element`](https://uitive.dev/docs/api/core#element), [`ElementOf`](https://uitive.dev/docs/api/core#elementof), [`FormProps`](https://uitive.dev/docs/api/core#formprops), [`GenericName`](https://uitive.dev/docs/api/core#genericname), [`GenericProps`](https://uitive.dev/docs/api/core#genericprops), [`GenericScope`](https://uitive.dev/docs/api/core#genericscope), [`Layout`](https://uitive.dev/docs/api/core#layout), [`LinksProps`](https://uitive.dev/docs/api/core#linksprops), [`ListProps`](https://uitive.dev/docs/api/core#listprops), [`MetricProps`](https://uitive.dev/docs/api/core#metricprops), [`NamedQuery`](https://uitive.dev/docs/api/core#namedquery), [`Node`](https://uitive.dev/docs/api/core#node), [`NoteProps`](https://uitive.dev/docs/api/core#noteprops), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue), [`RegionProps`](https://uitive.dev/docs/api/core#regionprops), [`RowAction`](https://uitive.dev/docs/api/core#rowaction), [`SectionProps`](https://uitive.dev/docs/api/core#sectionprops), [`SectionsPage`](https://uitive.dev/docs/api/core#sectionspage), [`TableProps`](https://uitive.dev/docs/api/core#tableprops), [`TabsProps`](https://uitive.dev/docs/api/core#tabsprops), [`TimelineProps`](https://uitive.dev/docs/api/core#timelineprops), [`ValidateOptions`](https://uitive.dev/docs/api/core#validateoptions)
- [Routes](https://uitive.dev/docs/api/core#routes): [`buildPath`](https://uitive.dev/docs/api/core#buildpath), [`entityRoute`](https://uitive.dev/docs/api/core#entityroute), [`matchRoute`](https://uitive.dev/docs/api/core#matchroute), [`route`](https://uitive.dev/docs/api/core#route), [`routeLabel`](https://uitive.dev/docs/api/core#routelabel), [`segments`](https://uitive.dev/docs/api/core#segments), [`validateRoutes`](https://uitive.dev/docs/api/core#validateroutes), [`RouteSegment`](https://uitive.dev/docs/api/core#routesegment), [`RouteSpec`](https://uitive.dev/docs/api/core#routespec)
- [The client](https://uitive.dev/docs/api/core#the-client): [`createUitive`](https://uitive.dev/docs/api/core#createuitive), [`localStore`](https://uitive.dev/docs/api/core#localstore), [`memoryStore`](https://uitive.dev/docs/api/core#memorystore), [`Adaptation`](https://uitive.dev/docs/api/core#adaptation), [`Autonomy`](https://uitive.dev/docs/api/core#autonomy), [`DefinitionDocument`](https://uitive.dev/docs/api/core#definitiondocument), [`Location`](https://uitive.dev/docs/api/core#location), [`PageInput`](https://uitive.dev/docs/api/core#pageinput), [`RecordOptions`](https://uitive.dev/docs/api/core#recordoptions), [`Snapshot`](https://uitive.dev/docs/api/core#snapshot), [`Store`](https://uitive.dev/docs/api/core#store), [`Uitive`](https://uitive.dev/docs/api/core#uitive), [`UitiveOptions`](https://uitive.dev/docs/api/core#uitiveoptions), [`View`](https://uitive.dev/docs/api/core#view)
- [Planners](https://uitive.dev/docs/api/core#planners): [`command`](https://uitive.dev/docs/api/core#command), [`heuristicPlanner`](https://uitive.dev/docs/api/core#heuristicplanner), [`keywordCommand`](https://uitive.dev/docs/api/core#keywordcommand), [`MARGIN`](https://uitive.dev/docs/api/core#margin), [`MIN_PROMOTE`](https://uitive.dev/docs/api/core#min_promote), [`planResultSchema`](https://uitive.dev/docs/api/core#planresultschema), [`remotePlanner`](https://uitive.dev/docs/api/core#remoteplanner), [`ClaimedEvidence`](https://uitive.dev/docs/api/core#claimedevidence), [`CommandResult`](https://uitive.dev/docs/api/core#commandresult), [`CommandStatus`](https://uitive.dev/docs/api/core#commandstatus), [`Environment`](https://uitive.dev/docs/api/core#environment), [`FetchLike`](https://uitive.dev/docs/api/core#fetchlike), [`PlanMeta`](https://uitive.dev/docs/api/core#planmeta), [`Planner`](https://uitive.dev/docs/api/core#planner), [`PlannerResponse`](https://uitive.dev/docs/api/core#plannerresponse), [`PlannerStream`](https://uitive.dev/docs/api/core#plannerstream), [`PlanOptions`](https://uitive.dev/docs/api/core#planoptions), [`PlanProgress`](https://uitive.dev/docs/api/core#planprogress), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest), [`PlanResult`](https://uitive.dev/docs/api/core#planresult), [`ProposedOperation`](https://uitive.dev/docs/api/core#proposedoperation), [`RemotePlannerOptions`](https://uitive.dev/docs/api/core#remoteplanneroptions), [`StateView`](https://uitive.dev/docs/api/core#stateview)
- [Definitions and policy](https://uitive.dev/docs/api/core#definitions-and-policy): [`canonical`](https://uitive.dev/docs/api/core#canonical), [`check`](https://uitive.dev/docs/api/core#check), [`checkPageValue`](https://uitive.dev/docs/api/core#checkpagevalue), [`DEFAULT_STABILIZER`](https://uitive.dev/docs/api/core#default_stabilizer), [`describe`](https://uitive.dev/docs/api/core#describe), [`emptyDefinition`](https://uitive.dev/docs/api/core#emptydefinition), [`EVERY`](https://uitive.dev/docs/api/core#every), [`isApplied`](https://uitive.dev/docs/api/core#isapplied), [`MAX_USER_PAGES`](https://uitive.dev/docs/api/core#max_user_pages), [`METRICS`](https://uitive.dev/docs/api/core#metrics), [`migrateDefinition`](https://uitive.dev/docs/api/core#migratedefinition), [`MIN_IDLE`](https://uitive.dev/docs/api/core#min_idle), [`NOTE_LENGTH`](https://uitive.dev/docs/api/core#note_length), [`operationKey`](https://uitive.dev/docs/api/core#operationkey), [`redesigned`](https://uitive.dev/docs/api/core#redesigned), [`resolveChoice`](https://uitive.dev/docs/api/core#resolvechoice), [`resolveCollection`](https://uitive.dev/docs/api/core#resolvecollection), [`resolveList`](https://uitive.dev/docs/api/core#resolvelist), [`resolvePage`](https://uitive.dev/docs/api/core#resolvepage), [`resolveUserPages`](https://uitive.dev/docs/api/core#resolveuserpages), [`SLUG_PATTERN`](https://uitive.dev/docs/api/core#slug_pattern), [`TEXT_LENGTH`](https://uitive.dev/docs/api/core#text_length), [`TITLE_LENGTH`](https://uitive.dev/docs/api/core#title_length), [`USER_PAGES`](https://uitive.dev/docs/api/core#user_pages), [`validateOutput`](https://uitive.dev/docs/api/core#validateoutput), [`AppliedOperation`](https://uitive.dev/docs/api/core#appliedoperation), [`Change`](https://uitive.dev/docs/api/core#change), [`CheckResult`](https://uitive.dev/docs/api/core#checkresult), [`ChoiceChange`](https://uitive.dev/docs/api/core#choicechange), [`CollectionChange`](https://uitive.dev/docs/api/core#collectionchange), [`Definition`](https://uitive.dev/docs/api/core#definition), [`Evidence`](https://uitive.dev/docs/api/core#evidence), [`Explanation`](https://uitive.dev/docs/api/core#explanation), [`ListChange`](https://uitive.dev/docs/api/core#listchange), [`ListState`](https://uitive.dev/docs/api/core#liststate), [`Metric`](https://uitive.dev/docs/api/core#metric), [`Operation`](https://uitive.dev/docs/api/core#operation), [`Origin`](https://uitive.dev/docs/api/core#origin), [`OutputRejection`](https://uitive.dev/docs/api/core#outputrejection), [`PageChange`](https://uitive.dev/docs/api/core#pagechange), [`Pending`](https://uitive.dev/docs/api/core#pending), [`PolicyContext`](https://uitive.dev/docs/api/core#policycontext), [`Rejection`](https://uitive.dev/docs/api/core#rejection), [`Rule`](https://uitive.dev/docs/api/core#rule), [`StabilizerOptions`](https://uitive.dev/docs/api/core#stabilizeroptions), [`Status`](https://uitive.dev/docs/api/core#status), [`UserPage`](https://uitive.dev/docs/api/core#userpage), [`UserPageChange`](https://uitive.dev/docs/api/core#userpagechange)
- [Usage and simulation](https://uitive.dev/docs/api/core#usage-and-simulation): [`DECAY`](https://uitive.dev/docs/api/core#decay), [`random`](https://uitive.dev/docs/api/core#random), [`rank`](https://uitive.dev/docs/api/core#rank), [`simulate`](https://uitive.dev/docs/api/core#simulate), [`summarize`](https://uitive.dev/docs/api/core#summarize), [`VIAS`](https://uitive.dev/docs/api/core#vias), [`visibleLists`](https://uitive.dev/docs/api/core#visiblelists), [`WINDOW`](https://uitive.dev/docs/api/core#window), [`Persona`](https://uitive.dev/docs/api/core#persona), [`SessionRecord`](https://uitive.dev/docs/api/core#sessionrecord), [`SessionReport`](https://uitive.dev/docs/api/core#sessionreport), [`UsageEvent`](https://uitive.dev/docs/api/core#usageevent), [`UsageRow`](https://uitive.dev/docs/api/core#usagerow), [`UsageSummary`](https://uitive.dev/docs/api/core#usagesummary), [`Via`](https://uitive.dev/docs/api/core#via)
- [Advanced](https://uitive.dev/docs/api/core#advanced): [`actionsInScope`](https://uitive.dev/docs/api/core#actionsinscope), [`areasOf`](https://uitive.dev/docs/api/core#areasof), [`EXTRA_AREAS`](https://uitive.dev/docs/api/core#extra_areas), [`hash`](https://uitive.dev/docs/api/core#hash), [`MAX_ACTIONS`](https://uitive.dev/docs/api/core#max_actions), [`MAX_SOURCES`](https://uitive.dev/docs/api/core#max_sources), [`rankAreas`](https://uitive.dev/docs/api/core#rankareas), [`selectSubset`](https://uitive.dev/docs/api/core#selectsubset), [`sourcesInView`](https://uitive.dev/docs/api/core#sourcesinview), [`stableStringify`](https://uitive.dev/docs/api/core#stablestringify), [`terms`](https://uitive.dev/docs/api/core#terms), [`Area`](https://uitive.dev/docs/api/core#area), [`Subset`](https://uitive.dev/docs/api/core#subset), [`SubsetOptions`](https://uitive.dev/docs/api/core#subsetoptions)

## Contracts

Source: [`contract.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/contract.ts), [`ids.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/ids.ts), [`json.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/json.ts)

### action

Declares something people can do, such as `orders.cancel`. Without an `effect` it belongs to
the interface only; with one it runs through the bindings' `perform`, and writes wait for the
person's yes.

```ts
function action<const P extends z.ZodObject = z.ZodObject<{}>>(spec: ActionSpec<P>): ActionSpec<P>;
```

Uses: [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec).

### assertIds

Throws unless every ID matches its pattern and none collide ignoring case.

```ts
function assertIds(domain: string, ids: readonly string[], pattern?: RegExp): void;
```

### block

Declares a part pages are built from: one of the application's own components, with typed props.

```ts
function block<P>(spec: BlockSpec<P>): BlockSpec<P>;
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec).

### canonicalizer

Maps a value to the canonical ID it names, comparing case-insensitively.

```ts
function canonicalizer(ids: readonly string[]): (value: string) => string | undefined;
```

### choice

Declares one value out of a fixed set, such as a theme or a density.

```ts
function choice<const V extends string>(
  spec: Omit<ChoiceSpec<V>, 'kind' | 'default'> & {
    default: NoInfer<V>;
  },
): ChoiceSpec<V>;
```

Uses: [`ChoiceSpec`](https://uitive.dev/docs/api/core#choicespec).

### collection

Declares generated items, such as saved views or macros, that people accept, edit or dismiss.

```ts
function collection<T>(spec: Omit<CollectionSpec<T>, 'kind'>): CollectionSpec<T>;
```

Uses: [`CollectionSpec`](https://uitive.dev/docs/api/core#collectionspec).

### CONTRACT_FORMAT

What a JSON contract says it is, in its `format` field.

```ts
const CONTRACT_FORMAT = 'uitive.contract';
```

### defineApp

Declares what may adapt in an application. Validates every ID and reference, and freezes
the result: the contract is the boundary planners work within.

```ts
function defineApp<
  const A extends Record<string, ActionSpec>,
  const S extends Record<string, SurfaceSpec<Extract<keyof A, string>>>,
  const C extends Record<string, readonly string[]> = Record<never, never>,
  const D extends Record<string, AnySourceSpec> = Record<never, never>,
>(spec: ContractSpec<A, S, C, D>): Contract<A, S, C, D>;
```

Uses: [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec), [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`Contract`](https://uitive.dev/docs/api/core#contract), [`ContractSpec`](https://uitive.dev/docs/api/core#contractspec), [`SurfaceSpec`](https://uitive.dev/docs/api/core#surfacespec).

### fieldsFromJson

Fields back from JSON, as the zod object describeFields reads them from.

```ts
function fieldsFromJson(json: FieldsJson): z.ZodObject;
```

Uses: [`FieldsJson`](https://uitive.dev/docs/api/core#fieldsjson).

### fieldsToJson

Fields as canonical JSON: every meaning written out, so nothing is inferred on the way back.

```ts
function fieldsToJson(fields: readonly Field[]): FieldsJson;
```

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type), [`FieldsJson`](https://uitive.dev/docs/api/core#fieldsjson).

### FORMAT_VERSION

The JSON contract format's version.

```ts
const FORMAT_VERSION = 2;
```

### fromJson

Loads a contract from JSON. It is checked as `defineApp` checks any contract; validators can
be reattached through `runtime`, since JSON can't carry them.

```ts
function fromJson(raw: unknown, runtime?: Runtime): Contract;
```

Uses: [`Contract`](https://uitive.dev/docs/api/core#contract), [`Runtime`](https://uitive.dev/docs/api/core#runtime).

### ID_PATTERN

Action IDs, context values and choice values: everything a planner may emit as an enum
value. Lowercase only, because structured outputs don't guarantee the casing of enum values.

```ts
const ID_PATTERN: RegExp = /^[a-z0-9][a-z0-9.:-]*$/;
```

### itemSchema

The JSON Schema of a collection item, or a marker when zod can't represent it.

```ts
function itemSchema(schema: z.ZodType): unknown;
```

### list

Declares an ordered selection of actions, such as a toolbar or a menu: the first `capacity` show
and the rest wait in overflow.

```ts
function list<const A extends string>(
  spec: Omit<ListSpec<A>, 'kind' | 'required' | 'available'> & {
    required?: readonly NoInfer<A>[];
    available?(value: string): readonly NoInfer<A>[];
  },
): ListSpec<A>;
```

Uses: [`ListSpec`](https://uitive.dev/docs/api/core#listspec).

### page

A page made of these blocks: `page({ table, chart })({ label, description, standard })`.
Taking the blocks first fixes their types, so the standard page is checked against them.

```ts
function page<const B extends Record<string, BlockSpec>>(
  blocks: B,
): (spec: Omit<PageSpec<B>, 'kind' | 'blocks'>) => PageSpec<B>;
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`PageSpec`](https://uitive.dev/docs/api/core#pagespec).

### SURFACE_PATTERN

Surface names are identifiers in application code.

```ts
const SURFACE_PATTERN: RegExp = /^[a-z][a-zA-Z0-9]*$/;
```

### toJson

A contract as data. Functions become data (a list's items per context value, standard pages)
or are left out (validators). Schemas that would not survive the trip back are refused, so
`fromJson(toJson(c)).hash === c.hash`.

```ts
function toJson(contract: AnyContract): ContractJson;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`ContractJson`](https://uitive.dev/docs/api/core#contractjson).

### ActionIdOf

A contract's action IDs, as a union, such as `ActionIdOf<typeof shop>`.

```ts
type ActionIdOf<T extends AnyContract> = Extract<keyof T['actions'], string>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### ActionJson

One action as JSON: its label, description, params as JSON Schema, and effect.

Uses: [`Effect`](https://uitive.dev/docs/api/core#effect), [`FieldsJson`](https://uitive.dev/docs/api/core#fieldsjson), [`Filter`](https://uitive.dev/docs/api/core#filter).

| Property | Type | Description |
| - | - | - |
| `label` | `string` | Shown to people and to the model. |
| `description` | `string` | What the action does. |
| `group?` | `string` | The action's group. |
| `aliases?` | `string[]` | Former IDs, so stored usage survives a rename. |
| `params?` | `FieldsJson` | What a run takes. |
| `effect?` | `Effect` | What a run does to data. |
| `confirm?` | `string` | For destructive actions: the phrase a run asks for. |
| `when?` | `Filter[]` | For row actions: the rows it applies to. |
| `invalidates?` | `string[]` | Sources a run changes. |

### ActionSpec

Something a user can do.

Uses: [`Effect`](https://uitive.dev/docs/api/core#effect), [`Filter`](https://uitive.dev/docs/api/core#filter).

Type parameters: `P extends z.ZodObject = z.ZodObject`.

| Property | Type | Default | Description |
| - | - | - | - |
| `label` | `string` | | Shown to people and to the model. |
| `description` | `string` | | What the action does, written for people and models alike. |
| `group?` | `string` | | Groups related actions, for display and for the model. |
| `aliases?` | `readonly string[]` | `[]` | Former IDs of this action, so stored usage survives a rename. |
| `params?` | `P` | | What a run takes: flat fields, like a source's row. A `ref` param makes it a row action. |
| `effect?` | `Effect` | | What a run does. Without one, the action belongs to the interface only. |
| `confirm?` | `string` | the label | For destructive actions: what the user types to confirm. |
| `when?` | `readonly Filter[]` | every row | For row actions: the rows it applies to, as filters on the row's source. |
| `invalidates?` | `readonly string[]` | `[]` | Sources a run changes, so results that read them refresh. |

### ActionView

An action as a surface shows it.

Type parameters: `A extends string = string`.

| Property | Type | Description |
| - | - | - |
| `id` | `A` | The action's ID. |
| `label` | `string` | The action's label. |
| `description` | `string` | What the action does. |
| `group?` | `string` | The action's group, when it has one. |
| `pinned` | `boolean` | The user pinned it here. |
| `moved` | `boolean` | It moved here through an applied operation, for "moved" markers. |

### AnyContract

Any contract, with its IDs widened to strings: what generic code works with.

Uses: [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec), [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`Field`](https://uitive.dev/docs/api/core#field-type), [`FieldPath`](https://uitive.dev/docs/api/core#fieldpath), [`RegionSpec`](https://uitive.dev/docs/api/core#regionspec), [`ResolvedSource`](https://uitive.dev/docs/api/core#resolvedsource), [`RouteSpec`](https://uitive.dev/docs/api/core#routespec), [`SurfaceSpec`](https://uitive.dev/docs/api/core#surfacespec).

| Property | Type | Description |
| - | - | - |
| `id` | `string` | The application's ID. |
| `version` | `string` | The version the application gave, for changes the hash can't see. |
| `description` | `string` | What the application is, for the model. |
| `actions` | `Readonly<Record<string, ActionSpec>>` | Every action, by ID. |
| `contexts` | `Readonly<Record<string, readonly string[]>>` | Every context, with its values. |
| `sources` | `Readonly<Record<string, AnySourceSpec>>` | Every source, by ID. |
| `regions` | `Readonly<Record<string, RegionSpec>>` | Every region, by name. |
| `routes` | `Readonly<Record<string, RouteSpec>>` | Every route, by ID. |
| `surfaces` | `Readonly<Record<string, SurfaceSpec>>` | Every surface, by name. |
| `hash` | `string` | Changes whenever anything a planner sees changes, standard pages included. |
| `actionIds` | `readonly string[]` | Every action ID, in declaration order. |
| `sourceIds` | `readonly string[]` | Every source ID, in declaration order. |
| `routeIds` | `readonly string[]` | Every route ID, in declaration order. |
| `surfaceIds` | `readonly string[]` | Every surface name, in declaration order. |
| `action()` | `(id: string) => string \| undefined` | The action an ID or former ID names, compared case-insensitively. |
| `surface()` | `(name: string) => string \| undefined` | The surface a name refers to, compared case-insensitively. |
| `contextValue()` | `(context: string, value: string) => string \| undefined` | The canonical value of a context, compared case-insensitively. |
| `items()` | `(surface: string, context?: string) => readonly string[]` | The items a list offers, for one context value when the list is keyed by context. |
| `source()` | `(id: string) => ResolvedSource \| undefined` | A source with its fields described, by ID compared case-insensitively. |
| `path()` | `(name: string) => FieldPath \| undefined` | A qualified field name such as `payments.customer.email`, compared case-insensitively. |
| `params()` | `(action: string) => readonly Field[]` | An action's params, described as fields. Empty when it takes none. |
| `route()` | `(name: string) => string \| undefined` | The route a name refers to, compared case-insensitively. |

### AnyPageSpec

Any page surface, with its blocks widened.

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`GenericName`](https://uitive.dev/docs/api/core#genericname), [`SectionsPage`](https://uitive.dev/docs/api/core#sectionspage).

| Property | Type | Default | Description |
| - | - | - | - |
| `kind` | `'page'` | | Says the surface is a page. |
| `blocks` | `Readonly<Record<string, BlockSpec>>` | | The application's own blocks the page may use, besides sections, tabs and regions. |
| `context?` | `string` | | The context that keys this page, such as `service`; it can be redesigned per value or for all. |
| `entity?` | `string` | | The source whose rows this page is about, such as `customers`; `$current` names the row. |
| `generic?` | `boolean \| readonly GenericName[]` | every one the contract can feed | Generic blocks the page offers. |
| `standard()` | `(context: string \| undefined) => AnyPage \| SectionsPage` | | The page before anyone changes it, for a context value when the page has a context. |
| `maxElements?` | `number` | `40` | How many elements a page may hold. |
| `maxDepth?` | `number` | `4` | How deeply a page's sections may nest. |
| `maxQueries?` | `number` | `8` | Queries a page may run. |
| `label` | `string` | | Shown to people, such as "Toolbar". |
| `description` | `string` | | What the surface is for, written for people and models alike. |

### BlockOf

One placed block: which block, with which props.

```ts
type BlockOf<B extends Record<string, BlockSpec>> = {
  [K in Extract<keyof B, string>]: {
    block: K;
    props: PropsOf<B[K]>;
  };
}[Extract<keyof B, string>];
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`PropsOf`](https://uitive.dev/docs/api/core#propsof).

### BlockSpec

A part pages are built from: a component the application renders, with typed props.

Type parameters: `P = unknown`.

| Property | Type | Description |
| - | - | - |
| `label` | `string` | Shown to people, such as "Resource table". |
| `description` | `string` | What the block shows and how its props change it, for people and models alike. |
| `props` | `z.ZodType<P>` | The schema of the block's props. Planners can only produce props it accepts. |
| `validate?()` | `(props: P, context: string \| undefined) => string \| undefined` | Application rules beyond the schema, given the page's context value; returns why props are invalid. |

### ChoiceSpec

One value out of a fixed set.

Type parameters: `V extends string = string`.

| Property | Type | Description |
| - | - | - |
| `kind` | `'choice'` | Says the surface is a choice. |
| `values` | `readonly V[]` | Every value, in the order people see them. |
| `default` | `V` | The value before anyone chooses one. |
| `label` | `string` | Shown to people, such as "Toolbar". |
| `description` | `string` | What the surface is for, written for people and models alike. |

### CollectionEntry

One item of a collection, with the operation that added it.

Type parameters: `T = unknown`.

| Property | Type | Description |
| - | - | - |
| `id` | `string` | The item's ID. |
| `title` | `string` | Its title, from the collection's `title`. |
| `value` | `T` | The item itself. |
| `operation` | `string` | The operation that added it, for Revert, Keep and explanations. |

### CollectionSpec

Generated items, such as macros or saved views, that users accept, edit or dismiss.

Type parameters: `T = unknown`.

| Property | Type | Description |
| - | - | - |
| `kind` | `'collection'` | Says the surface is a collection. |
| `item` | `z.ZodType<T>` | The schema of one item. Planners can only produce items it accepts. |
| `max` | `number` | At most this many accepted items. |
| `title()` | `(item: T) => string` | A short title for an item, shown to people. |
| `validate?()` | `(item: T) => string \| undefined` | Application rules beyond the schema; returns why an item is invalid. |
| `label` | `string` | Shown to people, such as "Toolbar". |
| `description` | `string` | What the surface is for, written for people and models alike. |

### CollectionValue

A collection as a person's interface has it: the items they accepted, and suggestions waiting for
an answer.

Uses: [`CollectionEntry`](https://uitive.dev/docs/api/core#collectionentry).

Type parameters: `T = unknown`.

| Property | Type | Description |
| - | - | - |
| `items` | `readonly CollectionEntry<T>[]` | Items the person accepted or added. |
| `suggestions` | `readonly CollectionEntry<T>[]` | Proposed items waiting for the user to accept or dismiss them. |

### ContextOf

A contract's context names, as a union.

```ts
type ContextOf<T extends AnyContract> = Extract<keyof T['contexts'], string>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### Contract

A contract as `defineApp` returns it: the spec checked and frozen, with its IDs listed and the
hash that identifies it.

Uses: [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec), [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`SurfaceSpec`](https://uitive.dev/docs/api/core#surfacespec).

Type parameters: `A extends Record<string, ActionSpec> = Record<string, ActionSpec>`, `S extends Record<string, SurfaceSpec> = Record<string, SurfaceSpec>`, `C extends Record<string, readonly string[]> = Record<string, readonly string[]>`, `D extends Record<string, AnySourceSpec> = Record<string, AnySourceSpec>`.

| Property | Type | Description |
| - | - | - |
| `actions` | `A` | Every action, by ID. |
| `contexts` | `C` | Every context, with its values. |
| `sources` | `D` | Every source, by ID. |
| `surfaces` | `S` | Every surface, by name. |
| `actionIds` | `readonly Extract<keyof A, string>[]` | Every action ID, in declaration order. |
| `sourceIds` | `readonly Extract<keyof D, string>[]` | Every source ID, in declaration order. |
| `surfaceIds` | `readonly Extract<keyof S, string>[]` | Every surface name, in declaration order. |
| `action()` | `(id: string) => Extract<keyof A, string> \| undefined` | The action an ID or former ID names, compared case-insensitively. |
| `surface()` | `(name: string) => Extract<keyof S, string> \| undefined` | The surface a name refers to, compared case-insensitively. |
| `id` | `string` | The application's ID. |
| `version` | `string` | The version the application gave, for changes the hash can't see. |
| `description` | `string` | What the application is, for the model. |
| `regions` | `Readonly<Record<string, RegionSpec>>` | Every region, by name. |
| `routes` | `Readonly<Record<string, RouteSpec>>` | Every route, by ID. |
| `hash` | `string` | Changes whenever anything a planner sees changes, standard pages included. |
| `routeIds` | `readonly string[]` | Every route ID, in declaration order. |
| `contextValue()` | `(context: string, value: string) => string \| undefined` | The canonical value of a context, compared case-insensitively. |
| `items()` | `(surface: string, context?: string) => readonly string[]` | The items a list offers, for one context value when the list is keyed by context. |
| `source()` | `(id: string) => ResolvedSource \| undefined` | A source with its fields described, by ID compared case-insensitively. |
| `path()` | `(name: string) => FieldPath \| undefined` | A qualified field name such as `payments.customer.email`, compared case-insensitively. |
| `params()` | `(action: string) => readonly Field[]` | An action's params, described as fields. Empty when it takes none. |
| `route()` | `(name: string) => string \| undefined` | The route a name refers to, compared case-insensitively. |

### ContractJson

A contract as data: what adapters, agents and hosted planners exchange.

Uses: [`CONTRACT_FORMAT`](https://uitive.dev/docs/api/core#contract_format), [`FORMAT_VERSION`](https://uitive.dev/docs/api/core#format_version), [`ActionJson`](https://uitive.dev/docs/api/core#actionjson), [`RegionSpec`](https://uitive.dev/docs/api/core#regionspec), [`RouteSpec`](https://uitive.dev/docs/api/core#routespec), [`SourceJson`](https://uitive.dev/docs/api/core#sourcejson), [`SurfaceJson`](https://uitive.dev/docs/api/core#surfacejson).

| Property | Type | Description |
| - | - | - |
| `format` | `typeof CONTRACT_FORMAT` | Says what the document is. |
| `formatVersion` | `typeof FORMAT_VERSION` | The JSON format's version. |
| `id` | `string` | The application's ID. |
| `version` | `string` | The version the application gave. |
| `description` | `string` | What the application is, for the model. |
| `actions` | `Record<string, ActionJson>` | Every action, by ID. |
| `contexts` | `Record<string, string[]>` | Every context, with its values. |
| `sources` | `Record<string, SourceJson>` | Every source, by ID. |
| `regions` | `Record<string, RegionSpec>` | Every region, by name. |
| `routes` | `Record<string, RouteSpec>` | Every route, by ID. |
| `surfaces` | `Record<string, SurfaceJson>` | Every surface, by name, with pages' standards written out. |
| `hash` | `string` | The contract's hash, for checking that two sides mean the same contract. |

### ContractSpec

What `defineApp` takes: the application's actions and surfaces, and optionally its sources,
regions, routes and contexts.

Uses: [`ActionSpec`](https://uitive.dev/docs/api/core#actionspec), [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`RegionSpec`](https://uitive.dev/docs/api/core#regionspec), [`RouteSpec`](https://uitive.dev/docs/api/core#routespec), [`SurfaceSpec`](https://uitive.dev/docs/api/core#surfacespec).

Type parameters: `A extends Record<string, ActionSpec>`, `S extends Record<string, SurfaceSpec<Extract<keyof A, string>>>`, `C extends Record<string, readonly string[]>`, `D extends Record<string, AnySourceSpec> = Record<never, never>`.

| Property | Type | Default | Description |
| - | - | - | - |
| `id` | `string` | | Identifies the application, such as `cloud-console`. |
| `version?` | `string` | `'1'` | Bump when behavior that can't be hashed changes, such as a validator. |
| `description` | `string` | | What the application is, written for the model. |
| `actions` | `A` | | What people can do. IDs are lowercase, with dots, colons or dashes, such as `orders.cancel` or `table.add-empty`, since structured outputs don't guarantee the casing of enum values. |
| `contexts?` | `C` | `{}` | Every value of each context, such as every tool. Names are camelCase; values are lowercase, like action IDs. |
| `sources?` | `D` | `{}` | Data pages can show, as typed read models. |
| `regions?` | `Readonly<Record<string, RegionSpec>>` | `{}` | Parts of the application as it already is, which pages can embed. |
| `routes?` | `Readonly<Record<string, RouteSpec>>` | `{}` | Places in the application, for links and for knowing which row a page is about. |
| `surfaces` | `S` | | The parts of the interface people can reshape: lists, choices, collections and pages. Names are identifiers in application code, camelCase, such as `addNew`. |

### FieldJson

One field as JSON: its JSON type, and what it means under `x-uitive`.

Uses: [`FieldMeta`](https://uitive.dev/docs/api/core#fieldmeta).

| Property | Type | Description |
| - | - | - |
| `type` | `'string' \| 'number' \| 'boolean'` | The JSON type the value is stored as. |
| `enum?` | `string[]` | For enums: every value. |
| `description?` | `string` | What the field holds. |
| `x-uitive` | `FieldMeta` | What the value means to Uitive, beyond its JSON type, such as a money field's currency. |

### FieldsJson

Flat fields as a JSON Schema object: a source's row or an action's params.

Uses: [`FieldJson`](https://uitive.dev/docs/api/core#fieldjson).

| Property | Type | Description |
| - | - | - |
| `type` | `'object'` | Always an object. |
| `properties` | `Record<string, FieldJson>` | Each field, by name. |
| `required` | `string[]` | The fields every row or run has. |

### ListSpec

An ordered selection of actions: the first `capacity` show, the rest wait in overflow.

Type parameters: `A extends string = string`.

| Property | Type | Default | Description |
| - | - | - | - |
| `kind` | `'list'` | | Says the surface is a list. |
| `items` | `readonly A[]` | | Every action the list can show, in standard order. |
| `capacity` | `number` | | How many items show before the rest move to overflow. |
| `required?` | `readonly A[]` | `[]` | Items that never move to overflow. |
| `reorderable?` | `boolean` | `false` | Whether items may leave the standard order. |
| `context?` | `string` | | The context that keys this list, such as `tool`; each of its values adapts separately. |
| `available?()` | `(value: string) => readonly A[]` | every item | The items available for one context value. |
| `label` | `string` | | Shown to people, such as "Toolbar". |
| `description` | `string` | | What the surface is for, written for people and models alike. |

### ListValue

A list as a person's interface has it: the actions that show, then those waiting in overflow.

Uses: [`ActionView`](https://uitive.dev/docs/api/core#actionview).

Type parameters: `A extends string = string`.

| Property | Type | Description |
| - | - | - |
| `visible` | `readonly ActionView<A>[]` | The actions that show, in order. |
| `overflow` | `readonly ActionView<A>[]` | The rest, for a More menu or the palette. |

### PageSection

A section of the first page format, with its blocks typed.

Uses: [`BlockOf`](https://uitive.dev/docs/api/core#blockof), [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`Layout`](https://uitive.dev/docs/api/core#layout).

Type parameters: `B extends Record<string, BlockSpec> = Record<string, BlockSpec>`.

| Property | Type | Description |
| - | - | - |
| `title` | `string` | May be empty. |
| `layout` | `Layout` | How its blocks are laid out: a stack, a grid or columns. |
| `blocks` | `readonly BlockOf<B>[]` | Its blocks, in order. |

### PageSpec

A page composed from the application's blocks. Users (or a planner, on their behalf) can
redesign it completely, but only out of these parts.

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue), [`SectionPage`](https://uitive.dev/docs/api/core#sectionpage).

Type parameters: `B extends Record<string, BlockSpec> = Record<string, BlockSpec>`.

| Property | Type | Default | Description |
| - | - | - | - |
| `blocks` | `B` | | The application's own blocks the page may use, besides sections, tabs and regions. |
| `standard()` | `(context: string \| undefined) => PageValue<B> \| SectionPage<B> \| AnyPage` | | Typed sections, typed elements, or any page (such as one built with `ui`): all are validated. |
| `kind` | `'page'` | | Says the surface is a page. |
| `context?` | `string` | | The context that keys this page, such as `service`; it can be redesigned per value or for all. |
| `entity?` | `string` | | The source whose rows this page is about, such as `customers`; `$current` names the row. |
| `generic?` | `boolean \| readonly GenericName[]` | every one the contract can feed | Generic blocks the page offers. |
| `maxElements?` | `number` | `40` | How many elements a page may hold. |
| `maxDepth?` | `number` | `4` | How deeply a page's sections may nest. |
| `maxQueries?` | `number` | `8` | Queries a page may run. |
| `label` | `string` | | Shown to people, such as "Toolbar". |
| `description` | `string` | | What the surface is for, written for people and models alike. |

### PropsOf

The props a block takes.

```ts
type PropsOf<B> = B extends BlockSpec<infer P> ? P : never;
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec).

### RegionSpec

Part of the application as it already is, which pages can embed, such as the original page.

| Property | Type | Description |
| - | - | - |
| `label` | `string` | Shown to people and to the model, such as "Payments table". |
| `description` | `string` | What it shows, for people and models alike. |
| `entity?` | `string` | The source whose row it is about, so only pages about that source can embed it. |

### RowOf

One row of a source, as its binding returns it.

```ts
type RowOf<T extends AnyContract, K extends SourceIdOf<T>> = z.infer<T['sources'][K]['row']>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`SourceIdOf`](https://uitive.dev/docs/api/core#sourceidof).

### Runtime

Functions a JSON contract can't carry, reattached when it is loaded.

```ts
interface Runtime {
  validators?: Readonly<
    Record<string, (value: never, context: string | undefined) => string | undefined>
  >;
}
```

| Property | Description |
| - | - |
| `validators?` | Validators by `surface.block` for page blocks, or by surface for collections. |

### SectionPage

A page in the first format, sections of blocks, typed: still accepted for standard pages.

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`PageSection`](https://uitive.dev/docs/api/core#pagesection).

Type parameters: `B extends Record<string, BlockSpec> = Record<string, BlockSpec>`.

| Property | Type | Description |
| - | - | - |
| `sections` | `readonly PageSection<B>[]` | The page's sections, in order. |

### SourceIdOf

A contract's source IDs, as a union.

```ts
type SourceIdOf<T extends AnyContract> = Extract<keyof T['sources'], string>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### SourceJson

One source as JSON: its fields, key, capabilities and limits.

Uses: [`Capabilities`](https://uitive.dev/docs/api/core#capabilities), [`FieldsJson`](https://uitive.dev/docs/api/core#fieldsjson).

| Property | Type | Description |
| - | - | - |
| `label` | `string` | What people call it. |
| `description` | `string` | What its rows are. |
| `keywords` | `string[]` | Other words people use for it. |
| `row` | `FieldsJson` | The fields of its rows. |
| `key` | `string` | The field that identifies a row. |
| `title` | `string` | The field that names a row. |
| `summary` | `string[]` | The fields that sum a row up. |
| `capabilities` | `Required<Capabilities>` | What the binding does by itself. |
| `scan` | `number` | Most rows fetched to answer one query on the client. |
| `maxLimit` | `number` | Most rows one query may ask for. |
| `ttl` | `number` | Seconds a result stays fresh. |

### SurfaceIdOf

A contract's surface names, as a union.

```ts
type SurfaceIdOf<T extends AnyContract> = Extract<keyof T['surfaces'], string>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### SurfaceJson

One surface as JSON, by kind: functions are evaluated, so a page's standard is written out.

```ts
type SurfaceJson =
  | {
      kind: 'list';
      label: string;
      description: string;
      items: string[];
      capacity: number;
      required?: string[];
      reorderable?: boolean;
      context?: string;
      available?: Record<string, string[]>;
    }
  | {
      kind: 'choice';
      label: string;
      description: string;
      values: string[];
      default: string;
    }
  | {
      kind: 'collection';
      label: string;
      description: string;
      item: Record<string, unknown>;
      max: number;
      title: string;
    }
  | {
      kind: 'page';
      label: string;
      description: string;
      context?: string;
      entity?: string;
      generic?: boolean | string[];
      maxElements?: number;
      maxDepth?: number;
      maxQueries?: number;
      blocks: Record<
        string,
        {
          label: string;
          description: string;
          props: Record<string, unknown>;
        }
      >;
      standard: {
        page: AnyPage;
        values?: Record<string, AnyPage>;
      };
    };
```

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage).

### SurfaceSpec

Any surface a contract declares: a list, a choice, a collection or a page.

```ts
type SurfaceSpec<A extends string = string> =
  ListSpec<A> | ChoiceSpec | CollectionSpec | AnyPageSpec;
```

Uses: [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`ChoiceSpec`](https://uitive.dev/docs/api/core#choicespec), [`CollectionSpec`](https://uitive.dev/docs/api/core#collectionspec), [`ListSpec`](https://uitive.dev/docs/api/core#listspec).

### SurfaceValue

What a surface holds, by its kind: a list's visible and overflow actions, a choice's value, a
collection's items or a page.

```ts
type SurfaceValue<Spec> =
  Spec extends ListSpec<infer A>
    ? ListValue<A>
    : Spec extends ChoiceSpec<infer V>
      ? V
      : Spec extends CollectionSpec<infer T>
        ? CollectionValue<T>
        : Spec extends PageSpec<infer B>
          ? PageValue<B>
          : Spec extends AnyPageSpec
            ? AnyPage
            : never;
```

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`ChoiceSpec`](https://uitive.dev/docs/api/core#choicespec), [`CollectionSpec`](https://uitive.dev/docs/api/core#collectionspec), [`CollectionValue`](https://uitive.dev/docs/api/core#collectionvalue), [`ListSpec`](https://uitive.dev/docs/api/core#listspec), [`ListValue`](https://uitive.dev/docs/api/core#listvalue), [`PageSpec`](https://uitive.dev/docs/api/core#pagespec), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue).

### SurfaceValueOf

What one surface of a contract holds, such as `SurfaceValueOf<typeof shop, 'orders'>`.

```ts
type SurfaceValueOf<T extends AnyContract, K extends SurfaceIdOf<T>> = SurfaceValue<
  T['surfaces'][K]
>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`SurfaceIdOf`](https://uitive.dev/docs/api/core#surfaceidof), [`SurfaceValue`](https://uitive.dev/docs/api/core#surfacevalue).

## Sources and fields

Source: [`field.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/field.ts), [`source.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/source.ts)

### ARITY

How many values each operator takes: `[least, most]`.

```ts
const ARITY: Readonly<Record<Op, readonly [number, number]>>;
```

Uses: [`Op`](https://uitive.dev/docs/api/core#op).

### currencyDigits

Decimal places of a currency's minor unit in ISO 4217, such as 2 for USD, 0 for JPY and 3 for
KWD; 2 for codes it doesn't list.

```ts
function currencyDigits(code: string): number;
```

### describeFields

Describes every field of a row schema. Throws on fields a source can't hold.

```ts
function describeFields(row: z.ZodType, owner?: string): Field[];
```

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

### field

Field helpers: zod schemas that also say what a value means, such as money in cents or a
reference to another source. Plain zod types work too, with their meaning inferred.

```ts
const field: {
  text(options?: FieldOptions): z.ZodString;
  number(options?: FieldOptions): z.ZodNumber;
  money(options?: MoneyOptions): z.ZodNumber;
  time(
    options?: FieldOptions & {
      unit?: 'iso' | 'date';
    },
  ): z.ZodString;
  time(
    options: FieldOptions & {
      unit: 's' | 'ms';
    },
  ): z.ZodNumber;
  enum<const V extends readonly [string, ...string[]]>(
    values: V,
    options?: FieldOptions,
  ): z.ZodEnum<{
    [K in V[number]]: K;
  }>;
  ref(source: string, options?: FieldOptions): z.ZodString;
  bool(options?: FieldOptions): z.ZodBoolean;
};
```

Uses: [`FieldOptions`](https://uitive.dev/docs/api/core#fieldoptions), [`MoneyOptions`](https://uitive.dev/docs/api/core#moneyoptions).

| Member | Description |
| - | - |
| `text()` | Text, such as a name or a description. |
| `number()` | A number that isn't money, such as a count. |
| `money()` | `currency` names the field holding each row's currency; `code` fixes one for every row; `minor` stores amounts in minor units, with ISO 4217's decimal places unless `digits` says otherwise. |
| `time()` | A moment: an ISO date-time, an ISO date with `unit: 'date'`, or seconds or milliseconds since the epoch with `unit: 's'` or `'ms'`. |
| `enum()` | One of a fixed set of values, such as a status. |
| `ref()` | The key of a row in another source, which makes the field a relation. |
| `bool()` | Yes or no. |

### FIELD_META

Where field metadata lives on a zod schema, and in its JSON Schema.

```ts
const FIELD_META = 'x-uitive';
```

### FIELD_PATTERN

Field names appear in planner enums, so they must survive any casing.

```ts
const FIELD_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9_]*$/;
```

### FIELD_TYPES

Every type a field may have.

```ts
const FIELD_TYPES: readonly ['text', 'number', 'money', 'time', 'enum', 'ref', 'bool'];
```

### humanize

`amount_refunded` and `amountRefunded` both read "Amount refunded".

```ts
function humanize(name: string): string;
```

### MAX_LIMIT

Rows one query may ask for, unless the source says otherwise.

```ts
const MAX_LIMIT = 100;
```

### OPS

Every filter operator; which ones a field takes depends on its type.

```ts
const OPS: readonly [
  'eq',
  'ne',
  'gt',
  'gte',
  'lt',
  'lte',
  'between',
  'in',
  'nin',
  'contains',
  'prefix',
  'empty',
  'present',
];
```

### OPS_BY_TYPE

The operators each field type supports.

```ts
const OPS_BY_TYPE: Readonly<Record<FieldType, readonly Op[]>>;
```

Uses: [`FieldType`](https://uitive.dev/docs/api/core#fieldtype), [`Op`](https://uitive.dev/docs/api/core#op).

### qualifiedFields

Every qualified field name a query on these sources may use.

```ts
function qualifiedFields(
  sources: Readonly<Record<string, ResolvedSource>>,
  ids?: readonly string[],
): string[];
```

Uses: [`ResolvedSource`](https://uitive.dev/docs/api/core#resolvedsource).

### resolvePath

Resolves a qualified field name case-insensitively. A hop reaches only the target source's
summary fields, which keeps the names a planner can emit few.

```ts
function resolvePath(
  sources: Readonly<Record<string, ResolvedSource>>,
  name: string,
): FieldPath | undefined;
```

Uses: [`FieldPath`](https://uitive.dev/docs/api/core#fieldpath), [`ResolvedSource`](https://uitive.dev/docs/api/core#resolvedsource).

### resolveSources

Describes and checks every source; refs must point at sources that exist.

```ts
function resolveSources(
  sources: Readonly<Record<string, AnySourceSpec>>,
): Record<string, ResolvedSource>;
```

Uses: [`AnySourceSpec`](https://uitive.dev/docs/api/core#anysourcespec), [`ResolvedSource`](https://uitive.dev/docs/api/core#resolvedsource).

### SCAN

Rows fetched to answer one query on the client, unless the source says otherwise.

```ts
const SCAN = 500;
```

### source

Declares data pages can show: a typed read model of rows, with the fields that identify and name
them and what the binding does itself. Planners see its schema, never its rows.

```ts
function source<const R extends z.ZodObject>(spec: SourceSpec<R>): SourceSpec<R>;
```

Uses: [`SourceSpec`](https://uitive.dev/docs/api/core#sourcespec).

### SOURCE_PATTERN

Source IDs prefix qualified field names (`payments.amount`), so they hold no dots.

```ts
const SOURCE_PATTERN: RegExp = /^[a-z][a-z0-9-]*$/;
```

### TTL

Seconds a result stays fresh, unless the source says otherwise.

```ts
const TTL = 30;
```

### AnySourceSpec

Any source, with its field names widened: what generic code works with.

Uses: [`Capabilities`](https://uitive.dev/docs/api/core#capabilities).

| Property | Type | Default | Description |
| - | - | - | - |
| `label` | `string` | | Shown to people and to the model, such as "Payments". |
| `description` | `string` | | What the rows are, written for people and models alike. |
| `keywords?` | `readonly string[]` | `[]` | Other words people use for this data, for finding it. |
| `row` | `z.ZodObject` | | One row: flat fields only. |
| `key` | `string` | | The field that identifies a row. |
| `title?` | `string` | the key | The field that names a row. |
| `summary?` | `readonly string[]` | `[title]` | Fields that sum up a row, shown in compact views and reachable through relations. |
| `capabilities?` | `Capabilities` | none of them | What the binding does itself: filters, sorts, search and paging. |
| `scan?` | `number` | `500` | Most rows fetched to answer one query on the client. |
| `maxLimit?` | `number` | `100` | Most rows one query may ask for. |
| `ttl?` | `number` | `30` | Seconds a result stays fresh, counted from when it arrives; at least one. |

### Capabilities

What a source's binding does itself. Core does everything else on the client.

Uses: [`Op`](https://uitive.dev/docs/api/core#op).

Type parameters: `F extends string = string`.

| Property | Type | Default | Description |
| - | - | - | - |
| `filter?` | `Partial<Record<F, readonly Op[]>>` | `{}` | Filters the binding applies, by field. |
| `sort?` | `readonly F[]` | `[]` | Fields the binding sorts by. |
| `search?` | `boolean` | `false` | Whether the binding searches text itself. |
| `pagination?` | `'cursor' \| 'offset' \| 'none'` | `'none'` | How the binding pages through results. |

### Field type

One field of a source's rows, as everything after the contract sees it.

Uses: [`FieldType`](https://uitive.dev/docs/api/core#fieldtype), [`TimeUnit`](https://uitive.dev/docs/api/core#timeunit).

| Property | Type | Description |
| - | - | - |
| `name` | `string` | The field's name in its source's rows. |
| `type` | `FieldType` | What the value means, which decides how it shows and filters. |
| `label` | `string` | What people call it. |
| `description` | `string` | What it holds, for people and models. |
| `nullable` | `boolean` | Whether rows may lack a value. |
| `values` | `readonly string[]` | For enums: every value. |
| `source?` | `string` | For refs: the source whose key the field holds. |
| `currency?` | `string` | For money: the field holding each row's currency. |
| `code?` | `string` | For money: one currency for every row. |
| `minor` | `boolean` | For money: whether amounts are in minor units. |
| `digits?` | `Readonly<Record<string, number>>` | For money in minor units: decimal places by currency, where they differ from ISO 4217's. |
| `unit?` | `TimeUnit` | For time: how instants are stored. |

### FieldMeta

What a field helper records about a field, beyond its zod type.

Uses: [`FieldType`](https://uitive.dev/docs/api/core#fieldtype), [`TimeUnit`](https://uitive.dev/docs/api/core#timeunit).

| Property | Type | Default | Description |
| - | - | - | - |
| `type` | `FieldType` | | What the value means, which decides how it shows and filters. |
| `label?` | `string` | the field's name, humanized | Shown to people. |
| `currency?` | `string` | | For money: the field holding each row's ISO 4217 currency code. |
| `code?` | `string` | | For money: one ISO 4217 currency for every row. |
| `minor?` | `boolean` | `false` | For money: whether amounts are stored in minor units, such as cents. |
| `digits?` | `Readonly<Record<string, number>>` | `{}` | For money in minor units: decimal places by currency where the API's minor units differ from ISO 4217's, such as `{ ISK: 2, MGA: 0 }` for Stripe. |
| `unit?` | `TimeUnit` | | For time: how instants are stored. |
| `source?` | `string` | | For ref: the source whose key this field holds. |

### FieldNameOf

A source row's field names, as a union.

```ts
type FieldNameOf<R extends z.ZodObject> = Extract<keyof R['shape'], string>;
```

### FieldOptions

What every field helper takes.

| Property | Type | Default | Description |
| - | - | - | - |
| `label?` | `string` | the field's name, humanized | Shown to people, such as a column's header. |
| `description?` | `string` | | What the field holds, for planners and for people. |

### FieldPath

A field named by a planner: `payments.amount`, or one hop away, `payments.customer.email`.

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

| Property | Type | Description |
| - | - | - |
| `name` | `string` | The qualified name, in canonical spelling. |
| `source` | `string` | The source whose rows the query reads. |
| `via?` | `string` | The ref field followed, for a hop. |
| `target?` | `string` | The source a hop reaches. |
| `field` | `Field` | The field the name reaches. |

### FieldType

What a field holds, which decides how it is filtered, sorted, summed and shown.

```ts
type FieldType = (typeof FIELD_TYPES)[number];
```

Uses: [`FIELD_TYPES`](https://uitive.dev/docs/api/core#field_types).

### MoneyOptions

What `field.money` takes: where each amount's currency comes from, and how it is stored.

| Property | Type | Default | Description |
| - | - | - | - |
| `currency?` | `string` | | The field holding each row's ISO 4217 currency code. |
| `code?` | `string` | | One ISO 4217 currency for every row. |
| `minor?` | `boolean` | `false` | Whether amounts are stored in minor units, such as cents. |
| `digits?` | `Readonly<Record<string, number>>` | `{}` | For minor units: decimal places by currency where the API's minor units differ from ISO 4217's, such as `{ ISK: 2, MGA: 0 }` for Stripe. |
| `label?` | `string` | the field's name, humanized | Shown to people, such as a column's header. |
| `description?` | `string` | | What the field holds, for planners and for people. |

### Op

A filter operator. Lowercase, since planners emit them as enum values.

```ts
type Op = (typeof OPS)[number];
```

Uses: [`OPS`](https://uitive.dev/docs/api/core#ops).

### ResolvedSource

A source with its fields described and its defaults filled in.

Uses: [`Capabilities`](https://uitive.dev/docs/api/core#capabilities), [`Field`](https://uitive.dev/docs/api/core#field-type).

| Property | Type | Description |
| - | - | - |
| `id` | `string` | The source's ID. |
| `label` | `string` | What people call it. |
| `description` | `string` | What its rows are. |
| `keywords` | `readonly string[]` | Other words people use for it. |
| `key` | `string` | The field that identifies a row. |
| `title` | `string` | The field that names a row. |
| `summary` | `readonly string[]` | The fields that sum a row up. |
| `fields` | `readonly Field[]` | Every field, described. |
| `capabilities` | `Required<Capabilities>` | What the binding does by itself, with nothing left out. |
| `scan` | `number` | Most rows fetched to answer one query on the client. |
| `maxLimit` | `number` | Most rows one query may ask for. |
| `ttl` | `number` | Seconds a result stays fresh. |

### SourceSpec

Data an application exposes for pages to show: a typed read model, never the rows.

Uses: [`Capabilities`](https://uitive.dev/docs/api/core#capabilities), [`FieldNameOf`](https://uitive.dev/docs/api/core#fieldnameof).

Type parameters: `R extends z.ZodObject = z.ZodObject`.

| Property | Type | Default | Description |
| - | - | - | - |
| `label` | `string` | | Shown to people and to the model, such as "Payments". |
| `description` | `string` | | What the rows are, written for people and models alike. |
| `keywords?` | `readonly string[]` | `[]` | Other words people use for this data, for finding it. |
| `row` | `R` | | One row: flat fields only. Field helpers say what values mean, such as money in cents. |
| `key` | `FieldNameOf<R>` | | The field that identifies a row. |
| `title?` | `FieldNameOf<R>` | the key | The field that names a row. |
| `summary?` | `readonly FieldNameOf<R>[]` | `[title]` | Fields that sum up a row, shown in compact views and reachable through relations. |
| `capabilities?` | `Capabilities<FieldNameOf<R>>` | none of them | What the binding does itself: filters, sorts, search and paging. |
| `scan?` | `number` | `500` | Most rows fetched to answer one query on the client. |
| `maxLimit?` | `number` | `100` | Most rows one query may ask for. |
| `ttl?` | `number` | `30` | Seconds a result stays fresh, counted from when it arrives; at least one. |

### TimeUnit

How instants are stored: ISO 8601 date-times, ISO 8601 dates (`2026-10-03`, a day in the
person's time zone), or seconds or milliseconds since the epoch.

```ts
type TimeUnit = 'iso' | 'date' | 's' | 'ms';
```

## Queries and data

Source: [`cache.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/cache.ts), [`data.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/data.ts), [`query.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/query.ts), [`values.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/values.ts)

### BUCKETS

Every way time may group; `none` when it doesn't.

```ts
const BUCKETS: readonly ['none', 'hour', 'day', 'week', 'month', 'quarter', 'year'];
```

### bucketStart

The start of the bucket containing an instant, by the wall clock in a zone.

```ts
function bucketStart(ms: number, bucket: Bucket, zone?: string): number;
```

Uses: [`Bucket`](https://uitive.dev/docs/api/core#bucket).

### checkQuery

Checks a query against the contract and returns it in canonical spelling: the source exists,
every field belongs to it, operators suit their fields, values parse, tokens sit where they
mean something, limits hold and aggregates are well formed.

```ts
function checkQuery(contract: AnyContract, raw: unknown, scope?: QueryScope): QueryCheck;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`QueryCheck`](https://uitive.dev/docs/api/core#querycheck), [`QueryScope`](https://uitive.dev/docs/api/core#queryscope).

### createData

Runs queries through the bindings, sharing results between everything that asks.

```ts
function createData(contract: AnyContract, fetchers: Fetchers, options?: DataOptions): DataClient;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`DataClient`](https://uitive.dev/docs/api/core#dataclient), [`DataOptions`](https://uitive.dev/docs/api/core#dataoptions), [`Fetchers`](https://uitive.dev/docs/api/core#fetchers).

### DEFAULT_LIMIT

Rows a query returns when it doesn't say.

```ts
const DEFAULT_LIMIT = 20;
```

### DIRECTIONS

Both sort directions.

```ts
const DIRECTIONS: readonly ['asc', 'desc'];
```

### formatValue

Formats a stored value for people, by its field's type.

```ts
function formatValue(field: Field, value: unknown, currency?: string, locale?: string): string;
```

Also exported by `@plurid/uitive-react`.

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

### fromRows

A fetcher over rows held in memory, applying every filter, sort and page it is asked for, as an
API would: values compare exactly, and only `contains` and `prefix` ignore case. For
demonstrations, tests and data an application already has.

```ts
function fromRows(rows: Readonly<Record<string, readonly object[]>>): Fetch;
```

Uses: [`Fetch`](https://uitive.dev/docs/api/core#fetch).

### isToken

Whether a value is a token.

```ts
function isToken(value: string): value is Token;
```

Uses: [`Token`](https://uitive.dev/docs/api/core#token).

### MAX_FIELDS

Fields a query may read.

```ts
const MAX_FIELDS = 12;
```

### MAX_FILTERS

Filters a query may apply.

```ts
const MAX_FILTERS = 8;
```

### MAX_SORTS

Sorts a query may apply.

```ts
const MAX_SORTS = 3;
```

### MEASURES

Every way a summary measures its rows; `none` for queries that return rows.

```ts
const MEASURES: readonly ['none', 'count', 'sum', 'avg', 'min', 'max', 'distinct'];
```

### NO_AGGREGATE

The aggregate of a query that returns rows: no measure, no grouping.

```ts
const NO_AGGREGATE: Aggregate;
```

Uses: [`Aggregate`](https://uitive.dev/docs/api/core#aggregate).

### NONE

Stands in for "no field" wherever a schema can't leave a value out.

```ts
const NONE = 'none';
```

### parseTime

An instant in milliseconds, from an ISO date or time, or a token relative to the clock.

```ts
function parseTime(raw: string, clock: Clock): number | undefined;
```

Uses: [`Clock`](https://uitive.dev/docs/api/core#clock).

### parseValue

Parses one filter value for a field. Relative times such as `-7d`, `today` and
`start:month` resolve against the clock, so a saved query stays relative.

```ts
function parseValue(field: Field, raw: string, clock: Clock): Parsed | undefined;
```

Uses: [`Clock`](https://uitive.dev/docs/api/core#clock), [`Field`](https://uitive.dev/docs/api/core#field-type), [`Parsed`](https://uitive.dev/docs/api/core#parsed).

### partsIn

The wall-clock date and time of an instant in a zone.

```ts
function partsIn(ms: number, zone?: string): LocalParts;
```

Uses: [`LocalParts`](https://uitive.dev/docs/api/core#localparts).

### PERIODS

Every calendar period relative times may name.

```ts
const PERIODS: readonly ['day', 'week', 'month', 'quarter', 'year'];
```

### query

Builds a query in code, filling in what's left out.

```ts
function query(
  source: string,
  parts?: {
    fields?: readonly string[];
    filter?: readonly Filter[];
    sort?: readonly Sort[];
    limit?: number;
    search?: string;
    aggregate?: Partial<Aggregate>;
  },
): Query;
```

Uses: [`Aggregate`](https://uitive.dev/docs/api/core#aggregate), [`Filter`](https://uitive.dev/docs/api/core#filter), [`Query`](https://uitive.dev/docs/api/core#query-type), [`Sort`](https://uitive.dev/docs/api/core#sort).

### runQuery

Runs a checked query: pushes down what the binding supports, does the rest here.

```ts
function runQuery(
  contract: AnyContract,
  fetchers: Fetchers,
  query: Query,
  options: RunOptions,
): Promise<QueryResult>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Fetchers`](https://uitive.dev/docs/api/core#fetchers), [`Query`](https://uitive.dev/docs/api/core#query-type), [`QueryResult`](https://uitive.dev/docs/api/core#queryresult), [`RunOptions`](https://uitive.dev/docs/api/core#runoptions).

### SEARCH_LENGTH

Characters a query's search may hold.

```ts
const SEARCH_LENGTH = 100;
```

### startOf

The start of the day, ISO week, month, quarter or year containing an instant, in a zone.

```ts
function startOf(ms: number, period: Period, zone?: string): number;
```

Uses: [`Period`](https://uitive.dev/docs/api/core#period).

### timeOf

A stored time as milliseconds since the epoch, whatever the field's unit. A date without a time
is the start of that day in `zone`.

```ts
function timeOf(field: Field, value: unknown, zone?: string): number | undefined;
```

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

### TOKENS

The page's entity, and the signed-in user, where the binding knows them.

```ts
const TOKENS: readonly ['$current', '$me'];
```

### VALUE_LENGTH

Longest text a filter value may hold.

```ts
const VALUE_LENGTH = 200;
```

### Aggregate

A summary instead of rows: one number, or one per group.

Uses: [`Bucket`](https://uitive.dev/docs/api/core#bucket), [`Measure`](https://uitive.dev/docs/api/core#measure).

| Property | Type | Description |
| - | - | - |
| `measure` | `Measure` | What to compute: a count, a sum, an average, a minimum, a maximum or a distinct count. |
| `of` | `string` | The field measured, or `none` to count rows. |
| `by` | `string` | The field rows group by, or `none` for one number. |
| `split` | `string` | A second grouping, for stacked charts, or `none`. |
| `bucket` | `Bucket` | For time groupings: the size of each group. |

### BindingContext

Who and where the user is, as far as the binding knows.

| Property | Type | Default | Description |
| - | - | - | - |
| `me?` | `string` | | The signed-in user, for `$me`: the value fields that hold a person are compared with. |
| `timeZone?` | `string` | `'UTC'` | An IANA time zone, for "today" and time buckets. |
| `locale?` | `string` | | A BCP 47 locale, for formatting. |

### Bucket

How time groups: by hour, day, ISO week, month, quarter or year.

```ts
type Bucket = (typeof BUCKETS)[number];
```

Uses: [`BUCKETS`](https://uitive.dev/docs/api/core#buckets).

### Clock

When a query runs, and where: "today" and "this month" depend on the user's time zone.

| Property | Type | Default | Description |
| - | - | - | - |
| `now` | `number` | | Milliseconds since the epoch. |
| `timeZone?` | `string` | `'UTC'` | An IANA time zone. |

### DataClient

Query results shared across an interface: fetched once, cached, refreshed when stale or after a
write to their source.

Uses: [`DataEntry`](https://uitive.dev/docs/api/core#dataentry), [`DataScope`](https://uitive.dev/docs/api/core#datascope), [`Filter`](https://uitive.dev/docs/api/core#filter), [`Query`](https://uitive.dev/docs/api/core#query-type), [`QueryResult`](https://uitive.dev/docs/api/core#queryresult), [`Row`](https://uitive.dev/docs/api/core#row).

| Property | Type | Description |
| - | - | - |
| `read()` | `(query: Query, scope?: DataScope) => DataEntry` | The entry for a query, fetching when there is none, or when it is stale. |
| `peek()` | `(query: Query, scope?: DataScope) => DataEntry \| undefined` | The entry for a query as it stands, without fetching: safe inside a render. |
| `load()` | `(query: Query, scope?: DataScope) => Promise<QueryResult>` | The result of a query, fresh or cached. |
| `subscribe()` | `(listener: () => void) => () => void` | Calls the listener whenever an entry changes; returns its removal. |
| `invalidate()` | `(sources: readonly string[]) => void` | Marks results that read these sources stale, so they fetch again when next read. |
| `matches()` | `(filters: readonly Filter[], row: Row, scope?: DataScope) => boolean` | Whether a result row passes filters as queries apply them, on this client's clock, time zone and user: for the rows an action's `when` allows. |

### DataEntry

A query's result as far as it is known. Stable between changes, so it is safe to render.

Uses: [`QueryResult`](https://uitive.dev/docs/api/core#queryresult).

| Property | Type | Description |
| - | - | - |
| `status` | `'loading' \| 'ready' \| 'error'` | Whether the result is loading, ready, or failed. |
| `result?` | `QueryResult` | The result, once there is one; kept while a fresh one loads. |
| `error?` | `string` | Why it failed, in words people read. |
| `stale` | `boolean` | The result is older than its sources allow, or a write changed them; a fresh one is coming. |

### DataOptions

How a data client fetches and caches.

Uses: [`BindingContext`](https://uitive.dev/docs/api/core#bindingcontext).

| Property | Type | Default | Description |
| - | - | - | - |
| `now?` | `() => number` | `Date.now` | The clock, in milliseconds, for freshness and relative times. |
| `context?` | `() => BindingContext` | | Who and where the user is: `me`, time zone and locale. |
| `concurrency?` | `number` | `4` | Fetches running at once. |
| `capacity?` | `number` | `200` | Results kept. |
| `onError?` | `(error: unknown) => void` | | Told when a fetch fails; the result says so too, and the last good one stays shown. |

### DataScope

What a page's queries need to know about the page: the row it is about.

| Property | Type | Description |
| - | - | - |
| `current?` | `string` | The key of the row a page is about, for `$current`. |

### Direction

A sort direction: ascending or descending.

```ts
type Direction = (typeof DIRECTIONS)[number];
```

Uses: [`DIRECTIONS`](https://uitive.dev/docs/api/core#directions).

### Fetch

The application's code that reads a source: a request in, rows out. It reads with the person's
own permissions, applying only the filters, sorts and paging its source declares.

```ts
type Fetch<R = unknown> = (
  request: FetchRequest,
  context: BindingContext,
) => Promise<FetchResult<R>>;
```

Uses: [`BindingContext`](https://uitive.dev/docs/api/core#bindingcontext), [`FetchRequest`](https://uitive.dev/docs/api/core#fetchrequest), [`FetchResult`](https://uitive.dev/docs/api/core#fetchresult).

### Fetchers

One fetcher for every source, or one per source.

```ts
type Fetchers<C extends AnyContract = AnyContract> =
  | Fetch
  | {
      [S in SourceIdOf<C>]?: Fetch<RowOf<C, S>>;
    };
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Fetch`](https://uitive.dev/docs/api/core#fetch), [`RowOf`](https://uitive.dev/docs/api/core#rowof), [`SourceIdOf`](https://uitive.dev/docs/api/core#sourceidof).

### FetchFilter

One filter a binding is asked to apply, on one of the source's own fields.

Uses: [`Op`](https://uitive.dev/docs/api/core#op), [`Stored`](https://uitive.dev/docs/api/core#stored).

| Property | Type | Description |
| - | - | - |
| `field` | `string` | One of the source's own fields. |
| `op` | `Op` | The operator, one the source's capabilities declare. |
| `values` | `readonly Stored[]` | The values, parsed by the field's type. |

### FetchRequest

What a binding is asked for. It applies only what its source's capabilities declare;
core does the rest.

Uses: [`Direction`](https://uitive.dev/docs/api/core#direction), [`FetchFilter`](https://uitive.dev/docs/api/core#fetchfilter).

| Property | Type | Description |
| - | - | - |
| `source` | `string` | The source to read. |
| `fields` | `readonly string[]` | The fields core needs, for bindings that select columns. |
| `filter` | `readonly FetchFilter[]` | Filters to apply, from those the source declares. |
| `sort` | `readonly { field: string; direction: Direction }[]` | Sorts to apply, from those the source declares. |
| `limit` | `number` | Rows per page. |
| `cursor?` | `string` | The `next` of the previous page. |
| `search?` | `string` | Text to look for, when the source searches itself. |
| `signal?` | `unknown` | An `AbortSignal` where the platform has one. |

### FetchResult

What a `fetch` binding answers: the rows, where the next page starts, and the total when the API
knows it.

Type parameters: `R = unknown`.

| Property | Type | Description |
| - | - | - |
| `rows` | `readonly R[]` | The rows, as the API returns them. |
| `next?` | `string` | Passed back as `cursor` for the next page; absent on the last page. |
| `total?` | `number` | Every matching row, when the API counts them. |

### Filter

One filter of a query: a field, an operator, and its values as text, parsed by the field's type.

Uses: [`Op`](https://uitive.dev/docs/api/core#op).

| Property | Type | Description |
| - | - | - |
| `field` | `string` | A qualified field name, such as `payments.status`. |
| `op` | `Op` | The operator, one the field's type allows. |
| `values` | `readonly string[]` | The values, as text: `between` takes two, `empty` and `present` none. |

### Group

One group of a summary. Money is in major units.

Uses: [`Stored`](https://uitive.dev/docs/api/core#stored).

| Property | Type | Description |
| - | - | - |
| `by` | `Stored \| null` | The group's value of the grouping field, or `null` for one number. |
| `label` | `string` | The group's value, as people read it. Time buckets read as local dates in the person's time zone: `2026-10-03T14:00` for hours, `2026-10-03` for days and weeks, `2026-10`, `2026-Q4` and `2026` for months, quarters and years. Rows without a time group as `None`, last. |
| `split` | `Stored \| null` | The value of the second grouping, or `null` without one. |
| `splitLabel` | `string` | The second grouping's value, as people read it. |
| `value` | `number \| null` | The measure, or `null` when nothing was measured. |
| `currency?` | `string` | For money: the currency the value is in, when one applies. |

### LocalParts

A moment's calendar parts in a time zone.

| Property | Type | Description |
| - | - | - |
| `year` | `number` | The year. |
| `month` | `number` | The month, from 1. |
| `day` | `number` | The day of the month, from 1. |
| `hour` | `number` | The hour, from 0 to 23. |
| `minute` | `number` | The minute. |
| `second` | `number` | The second. |

### Measure

How a summary measures its rows: count, sum, average, minimum, maximum or distinct values.

```ts
type Measure = (typeof MEASURES)[number];
```

Uses: [`MEASURES`](https://uitive.dev/docs/api/core#measures).

### Parsed

A filter value, parsed for its field: money is in major units, times in milliseconds.

```ts
type Parsed =
  | {
      kind: 'text';
      value: string;
    }
  | {
      kind: 'number';
      value: number;
    }
  | {
      kind: 'time';
      value: number;
    }
  | {
      kind: 'bool';
      value: boolean;
    };
```

### Period

A calendar period that `start:` tokens and time buckets refer to.

```ts
type Period = (typeof PERIODS)[number];
```

Uses: [`PERIODS`](https://uitive.dev/docs/api/core#periods).

### Query type

A question about a source, as plain data: planners fill these in, and policy checks every
part. Nothing is optional, so the planner schema needs neither optional fields nor unions.

Uses: [`Aggregate`](https://uitive.dev/docs/api/core#aggregate), [`Filter`](https://uitive.dev/docs/api/core#filter), [`Sort`](https://uitive.dev/docs/api/core#sort).

| Property | Type | Description |
| - | - | - |
| `source` | `string` | The source asked about. |
| `fields` | `readonly string[]` | Qualified field names: the source's own, or one hop through a ref. |
| `filter` | `readonly Filter[]` | Filters, all of which a row must pass. |
| `sort` | `readonly Sort[]` | Sorts, in order of precedence. |
| `limit` | `number` | Most rows to return. |
| `search` | `string` | Text to look for, or empty. |
| `aggregate` | `Aggregate` | A summary instead of rows; `measure: 'none'` for rows. |

### QueryCheck

What checking a query gives: the query in canonical spelling, or the problem with it.

```ts
type QueryCheck =
  | {
      ok: true;
      query: Query;
    }
  | {
      ok: false;
      problem: string;
    };
```

Uses: [`Query`](https://uitive.dev/docs/api/core#query-type).

### QueryResult

A query's answer: rows, or groups for a summary, and whether it was cut short. Money keeps its
currency beside it: `orders.currency` beside `orders.total`, and `orders.customer.currency`
beside `orders.customer.balance`.

Uses: [`Group`](https://uitive.dev/docs/api/core#group), [`Row`](https://uitive.dev/docs/api/core#row).

| Property | Type | Description |
| - | - | - |
| `rows` | `readonly Row[]` | The rows, for queries without a summary. |
| `groups` | `readonly Group[]` | The groups, for summaries. |
| `partial` | `boolean` | Not every row was read: the scan cap stopped before the last page, a source without paging filled its one page, or related rows were left unread. Counts and sums may be low. |
| `at` | `number` | When the data was read, in milliseconds. |
| `reads` | `readonly string[]` | Every source read, for invalidation. |

### QueryScope

What a query may refer to where it is used.

Uses: [`Clock`](https://uitive.dev/docs/api/core#clock).

| Property | Type | Default | Description |
| - | - | - | - |
| `entity?` | `string` | | The source a page is about, so `$current` names its row. |
| `me?` | `boolean` | `false` | Whether the binding knows who `$me` is. |
| `limit?` | `number` | | The most rows the block showing the result can display. |
| `clock?` | `Clock` | the current time, in UTC | Validates relative times; any clock will do. |

### Row

A result row, keyed by qualified field name.

```ts
type Row = Readonly<Record<string, unknown>>;
```

### RunOptions

What running a query needs besides the query: the clock and the person's context.

Uses: [`BindingContext`](https://uitive.dev/docs/api/core#bindingcontext), [`Clock`](https://uitive.dev/docs/api/core#clock).

| Property | Type | Description |
| - | - | - |
| `clock` | `Clock` | The time and time zone relative values such as `-7d` resolve against. |
| `current?` | `string` | The key of the row a page is about, for `$current`. |
| `context?` | `BindingContext` | Who and where the person is, for `$me` and the bindings. |
| `signal?` | `unknown` | An `AbortSignal` that cancels the fetches. |

### Sort

One sort of a query: a field and a direction.

Uses: [`Direction`](https://uitive.dev/docs/api/core#direction).

| Property | Type | Description |
| - | - | - |
| `field` | `string` | A qualified field name, such as `orders.placed`. |
| `direction` | `Direction` | Ascending or descending. |

### Stored

A value as a source stores it: money in its own units, times in the field's unit.

```ts
type Stored = string | number | boolean;
```

### Token

A value that stands for something known only when a query runs: `$current`, the page's row, or
`$me`, the person.

```ts
type Token = (typeof TOKENS)[number];
```

Uses: [`TOKENS`](https://uitive.dev/docs/api/core#tokens).

## Actions and bindings

Source: [`action.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/action.ts), [`rest.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/rest.ts)

### EFFECTS

Every effect an action may declare, from least to most serious.

```ts
const EFFECTS: readonly ['read', 'write', 'destructive'];
```

### pointer

The value a JSON pointer names, such as `/data/0/id`.

```ts
function pointer(value: unknown, path: string): unknown;
```

### restFetch

A fetch binding over REST endpoints described as data: filters become query parameters,
pages chain by cursor, offset or page number, and rows come from a JSON pointer. Declare as
capabilities only the filters and sorts the endpoints apply; core does the rest.

```ts
function restFetch(config: RestFetchConfig): Fetch;
```

Uses: [`Fetch`](https://uitive.dev/docs/api/core#fetch), [`RestFetchConfig`](https://uitive.dev/docs/api/core#restfetchconfig).

### restPerform

A perform binding over REST endpoints: path placeholders from params, the rest as the body.

```ts
function restPerform(config: RestPerformConfig): Perform;
```

Uses: [`Perform`](https://uitive.dev/docs/api/core#perform), [`RestPerformConfig`](https://uitive.dev/docs/api/core#restperformconfig).

### rowParam

The first param that holds a row of some source: what makes an action a row action.

```ts
function rowParam(fields: readonly Field[]): Field | undefined;
```

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

### Bindings

The application's code behind a contract.

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`BindingContext`](https://uitive.dev/docs/api/core#bindingcontext), [`Fetchers`](https://uitive.dev/docs/api/core#fetchers), [`Performers`](https://uitive.dev/docs/api/core#performers).

Type parameters: `C extends AnyContract = AnyContract`.

| Property | Type | Description |
| - | - | - |
| `fetch?` | `Fetchers<C>` | Reads sources with the user's own permissions. |
| `perform?` | `Performers<C>` | Runs actions. Every confirmed run is recorded as usage, without its params. |
| `context?()` | `() => BindingContext` | Who and where the user is: `me`, time zone and locale. |
| `navigate?()` | `(href: string) => void` | Follows a link inside the application, such as through its router. |

### Confirmation

A run waiting for the user's yes.

Uses: [`Field`](https://uitive.dev/docs/api/core#field-type).

| Property | Type | Description |
| - | - | - |
| `id` | `string` | The run's ID, for `confirm` and `cancel`. |
| `action` | `string` | The action's ID. |
| `label` | `string` | The action's label. |
| `description` | `string` | What the action does. |
| `effect` | `'write' \| 'destructive'` | A `write` waits for one yes; a `destructive` run for a typed phrase. |
| `params` | `Readonly<Record<string, unknown>>` | What the run will use, shown before the person says yes. |
| `fields` | `readonly Field[]` | The params' fields, for showing what will happen. |
| `phrase?` | `string` | For destructive actions: what the user must type. |

### DeclaredParams

What an action's `params` schema declares, inferred: an empty record when it declares none.

```ts
type DeclaredParams<C extends AnyContract, A extends ActionIdOf<C>> =
  NonNullable<C['actions'][A]['params']> extends infer P
    ? P extends z.ZodType
      ? z.infer<P>
      : Record<string, never>
    : never;
```

Uses: [`ActionIdOf`](https://uitive.dev/docs/api/core#actionidof), [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### Effect

What running an action does: `read` changes nothing, `write` changes data, `destructive`
can't be undone. Actions without an effect belong to the interface only, as links and tools do.

```ts
type Effect = (typeof EFFECTS)[number];
```

Uses: [`EFFECTS`](https://uitive.dev/docs/api/core#effects).

### HttpFetch

The `fetch` a REST binding calls: the platform's, or one that adds what a site needs.

```ts
type HttpFetch = (
  url: string,
  init: {
    method: string;
    headers: Record<string, string>;
    body?: string;
    signal?: unknown;
    credentials?: string;
  },
) => Promise<HttpResponse>;
```

Uses: [`HttpResponse`](https://uitive.dev/docs/api/core#httpresponse).

### HttpResponse

What a REST binding reads from a response: the platform's `Response` fits.

| Property | Type | Description |
| - | - | - |
| `ok` | `boolean` | Whether the status is in the 200s. |
| `status` | `number` | The HTTP status. |
| `json()` | `() => Promise<unknown>` | The body, parsed. |

### ParamsOf

What an action takes, from its `params` schema: nothing when it declares none. For contracts
typed loosely, as generic renderers see them, any record.

```ts
type ParamsOf<C extends AnyContract, A extends ActionIdOf<C>> =
  string extends ActionIdOf<C>
    ? Readonly<Record<string, unknown>>
    : string extends keyof DeclaredParams<C, A>
      ? Record<string, never>
      : DeclaredParams<C, A>;
```

Uses: [`ActionIdOf`](https://uitive.dev/docs/api/core#actionidof), [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`DeclaredParams`](https://uitive.dev/docs/api/core#declaredparams).

### Perform

The application's code that runs an action: its params in, an outcome out. It runs with the
person's own permissions.

```ts
type Perform<P = unknown> = (
  params: P,
  context: PerformContext,
) => Promise<PerformOutcome> | PerformOutcome;
```

Uses: [`PerformContext`](https://uitive.dev/docs/api/core#performcontext), [`PerformOutcome`](https://uitive.dev/docs/api/core#performoutcome).

### PerformContext

What a `perform` binding learns about a run, besides its params: who and where, which action, and
a key for doing it once.

| Property | Type | Default | Description |
| - | - | - | - |
| `action` | `string` | | The action being run. |
| `idempotencyKey` | `string` | | Unique to one confirmed run, so a binding can refuse to do it twice. |
| `me?` | `string` | | The signed-in user, for `$me`: the value fields that hold a person are compared with. |
| `timeZone?` | `string` | `'UTC'` | An IANA time zone, for "today" and time buckets. |
| `locale?` | `string` | | A BCP 47 locale, for formatting. |

### Performers

One performer for every action, or one per action.

```ts
type Performers<C extends AnyContract = AnyContract> =
  | Perform
  | {
      [A in ActionIdOf<C>]?: Perform<ParamsOf<C, A>>;
    };
```

Uses: [`ActionIdOf`](https://uitive.dev/docs/api/core#actionidof), [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`ParamsOf`](https://uitive.dev/docs/api/core#paramsof), [`Perform`](https://uitive.dev/docs/api/core#perform).

### PerformOptions

How a run came about, for `perform`: where it was started, by what, and whether the person
already said yes.

Uses: [`Via`](https://uitive.dev/docs/api/core#via).

| Property | Type | Default | Description |
| - | - | - | - |
| `via?` | `Via` | `'region'` | How the person reached the action. |
| `surface?` | `string` | | The surface the action was run from. |
| `element?` | `string` | | The page element it was run from. |
| `typed?` | `boolean` | | For palette picks: whether the user typed a search first. |
| `origin?` | `'native' \| 'generated'` | `'generated'` | `native` runs come from the application's own controls, which ask for confirmation themselves; `generated` ones come from interfaces Uitive drew. |
| `confirmed?` | `boolean` | | The user already saw the params and said yes, such as by submitting a complete form. |

### PerformOutcome

What a `perform` binding may answer: a message for the person, and where to go next.

```ts
type PerformOutcome = {
  message?: string;
  navigate?: Target;
} | void;
```

Uses: [`Target`](https://uitive.dev/docs/api/core#target).

### PerformResult

How a run ended: `done`, `canceled` by the person, `failed` in the binding, or `refused` before
it started, such as when nothing could ask for confirmation.

| Property | Type | Description |
| - | - | - |
| `status` | `'done' \| 'canceled' \| 'failed' \| 'refused'` | `refused` runs never started; `failed` ones started and threw. |
| `message?` | `string` | The binding's message, or why the run was refused or failed. |

### RestAction

How one action's endpoint works.

| Property | Type | Default | Description |
| - | - | - | - |
| `method` | `'POST' \| 'PUT' \| 'PATCH' \| 'DELETE'` | | The HTTP method. |
| `path` | `string` | | The path, with `{param}` placeholders filled from the run's params. |
| `body?` | `'json' \| 'form'` | `'json'` | How the remaining params are sent. |

### RestFetchConfig

What `restFetch` takes: where the API is, how to authenticate, and each source's endpoint as
data.

Uses: [`RestSource`](https://uitive.dev/docs/api/core#restsource).

| Property | Type | Default | Description |
| - | - | - | - |
| `sources` | `Readonly<Record<string, RestSource>>` | | Each source's list endpoint and how it pages, filters and sorts, by source ID. |
| `base` | `string` | | The API's base URL, such as `https://api.example.com`; empty for the page's own origin. |
| `headers?` | `(context: BindingContext) => Record<string, string> \| Promise<Record<string, string>>` | | Headers for every request, such as authorization. |
| `credentials?` | `'omit' \| 'same-origin' \| 'include'` | `'same-origin'` | Sends cookies, for an application's own API. |
| `fetch?` | `HttpFetch` | `globalThis.fetch` | The `fetch` it calls, such as one that adds a CSRF token. |

### RestPerformConfig

What `restPerform` takes: where the API is, how to authenticate, and each action's endpoint as
data.

Uses: [`RestAction`](https://uitive.dev/docs/api/core#restaction).

| Property | Type | Default | Description |
| - | - | - | - |
| `actions` | `Readonly<Record<string, RestAction>>` | | Each action's method and path, by action ID; params fill `{placeholders}` in the path, and the rest go in the body. |
| `idempotency?` | `string` | | The header that carries each run's idempotency key, for APIs that honor one. |
| `base` | `string` | | The API's base URL, such as `https://api.example.com`; empty for the page's own origin. |
| `headers?` | `(context: BindingContext) => Record<string, string> \| Promise<Record<string, string>>` | | Headers for every request, such as authorization. |
| `credentials?` | `'omit' \| 'same-origin' \| 'include'` | `'same-origin'` | Sends cookies, for an application's own API. |
| `fetch?` | `HttpFetch` | `globalThis.fetch` | The `fetch` it calls, such as one that adds a CSRF token. |

### RestSource

How one source's list endpoint works, as data a generator can write.

```ts
interface RestSource {
  path: string;
  rows?: string;
  filters?: Readonly<Record<string, string>>;
  repeat?: readonly string[];
  limit?: string;
  pagination?:
    | {
        kind: 'cursor';
        param: string;
        next?: string;
      }
    | {
        kind: 'offset';
        param: string;
      }
    | {
        kind: 'page';
        param: string;
      }
    | {
        kind: 'none';
      };
  more?: string;
  sort?: {
    param: string;
    format: 'field:direction' | '-field';
  };
  search?: string;
  key?: string;
  pick?: Readonly<Record<string, string>>;
  query?: Readonly<Record<string, string>>;
  item?: {
    path: string;
    row?: string;
  };
}
```

| Property | Default | Description |
| - | - | - |
| `path` | | The list endpoint, such as `/v1/charges`. |
| `rows?` | `''` | A JSON pointer to the rows in a response, such as `/data`; empty when the body is the array. |
| `filters?` | | Filters the endpoint applies: `field:op` to a query parameter, such as `created:gte` to `created[gte]`. |
| `repeat?` | `[]` | Parameters sent once per value (`status=a&status=b`) rather than joined by commas. |
| `limit?` | `'limit'` | The page-size parameter; empty when the endpoint has none. |
| `pagination?` | `{ kind: 'none' }` | How pages chain. |
| `more?` | | A JSON pointer to a boolean saying whether more rows exist, such as `/has_more`. Without it, a cursor's `next` pointer says so, and otherwise a page shorter than the limit is the last. |
| `sort?` | | Sorting: the parameter, and how a field and direction are written. |
| `search?` | | The text-search parameter. |
| `key?` | `'id'` | The key field, for cursors made from the last row and for `item`. |
| `pick?` | | Fields lifted from nested values by JSON pointer, such as `brand` from `/card/brand`. |
| `query?` | | Parameters sent with every list request, such as `expand[]` to include nested objects. |
| `item?` | | The endpoint for one row, such as `/v1/charges/{id}`, for queries that ask for rows by key when the list endpoint can't. `row` points to the row in its response. Declare `eq` and `in` on the key as capabilities. |

### Target

Where an action leads: a URL, or one of the contract's routes.

```ts
type Target =
  | {
      href: string;
    }
  | {
      route: string;
      params?: Readonly<Record<string, string>>;
    };
```

## Pages and blocks

Source: [`generic.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/generic.ts), [`page.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/page.ts)

### BUILT_IN

Blocks every page has: sections and tabs arrange other elements; regions embed what exists.

```ts
const BUILT_IN: readonly ['section', 'tabs', 'region'];
```

### builtInBlocks

The blocks every page has, as block specs.

```ts
const builtInBlocks: Readonly<Record<BuiltIn, BlockSpec>>;
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`BuiltIn`](https://uitive.dev/docs/api/core#builtin).

### checkGeneric

Checks a generic block's props against its queries and actions; returns them canonical.

```ts
function checkGeneric(name: GenericName, props: unknown, scope: GenericScope): unknown;
```

Uses: [`GenericName`](https://uitive.dev/docs/api/core#genericname), [`GenericScope`](https://uitive.dev/docs/api/core#genericscope).

### DATA_BLOCKS

Blocks that show the result of one of the page's named queries.

```ts
const DATA_BLOCKS: readonly GenericName[];
```

Uses: [`GenericName`](https://uitive.dev/docs/api/core#genericname).

### DATA_PATTERN

Data names are referenced from props.

```ts
const DATA_PATTERN: RegExp = /^[a-z][a-zA-Z0-9]{0,31}$/;
```

### ELEMENT_PATTERN

Element IDs are free text a planner writes, so only their shape is fixed.

```ts
const ELEMENT_PATTERN: RegExp = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
```

### fromSections

Converts a page of sections into the flat format: a root section holding one per section.

```ts
function fromSections(page: SectionsPage): PageValue;
```

Uses: [`PageValue`](https://uitive.dev/docs/api/core#pagevalue), [`SectionsPage`](https://uitive.dev/docs/api/core#sectionspage).

### GENERIC

Every generic block's name.

```ts
const GENERIC: readonly [
  'table',
  'list',
  'detail',
  'metric',
  'chart',
  'timeline',
  'board',
  'form',
  'actions',
  'note',
  'links',
];
```

### genericBlocks

Every generic block as a block spec: its label, description and props schema.

```ts
const genericBlocks: {
  readonly [K in GenericName]: BlockSpec<GenericProps[K]>;
};
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`GenericName`](https://uitive.dev/docs/api/core#genericname), [`GenericProps`](https://uitive.dev/docs/api/core#genericprops).

### genericFor

The generic blocks a page may use: those it hasn't replaced with its own block of the same
name, and that the contract can feed (data blocks need sources, forms need actions with params).

```ts
function genericFor(contract: AnyContract, spec: AnyPageSpec): GenericName[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`GenericName`](https://uitive.dev/docs/api/core#genericname).

### GenericProblem

Why a generic block's props were rejected.

```ts
class GenericProblem extends Error {
  readonly rule: 'unknown' | 'validator' | 'kind';
  constructor(rule: 'unknown' | 'validator' | 'kind', message: string);
}
```

### LAYOUTS

Every layout a section may have.

```ts
const LAYOUTS: readonly ['stack', 'grid', 'columns'];
```

### MAX_DEPTH

How deeply a page's sections may nest, unless its spec says otherwise.

```ts
const MAX_DEPTH = 4;
```

### MAX_ELEMENTS

Elements a page may hold, unless its spec says otherwise.

```ts
const MAX_ELEMENTS = 40;
```

### MAX_QUERIES

Queries a page may run, unless its spec says otherwise.

```ts
const MAX_QUERIES = 8;
```

### PageProblem

Why a page was rejected: an unknown name, a broken rule, or something only the user may do.

```ts
class PageProblem extends Error {
  readonly rule: 'unknown' | 'validator' | 'kind';
  constructor(rule: 'unknown' | 'validator' | 'kind', message: string);
}
```

### periodOf

For comparisons with the previous period: the time filter a query starts at, if any.

```ts
function periodOf(
  query: Query,
  contract: AnyContract,
):
  | {
      field: string;
      from: string;
      to?: string;
    }
  | undefined;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Query`](https://uitive.dev/docs/api/core#query-type).

### regionsFor

The regions a page may embed: those about nothing in particular, or about its entity.

```ts
function regionsFor(contract: AnyContract, spec: AnyPageSpec): string[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec).

### toPage

A page in the flat format, whichever format it came in. Malformed sections stay as they are.

```ts
function toPage(value: unknown): unknown;
```

### ui

Builds pages as trees and flattens them: `ui.page(ui.section('', 'stack', [ui.region('main')]))`.

```ts
const ui: {
  section(title: string, layout: Layout, children: readonly Node[], id?: string): Node;
  tabs(title: string, children: readonly Node[], id?: string): Node;
  region(name: string, id?: string): Node;
  block(name: string, props?: unknown, id?: string): Node;
  page(root: Node, data?: readonly NamedQuery[]): PageValue;
};
```

Uses: [`NamedQuery`](https://uitive.dev/docs/api/core#namedquery), [`Node`](https://uitive.dev/docs/api/core#node), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue).

| Member | Description |
| - | - |
| `section()` | A section: a title, which may be empty, a layout and its children. |
| `tabs()` | Tabs: one section shown at a time, picked by the sections' titles. |
| `region()` | One of the contract's regions: part of the application as it is. |
| `block()` | A block, generic or the application's own, with its props. |
| `page()` | The page: its root element, flattened, and the named queries its blocks show. |

### USER_PAGE_PATH

Where a user's page lives in the application.

```ts
const USER_PAGE_PATH = '/uitive/:slug';
```

### userPagePath

Where one of the user's pages lives.

```ts
function userPagePath(slug: string): string;
```

### userPageSpec

What the user's own pages may hold: built-in and generic blocks, and regions about nothing in
particular. Their own validation, like any page's.

```ts
function userPageSpec(): AnyPageSpec;
```

Uses: [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec).

### validatePage

Validates a whole page against its blocks, queries, regions and limits, and returns it in
canonical form: canonical names, a single tree from the root, elements in tree order. Queries
may compare with `$me`, whoever the bindings' `context()` says is signed in when they run.

```ts
function validatePage(
  contract: AnyContract,
  spec: AnyPageSpec,
  raw: unknown,
  context?: string,
  options?: ValidateOptions,
): PageValue;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue), [`ValidateOptions`](https://uitive.dev/docs/api/core#validateoptions).

### walk

The elements of a page in tree order, with each one's depth.

```ts
function walk(page: PageValue): {
  element: Element;
  depth: number;
}[];
```

Uses: [`Element`](https://uitive.dev/docs/api/core#element), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue).

### ActionsProps

Buttons for actions: a list's visible items, or chosen actions with their params.

Uses: [`RowAction`](https://uitive.dev/docs/api/core#rowaction).

| Property | Type | Description |
| - | - | - |
| `list` | `string` | A list surface whose visible items become buttons, or `none`. |
| `items` | `readonly RowAction[]` | Actions to offer, besides the list's, with their params. |
| `size` | `'small' \| 'regular' \| 'large'` | How large the buttons are. |

### AnyPage

Any page, with its props unknown: what generic code works with.

Uses: [`Element`](https://uitive.dev/docs/api/core#element), [`NamedQuery`](https://uitive.dev/docs/api/core#namedquery).

| Property | Type | Description |
| - | - | - |
| `root` | `string` | The ID of the outermost element, usually a section. |
| `elements` | `readonly Element[]` | Every element, the root included. |
| `data` | `readonly NamedQuery[]` | The queries its blocks show. |

### BoardProps

A query's rows in columns by an enum field, such as orders by status. Read only.

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries, whose result the block shows. |
| `column` | `string` | The enum field whose values are the columns. |
| `title` | `string` | The field each card is titled by. |
| `meta` | `string` | A second field on each card, or `none`. |

### BuiltIn

The name of a block every page has.

```ts
type BuiltIn = (typeof BUILT_IN)[number];
```

Uses: [`BUILT_IN`](https://uitive.dev/docs/api/core#built_in).

### BuiltInElement

An element of a block every page has, with its props typed.

```ts
type BuiltInElement =
  Element<'section', SectionProps> | Element<'tabs', TabsProps> | Element<'region', RegionProps>;
```

Uses: [`Element`](https://uitive.dev/docs/api/core#element), [`RegionProps`](https://uitive.dev/docs/api/core#regionprops), [`SectionProps`](https://uitive.dev/docs/api/core#sectionprops), [`TabsProps`](https://uitive.dev/docs/api/core#tabsprops).

### ChartProps

A chart of a grouped summary: lines, bars, areas or a pie.

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries: a summary grouped by a field or a time bucket. |
| `kind` | `'line' \| 'bar' \| 'area' \| 'pie'` | The kind of chart; a pie can't group by time or split. |
| `stacked` | `boolean` | Whether a split stacks, for bars and areas. |

### DetailProps

One row's fields, in columns, such as the order a page is about.

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries; its limit must be 1. |
| `fields` | `readonly string[]` | The fields to show, in order. |
| `columns` | `number` | How many columns the fields sit in, from 1 to 3. |

### Element

One placed block. Only sections and tabs have children.

Type parameters: `K extends string = string`, `P = unknown`.

| Property | Type | Description |
| - | - | - |
| `id` | `string` | Its ID within the page. |
| `block` | `K` | The block it places. |
| `props` | `P` | The block's props. |
| `children` | `readonly string[]` | The IDs of the elements inside it, in order. |

### ElementOf

Any element a page built from these blocks can hold, with its props typed.

```ts
type ElementOf<B extends Record<string, BlockSpec>> =
  | BuiltInElement
  | {
      [K in Extract<keyof B, string>]: Element<K, PropsOf<B[K]>>;
    }[Extract<keyof B, string>];
```

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`BuiltInElement`](https://uitive.dev/docs/api/core#builtinelement), [`Element`](https://uitive.dev/docs/api/core#element), [`PropsOf`](https://uitive.dev/docs/api/core#propsof).

### FormProps

A form that runs one action, asking for the params it doesn't fill in itself.

| Property | Type | Description |
| - | - | - |
| `action` | `string` | The action to run: one with an effect and params. |
| `set` | `readonly { param: string; value: string }[]` | Params filled in, such as the page's row with `$current`; the form asks for the rest. |

### GenericName

Blocks Uitive draws itself from the contract's sources and actions.

```ts
type GenericName = (typeof GENERIC)[number];
```

Uses: [`GENERIC`](https://uitive.dev/docs/api/core#generic).

### GenericProps

Props of each generic block, by name.

Uses: [`ActionsProps`](https://uitive.dev/docs/api/core#actionsprops), [`BoardProps`](https://uitive.dev/docs/api/core#boardprops), [`ChartProps`](https://uitive.dev/docs/api/core#chartprops), [`DetailProps`](https://uitive.dev/docs/api/core#detailprops), [`FormProps`](https://uitive.dev/docs/api/core#formprops), [`LinksProps`](https://uitive.dev/docs/api/core#linksprops), [`ListProps`](https://uitive.dev/docs/api/core#listprops), [`MetricProps`](https://uitive.dev/docs/api/core#metricprops), [`NoteProps`](https://uitive.dev/docs/api/core#noteprops), [`TableProps`](https://uitive.dev/docs/api/core#tableprops), [`TimelineProps`](https://uitive.dev/docs/api/core#timelineprops).

| Property | Type | Description |
| - | - | - |
| `table` | `TableProps` | A table of rows. |
| `list` | `ListProps` | A list of rows. |
| `detail` | `DetailProps` | One row's fields. |
| `metric` | `MetricProps` | One figure. |
| `chart` | `ChartProps` | A chart. |
| `timeline` | `TimelineProps` | Rows in time order. |
| `board` | `BoardProps` | Rows in columns. |
| `form` | `FormProps` | A form for one action. |
| `actions` | `ActionsProps` | Buttons for actions. |
| `note` | `NoteProps` | A note. |
| `links` | `LinksProps` | Links to routes. |

### GenericScope

What checking a generic block needs: the contract, the page and its queries.

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec), [`Query`](https://uitive.dev/docs/api/core#query-type).

| Property | Type | Description |
| - | - | - |
| `contract` | `AnyContract` | The contract the page belongs to. |
| `spec` | `AnyPageSpec` | The page's spec. |
| `data` | `ReadonlyMap<string, Query>` | The page's checked queries, by name. |
| `used` | `Set<string>` | Names of queries a block used, filled in as blocks are checked. |
| `planned` | `boolean` | A planner placed it, unasked: it may not place destructive actions or fill in writes. |

### Layout

How a section arranges its children: one under another, in a responsive grid, or side by side.

```ts
type Layout = (typeof LAYOUTS)[number];
```

Uses: [`LAYOUTS`](https://uitive.dev/docs/api/core#layouts).

### LinksProps

Links to the contract's routes, each with its own label.

| Property | Type | Description |
| - | - | - |
| `items` | `readonly { label: string; route: string; entity: string }[]` | The links: a label, or empty for the route's own, a route, and for a route about one row, its key or `$current`, the page's own row. Planners, who never see rows, write only `$current`. |

### ListProps

A list of a query's rows, each with a title, a subtitle, a detail and a badge drawn from its
fields.

Uses: [`RowAction`](https://uitive.dev/docs/api/core#rowaction).

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries, whose result the block shows. |
| `title` | `string` | The field each row is titled by. |
| `subtitle` | `string` | A second field under the title, or `none`. |
| `meta` | `string` | A field shown beside the row, such as a time, or `none`. |
| `badge` | `string` | An enum field drawn as a badge, such as a status, or `none`. |
| `rowActions` | `readonly RowAction[]` | Actions on each row. |
| `link` | `'none' \| 'entity'` | `entity` opens each row's own page. |

### MetricProps

One figure from a summary, such as a count or a sum, compared with the period before when asked.

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries: an ungrouped summary. |
| `label` | `string` | What the figure is, such as "Paid, not shipped". |
| `compare` | `'none' \| 'previous'` | `previous` compares with the period before the query's time filter. |

### NamedQuery

A named query whose result blocks show; several blocks may share one.

Uses: [`Query`](https://uitive.dev/docs/api/core#query-type).

| Property | Type | Description |
| - | - | - |
| `name` | `string` | Its name, which blocks use in their `data` prop. |
| `query` | `Query` | The query. |

### Node

A page written as a tree, for standard pages in code.

| Property | Type | Default | Description |
| - | - | - | - |
| `block` | `string` | | The block it places. |
| `props` | `unknown` | | The block's props. |
| `children?` | `readonly Node[]` | | For sections and tabs: what is inside, in order. |
| `id?` | `string` | the block's name and a number | Its ID within the page. |

### NoteProps

A short note: a title and up to 500 characters of text.

| Property | Type | Description |
| - | - | - |
| `title` | `string` | The note's title. |
| `text` | `string` | The note itself. |

### PageValue

A whole page, flat: elements keyed by ID, each listing its children. Nesting goes as deep as
the page allows while the planner schema stays free of recursion and of maps.

Uses: [`BlockSpec`](https://uitive.dev/docs/api/core#blockspec), [`ElementOf`](https://uitive.dev/docs/api/core#elementof).

Type parameters: `B extends Record<string, BlockSpec> = Record<string, BlockSpec>`.

| Property | Type | Description |
| - | - | - |
| `elements` | `readonly ElementOf<B>[]` | Every element, the root included, with its props typed. |
| `root` | `string` | The ID of the outermost element, usually a section. |
| `data` | `readonly NamedQuery[]` | The queries its blocks show. |

### RegionProps

A region's props: which of the contract's regions it embeds.

| Property | Type | Description |
| - | - | - |
| `name` | `string` | One of the contract's regions. |

### RowAction

An action offered on each row, or as a button, with the params it fills in.

| Property | Type | Description |
| - | - | - |
| `action` | `string` | The action's ID. |
| `set` | `readonly { param: string; value: string }[]` | Params filled in: literals, `$current`, or `$row.<field>` for row actions. |

### SectionProps

A section's props: a title, and how its children are laid out.

Uses: [`Layout`](https://uitive.dev/docs/api/core#layout).

| Property | Type | Description |
| - | - | - |
| `title` | `string` | May be empty. |
| `layout` | `Layout` | How its children are arranged. |

### SectionsPage

The first page format: sections of blocks, two levels. Still accepted, and converted.

```ts
interface SectionsPage {
  sections: readonly {
    title: string;
    layout: Layout;
    blocks: readonly {
      block: string;
      props: unknown;
    }[];
  }[];
}
```

Uses: [`Layout`](https://uitive.dev/docs/api/core#layout).

| Property | Description |
| - | - |
| `sections` | The page's sections, each with its blocks. |

### TableProps

A table of a query's rows: `columns` from its fields, figures from other queries as `lookups`,
and actions on each row.

Uses: [`RowAction`](https://uitive.dev/docs/api/core#rowaction).

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries, whose result the block shows. |
| `columns` | `readonly string[]` | The query's fields to show, in order, such as `orders.total`. |
| `lookups` | `readonly { data: string; label: string }[]` | Figures from other queries, one per row: an aggregate grouped by a ref to this source. |
| `rowActions` | `readonly RowAction[]` | Actions on each row; a ref param naming the table's source is filled with the row's key. |
| `density` | `'comfortable' \| 'compact'` | How tightly rows sit. |
| `link` | `'none' \| 'entity'` | `entity` opens each row's own page. |

### TabsProps

Tabs' props: a title for the set. Each tab is a section, titled by its own title.

| Property | Type | Description |
| - | - | - |
| `title` | `string` | The tabs' accessible name. |

### TimelineProps

A query's rows in time order, each with a title and a detail.

| Property | Type | Description |
| - | - | - |
| `data` | `string` | The name of one of the page's queries, whose result the block shows. |
| `time` | `string` | The time field that orders the rows. |
| `title` | `string` | The field each entry is titled by. |
| `detail` | `string` | A field under each title, or `none`. |

### ValidateOptions

How a page is validated: as the person's own, or as a planner's unasked suggestion.

| Property | Type | Description |
| - | - | - |
| `planned?` | `boolean` | A planner placed the page, unasked: no destructive actions, no filled-in writes. |

## Routes

Source: [`route.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/route.ts)

### buildPath

The path of a route with its params filled in, or undefined when one is missing or can't be one
segment, such as `..`.

```ts
function buildPath(
  contract: AnyContract,
  id: string,
  params?: Readonly<Record<string, string>>,
): string | undefined;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### entityRoute

The route that shows one row of a source, for links from rows.

```ts
function entityRoute(contract: AnyContract, source: string): string | undefined;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### matchRoute

The route a path names, with its params; literal segments beat params.

```ts
function matchRoute(
  contract: AnyContract,
  path: string,
):
  | {
      route: string;
      params: Record<string, string>;
    }
  | undefined;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### route

Declares a place in the application, such as `/orders/:id`: the page it shows, the source whose
row it is about, and the action a visit records.

```ts
function route(spec: RouteSpec): RouteSpec;
```

Uses: [`RouteSpec`](https://uitive.dev/docs/api/core#routespec).

### routeLabel

What links to a route say: its own label, else its page's label, else its ID.

```ts
function routeLabel(contract: AnyContract, id: string): string;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### segments

Splits a path pattern into segments; throws on patterns a router couldn't match.

```ts
function segments(pattern: string): RouteSegment[];
```

Uses: [`RouteSegment`](https://uitive.dev/docs/api/core#routesegment).

### validateRoutes

Checks every route against the contract's sources, pages and actions.

```ts
function validateRoutes(contract: AnyContract): void;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract).

### RouteSegment

One segment of a route's path: literal text, or a param such as `:id`.

```ts
type RouteSegment =
  | {
      literal: string;
    }
  | {
      param: string;
    };
```

### RouteSpec

A place in the application, such as `/customers/:id`.

| Property | Type | Default | Description |
| - | - | - | - |
| `path` | `string` | | A path pattern: literal segments and `:param` segments. |
| `label?` | `string` | the page's label, else the route's ID | Shown in links. |
| `entity?` | `string` | | The source whose row the route shows; the `key` param holds the row's key. |
| `key?` | `string` | `'id'` | The param holding the entity's key. |
| `page?` | `string` | | The page surface the route shows. |
| `action?` | `string` | | The action a visit records, such as `go.payments`. |

## The client

Source: [`client.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/client.ts), [`storage.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/storage.ts)

### createUitive

Creates a client for one person's interface. State loads synchronously from the store, so a
stored interface shows on the first paint.

```ts
function createUitive<C extends AnyContract>(options: UitiveOptions<C>): Uitive<C>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Uitive`](https://uitive.dev/docs/api/core#uitive), [`UitiveOptions`](https://uitive.dev/docs/api/core#uitiveoptions).

### localStore

Keeps state in the browser's `localStorage`; does nothing where there is none.

```ts
function localStore(key: string): Store;
```

Uses: [`Store`](https://uitive.dev/docs/api/core#store).

### memoryStore

Keeps state in memory, as JSON, so every load is an independent copy.

```ts
function memoryStore(initial?: unknown): Store;
```

Uses: [`Store`](https://uitive.dev/docs/api/core#store).

### Adaptation

One batch of changes, kept for banners, history and the debug panel.

Uses: [`CommandStatus`](https://uitive.dev/docs/api/core#commandstatus), [`PlanMeta`](https://uitive.dev/docs/api/core#planmeta), [`Rejection`](https://uitive.dev/docs/api/core#rejection).

| Property | Type | Description |
| - | - | - |
| `id` | `string` | Its ID, for `revertAdaptation`. |
| `kind` | `'plan' \| 'apply' \| 'command' \| 'user' \| 'import' \| 'reset'` | What made it: a plan, pending changes applied, a command, the person acting, an import or a reset. |
| `session` | `number` | The session it happened in. |
| `applied` | `readonly string[]` | Operations it applied, or added as suggestions. |
| `rejected` | `readonly Rejection[]` | What policy refused, with reasons. |
| `pending` | `number` | Operations still waiting for a safe moment or a second plan. |
| `status?` | `CommandStatus` | For commands: what became of the request. |
| `candidates?` | `readonly string[]` | For ambiguous commands: what the words could mean. |
| `text?` | `string` | For commands: the request, in the person's words. |
| `meta?` | `PlanMeta` | How the plan was made: the planner, how long it took, and any fallback. |

### Autonomy

How far the system may act on its own. `suggest`: planned changes wait for the person's yes.
`mixed`: planned changes apply at a safe moment, a model's once a plan in a later session agrees
or it clears the margin. `auto`: planned changes apply at the next safe moment, and suggested
items join the interface at once. In every mode a redesign stays a suggestion until the person
accepts it.

```ts
type Autonomy = 'suggest' | 'mixed' | 'auto';
```

### DefinitionDocument

The portable form of a definition, for export and import.

Uses: [`Definition`](https://uitive.dev/docs/api/core#definition).

| Property | Type | Description |
| - | - | - |
| `format` | `'uitive.definition'` | Says what the document is. |
| `version` | `1` | The document format's version. |
| `contract` | `{ id: string; hash: string }` | The contract it was exported from; an import checks its changes against the current one. |
| `definition` | `Definition` | The person's definition. |

### Location

Where the user is, as the application's router reports it.

| Property | Type | Description |
| - | - | - |
| `path` | `string` | The path, with its query. |
| `route?` | `string` | The contract route the path matches. |
| `params` | `Readonly<Record<string, string>>` | The route's params, by name. |
| `entity?` | `{ source: string; key: string }` | The row the page is about, on routes that show one: what `$current` names. |
| `userPage?` | `string` | One of the user's own pages, at `/uitive/<slug>`. |

### PageInput

A page as code may write it: flat elements, or sections of blocks.

```ts
type PageInput<C extends AnyContract, K extends SurfaceIdOf<C>> =
  C['surfaces'][K] extends PageSpec<infer B>
    ? PageValue<B> | SectionPage<B> | AnyPage
    : AnyPage | SectionsPage;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`PageSpec`](https://uitive.dev/docs/api/core#pagespec), [`PageValue`](https://uitive.dev/docs/api/core#pagevalue), [`SectionPage`](https://uitive.dev/docs/api/core#sectionpage), [`SectionsPage`](https://uitive.dev/docs/api/core#sectionspage), [`SurfaceIdOf`](https://uitive.dev/docs/api/core#surfaceidof).

### RecordOptions

How one use of an action came about, for `record`.

Uses: [`Via`](https://uitive.dev/docs/api/core#via).

| Property | Type | Default | Description |
| - | - | - | - |
| `via?` | `Via` | `'region'` | How the person reached it: straight from where it shows, from overflow, the palette, a suggestion, a shortcut or a command. |
| `surface?` | `string` | | The surface it was used from, such as `toolbar`, so learning knows which list it belongs to: the use then counts toward that surface alone. Without one, it counts toward every list holding the action. |
| `element?` | `string` | | The page element it came from. |
| `typed?` | `boolean` | | For palette picks: whether the user typed a search first. |

### Snapshot

Everything a client holds right now, for panels such as "Your interface" and the debug panel: the
definition, what is pending, recent adaptations, where the person is and any run waiting for
their yes.

Uses: [`Adaptation`](https://uitive.dev/docs/api/core#adaptation), [`Autonomy`](https://uitive.dev/docs/api/core#autonomy), [`Confirmation`](https://uitive.dev/docs/api/core#confirmation), [`Definition`](https://uitive.dev/docs/api/core#definition), [`Location`](https://uitive.dev/docs/api/core#location), [`Pending`](https://uitive.dev/docs/api/core#pending), [`View`](https://uitive.dev/docs/api/core#view).

| Property | Type | Description |
| - | - | - |
| `session` | `number` | The current session, counted from the first. |
| `view` | `View` | Whether the person sees their own interface or the standard one. |
| `autonomy` | `Autonomy` | How far planned changes may go without the person. |
| `definition` | `Definition` | The person's definition: every applied operation, cooldowns and blocks. |
| `pending` | `readonly Pending[]` | Changes waiting for the next safe moment. |
| `latest` | `Adaptation \| undefined` | The most recent adaptation, for banners. |
| `adaptations` | `readonly Adaptation[]` | Recent adaptations, oldest first. |
| `contexts` | `Readonly<Record<string, string>>` | Context values active now, by context name. |
| `usage` | `number` | Increments with every usage event. |
| `preview` | `string \| undefined` | A suggested redesign shown in place, before the user accepts or dismisses it. |
| `confirmation` | `Confirmation \| undefined` | A run waiting for the user's yes. |
| `location` | `Location \| undefined` | Where the user is, once the application reports it. |

### Store

Where a client keeps its state. Loading is synchronous, so a stored interface renders on the
first paint, with no layout shift.

| Property | Type | Description |
| - | - | - |
| `load()` | `() => unknown` | The stored state, or nothing; synchronous, so the first paint shows the person's interface. |
| `save()` | `(state: unknown) => void` | Stores the state. |
| `clear()` | `() => void` | Deletes the stored state. |
| `watch?()` | `(listener: () => void) => () => void` | Calls `listener` when something else changes the stored state, such as another tab. |

### Uitive

A client: one person's adapting interface. It records use, answers requests, applies what policy
allows at safe moments, runs actions through the bindings, and keeps the person's definition in
its store.

```ts
interface Uitive<C extends AnyContract = AnyContract> {
  readonly contract: C;
  readonly data: DataClient | undefined;
  getSnapshot(): Snapshot;
  subscribe(listener: () => void): () => void;
  surface<K extends SurfaceIdOf<C>>(id: K, context?: string): SurfaceValueOf<C, K>;
  standard<K extends SurfaceIdOf<C>>(id: K, context?: string): SurfaceValueOf<C, K>;
  events(limit?: number): readonly UsageEvent[];
  ranked(): readonly ActionView<ActionIdOf<C>>[];
  record(action: ActionIdOf<C>, options?: RecordOptions): void;
  perform<A extends ActionIdOf<C>>(
    action: A,
    params?: ParamsOf<C, A>,
    options?: PerformOptions,
  ): Promise<PerformResult>;
  confirm(id: string, phrase?: string): boolean;
  cancel(id: string): void;
  confirmations(): () => void;
  setLocation(path: string): void;
  navigate(target: Target): string | undefined;
  attachRouter(navigate: (href: string) => void): () => void;
  userPages(): readonly UserPage[];
  createPage(
    title: string,
    value?: AnyPage | SectionsPage,
  ): {
    slug: string;
    adaptation: Adaptation;
  };
  renamePage(slug: string, title: string): Adaptation;
  setUserPage(slug: string, value: AnyPage | SectionsPage): Adaptation;
  deletePage(slug: string): Adaptation;
  setContext(name: ContextOf<C>, value: string | undefined): void;
  resume(): Adaptation | undefined;
  nextSession(): Adaptation | undefined;
  apply(): Adaptation | undefined;
  plan(): Promise<Adaptation>;
  learn(): Promise<Adaptation | undefined>;
  ask(
    text: string,
    options?: {
      goal?: boolean;
    },
  ): Promise<Adaptation>;
  pin(surface: SurfaceIdOf<C>, action: ActionIdOf<C>, context?: string): Adaptation;
  unpin(surface: SurfaceIdOf<C>, action: ActionIdOf<C>, context?: string): Adaptation;
  hide(surface: SurfaceIdOf<C>, action: ActionIdOf<C>, context?: string): Adaptation;
  restore(surface: SurfaceIdOf<C>, action: ActionIdOf<C>, context?: string): Adaptation;
  move(surface: SurfaceIdOf<C>, action: ActionIdOf<C>, index: number, context?: string): Adaptation;
  set(surface: SurfaceIdOf<C>, value: string): Adaptation;
  setPage<K extends SurfaceIdOf<C>>(
    surface: K,
    value: PageInput<C, K>,
    context?: string,
  ): Adaptation;
  resetPage(surface: SurfaceIdOf<C>, context?: string): Adaptation;
  preview(operation: string | undefined): void;
  addItem(surface: SurfaceIdOf<C>, value: unknown): Adaptation;
  updateItem(surface: SurfaceIdOf<C>, item: string, value: unknown): Adaptation;
  removeItem(surface: SurfaceIdOf<C>, item: string): Adaptation;
  revert(operation: string): void;
  revertAdaptation(adaptation: string): void;
  keep(operation: string): void;
  accept(operation: string): boolean;
  dismiss(operation: string): void;
  freeze(frozen: boolean): void;
  setGoal(goal: string | undefined): void;
  setView(view: View): void;
  setAutonomy(autonomy: Autonomy): void;
  reset(): void;
  clearData(): void;
  export(): DefinitionDocument;
  import(document: unknown): Adaptation;
  explain(operation: string | Operation): Explanation | undefined;
  request(kind: 'plan' | 'command', text?: string): PlanRequest;
  summary(): UsageSummary;
  flush(): void;
}
```

Uses: [`ActionIdOf`](https://uitive.dev/docs/api/core#actionidof), [`ActionView`](https://uitive.dev/docs/api/core#actionview), [`Adaptation`](https://uitive.dev/docs/api/core#adaptation), [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`Autonomy`](https://uitive.dev/docs/api/core#autonomy), [`ContextOf`](https://uitive.dev/docs/api/core#contextof), [`DataClient`](https://uitive.dev/docs/api/core#dataclient), [`DefinitionDocument`](https://uitive.dev/docs/api/core#definitiondocument), [`Explanation`](https://uitive.dev/docs/api/core#explanation), [`Operation`](https://uitive.dev/docs/api/core#operation), [`PageInput`](https://uitive.dev/docs/api/core#pageinput), [`ParamsOf`](https://uitive.dev/docs/api/core#paramsof), [`PerformOptions`](https://uitive.dev/docs/api/core#performoptions), [`PerformResult`](https://uitive.dev/docs/api/core#performresult), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest), [`RecordOptions`](https://uitive.dev/docs/api/core#recordoptions), [`SectionsPage`](https://uitive.dev/docs/api/core#sectionspage), [`Snapshot`](https://uitive.dev/docs/api/core#snapshot), [`SurfaceIdOf`](https://uitive.dev/docs/api/core#surfaceidof), [`SurfaceValueOf`](https://uitive.dev/docs/api/core#surfacevalueof), [`Target`](https://uitive.dev/docs/api/core#target), [`UsageEvent`](https://uitive.dev/docs/api/core#usageevent), [`UsageSummary`](https://uitive.dev/docs/api/core#usagesummary), [`UserPage`](https://uitive.dev/docs/api/core#userpage), [`View`](https://uitive.dev/docs/api/core#view).

| Property | Description |
| - | - |
| `contract` | The contract the client adapts. |
| `data` | Query results, shared and cached, when the bindings can fetch. |
| `getSnapshot()` | Everything the client holds right now; stable between changes, for `useSyncExternalStore`. |
| `subscribe()` | Calls the listener after every change; returns its removal. |
| `surface()` | A surface's current value. Stable between changes, so it is safe to render from. |
| `standard()` | A surface as the application ships it, whatever the user's definition. |
| `events()` | The most recent usage events, newest last. |
| `ranked()` | Every action, ranked for a palette by how the user reaches for them. |
| `record()` | Records one use of an action, never its params or any text: the evidence learning and planners work from. |
| `perform()` | Runs an action through the bindings. Writes from generated interfaces wait for the user's yes, destructive ones for a typed phrase; a confirmed run is recorded without its params. |
| `confirm()` | Says yes to the waiting run. For destructive actions, `phrase` must match. |
| `cancel()` | Says no to the waiting run. |
| `confirmations()` | Declares an interface that can ask for confirmation; returns its removal. |
| `setLocation()` | Tells the client where the user is; call it on every route change. Sets the page's row and any context named like a route param, and records the route's action. |
| `navigate()` | Follows a link or route through the router binding; returns the URL. |
| `attachRouter()` | Lets a router follow links, ahead of the bindings' `navigate`; returns its removal. |
| `userPages()` | The pages the user made, in the order they made them. |
| `createPage()` | Makes a page of the user's own; it lives at `/uitive/<slug>`. |
| `renamePage()` | Renames one of the user's pages. |
| `setUserPage()` | Redesigns one of the user's pages outright. |
| `deletePage()` | Deletes one of the user's pages. |
| `setContext()` | Sets a context, such as the service on screen, so surfaces keyed by it show that value's layout. |
| `resume()` | A safe moment after the page was hidden: starts a session and applies pending changes. |
| `nextSession()` | Ends the session now and applies pending changes, as if the user came back later. |
| `apply()` | Applies pending changes now: an explicit safe moment. |
| `plan()` | Asks the planner for changes from usage and any stated goal. What policy accepts waits for a safe moment, and redesigns stay suggestions. Calls while a plan is on its way share it. |
| `learn()` | Plans from use once a session; the provider and `startUitive` call it whenever one starts. Does nothing when this session was planned already, when the interface is frozen, or when the client was created with `learn: false`. |
| `ask()` | A request in the user's own words, answered at once. With `goal`, the words are kept as their stated goal; blank words clear it. |
| `pin()` | Keeps an action visible in a list, bringing it out of overflow if needed. |
| `unpin()` | Lets a pinned action move again; after a pin, it reverts the pin. |
| `hide()` | Moves an action out of a list's visible part, into overflow. Required actions refuse. |
| `restore()` | Brings a hidden action back; after a hide, it reverts the hide. |
| `move()` | Moves an action to a position among the visible ones, in a reorderable list. |
| `set()` | Sets a choice to one of its values. |
| `setPage()` | Redesigns a page outright; for a page keyed by context, one value or `*` for every value. |
| `resetPage()` | Puts a page back to standard. |
| `preview()` | Shows a suggested redesign in place without applying it; nothing to stop previewing. Only a redesign still suggested can be previewed, and the preview ends when it no longer is. |
| `addItem()` | Adds an item to a collection, checked against its schema and validator. |
| `updateItem()` | Changes an item of a collection. |
| `removeItem()` | Removes an item from a collection. |
| `revert()` | Undoes an applied change. A planned change cools down; a second revert blocks it. |
| `revertAdaptation()` | Undoes every change an adaptation applied. |
| `keep()` | Confirms a change; it joins the user's own layer. |
| `accept()` | Accepts a pending change or a suggested item; either joins the user's own layer. |
| `dismiss()` | Declines a pending change or a suggested item; it cools down. |
| `freeze()` | Stops or resumes planned changes; the person's own still apply. |
| `setGoal()` | Keeps or clears the person's stated goal, such as "I watch costs", which planners read. It is trimmed and kept to 500 characters; a blank one clears it. |
| `setView()` | Shows the person's interface, or the application as shipped. |
| `setAutonomy()` | Sets how far the system may act on its own. |
| `reset()` | Puts the layout back to standard. Usage is kept, and so are freeze, blocked changes, cooldowns and the stated goal. |
| `clearData()` | Forgets everything: usage, definition and history. |
| `export()` | The person's definition, portable, for a file or another device. |
| `import()` | Takes a definition from `export`, checked against this contract like any change: what breaks the contract's rules is skipped with its reason, and a file that isn't a definition is refused. |
| `explain()` | Why a change was made, in plain words, with its evidence. |
| `request()` | Exactly what a planner would receive: all that leaves the device. |
| `summary()` | Usage summarized per action and surface, as planners see it. |
| `flush()` | Writes pending state to the store now. |

### UitiveOptions

What `createUitive` takes: the contract, and where state lives, who plans and the
application's code behind the contract.

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Autonomy`](https://uitive.dev/docs/api/core#autonomy), [`Bindings`](https://uitive.dev/docs/api/core#bindings), [`Environment`](https://uitive.dev/docs/api/core#environment), [`Planner`](https://uitive.dev/docs/api/core#planner), [`StabilizerOptions`](https://uitive.dev/docs/api/core#stabilizeroptions), [`Store`](https://uitive.dev/docs/api/core#store).

Type parameters: `C extends AnyContract`.

| Property | Type | Default | Description |
| - | - | - | - |
| `contract` | `C` | | The contract `defineApp` returned. |
| `store?` | `Store` | `memoryStore()` | Where state persists. |
| `planner?` | `Planner` | `heuristicPlanner()` | Who plans: the deterministic planner, or `remotePlanner` for a model on the application's server. Simple commands are always answered locally. |
| `now?` | `() => number` | `Date.now` | The clock, in milliseconds; tests pass one that moves only when told. |
| `idleMinutes?` | `number` | `30` | Minutes without activity that end a session. |
| `autonomy?` | `Autonomy` | `'mixed'` | Used until the user chooses otherwise. |
| `learn?` | `boolean` | `true` | Whether the client plans from use by itself, once a session (see `learn`). With a model planner, each plan is one request to the application's server. |
| `stabilizer?` | `Partial<StabilizerOptions>` | | How cautiously planned changes apply: how many per session, after how many sessions, and how long a reverted one waits. |
| `bindings?` | `Bindings<C>` | | The application's code behind the contract: reading sources, running actions, routing. |
| `onError?` | `(error: unknown) => void` | | Called when storage or a planner fails, including a remote planner whose fallback answered instead, and when another tab runs a different version of the application; the interface keeps working. |
| `environment?` | `() => Environment \| undefined` | | For pages Uitive adapts from outside, such as in a browser extension: what the page offers now, sent with each request. Structure only, never the page's text. |

### View

`standard` shows the application as shipped; `yours` applies the user's definition.

```ts
type View = 'yours' | 'standard';
```

## Planners

Source: [`heuristic.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/heuristic.ts), [`planner.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/planner.ts)

### command

Keyword commands. Words are matched against items only for a stated goal; anything else
needs a model to understand, and guessing from shared words would only add noise.

```ts
function command(request: PlanRequest, contract: AnyContract): CommandResult;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`CommandResult`](https://uitive.dev/docs/api/core#commandresult), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest).

### heuristicPlanner

The deterministic planner: swaps rising overflow items with idle visible ones, under
capacity pressure and past a margin; understands keyword commands; and matches goals by
shared words: a deliberately naive stand-in that shows what a model adds.

```ts
function heuristicPlanner(): Planner;
```

Uses: [`Planner`](https://uitive.dev/docs/api/core#planner).

### keywordCommand

Commands that name what to change ("hide share", "pin export", "compact"), answered
locally and instantly. Returns nothing for anything else.

```ts
function keywordCommand(request: PlanRequest, contract: AnyContract): CommandResult | undefined;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`CommandResult`](https://uitive.dev/docs/api/core#commandresult), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest).

### MARGIN

How much more an item must be used than the one it replaces: one recent use, plus a quarter
of the other's use, so two items used about equally never trade places on noise.

```ts
const MARGIN = 1;
```

### MIN_PROMOTE

A placement score worth about two recent uses: the least that earns a promotion.

```ts
const MIN_PROMOTE = 2;
```

### planResultSchema

Validates a plan result that arrived over the network.

```ts
const planResultSchema: ZodObject;
```

### remotePlanner

Asks a server-side planner, falling back locally on any failure, with the reason recorded.

```ts
function remotePlanner(options: RemotePlannerOptions): Planner;
```

Uses: [`Planner`](https://uitive.dev/docs/api/core#planner), [`RemotePlannerOptions`](https://uitive.dev/docs/api/core#remoteplanneroptions).

### ClaimedEvidence

Evidence as a planner claims it. Policy replaces it with values from the local summary.

```ts
type ClaimedEvidence =
  | {
      action: string;
      metric: Metric;
    }
  | {
      intent: true;
    };
```

Uses: [`Metric`](https://uitive.dev/docs/api/core#metric).

### CommandResult

What the deterministic planner makes of a command: the operations, its status, and the candidates
when it was ambiguous.

```ts
type CommandResult = Pick<PlanResult, 'operations' | 'status' | 'candidates'>;
```

Uses: [`PlanResult`](https://uitive.dev/docs/api/core#planresult).

### CommandStatus

What became of a request in the person's words: done, partly done, not allowed, ambiguous, not
something the application can change, or unanswered.

```ts
type CommandStatus =
  'done' | 'partial' | 'not_allowed' | 'ambiguous' | 'unsupported' | 'unavailable';
```

### Environment

The shape of a page the application doesn't describe itself, as a browser extension sees it:
which anchors and sources it found. Structure only; never the page's text.

| Property | Type | Description |
| - | - | - |
| `route` | `string \| null` | The adapter route the page matched. |
| `anchors` | `Readonly<Record<string, 'found' \| 'missing' \| 'ambiguous'>>` | Whether each anchor was found once, not at all, or more than once. |
| `sources` | `Readonly<Record<string, 'live' \| 'partial' \| 'unavailable'>>` | Whether each source could be read. |
| `unmapped` | `{ links: number; buttons: number; tables: number }` | What the adapter doesn't know about, counted and never named. |

### FetchLike

The `fetch` `remotePlanner` calls: the platform's, or one that adds what a site needs, such as a
header.

```ts
type FetchLike = (
  url: string,
  init: {
    method: string;
    headers: Record<string, string>;
    body: string;
    signal?: unknown;
  },
) => Promise<PlannerResponse>;
```

Uses: [`PlannerResponse`](https://uitive.dev/docs/api/core#plannerresponse).

### PlanMeta

How a plan was made: by which planner and model, how fast, at what cost, and whether it was
scoped or repaired.

| Property | Type | Description |
| - | - | - |
| `planner` | `string` | The planner's name. |
| `ms` | `number` | How long planning took, in milliseconds. |
| `subset?` | `readonly string[]` | The sources the request was scoped to, for large contracts. |
| `repaired?` | `boolean` | A second round fixed what policy rejected in the first. |
| `unrepaired?` | `string` | Why the second round failed, when what policy accepted of the first answer was kept instead. |
| `stages?` | `number` | Model calls made. |
| `model?` | `string` | The model that planned, for model planners. |
| `fellBack?` | `string` | Why a fallback planner answered instead. |
| `usage?` | `{ input: number; output: number; cacheRead: number; cacheWrite: number }` | Tokens the model read and wrote, and what the prompt cache saved. |
| `cost?` | `number` | Estimated cost in US dollars. |

### Planner

Something that plans: the deterministic planner, a remote one, or a model planner on a server.

```ts
interface Planner {
  readonly name: string;
  plan(request: PlanRequest, contract: AnyContract, options?: PlanOptions): Promise<PlanResult>;
}
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`PlanOptions`](https://uitive.dev/docs/api/core#planoptions), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest), [`PlanResult`](https://uitive.dev/docs/api/core#planresult).

| Property | Description |
| - | - |
| `name` | The planner's name, as plans report it. |
| `plan()` | Proposes operations for a request. It sees schemas and usage, never rows. |

### PlannerResponse

What `remotePlanner` reads from a response: the platform's `Response` fits.

Uses: [`PlannerStream`](https://uitive.dev/docs/api/core#plannerstream).

| Property | Type | Description |
| - | - | - |
| `ok` | `boolean` | Whether the status is in the 200s. |
| `status` | `number` | The HTTP status. |
| `json()` | `() => Promise<unknown>` | The body, parsed. |
| `headers?` | `{ get(name: string): string \| null }` | The response's headers, for its content type. |
| `body?` | `PlannerStream \| null` | The body as a stream, when progress lines arrive. |

### PlannerStream

A response body read as a stream, for progress lines: the platform's `ReadableStream` fits.

| Property | Type | Description |
| - | - | - |
| `getReader()` | `() => { read(): Promise<{ done: boolean; value?: Uint8Array }> }` | Reads the body chunk by chunk. |

### PlanOptions

What a planner may be given besides the request: a way to cancel, and a listener for progress.

Uses: [`PlanProgress`](https://uitive.dev/docs/api/core#planprogress).

| Property | Type | Description |
| - | - | - |
| `signal?` | `unknown` | An `AbortSignal` where the platform has one. |
| `onProgress?` | `(progress: PlanProgress) => void` | Called as the plan arrives; planners that can't stream never call it. |

### PlanProgress

How far a plan has come, for showing progress on long redesigns.

| Property | Type | Description |
| - | - | - |
| `stage` | `'planning' \| 'repairing'` | Whether the model is planning, or repairing what policy rejected. |
| `elements` | `number` | Page elements written so far. |

### PlanRequest

Everything a planner receives. This is all that leaves the device.

Uses: [`Environment`](https://uitive.dev/docs/api/core#environment), [`StateView`](https://uitive.dev/docs/api/core#stateview), [`UsageSummary`](https://uitive.dev/docs/api/core#usagesummary).

| Property | Type | Description |
| - | - | - |
| `kind` | `'plan' \| 'command'` | A plan from use, or a command in the person's words. |
| `contract` | `{ id: string; hash: string }` | The contract's ID and hash; the server holds the contract itself. |
| `session` | `number` | The current session. |
| `summary` | `UsageSummary` | Usage, as numbers. |
| `state` | `StateView` | The interface as it is, as IDs. |
| `contexts` | `Readonly<Record<string, string>>` | Context values active now, by context name. |
| `route?` | `string` | The route in view; never the row it shows. |
| `text?` | `string` | The command, in the user's words. |
| `goal?` | `string` | The goal the user stated, in their words. |
| `environment?` | `Environment` | For pages Uitive adapts from outside, such as in the extension: what was found. |

### PlanResult

What a planner answers: proposed operations, a status for commands, and how the plan was made.

Uses: [`CommandStatus`](https://uitive.dev/docs/api/core#commandstatus), [`PlanMeta`](https://uitive.dev/docs/api/core#planmeta), [`ProposedOperation`](https://uitive.dev/docs/api/core#proposedoperation).

| Property | Type | Description |
| - | - | - |
| `origin` | `'heuristic' \| 'model'` | Which planner produced the operations. |
| `operations` | `readonly ProposedOperation[]` | The proposed operations, for policy to check. |
| `status?` | `CommandStatus` | For commands: what became of the request. |
| `candidates?` | `readonly string[]` | For ambiguous commands: what the words could mean. |
| `meta` | `PlanMeta` | How the plan was made. |

### ProposedOperation

A change a planner proposes, with the evidence it claims; policy checks both before anything
applies.

Uses: [`Change`](https://uitive.dev/docs/api/core#change), [`ClaimedEvidence`](https://uitive.dev/docs/api/core#claimedevidence).

| Property | Type | Description |
| - | - | - |
| `change` | `Change` | What it would change. |
| `evidence` | `readonly ClaimedEvidence[]` | What it claims to rest on; policy replaces the figures with the true ones. |
| `note?` | `string` | A short plain-text note, shown beneath the deterministic reason. |
| `scope?` | `'explicit' \| 'goal'` | For commands: `explicit` when the user named the target, `goal` when it serves their goal. |

### RemotePlannerOptions

Where `remotePlanner` sends requests, and what answers when the server can't.

Uses: [`FetchLike`](https://uitive.dev/docs/api/core#fetchlike), [`Planner`](https://uitive.dev/docs/api/core#planner).

| Property | Type | Default | Description |
| - | - | - | - |
| `url` | `string` | | The handler's base URL; requests go to `<url>/plan` and `<url>/command`. |
| `fallback?` | `Planner` | | Answers when the server can't. |
| `fetch?` | `FetchLike` | `globalThis.fetch` | The `fetch` it calls. |
| `timeoutMs?` | `number` | 60000 for plans, 20000 for commands | How long to wait for the server before the fallback answers. While progress streams, each line from the server starts the wait again, so a long redesign isn't cut short. |
| `headers?` | `Record<string, string>` | | Headers sent with every request, such as one the server's `authorize` reads. |

### StateView

The current interface, as a planner sees it: IDs only.

```ts
interface StateView {
  lists: readonly {
    surface: string;
    context?: string;
    visible: readonly string[];
    pinned: readonly string[];
  }[];
  choices: Readonly<Record<string, string>>;
  collections: Readonly<Record<string, readonly string[]>>;
  pages: readonly {
    surface: string;
    context?: string;
    value: AnyPage;
  }[];
  userPages: readonly {
    slug: string;
    title: string;
  }[];
  userPage?: {
    slug: string;
    value: AnyPage;
  };
  user: readonly string[];
  cooldowns: readonly string[];
  blocked: readonly string[];
  frozen: boolean;
  recent: readonly {
    key: string;
    outcome: 'kept' | 'reverted';
  }[];
}
```

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage).

| Property | Description |
| - | - |
| `lists` | Each list's visible and pinned items, per context value in view. |
| `choices` | Each choice's value. |
| `collections` | Each collection's item titles, as the person sees them. |
| `pages` | The pages in view now, as they are. |
| `userPages` | The pages the user made. |
| `userPage?` | The user's own page in view, if any. |
| `user` | Operation keys the user decided themselves; planners leave these alone. |
| `cooldowns` | Operation keys cooling down after a revert. |
| `blocked` | Operation keys reverted twice, never proposed again. |
| `frozen` | Whether the person froze planned changes. |
| `recent` | How the user answered recent changes. |

## Definitions and policy

Source: [`definition.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/definition.ts), [`explain.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/explain.ts), [`limits.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/limits.ts), [`policy.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/policy.ts), [`stabilizer.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/stabilizer.ts)

### canonical

Resolves every ID in a change to the contract's canonical spelling.

```ts
function canonical(change: Change, contract: AnyContract): Change;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Change`](https://uitive.dev/docs/api/core#change).

### check

Checks operations in order, each against the definition it is given: callers that apply one
before checking the next pass the definition as it then is.

```ts
function check(operations: readonly Operation[], context: PolicyContext): CheckResult;
```

Uses: [`CheckResult`](https://uitive.dev/docs/api/core#checkresult), [`Operation`](https://uitive.dev/docs/api/core#operation), [`PolicyContext`](https://uitive.dev/docs/api/core#policycontext).

### checkPageValue

Validates a whole page against its blocks, regions, limits and the application's rules.

```ts
function checkPageValue(
  contract: AnyContract,
  spec: AnyPageSpec,
  value: unknown,
  context?: string,
  planned?: boolean,
): AnyPage;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`AnyPageSpec`](https://uitive.dev/docs/api/core#anypagespec).

### DEFAULT_STABILIZER

The stabilizer's defaults: two changes per safe moment, three sessions of dwell, five of cooldown
and expiry.

```ts
const DEFAULT_STABILIZER: StabilizerOptions;
```

Uses: [`StabilizerOptions`](https://uitive.dev/docs/api/core#stabilizeroptions).

### describe

Explains an operation in plain words: what changed and where, who proposed it, and on what
evidence.

```ts
function describe(operation: Operation, contract: AnyContract): Explanation;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Explanation`](https://uitive.dev/docs/api/core#explanation), [`Operation`](https://uitive.dev/docs/api/core#operation).

### emptyDefinition

A definition with no changes yet: the application as shipped.

```ts
function emptyDefinition(contract: AnyContract): Definition;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Definition`](https://uitive.dev/docs/api/core#definition).

### EVERY

Pages keyed by context can be redesigned for one value, or for every value at once.

```ts
const EVERY = '*';
```

### isApplied

Whether an operation counts toward the interface: active, or kept by the person.

```ts
function isApplied(operation: AppliedOperation): boolean;
```

Uses: [`AppliedOperation`](https://uitive.dev/docs/api/core#appliedoperation).

### MAX_USER_PAGES

Most pages one person can make.

```ts
const MAX_USER_PAGES = 20;
```

### METRICS

Every usage statistic an operation may cite as evidence.

```ts
const METRICS: readonly Metric[];
```

Uses: [`Metric`](https://uitive.dev/docs/api/core#metric).

### migrateDefinition

Brings a stored definition up to date: version 1 kept pages as sections of blocks, which
convert mechanically to flat elements.

```ts
function migrateDefinition(
  definition: Omit<Definition, 'schemaVersion'> & {
    schemaVersion: number;
  },
): Definition;
```

Uses: [`Definition`](https://uitive.dev/docs/api/core#definition).

### MIN_IDLE

Sessions an item must sit unused before usage alone justifies moving it to overflow.

```ts
const MIN_IDLE = 3;
```

### NOTE_LENGTH

Longest model note shown; notes with digits are dropped, since numbers come from the summary.

```ts
const NOTE_LENGTH = 140;
```

### operationKey

Identifies what an operation does, regardless of when or by whom: for cooldowns and repeats.

```ts
function operationKey(change: Change): string;
```

Uses: [`Change`](https://uitive.dev/docs/api/core#change).

### redesigned

Whether a page has a redesign of its own, for this context value or for every value.

```ts
function redesigned(definition: Definition, surface: string, context: string | undefined): boolean;
```

Uses: [`Definition`](https://uitive.dev/docs/api/core#definition).

### resolveChoice

A choice's value after a definition: the last applied choice, or its default.

```ts
function resolveChoice(
  contract: AnyContract,
  definition: Definition | undefined,
  surface: string,
): string;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Definition`](https://uitive.dev/docs/api/core#definition).

### resolveCollection

A collection after a definition: accepted items and waiting suggestions.

```ts
function resolveCollection(
  contract: AnyContract,
  definition: Definition | undefined,
  surface: string,
): CollectionValue;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`CollectionValue`](https://uitive.dev/docs/api/core#collectionvalue), [`Definition`](https://uitive.dev/docs/api/core#definition).

### resolveList

Folds a definition over a list. `since` marks items moved by operations applied in or after
that session, for "moved" markers.

```ts
function resolveList(
  contract: AnyContract,
  definition: Definition | undefined,
  surface: string,
  context?: string,
  since?: number,
): ListState;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Definition`](https://uitive.dev/docs/api/core#definition), [`ListState`](https://uitive.dev/docs/api/core#liststate).

### resolvePage

The page a definition yields: a redesign for this context value, else one for every value,
else the standard page. A suggested redesign can be previewed without applying it.

```ts
function resolvePage(
  contract: AnyContract,
  definition: Definition | undefined,
  surface: string,
  context?: string,
  preview?: string,
): AnyPage;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`AnyPage`](https://uitive.dev/docs/api/core#anypage), [`Definition`](https://uitive.dev/docs/api/core#definition).

### resolveUserPages

The user's own pages, in the order they made them.

```ts
function resolveUserPages(definition: Definition | undefined): UserPage[];
```

Uses: [`Definition`](https://uitive.dev/docs/api/core#definition), [`UserPage`](https://uitive.dev/docs/api/core#userpage).

### SLUG_PATTERN

User page slugs: short, lowercase, URL-safe.

```ts
const SLUG_PATTERN: RegExp = /^[a-z0-9][a-z0-9-]{0,39}$/;
```

### TEXT_LENGTH

Longest string anywhere in a block's props or a collection item.

```ts
const TEXT_LENGTH = 500;
```

### TITLE_LENGTH

Longest title a section, tab, label or collection item may have.

```ts
const TITLE_LENGTH = 80;
```

### USER_PAGES

User pages share this reserved surface name: they belong to no surface the application declares.

```ts
const USER_PAGES = 'userPages';
```

### validateOutput

The half of policy that needs no user state: contract names, what planners may do, page and
query rules, and item schemas. The server runs it to give the model one chance to repair its
plan; the client still runs all of policy.

```ts
function validateOutput(
  contract: AnyContract,
  operations: readonly ProposedOperation[],
): {
  accepted: ProposedOperation[];
  rejected: OutputRejection[];
};
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`OutputRejection`](https://uitive.dev/docs/api/core#outputrejection), [`ProposedOperation`](https://uitive.dev/docs/api/core#proposedoperation).

### AppliedOperation

An operation in a person's definition, with its status: active, kept, reverted, suggested or
dismissed.

Uses: [`Status`](https://uitive.dev/docs/api/core#status).

| Property | Type | Description |
| - | - | - |
| `status` | `Status` | Whether it is active, kept, reverted, suggested or dismissed. |
| `session` | `number` | The session it was applied in. |
| `adaptation` | `string` | The adaptation that applied it. |
| `id` | `string` | Its ID, for revert, keep and explanations. |
| `change` | `Change` | What it changes. |
| `origin` | `Origin` | Who proposed it: learning, the model, or the person. |
| `layer` | `'model' \| 'user'` | User-layer operations outrank model-layer ones. |
| `evidence` | `readonly Evidence[]` | What it rests on: usage figures, or the person's words. |
| `note?` | `string` | A short plain-text note from the model, shown beneath the deterministic reason. |
| `basedOn` | `{ version: number; summary: string; session: number }` | What the operation was planned against, for rebasing and expiry. |

### Change

One change to one surface, by its kind.

```ts
type Change = ListChange | ChoiceChange | CollectionChange | PageChange | UserPageChange;
```

Uses: [`ChoiceChange`](https://uitive.dev/docs/api/core#choicechange), [`CollectionChange`](https://uitive.dev/docs/api/core#collectionchange), [`ListChange`](https://uitive.dev/docs/api/core#listchange), [`PageChange`](https://uitive.dev/docs/api/core#pagechange), [`UserPageChange`](https://uitive.dev/docs/api/core#userpagechange).

### CheckResult

What policy accepted, canonical, and what it refused, with reasons.

Uses: [`Operation`](https://uitive.dev/docs/api/core#operation), [`Rejection`](https://uitive.dev/docs/api/core#rejection).

| Property | Type | Description |
| - | - | - |
| `accepted` | `Operation[]` | The operations that passed, in canonical form. |
| `rejected` | `Rejection[]` | The operations refused, with reasons. |

### ChoiceChange

A choice set to one of its values.

| Property | Type | Description |
| - | - | - |
| `kind` | `'choice'` | Says the change is to a choice. |
| `surface` | `string` | The choice. |
| `op` | `'set'` | Choices are only ever set. |
| `value` | `string` | The value chosen. |

### CollectionChange

An item added to, changed in or removed from a collection.

| Property | Type | Description |
| - | - | - |
| `kind` | `'collection'` | Says the change is to a collection. |
| `surface` | `string` | The collection. |
| `op` | `'add' \| 'update' \| 'remove'` | Whether the item is added, changed or removed. |
| `item` | `string` | The item's ID. |
| `value?` | `unknown` | For `add` and `update`: the item itself. |

### Definition

One user's interface: the standard layout plus every operation applied to it.

Uses: [`AppliedOperation`](https://uitive.dev/docs/api/core#appliedoperation).

| Property | Type | Description |
| - | - | - |
| `schemaVersion` | `2` | 2 since pages became flat elements; version 1 definitions are migrated on load. |
| `contract` | `string` | The hash of the contract it was made against. |
| `version` | `number` | Increments on every change. |
| `operations` | `readonly AppliedOperation[]` | Every operation applied, in order. |
| `cooldowns` | `readonly { key: string; until: number }[]` | Operation keys a planner may not propose until a session. |
| `blocked` | `readonly string[]` | Operation keys reverted twice: never proposed again. |
| `frozen` | `boolean` | When frozen, planners change nothing. |
| `goal?` | `string` | The goal the user stated in their own words. |

### Evidence

Why an operation is justified: a usage statistic taken from the summary, or the user's words.

```ts
type Evidence =
  | {
      action: string;
      metric: Metric;
      value: number;
      window?: number;
    }
  | {
      intent: string;
    };
```

Uses: [`Metric`](https://uitive.dev/docs/api/core#metric).

### Explanation

What a person reads about an operation: what changed and why, with true numbers only.

| Property | Type | Description |
| - | - | - |
| `title` | `string` | What changed, such as "Table added to Toolbar". |
| `reason` | `string` | Why, with the evidence's true numbers. |
| `note?` | `string` | A short note from the model, if it wrote one. |

### ListChange

A change to a list: an action promoted or demoted by learning, or moved, pinned, unpinned, hidden
or restored by the person.

| Property | Type | Description |
| - | - | - |
| `kind` | `'list'` | Says the change is to a list. |
| `surface` | `string` | The list. |
| `context?` | `string` | The context value it applies to, for lists keyed by context. |
| `op` | `'promote' \| 'demote' \| 'move' \| 'pin' \| 'unpin' \| 'hide' \| 'restore'` | What happens to the item: learning promotes and demotes; the person moves, pins, unpins, hides and restores. |
| `target` | `string` | The action. |
| `index?` | `number` | For `move`: the position among visible items. |
| `evict?` | `string` | For operations that add a visible item: the item that made room, fixed when applied. |

### ListState

A list after folding a definition over it: its value, and what is visible, pinned, hidden and
standard.

Uses: [`ListValue`](https://uitive.dev/docs/api/core#listvalue).

| Property | Type | Description |
| - | - | - |
| `value` | `ListValue` | The list as the person has it. |
| `visible` | `Set<string>` | The items that show. |
| `pinned` | `Set<string>` | The items the person pinned. |
| `hidden` | `Set<string>` | Items the user hid, until they restore or pin them. |
| `standard` | `Set<string>` | The items that show in the standard layout. |

### Metric

Usage statistics an operation may cite.

```ts
type Metric = 'uses' | 'activeSessions' | 'viaOverflow' | 'viaPalette' | 'idleSessions';
```

### Operation

A change with its provenance: who proposed it, on what evidence, against which version, and on
which layer.

Uses: [`Change`](https://uitive.dev/docs/api/core#change), [`Evidence`](https://uitive.dev/docs/api/core#evidence), [`Origin`](https://uitive.dev/docs/api/core#origin).

| Property | Type | Description |
| - | - | - |
| `id` | `string` | Its ID, for revert, keep and explanations. |
| `change` | `Change` | What it changes. |
| `origin` | `Origin` | Who proposed it: learning, the model, or the person. |
| `layer` | `'model' \| 'user'` | User-layer operations outrank model-layer ones. |
| `evidence` | `readonly Evidence[]` | What it rests on: usage figures, or the person's words. |
| `note?` | `string` | A short plain-text note from the model, shown beneath the deterministic reason. |
| `basedOn` | `{ version: number; summary: string; session: number }` | What the operation was planned against, for rebasing and expiry. |

### Origin

Who proposed an operation: the deterministic planner, a model, or the person.

```ts
type Origin = 'heuristic' | 'model' | 'user';
```

### OutputRejection

A proposed operation the static half of policy turned down, and why.

Uses: [`ProposedOperation`](https://uitive.dev/docs/api/core#proposedoperation), [`Rule`](https://uitive.dev/docs/api/core#rule).

| Property | Type | Description |
| - | - | - |
| `operation` | `ProposedOperation` | The proposed operation refused. |
| `rule` | `Rule` | The rule it broke. |
| `message` | `string` | Why, for the model to repair. |

### PageChange

A page redesigned outright, or put back to standard.

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage).

| Property | Type | Description |
| - | - | - |
| `kind` | `'page'` | Says the change is to a page. |
| `surface` | `string` | The page. |
| `context?` | `string` | A context value, or `*` for every value. |
| `op` | `'set' \| 'reset'` | Redesigned outright, or put back to standard. |
| `value?` | `AnyPage` | For `set`: the whole new page. |

### Pending

A checked operation waiting for a safe moment.

| Property | Type | Description |
| - | - | - |
| `key` | `string` | What it does, regardless of when or by whom, for cooldowns and repeats. |
| `strength` | `number` | How strong its evidence is; past the margin, a model's change needs no second plan. |
| `held` | `boolean` | Held until a second plan proposes it again, unless its strength clears the margin. |
| `id` | `string` | Its ID, for revert, keep and explanations. |
| `change` | `Change` | What it changes. |
| `origin` | `Origin` | Who proposed it: learning, the model, or the person. |
| `layer` | `'model' \| 'user'` | User-layer operations outrank model-layer ones. |
| `evidence` | `readonly Evidence[]` | What it rests on: usage figures, or the person's words. |
| `note?` | `string` | A short plain-text note from the model, shown beneath the deterministic reason. |
| `basedOn` | `{ version: number; summary: string; session: number }` | What the operation was planned against, for rebasing and expiry. |

### PolicyContext

What policy checks operations against: the contract, the person's definition, usage, the session
and any stated intent.

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Definition`](https://uitive.dev/docs/api/core#definition), [`UsageSummary`](https://uitive.dev/docs/api/core#usagesummary).

| Property | Type | Default | Description |
| - | - | - | - |
| `contract` | `AnyContract` | | The contract. |
| `definition` | `Definition` | | The person's definition. |
| `summary` | `UsageSummary` | | Usage, as numbers. |
| `session` | `number` | | The current session. |
| `intent?` | `string` | | The user's own words behind this request: a command or their stated goal. |
| `interpreted?` | `boolean` | `false` | Whether a model read those words. What it says the person named outright joins their own layer, but it never deletes one of their pages and never brings back a change they blocked. |

### Rejection

An operation policy refused, the rule it broke, and why, in words people read.

Uses: [`Operation`](https://uitive.dev/docs/api/core#operation), [`Rule`](https://uitive.dev/docs/api/core#rule).

| Property | Type | Description |
| - | - | - |
| `operation` | `Operation` | The operation refused. |
| `rule` | `Rule` | The rule it broke. |
| `message` | `string` | Why, in words people read. |

### Rule

The rule an operation broke, named in its rejection: such as `required` for hiding a required
item, or `capacity` for a full list.

```ts
type Rule =
  | 'unknown'
  | 'kind'
  | 'required'
  | 'precedence'
  | 'frozen'
  | 'cooldown'
  | 'blocked'
  | 'evidence'
  | 'validator'
  | 'noop'
  | 'capacity';
```

### StabilizerOptions

How cautiously planned changes apply, so the interface never moves while someone works and
settles rather than churns.

| Property | Type | Default | Description |
| - | - | - | - |
| `budget` | `number` | `2` | Structural changes applied at one safe moment. |
| `dwell` | `number` | `3` | Sessions an item keeps its place after it moves. |
| `cooldown` | `number` | `5` | Sessions a reverted change waits before it may return. |
| `expiry` | `number` | `5` | Sessions a pending change stays valid. |
| `margin` | `number` | `1` | Strength at which a model change applies without waiting for a second plan. |

### Status

`suggested` operations add collection items, or redesign pages, for the user to accept; `kept`
ones were confirmed by the user and join the user layer.

```ts
type Status = 'active' | 'kept' | 'reverted' | 'suggested' | 'dismissed';
```

### UserPage

A page the user made.

Uses: [`AnyPage`](https://uitive.dev/docs/api/core#anypage).

| Property | Type | Description |
| - | - | - |
| `slug` | `string` | Its slug: the page lives at `/uitive/<slug>`. |
| `title` | `string` | Its title, as the person named it. |
| `value` | `AnyPage` | The page. |
| `operation` | `string` | The operation that created it. |

### UserPageChange

A page the user made themselves, served at `/uitive/<slug>`.

Uses: [`USER_PAGES`](https://uitive.dev/docs/api/core#user_pages), [`AnyPage`](https://uitive.dev/docs/api/core#anypage).

| Property | Type | Description |
| - | - | - |
| `kind` | `'userPage'` | Says the change is to one of the person's own pages. |
| `surface` | `typeof USER_PAGES` | Always `userPages`. |
| `op` | `'create' \| 'rename' \| 'set' \| 'delete'` | Whether the page is made, renamed, redesigned or deleted. |
| `slug` | `string` | The page's slug, in its address. |
| `title?` | `string` | For `create` and `rename`. |
| `value?` | `AnyPage` | For `create` and `set`: the whole page. |

## Usage and simulation

Source: [`simulate.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/simulate.ts), [`usage.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/usage.ts)

### DECAY

Each session back weighs this much less.

```ts
const DECAY = 0.85;
```

### random

A seeded pseudo-random generator (mulberry32), so a simulation repeats exactly.

```ts
function random(seed: number): () => number;
```

### rank

Every action ranked for a palette: decayed ranking score, then contract order.

```ts
function rank(contract: AnyContract, events: readonly UsageEvent[], session: number): string[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`UsageEvent`](https://uitive.dev/docs/api/core#usageevent).

### simulate

Drives a client through sessions as a persona would: each session starts (applying pending
changes at the safe moment), the persona works, and a plan is made at the end.

```ts
function simulate<C extends AnyContract>(
  client: Uitive<C>,
  persona: Persona,
  options: {
    sessions: number;
    seed: number;
    plan?: boolean;
  },
): Promise<SessionReport[]>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Persona`](https://uitive.dev/docs/api/core#persona), [`SessionReport`](https://uitive.dev/docs/api/core#sessionreport), [`Uitive`](https://uitive.dev/docs/api/core#uitive).

### summarize

Summarizes usage per action and surface over recent sessions, with older sessions weighing less.
`from` is the first session whose events are all kept: the window never reaches further back,
so figures cover only sessions whose use is known in full.

```ts
function summarize(
  contract: AnyContract,
  definition: Definition,
  events: readonly UsageEvent[],
  sessions: readonly SessionRecord[],
  session: number,
  from?: number,
): UsageSummary;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Definition`](https://uitive.dev/docs/api/core#definition), [`SessionRecord`](https://uitive.dev/docs/api/core#sessionrecord), [`UsageEvent`](https://uitive.dev/docs/api/core#usageevent), [`UsageSummary`](https://uitive.dev/docs/api/core#usagesummary).

### VIAS

Every way an action may be reached.

```ts
const VIAS: readonly Via[];
```

Uses: [`Via`](https://uitive.dev/docs/api/core#via).

### visibleLists

The visible items of every list, for reports and assertions.

```ts
function visibleLists<C extends AnyContract>(client: Uitive<C>): Record<string, readonly string[]>;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Uitive`](https://uitive.dev/docs/api/core#uitive).

### WINDOW

Sessions the summary looks back over, including the current one.

```ts
const WINDOW = 10;
```

### Persona

A simulated user: how often they use each action, and how they reach it.

| Property | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | | Its name, as reports show it. |
| `description` | `string` | | Who it stands for. |
| `weights` | `Readonly<Record<string, number>>` | | Relative frequencies of the actions this persona uses. |
| `actions?` | `readonly [number, number]` | `[12, 24]` | Actions per session, inclusive. |
| `contexts?` | `(action: string, draw: () => number) => Record<string, string> \| undefined` | | Context values active for an action, such as the service a verb happens on. |
| `shift?` | `{ session: number; weights: Readonly<Record<string, number>> }` | | From this session on, these weights apply instead: a change of behavior. |
| `palette?` | `number` | `0.3` | How often an overflow item is reached through the palette rather than overflow. |

### SessionRecord

One session: when it started, and the context values it saw.

| Property | Type | Description |
| - | - | - |
| `index` | `number` | The session's number, counted from the first. |
| `startedAt` | `number` | When it started, in milliseconds. |
| `contexts` | `Record<string, string[]>` | Context values active during the session, by context name. |

### SessionReport

One simulated session: what each list showed at its start, and what changed then and after.

Uses: [`Adaptation`](https://uitive.dev/docs/api/core#adaptation).

| Property | Type | Description |
| - | - | - |
| `session` | `number` | The session's number. |
| `visible` | `Record<string, readonly string[]>` | Visible items of each list at the session's start, keyed `surface` or `surface\|context`. |
| `applied?` | `Adaptation` | The adaptation applied at the session's start, if any. |
| `planned?` | `Adaptation` | The plan made at the session's end, if any. |

### UsageEvent

One activation. Never text typed into the application, never page content.

Uses: [`Via`](https://uitive.dev/docs/api/core#via).

| Property | Type | Description |
| - | - | - |
| `action` | `string` | The action used. |
| `via` | `Via` | How it was reached. |
| `session` | `number` | The session it happened in. |
| `surface?` | `string` | The surface it was reached on, when known: its use then counts there alone. |
| `element?` | `string` | The page element it came from, for actions run from generated pages. |
| `contexts?` | `Record<string, string>` | Context values active when it happened, by context name. |
| `typed?` | `boolean` | For palette picks: whether the user typed a search first. |

### UsageRow

One action's usage on one surface, as planners see it: uses, sessions, and how it was reached.

| Property | Type | Description |
| - | - | - |
| `surface` | `string` | The surface. |
| `context?` | `string` | The context value, for surfaces keyed by context. |
| `action` | `string` | The action. |
| `place` | `'visible' \| 'overflow'` | Where it is now. |
| `pinned` | `boolean` | Whether the person pinned it. |
| `uses` | `number` | Uses within the window. |
| `activeSessions` | `number` | Sessions within the window with at least one use. |
| `viaOverflow` | `number` | Uses reached from overflow, within the window. |
| `viaPalette` | `number` | Uses reached by searching, within the window. |
| `viaSuggested` | `number` | Uses reached through a suggestion, within the window. |
| `idleSessions` | `number` | Consecutive recent sessions it was visible and unused, while its surface was in use. |
| `placement` | `number` | Decayed placement score, with overflow use weighing most: decides who deserves a place. |
| `activity` | `number` | Decayed use with every path weighing the same: compares items for a swap. Comparing placement instead would oscillate: an item used from overflow always outscores its equal. |
| `ranking` | `number` | Decayed ranking score, rounded to hundredths. |

### UsageSummary

The deterministic statistics a planner sees: the only usage that leaves the device.

Uses: [`UsageRow`](https://uitive.dev/docs/api/core#usagerow).

| Property | Type | Description |
| - | - | - |
| `session` | `number` | The current session. |
| `window` | `number` | Sessions the window covers. |
| `rows` | `readonly UsageRow[]` | One row per action and surface. |
| `hash` | `string` | Changes when the leading items of any surface change. |

### Via

The path a user took to an action.

```ts
type Via = 'region' | 'overflow' | 'suggested' | 'palette' | 'shortcut' | 'command';
```

## Advanced

Used by Uitive's own packages and by tools built on them. These may change between minor versions.

Source: [`hash.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/hash.ts), [`retrieval.ts`](https://github.com/plurid/uitive/blob/3cbf3ac33467567dce35b83159d6d3b290f648d3/packages/core/src/retrieval.ts)

### actionsInScope

The actions a scoped request may name: every list's items, and the subset's actions.

```ts
function actionsInScope(contract: AnyContract, subset: Subset): string[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Subset`](https://uitive.dev/docs/api/core#subset).

### areasOf

The areas of a contract, one per source.

```ts
function areasOf(contract: AnyContract): Area[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Area`](https://uitive.dev/docs/api/core#area).

### EXTRA_AREAS

Areas added by relevance, beyond those on screen.

```ts
const EXTRA_AREAS = 2;
```

### hash

A short, deterministic, non-cryptographic hash (cyrb53) of a value's stable serialization.

```ts
function hash(value: unknown): string;
```

### MAX_ACTIONS

Actions in a subset at most, besides those lists hold.

```ts
const MAX_ACTIONS = 24;
```

### MAX_SOURCES

Sources in a subset at most.

```ts
const MAX_SOURCES = 8;
```

### rankAreas

Areas ranked by BM25 against some words, best first; areas with no match are left out.

```ts
function rankAreas(
  areas: readonly Area[],
  text: string,
): {
  source: string;
  score: number;
}[];
```

Uses: [`Area`](https://uitive.dev/docs/api/core#area).

### selectSubset

The part of a contract a request may use: everything, when it is small; otherwise the areas
on screen plus the most relevant few. Few distinct subsets keep compiled grammars and prompt
caches warm.

```ts
function selectSubset(contract: AnyContract, options?: SubsetOptions): Subset;
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`Subset`](https://uitive.dev/docs/api/core#subset), [`SubsetOptions`](https://uitive.dev/docs/api/core#subsetoptions).

### sourcesInView

The sources a request's screen shows: its pages' queries and the row its route is about.

```ts
function sourcesInView(contract: AnyContract, request: PlanRequest): string[];
```

Uses: [`AnyContract`](https://uitive.dev/docs/api/core#anycontract), [`PlanRequest`](https://uitive.dev/docs/api/core#planrequest).

### stableStringify

JSON with object keys sorted, so equal values always serialize to the same bytes. Values with
`toJSON`, such as dates, serialize as it says; other objects must be plain, and a value that
contains itself is refused.

```ts
function stableStringify(value: unknown): string;
```

### terms

Lowercase words, split at punctuation, snake_case and camelCase, stemmed lightly.

```ts
function terms(text: string): string[];
```

### Area

One source with everything that belongs to it: what a planner is shown together.

| Property | Type | Description |
| - | - | - |
| `source` | `string` | The source at its center. |
| `actions` | `readonly string[]` | Actions that act on its rows, or change it. |
| `routes` | `readonly string[]` | Routes that show its rows. |
| `terms` | `readonly string[]` | The words it is found by. |

### Subset

What a request may use: its sources, and the actions and routes that come with them.

| Property | Type | Description |
| - | - | - |
| `sources` | `readonly string[]` | The sources a request plans over. |
| `actions` | `readonly string[]` | Its areas' actions, and others its words name: at most `MAX_ACTIONS`. |
| `routes` | `readonly string[]` | The routes that show them. |

### SubsetOptions

How to scope a large contract for one request: what was said, what is on screen, and how much to
keep.

| Property | Type | Default | Description |
| - | - | - | - |
| `text?` | `string` | | What the person said, and their goal. |
| `inView?` | `readonly string[]` | | Sources on screen now, always included. |
| `maxSources?` | `number` | `8` | Sources the subset may hold. |
| `extra?` | `number` | `2` | Areas added by relevance beyond those on screen. |
