@plurid/uitive-core

On this page

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, Contracts, Data and actions, Pages.

Contracts

Source: contract.ts, ids.ts, 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.

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.

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.

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.

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, AnySourceSpec, Contract, ContractSpec, SurfaceSpec.

fieldsFromJson

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

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

Uses: 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, 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, 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.

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, 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, 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.

ActionJson

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

Uses: Effect, FieldsJson, Filter.

PropertyTypeDescription
labelstringShown to people and to the model.
descriptionstringWhat the action does.
group?stringThe action's group.
aliases?string[]Former IDs, so stored usage survives a rename.
params?FieldsJsonWhat a run takes.
effect?EffectWhat a run does to data.
confirm?stringFor 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, Filter.

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

PropertyTypeDefaultDescription
labelstringShown to people and to the model.
descriptionstringWhat the action does, written for people and models alike.
group?stringGroups related actions, for display and for the model.
aliases?readonly string[][]Former IDs of this action, so stored usage survives a rename.
params?PWhat a run takes: flat fields, like a source's row. A ref param makes it a row action.
effect?EffectWhat a run does. Without one, the action belongs to the interface only.
confirm?stringthe labelFor destructive actions: what the user types to confirm.
when?readonly Filter[]every rowFor 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.

PropertyTypeDescription
idAThe action's ID.
labelstringThe action's label.
descriptionstringWhat the action does.
group?stringThe action's group, when it has one.
pinnedbooleanThe user pinned it here.
movedbooleanIt 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, AnySourceSpec, Field, FieldPath, RegionSpec, ResolvedSource, RouteSpec, SurfaceSpec.

PropertyTypeDescription
idstringThe application's ID.
versionstringThe version the application gave, for changes the hash can't see.
descriptionstringWhat the application is, for the model.
actionsReadonly<Record<string, ActionSpec>>Every action, by ID.
contextsReadonly<Record<string, readonly string[]>>Every context, with its values.
sourcesReadonly<Record<string, AnySourceSpec>>Every source, by ID.
regionsReadonly<Record<string, RegionSpec>>Every region, by name.
routesReadonly<Record<string, RouteSpec>>Every route, by ID.
surfacesReadonly<Record<string, SurfaceSpec>>Every surface, by name.
hashstringChanges whenever anything a planner sees changes, standard pages included.
actionIdsreadonly string[]Every action ID, in declaration order.
sourceIdsreadonly string[]Every source ID, in declaration order.
routeIdsreadonly string[]Every route ID, in declaration order.
surfaceIdsreadonly string[]Every surface name, in declaration order.
action()(id: string) => string | undefinedThe action an ID or former ID names, compared case-insensitively.
surface()(name: string) => string | undefinedThe surface a name refers to, compared case-insensitively.
contextValue()(context: string, value: string) => string | undefinedThe 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 | undefinedA source with its fields described, by ID compared case-insensitively.
path()(name: string) => FieldPath | undefinedA 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 | undefinedThe route a name refers to, compared case-insensitively.

AnyPageSpec

Any page surface, with its blocks widened.

Uses: AnyPage, BlockSpec, GenericName, SectionsPage.

PropertyTypeDefaultDescription
kind'page'Says the surface is a page.
blocksReadonly<Record<string, BlockSpec>>The application's own blocks the page may use, besides sections, tabs and regions.
context?stringThe context that keys this page, such as service; it can be redesigned per value or for all.
entity?stringThe source whose rows this page is about, such as customers; $current names the row.
generic?boolean | readonly GenericName[]every one the contract can feedGeneric blocks the page offers.
standard()(context: string | undefined) => AnyPage | SectionsPageThe page before anyone changes it, for a context value when the page has a context.
maxElements?number40How many elements a page may hold.
maxDepth?number4How deeply a page's sections may nest.
maxQueries?number8Queries a page may run.
labelstringShown to people, such as "Toolbar".
descriptionstringWhat 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, PropsOf.

BlockSpec

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

Type parameters: P = unknown.

PropertyTypeDescription
labelstringShown to people, such as "Resource table".
descriptionstringWhat the block shows and how its props change it, for people and models alike.
propsz.ZodType<P>The schema of the block's props. Planners can only produce props it accepts.
validate?()(props: P, context: string | undefined) => string | undefinedApplication 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.

PropertyTypeDescription
kind'choice'Says the surface is a choice.
valuesreadonly V[]Every value, in the order people see them.
defaultVThe value before anyone chooses one.
labelstringShown to people, such as "Toolbar".
descriptionstringWhat 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.

PropertyTypeDescription
idstringThe item's ID.
titlestringIts title, from the collection's title.
valueTThe item itself.
operationstringThe 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.

PropertyTypeDescription
kind'collection'Says the surface is a collection.
itemz.ZodType<T>The schema of one item. Planners can only produce items it accepts.
maxnumberAt most this many accepted items.
title()(item: T) => stringA short title for an item, shown to people.
validate?()(item: T) => string | undefinedApplication rules beyond the schema; returns why an item is invalid.
labelstringShown to people, such as "Toolbar".
descriptionstringWhat 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.

Type parameters: T = unknown.

PropertyTypeDescription
itemsreadonly CollectionEntry<T>[]Items the person accepted or added.
suggestionsreadonly 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.

Contract

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

Uses: ActionSpec, AnySourceSpec, 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>.

PropertyTypeDescription
actionsAEvery action, by ID.
contextsCEvery context, with its values.
sourcesDEvery source, by ID.
surfacesSEvery surface, by name.
actionIdsreadonly Extract<keyof A, string>[]Every action ID, in declaration order.
sourceIdsreadonly Extract<keyof D, string>[]Every source ID, in declaration order.
surfaceIdsreadonly Extract<keyof S, string>[]Every surface name, in declaration order.
action()(id: string) => Extract<keyof A, string> | undefinedThe action an ID or former ID names, compared case-insensitively.
surface()(name: string) => Extract<keyof S, string> | undefinedThe surface a name refers to, compared case-insensitively.
idstringThe application's ID.
versionstringThe version the application gave, for changes the hash can't see.
descriptionstringWhat the application is, for the model.
regionsReadonly<Record<string, RegionSpec>>Every region, by name.
routesReadonly<Record<string, RouteSpec>>Every route, by ID.
hashstringChanges whenever anything a planner sees changes, standard pages included.
routeIdsreadonly string[]Every route ID, in declaration order.
contextValue()(context: string, value: string) => string | undefinedThe 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 | undefinedA source with its fields described, by ID compared case-insensitively.
path()(name: string) => FieldPath | undefinedA 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 | undefinedThe route a name refers to, compared case-insensitively.

ContractJson

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

Uses: CONTRACT_FORMAT, FORMAT_VERSION, ActionJson, RegionSpec, RouteSpec, SourceJson, SurfaceJson.

PropertyTypeDescription
formattypeof CONTRACT_FORMATSays what the document is.
formatVersiontypeof FORMAT_VERSIONThe JSON format's version.
idstringThe application's ID.
versionstringThe version the application gave.
descriptionstringWhat the application is, for the model.
actionsRecord<string, ActionJson>Every action, by ID.
contextsRecord<string, string[]>Every context, with its values.
sourcesRecord<string, SourceJson>Every source, by ID.
regionsRecord<string, RegionSpec>Every region, by name.
routesRecord<string, RouteSpec>Every route, by ID.
surfacesRecord<string, SurfaceJson>Every surface, by name, with pages' standards written out.
hashstringThe 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, AnySourceSpec, RegionSpec, RouteSpec, 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>.

PropertyTypeDefaultDescription
idstringIdentifies the application, such as cloud-console.
version?string'1'Bump when behavior that can't be hashed changes, such as a validator.
descriptionstringWhat the application is, written for the model.
actionsAWhat 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.
surfacesSThe 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.

PropertyTypeDescription
type'string' | 'number' | 'boolean'The JSON type the value is stored as.
enum?string[]For enums: every value.
description?stringWhat the field holds.
x-uitiveFieldMetaWhat 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.

PropertyTypeDescription
type'object'Always an object.
propertiesRecord<string, FieldJson>Each field, by name.
requiredstring[]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.

PropertyTypeDefaultDescription
kind'list'Says the surface is a list.
itemsreadonly A[]Every action the list can show, in standard order.
capacitynumberHow many items show before the rest move to overflow.
required?readonly A[][]Items that never move to overflow.
reorderable?booleanfalseWhether items may leave the standard order.
context?stringThe context that keys this list, such as tool; each of its values adapts separately.
available?()(value: string) => readonly A[]every itemThe items available for one context value.
labelstringShown to people, such as "Toolbar".
descriptionstringWhat 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.

Type parameters: A extends string = string.

PropertyTypeDescription
visiblereadonly ActionView<A>[]The actions that show, in order.
overflowreadonly 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, BlockSpec, Layout.

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

PropertyTypeDescription
titlestringMay be empty.
layoutLayoutHow its blocks are laid out: a stack, a grid or columns.
blocksreadonly 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, BlockSpec, PageValue, SectionPage.

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

PropertyTypeDefaultDescription
blocksBThe application's own blocks the page may use, besides sections, tabs and regions.
standard()(context: string | undefined) => PageValue<B> | SectionPage<B> | AnyPageTyped sections, typed elements, or any page (such as one built with ui): all are validated.
kind'page'Says the surface is a page.
context?stringThe context that keys this page, such as service; it can be redesigned per value or for all.
entity?stringThe source whose rows this page is about, such as customers; $current names the row.
generic?boolean | readonly GenericName[]every one the contract can feedGeneric blocks the page offers.
maxElements?number40How many elements a page may hold.
maxDepth?number4How deeply a page's sections may nest.
maxQueries?number8Queries a page may run.
labelstringShown to people, such as "Toolbar".
descriptionstringWhat 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.

RegionSpec

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

PropertyTypeDescription
labelstringShown to people and to the model, such as "Payments table".
descriptionstringWhat it shows, for people and models alike.
entity?stringThe 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, 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>
  >;
}
PropertyDescription
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, PageSection.

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

PropertyTypeDescription
sectionsreadonly 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.

SourceJson

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

Uses: Capabilities, FieldsJson.

PropertyTypeDescription
labelstringWhat people call it.
descriptionstringWhat its rows are.
keywordsstring[]Other words people use for it.
rowFieldsJsonThe fields of its rows.
keystringThe field that identifies a row.
titlestringThe field that names a row.
summarystring[]The fields that sum a row up.
capabilitiesRequired<Capabilities>What the binding does by itself.
scannumberMost rows fetched to answer one query on the client.
maxLimitnumberMost rows one query may ask for.
ttlnumberSeconds 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.

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.

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, ChoiceSpec, CollectionSpec, 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, AnyPageSpec, ChoiceSpec, CollectionSpec, CollectionValue, ListSpec, ListValue, PageSpec, 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, SurfaceIdOf, SurfaceValue.

Sources and fields

Source: field.ts, source.ts

ARITY

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

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

Uses: 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.

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, MoneyOptions.

MemberDescription
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, 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.

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, 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, 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.

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.

PropertyTypeDefaultDescription
labelstringShown to people and to the model, such as "Payments".
descriptionstringWhat the rows are, written for people and models alike.
keywords?readonly string[][]Other words people use for this data, for finding it.
rowz.ZodObjectOne row: flat fields only.
keystringThe field that identifies a row.
title?stringthe keyThe field that names a row.
summary?readonly string[][title]Fields that sum up a row, shown in compact views and reachable through relations.
capabilities?Capabilitiesnone of themWhat the binding does itself: filters, sorts, search and paging.
scan?number500Most rows fetched to answer one query on the client.
maxLimit?number100Most rows one query may ask for.
ttl?number30Seconds 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.

Type parameters: F extends string = string.

PropertyTypeDefaultDescription
filter?Partial<Record<F, readonly Op[]>>{}Filters the binding applies, by field.
sort?readonly F[][]Fields the binding sorts by.
search?booleanfalseWhether 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, TimeUnit.

PropertyTypeDescription
namestringThe field's name in its source's rows.
typeFieldTypeWhat the value means, which decides how it shows and filters.
labelstringWhat people call it.
descriptionstringWhat it holds, for people and models.
nullablebooleanWhether rows may lack a value.
valuesreadonly string[]For enums: every value.
source?stringFor refs: the source whose key the field holds.
currency?stringFor money: the field holding each row's currency.
code?stringFor money: one currency for every row.
minorbooleanFor 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?TimeUnitFor time: how instants are stored.

FieldMeta

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

Uses: FieldType, TimeUnit.

PropertyTypeDefaultDescription
typeFieldTypeWhat the value means, which decides how it shows and filters.
label?stringthe field's name, humanizedShown to people.
currency?stringFor money: the field holding each row's ISO 4217 currency code.
code?stringFor money: one ISO 4217 currency for every row.
minor?booleanfalseFor 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?TimeUnitFor time: how instants are stored.
source?stringFor 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.

PropertyTypeDefaultDescription
label?stringthe field's name, humanizedShown to people, such as a column's header.
description?stringWhat 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.

PropertyTypeDescription
namestringThe qualified name, in canonical spelling.
sourcestringThe source whose rows the query reads.
via?stringThe ref field followed, for a hop.
target?stringThe source a hop reaches.
fieldFieldThe 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.

MoneyOptions

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

PropertyTypeDefaultDescription
currency?stringThe field holding each row's ISO 4217 currency code.
code?stringOne ISO 4217 currency for every row.
minor?booleanfalseWhether 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?stringthe field's name, humanizedShown to people, such as a column's header.
description?stringWhat 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.

ResolvedSource

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

Uses: Capabilities, Field.

PropertyTypeDescription
idstringThe source's ID.
labelstringWhat people call it.
descriptionstringWhat its rows are.
keywordsreadonly string[]Other words people use for it.
keystringThe field that identifies a row.
titlestringThe field that names a row.
summaryreadonly string[]The fields that sum a row up.
fieldsreadonly Field[]Every field, described.
capabilitiesRequired<Capabilities>What the binding does by itself, with nothing left out.
scannumberMost rows fetched to answer one query on the client.
maxLimitnumberMost rows one query may ask for.
ttlnumberSeconds a result stays fresh.

SourceSpec

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

Uses: Capabilities, FieldNameOf.

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

PropertyTypeDefaultDescription
labelstringShown to people and to the model, such as "Payments".
descriptionstringWhat the rows are, written for people and models alike.
keywords?readonly string[][]Other words people use for this data, for finding it.
rowROne row: flat fields only. Field helpers say what values mean, such as money in cents.
keyFieldNameOf<R>The field that identifies a row.
title?FieldNameOf<R>the keyThe 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 themWhat the binding does itself: filters, sorts, search and paging.
scan?number500Most rows fetched to answer one query on the client.
maxLimit?number100Most rows one query may ask for.
ttl?number30Seconds 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, data.ts, query.ts, 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.

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, QueryCheck, 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, DataClient, DataOptions, 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.

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.

isToken

Whether a value is a token.

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

Uses: 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.

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.

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, Field, Parsed.

partsIn

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

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

Uses: 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, Filter, Query, 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, Fetchers, Query, QueryResult, 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.

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.

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, Measure.

PropertyTypeDescription
measureMeasureWhat to compute: a count, a sum, an average, a minimum, a maximum or a distinct count.
ofstringThe field measured, or none to count rows.
bystringThe field rows group by, or none for one number.
splitstringA second grouping, for stacked charts, or none.
bucketBucketFor time groupings: the size of each group.

BindingContext

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

PropertyTypeDefaultDescription
me?stringThe 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?stringA 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.

Clock

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

PropertyTypeDefaultDescription
nownumberMilliseconds 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, DataScope, Filter, Query, QueryResult, Row.

PropertyTypeDescription
read()(query: Query, scope?: DataScope) => DataEntryThe entry for a query, fetching when there is none, or when it is stale.
peek()(query: Query, scope?: DataScope) => DataEntry | undefinedThe 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) => () => voidCalls the listener whenever an entry changes; returns its removal.
invalidate()(sources: readonly string[]) => voidMarks results that read these sources stale, so they fetch again when next read.
matches()(filters: readonly Filter[], row: Row, scope?: DataScope) => booleanWhether 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.

PropertyTypeDescription
status'loading' | 'ready' | 'error'Whether the result is loading, ready, or failed.
result?QueryResultThe result, once there is one; kept while a fresh one loads.
error?stringWhy it failed, in words people read.
stalebooleanThe 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.

PropertyTypeDefaultDescription
now?() => numberDate.nowThe clock, in milliseconds, for freshness and relative times.
context?() => BindingContextWho and where the user is: me, time zone and locale.
concurrency?number4Fetches running at once.
capacity?number200Results kept.
onError?(error: unknown) => voidTold 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.

PropertyTypeDescription
current?stringThe 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.

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, FetchRequest, 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, Fetch, RowOf, SourceIdOf.

FetchFilter

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

Uses: Op, Stored.

PropertyTypeDescription
fieldstringOne of the source's own fields.
opOpThe operator, one the source's capabilities declare.
valuesreadonly 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, FetchFilter.

PropertyTypeDescription
sourcestringThe source to read.
fieldsreadonly string[]The fields core needs, for bindings that select columns.
filterreadonly FetchFilter[]Filters to apply, from those the source declares.
sortreadonly { field: string; direction: Direction }[]Sorts to apply, from those the source declares.
limitnumberRows per page.
cursor?stringThe next of the previous page.
search?stringText to look for, when the source searches itself.
signal?unknownAn 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.

PropertyTypeDescription
rowsreadonly R[]The rows, as the API returns them.
next?stringPassed back as cursor for the next page; absent on the last page.
total?numberEvery 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.

PropertyTypeDescription
fieldstringA qualified field name, such as payments.status.
opOpThe operator, one the field's type allows.
valuesreadonly 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.

PropertyTypeDescription
byStored | nullThe group's value of the grouping field, or null for one number.
labelstringThe 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.
splitStored | nullThe value of the second grouping, or null without one.
splitLabelstringThe second grouping's value, as people read it.
valuenumber | nullThe measure, or null when nothing was measured.
currency?stringFor money: the currency the value is in, when one applies.

LocalParts

A moment's calendar parts in a time zone.

PropertyTypeDescription
yearnumberThe year.
monthnumberThe month, from 1.
daynumberThe day of the month, from 1.
hournumberThe hour, from 0 to 23.
minutenumberThe minute.
secondnumberThe second.

Measure

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

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

Uses: 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.

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, Filter, Sort.

PropertyTypeDescription
sourcestringThe source asked about.
fieldsreadonly string[]Qualified field names: the source's own, or one hop through a ref.
filterreadonly Filter[]Filters, all of which a row must pass.
sortreadonly Sort[]Sorts, in order of precedence.
limitnumberMost rows to return.
searchstringText to look for, or empty.
aggregateAggregateA 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.

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, Row.

PropertyTypeDescription
rowsreadonly Row[]The rows, for queries without a summary.
groupsreadonly Group[]The groups, for summaries.
partialbooleanNot 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.
atnumberWhen the data was read, in milliseconds.
readsreadonly string[]Every source read, for invalidation.

QueryScope

What a query may refer to where it is used.

Uses: Clock.

PropertyTypeDefaultDescription
entity?stringThe source a page is about, so $current names its row.
me?booleanfalseWhether the binding knows who $me is.
limit?numberThe most rows the block showing the result can display.
clock?Clockthe current time, in UTCValidates 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, Clock.

PropertyTypeDescription
clockClockThe time and time zone relative values such as -7d resolve against.
current?stringThe key of the row a page is about, for $current.
context?BindingContextWho and where the person is, for $me and the bindings.
signal?unknownAn AbortSignal that cancels the fetches.

Sort

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

Uses: Direction.

PropertyTypeDescription
fieldstringA qualified field name, such as orders.placed.
directionDirectionAscending 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.

Actions and bindings

Source: action.ts, 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, 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, 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.

Bindings

The application's code behind a contract.

Uses: AnyContract, BindingContext, Fetchers, Performers.

Type parameters: C extends AnyContract = AnyContract.

PropertyTypeDescription
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?()() => BindingContextWho and where the user is: me, time zone and locale.
navigate?()(href: string) => voidFollows a link inside the application, such as through its router.

Confirmation

A run waiting for the user's yes.

Uses: Field.

PropertyTypeDescription
idstringThe run's ID, for confirm and cancel.
actionstringThe action's ID.
labelstringThe action's label.
descriptionstringWhat the action does.
effect'write' | 'destructive'A write waits for one yes; a destructive run for a typed phrase.
paramsReadonly<Record<string, unknown>>What the run will use, shown before the person says yes.
fieldsreadonly Field[]The params' fields, for showing what will happen.
phrase?stringFor 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, 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.

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.

HttpResponse

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

PropertyTypeDescription
okbooleanWhether the status is in the 200s.
statusnumberThe 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, AnyContract, 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, 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.

PropertyTypeDefaultDescription
actionstringThe action being run.
idempotencyKeystringUnique to one confirmed run, so a binding can refuse to do it twice.
me?stringThe 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?stringA 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, AnyContract, ParamsOf, Perform.

PerformOptions

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

Uses: Via.

PropertyTypeDefaultDescription
via?Via'region'How the person reached the action.
surface?stringThe surface the action was run from.
element?stringThe page element it was run from.
typed?booleanFor 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?booleanThe 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.

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.

PropertyTypeDescription
status'done' | 'canceled' | 'failed' | 'refused'refused runs never started; failed ones started and threw.
message?stringThe binding's message, or why the run was refused or failed.

RestAction

How one action's endpoint works.

PropertyTypeDefaultDescription
method'POST' | 'PUT' | 'PATCH' | 'DELETE'The HTTP method.
pathstringThe 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.

PropertyTypeDefaultDescription
sourcesReadonly<Record<string, RestSource>>Each source's list endpoint and how it pages, filters and sorts, by source ID.
basestringThe 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?HttpFetchglobalThis.fetchThe 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.

PropertyTypeDefaultDescription
actionsReadonly<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?stringThe header that carries each run's idempotency key, for APIs that honor one.
basestringThe 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?HttpFetchglobalThis.fetchThe 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;
  };
}
PropertyDefaultDescription
pathThe 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, 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, 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, GenericScope.

DATA_BLOCKS

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

ts
const DATA_BLOCKS: readonly GenericName[];

Uses: 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, 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, GenericName, 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, AnyPageSpec, 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, Query.

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, 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, Node, PageValue.

MemberDescription
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.

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, AnyPageSpec, PageValue, 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, PageValue.

ActionsProps

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

Uses: RowAction.

PropertyTypeDescription
liststringA list surface whose visible items become buttons, or none.
itemsreadonly 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, NamedQuery.

PropertyTypeDescription
rootstringThe ID of the outermost element, usually a section.
elementsreadonly Element[]Every element, the root included.
datareadonly NamedQuery[]The queries its blocks show.

BoardProps

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

PropertyTypeDescription
datastringThe name of one of the page's queries, whose result the block shows.
columnstringThe enum field whose values are the columns.
titlestringThe field each card is titled by.
metastringA 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.

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, RegionProps, SectionProps, TabsProps.

ChartProps

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

PropertyTypeDescription
datastringThe 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.
stackedbooleanWhether a split stacks, for bars and areas.

DetailProps

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

PropertyTypeDescription
datastringThe name of one of the page's queries; its limit must be 1.
fieldsreadonly string[]The fields to show, in order.
columnsnumberHow 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.

PropertyTypeDescription
idstringIts ID within the page.
blockKThe block it places.
propsPThe block's props.
childrenreadonly 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, BuiltInElement, Element, PropsOf.

FormProps

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

PropertyTypeDescription
actionstringThe action to run: one with an effect and params.
setreadonly { 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.

GenericProps

Props of each generic block, by name.

Uses: ActionsProps, BoardProps, ChartProps, DetailProps, FormProps, LinksProps, ListProps, MetricProps, NoteProps, TableProps, TimelineProps.

PropertyTypeDescription
tableTablePropsA table of rows.
listListPropsA list of rows.
detailDetailPropsOne row's fields.
metricMetricPropsOne figure.
chartChartPropsA chart.
timelineTimelinePropsRows in time order.
boardBoardPropsRows in columns.
formFormPropsA form for one action.
actionsActionsPropsButtons for actions.
noteNotePropsA note.
linksLinksPropsLinks to routes.

GenericScope

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

Uses: AnyContract, AnyPageSpec, Query.

PropertyTypeDescription
contractAnyContractThe contract the page belongs to.
specAnyPageSpecThe page's spec.
dataReadonlyMap<string, Query>The page's checked queries, by name.
usedSet<string>Names of queries a block used, filled in as blocks are checked.
plannedbooleanA 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.

LinksProps

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

PropertyTypeDescription
itemsreadonly { 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.

PropertyTypeDescription
datastringThe name of one of the page's queries, whose result the block shows.
titlestringThe field each row is titled by.
subtitlestringA second field under the title, or none.
metastringA field shown beside the row, such as a time, or none.
badgestringAn enum field drawn as a badge, such as a status, or none.
rowActionsreadonly 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.

PropertyTypeDescription
datastringThe name of one of the page's queries: an ungrouped summary.
labelstringWhat 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.

PropertyTypeDescription
namestringIts name, which blocks use in their data prop.
queryQueryThe query.

Node

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

PropertyTypeDefaultDescription
blockstringThe block it places.
propsunknownThe block's props.
children?readonly Node[]For sections and tabs: what is inside, in order.
id?stringthe block's name and a numberIts ID within the page.

NoteProps

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

PropertyTypeDescription
titlestringThe note's title.
textstringThe 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, ElementOf.

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

PropertyTypeDescription
elementsreadonly ElementOf<B>[]Every element, the root included, with its props typed.
rootstringThe ID of the outermost element, usually a section.
datareadonly NamedQuery[]The queries its blocks show.

RegionProps

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

PropertyTypeDescription
namestringOne of the contract's regions.

RowAction

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

PropertyTypeDescription
actionstringThe action's ID.
setreadonly { 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.

PropertyTypeDescription
titlestringMay be empty.
layoutLayoutHow 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.

PropertyDescription
sectionsThe 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.

PropertyTypeDescription
datastringThe name of one of the page's queries, whose result the block shows.
columnsreadonly string[]The query's fields to show, in order, such as orders.total.
lookupsreadonly { data: string; label: string }[]Figures from other queries, one per row: an aggregate grouped by a ref to this source.
rowActionsreadonly 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.

PropertyTypeDescription
titlestringThe tabs' accessible name.

TimelineProps

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

PropertyTypeDescription
datastringThe name of one of the page's queries, whose result the block shows.
timestringThe time field that orders the rows.
titlestringThe field each entry is titled by.
detailstringA field under each title, or none.

ValidateOptions

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

PropertyTypeDescription
planned?booleanA planner placed the page, unasked: no destructive actions, no filled-in writes.

Routes

Source: 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.

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.

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.

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.

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.

segments

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

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

Uses: RouteSegment.

validateRoutes

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

ts
function validateRoutes(contract: AnyContract): void;

Uses: 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.

PropertyTypeDefaultDescription
pathstringA path pattern: literal segments and :param segments.
label?stringthe page's label, else the route's IDShown in links.
entity?stringThe 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?stringThe page surface the route shows.
action?stringThe action a visit records, such as go.payments.

The client

Source: client.ts, 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, Uitive, UitiveOptions.

localStore

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

ts
function localStore(key: string): Store;

Uses: Store.

memoryStore

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

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

Uses: Store.

Adaptation

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

Uses: CommandStatus, PlanMeta, Rejection.

PropertyTypeDescription
idstringIts 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.
sessionnumberThe session it happened in.
appliedreadonly string[]Operations it applied, or added as suggestions.
rejectedreadonly Rejection[]What policy refused, with reasons.
pendingnumberOperations still waiting for a safe moment or a second plan.
status?CommandStatusFor commands: what became of the request.
candidates?readonly string[]For ambiguous commands: what the words could mean.
text?stringFor commands: the request, in the person's words.
meta?PlanMetaHow 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.

PropertyTypeDescription
format'uitive.definition'Says what the document is.
version1The document format's version.
contract{ id: string; hash: string }The contract it was exported from; an import checks its changes against the current one.
definitionDefinitionThe person's definition.

Location

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

PropertyTypeDescription
pathstringThe path, with its query.
route?stringThe contract route the path matches.
paramsReadonly<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?stringOne 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, AnyPage, PageSpec, PageValue, SectionPage, SectionsPage, SurfaceIdOf.

RecordOptions

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

Uses: Via.

PropertyTypeDefaultDescription
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?stringThe 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?stringThe page element it came from.
typed?booleanFor 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, Autonomy, Confirmation, Definition, Location, Pending, View.

PropertyTypeDescription
sessionnumberThe current session, counted from the first.
viewViewWhether the person sees their own interface or the standard one.
autonomyAutonomyHow far planned changes may go without the person.
definitionDefinitionThe person's definition: every applied operation, cooldowns and blocks.
pendingreadonly Pending[]Changes waiting for the next safe moment.
latestAdaptation | undefinedThe most recent adaptation, for banners.
adaptationsreadonly Adaptation[]Recent adaptations, oldest first.
contextsReadonly<Record<string, string>>Context values active now, by context name.
usagenumberIncrements with every usage event.
previewstring | undefinedA suggested redesign shown in place, before the user accepts or dismisses it.
confirmationConfirmation | undefinedA run waiting for the user's yes.
locationLocation | undefinedWhere 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.

PropertyTypeDescription
load()() => unknownThe stored state, or nothing; synchronous, so the first paint shows the person's interface.
save()(state: unknown) => voidStores the state.
clear()() => voidDeletes the stored state.
watch?()(listener: () => void) => () => voidCalls 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, ActionView, Adaptation, AnyContract, AnyPage, Autonomy, ContextOf, DataClient, DefinitionDocument, Explanation, Operation, PageInput, ParamsOf, PerformOptions, PerformResult, PlanRequest, RecordOptions, SectionsPage, Snapshot, SurfaceIdOf, SurfaceValueOf, Target, UsageEvent, UsageSummary, UserPage, View.

PropertyDescription
contractThe contract the client adapts.
dataQuery 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, Autonomy, Bindings, Environment, Planner, StabilizerOptions, Store.

Type parameters: C extends AnyContract.

PropertyTypeDefaultDescription
contractCThe contract defineApp returned.
store?StorememoryStore()Where state persists.
planner?PlannerheuristicPlanner()Who plans: the deterministic planner, or remotePlanner for a model on the application's server. Simple commands are always answered locally.
now?() => numberDate.nowThe clock, in milliseconds; tests pass one that moves only when told.
idleMinutes?number30Minutes without activity that end a session.
autonomy?Autonomy'mixed'Used until the user chooses otherwise.
learn?booleantrueWhether 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) => voidCalled 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 | undefinedFor 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, 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, CommandResult, 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.

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, CommandResult, 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, 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.

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.

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.

PropertyTypeDescription
routestring | nullThe adapter route the page matched.
anchorsReadonly<Record<string, 'found' | 'missing' | 'ambiguous'>>Whether each anchor was found once, not at all, or more than once.
sourcesReadonly<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.

PlanMeta

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

PropertyTypeDescription
plannerstringThe planner's name.
msnumberHow long planning took, in milliseconds.
subset?readonly string[]The sources the request was scoped to, for large contracts.
repaired?booleanA second round fixed what policy rejected in the first.
unrepaired?stringWhy the second round failed, when what policy accepted of the first answer was kept instead.
stages?numberModel calls made.
model?stringThe model that planned, for model planners.
fellBack?stringWhy 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?numberEstimated 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, PlanOptions, PlanRequest, PlanResult.

PropertyDescription
nameThe 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.

PropertyTypeDescription
okbooleanWhether the status is in the 200s.
statusnumberThe HTTP status.
json()() => Promise<unknown>The body, parsed.
headers?{ get(name: string): string | null }The response's headers, for its content type.
body?PlannerStream | nullThe body as a stream, when progress lines arrive.

PlannerStream

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

PropertyTypeDescription
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.

PropertyTypeDescription
signal?unknownAn AbortSignal where the platform has one.
onProgress?(progress: PlanProgress) => voidCalled 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.

PropertyTypeDescription
stage'planning' | 'repairing'Whether the model is planning, or repairing what policy rejected.
elementsnumberPage elements written so far.

PlanRequest

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

Uses: Environment, StateView, UsageSummary.

PropertyTypeDescription
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.
sessionnumberThe current session.
summaryUsageSummaryUsage, as numbers.
stateStateViewThe interface as it is, as IDs.
contextsReadonly<Record<string, string>>Context values active now, by context name.
route?stringThe route in view; never the row it shows.
text?stringThe command, in the user's words.
goal?stringThe goal the user stated, in their words.
environment?EnvironmentFor 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, PlanMeta, ProposedOperation.

PropertyTypeDescription
origin'heuristic' | 'model'Which planner produced the operations.
operationsreadonly ProposedOperation[]The proposed operations, for policy to check.
status?CommandStatusFor commands: what became of the request.
candidates?readonly string[]For ambiguous commands: what the words could mean.
metaPlanMetaHow the plan was made.

ProposedOperation

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

Uses: Change, ClaimedEvidence.

PropertyTypeDescription
changeChangeWhat it would change.
evidencereadonly ClaimedEvidence[]What it claims to rest on; policy replaces the figures with the true ones.
note?stringA 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, Planner.

PropertyTypeDefaultDescription
urlstringThe handler's base URL; requests go to <url>/plan and <url>/command.
fallback?PlannerAnswers when the server can't.
fetch?FetchLikeglobalThis.fetchThe fetch it calls.
timeoutMs?number60000 for plans, 20000 for commandsHow 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.

PropertyDescription
listsEach list's visible and pinned items, per context value in view.
choicesEach choice's value.
collectionsEach collection's item titles, as the person sees them.
pagesThe pages in view now, as they are.
userPagesThe pages the user made.
userPage?The user's own page in view, if any.
userOperation keys the user decided themselves; planners leave these alone.
cooldownsOperation keys cooling down after a revert.
blockedOperation keys reverted twice, never proposed again.
frozenWhether the person froze planned changes.
recentHow the user answered recent changes.

Definitions and policy

Source: definition.ts, explain.ts, limits.ts, policy.ts, 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, 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, Operation, 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, AnyPage, 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.

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, Explanation, Operation.

emptyDefinition

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

ts
function emptyDefinition(contract: AnyContract): Definition;

Uses: AnyContract, 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.

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.

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.

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.

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.

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, 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, CollectionValue, 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, Definition, 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, AnyPage, Definition.

resolveUserPages

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

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

Uses: Definition, 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, OutputRejection, ProposedOperation.

AppliedOperation

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

Uses: Status.

PropertyTypeDescription
statusStatusWhether it is active, kept, reverted, suggested or dismissed.
sessionnumberThe session it was applied in.
adaptationstringThe adaptation that applied it.
idstringIts ID, for revert, keep and explanations.
changeChangeWhat it changes.
originOriginWho proposed it: learning, the model, or the person.
layer'model' | 'user'User-layer operations outrank model-layer ones.
evidencereadonly Evidence[]What it rests on: usage figures, or the person's words.
note?stringA 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, CollectionChange, ListChange, PageChange, UserPageChange.

CheckResult

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

Uses: Operation, Rejection.

PropertyTypeDescription
acceptedOperation[]The operations that passed, in canonical form.
rejectedRejection[]The operations refused, with reasons.

ChoiceChange

A choice set to one of its values.

PropertyTypeDescription
kind'choice'Says the change is to a choice.
surfacestringThe choice.
op'set'Choices are only ever set.
valuestringThe value chosen.

CollectionChange

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

PropertyTypeDescription
kind'collection'Says the change is to a collection.
surfacestringThe collection.
op'add' | 'update' | 'remove'Whether the item is added, changed or removed.
itemstringThe item's ID.
value?unknownFor add and update: the item itself.

Definition

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

Uses: AppliedOperation.

PropertyTypeDescription
schemaVersion22 since pages became flat elements; version 1 definitions are migrated on load.
contractstringThe hash of the contract it was made against.
versionnumberIncrements on every change.
operationsreadonly AppliedOperation[]Every operation applied, in order.
cooldownsreadonly { key: string; until: number }[]Operation keys a planner may not propose until a session.
blockedreadonly string[]Operation keys reverted twice: never proposed again.
frozenbooleanWhen frozen, planners change nothing.
goal?stringThe 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.

Explanation

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

PropertyTypeDescription
titlestringWhat changed, such as "Table added to Toolbar".
reasonstringWhy, with the evidence's true numbers.
note?stringA 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.

PropertyTypeDescription
kind'list'Says the change is to a list.
surfacestringThe list.
context?stringThe 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.
targetstringThe action.
index?numberFor move: the position among visible items.
evict?stringFor 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.

PropertyTypeDescription
valueListValueThe list as the person has it.
visibleSet<string>The items that show.
pinnedSet<string>The items the person pinned.
hiddenSet<string>Items the user hid, until they restore or pin them.
standardSet<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, Evidence, Origin.

PropertyTypeDescription
idstringIts ID, for revert, keep and explanations.
changeChangeWhat it changes.
originOriginWho proposed it: learning, the model, or the person.
layer'model' | 'user'User-layer operations outrank model-layer ones.
evidencereadonly Evidence[]What it rests on: usage figures, or the person's words.
note?stringA 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, Rule.

PropertyTypeDescription
operationProposedOperationThe proposed operation refused.
ruleRuleThe rule it broke.
messagestringWhy, for the model to repair.

PageChange

A page redesigned outright, or put back to standard.

Uses: AnyPage.

PropertyTypeDescription
kind'page'Says the change is to a page.
surfacestringThe page.
context?stringA context value, or * for every value.
op'set' | 'reset'Redesigned outright, or put back to standard.
value?AnyPageFor set: the whole new page.

Pending

A checked operation waiting for a safe moment.

PropertyTypeDescription
keystringWhat it does, regardless of when or by whom, for cooldowns and repeats.
strengthnumberHow strong its evidence is; past the margin, a model's change needs no second plan.
heldbooleanHeld until a second plan proposes it again, unless its strength clears the margin.
idstringIts ID, for revert, keep and explanations.
changeChangeWhat it changes.
originOriginWho proposed it: learning, the model, or the person.
layer'model' | 'user'User-layer operations outrank model-layer ones.
evidencereadonly Evidence[]What it rests on: usage figures, or the person's words.
note?stringA 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, Definition, UsageSummary.

PropertyTypeDefaultDescription
contractAnyContractThe contract.
definitionDefinitionThe person's definition.
summaryUsageSummaryUsage, as numbers.
sessionnumberThe current session.
intent?stringThe user's own words behind this request: a command or their stated goal.
interpreted?booleanfalseWhether 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, Rule.

PropertyTypeDescription
operationOperationThe operation refused.
ruleRuleThe rule it broke.
messagestringWhy, 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.

PropertyTypeDefaultDescription
budgetnumber2Structural changes applied at one safe moment.
dwellnumber3Sessions an item keeps its place after it moves.
cooldownnumber5Sessions a reverted change waits before it may return.
expirynumber5Sessions a pending change stays valid.
marginnumber1Strength 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.

PropertyTypeDescription
slugstringIts slug: the page lives at /uitive/<slug>.
titlestringIts title, as the person named it.
valueAnyPageThe page.
operationstringThe operation that created it.

UserPageChange

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

Uses: USER_PAGES, AnyPage.

PropertyTypeDescription
kind'userPage'Says the change is to one of the person's own pages.
surfacetypeof USER_PAGESAlways userPages.
op'create' | 'rename' | 'set' | 'delete'Whether the page is made, renamed, redesigned or deleted.
slugstringThe page's slug, in its address.
title?stringFor create and rename.
value?AnyPageFor create and set: the whole page.

Usage and simulation

Source: simulate.ts, 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, 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, Persona, SessionReport, 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, Definition, SessionRecord, UsageEvent, UsageSummary.

VIAS

Every way an action may be reached.

ts
const VIAS: readonly Via[];

Uses: 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, 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.

PropertyTypeDefaultDescription
namestringIts name, as reports show it.
descriptionstringWho it stands for.
weightsReadonly<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> | undefinedContext 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?number0.3How often an overflow item is reached through the palette rather than overflow.

SessionRecord

One session: when it started, and the context values it saw.

PropertyTypeDescription
indexnumberThe session's number, counted from the first.
startedAtnumberWhen it started, in milliseconds.
contextsRecord<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.

PropertyTypeDescription
sessionnumberThe session's number.
visibleRecord<string, readonly string[]>Visible items of each list at the session's start, keyed surface or surface|context.
applied?AdaptationThe adaptation applied at the session's start, if any.
planned?AdaptationThe plan made at the session's end, if any.

UsageEvent

One activation. Never text typed into the application, never page content.

Uses: Via.

PropertyTypeDescription
actionstringThe action used.
viaViaHow it was reached.
sessionnumberThe session it happened in.
surface?stringThe surface it was reached on, when known: its use then counts there alone.
element?stringThe 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?booleanFor 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.

PropertyTypeDescription
surfacestringThe surface.
context?stringThe context value, for surfaces keyed by context.
actionstringThe action.
place'visible' | 'overflow'Where it is now.
pinnedbooleanWhether the person pinned it.
usesnumberUses within the window.
activeSessionsnumberSessions within the window with at least one use.
viaOverflownumberUses reached from overflow, within the window.
viaPalettenumberUses reached by searching, within the window.
viaSuggestednumberUses reached through a suggestion, within the window.
idleSessionsnumberConsecutive recent sessions it was visible and unused, while its surface was in use.
placementnumberDecayed placement score, with overflow use weighing most: decides who deserves a place.
activitynumberDecayed 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.
rankingnumberDecayed ranking score, rounded to hundredths.

UsageSummary

The deterministic statistics a planner sees: the only usage that leaves the device.

Uses: UsageRow.

PropertyTypeDescription
sessionnumberThe current session.
windownumberSessions the window covers.
rowsreadonly UsageRow[]One row per action and surface.
hashstringChanges 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, 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, Subset.

areasOf

The areas of a contract, one per source.

ts
function areasOf(contract: AnyContract): Area[];

Uses: AnyContract, 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.

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, Subset, 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, 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.

PropertyTypeDescription
sourcestringThe source at its center.
actionsreadonly string[]Actions that act on its rows, or change it.
routesreadonly string[]Routes that show its rows.
termsreadonly string[]The words it is found by.

Subset

What a request may use: its sources, and the actions and routes that come with them.

PropertyTypeDescription
sourcesreadonly string[]The sources a request plans over.
actionsreadonly string[]Its areas' actions, and others its words name: at most MAX_ACTIONS.
routesreadonly 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.

PropertyTypeDefaultDescription
text?stringWhat the person said, and their goal.
inView?readonly string[]Sources on screen now, always included.
maxSources?number8Sources the subset may hold.
extra?number2Areas added by relevance beyond those on screen.