@atscript/ui
Framework-agnostic core for type-driven UIs. Reads compiled Atscript metadata, builds form and table definitions, exposes a pluggable field resolver, validators, value-help, and a battery of pure utilities consumed by every Vue package. No Vue, no React — plain TypeScript.
Contents
- Plugin
- Form types
- Form factories
- Table types
- Table factory
- Navigate action hrefs
- Model nav routes
- Field resolver
- Annotation key constants
- Validators
- Form diff engine
- Path utilities
- Value-help
- Grid layout
- Decimal helpers
- Column helpers
- Error map utilities
- Type guards
- Misc utilities
- Client factory
- Meta cache
- UI texts
Plugin
@atscript/ui/plugin exposes the build-time plugin that registers every static @ui.* annotation key. Wire it in atscript.config.ts:
import uiPlugin from "@atscript/ui/plugin";
export default {
plugins: [uiPlugin()],
};For dynamic @ui.fn.* and @ui.form.validate, also register @atscript/ui-fns/plugin.
Form types
FormDef
Complete form definition produced by createFormDef(type).
interface FormDef {
type: TAtscriptAnnotatedType;
rootField: FormFieldDef;
fields: FormFieldDef[];
flatMap: Map<string, TAtscriptAnnotatedType>;
/** Since 0.1.170: `type` was served already translated (`deserializeServedType`) — a renderer does not translate its texts again. */
served?: true;
}FormFieldDef
Thin pointer to one atscript prop. Metadata lives on prop.metadata and is resolved on demand.
interface FormFieldDef {
/** Dot-separated path relative to the parent data container. `""` = root. */
path: string;
prop: TAtscriptAnnotatedType;
/** Render-kind: structural names (`array`, `object`, `union`, `tuple`) or primitive override from `@ui.form.type`. */
type: string;
/**
* Optional `@ui.form.type` / `@ui.type` override that lets a structured kind
* (`array`, `object`, `union`, `tuple`) dispatch to a different built-in
* renderer in the `:types` map. Reserved for built-in ids — custom
* components are wired via `@ui.form.component` + `:components`.
*/
customType?: string;
phantom: boolean;
name: string;
/** True when no `ui.fn.*` keys exist on the prop — perf flag. */
allStatic: boolean;
/** `@ui.form.pushDown` — render below the submit button instead of in the main grid. */
pushDown: boolean;
/**
* Value-help target for an FK field, resolved once by `extractValueHelp()`
* while the def is built (since 0.1.134). `undefined` for non-FK fields.
* Renderers read this instead of re-walking the annotations per mount —
* `<AsField>` forwards it to the control as the `valueHelp` prop.
*/
valueHelpInfo?: ValueHelpInfo;
/**
* Set for a field the server owns: `@db.column.derived`, a computed view
* column (`opts.metaFields`), or an `@db.onUpdate.now` / `.inc` field in an
* edit form (`opts.mode: "edit"`). `<AsField>` renders it read-only;
* validators and `buildFormDiff` skip it. Since 0.1.144.
*/
derived?: true;
/**
* The enclosing prop whose `@ui.literalLabel` labels also apply: the array
* prop of an item field (`flags: boolean[]`) or the union prop of a variant
* (`active: boolean | null`). Set only when that prop declares labels.
* Since 0.1.165.
*/
labelsFrom?: TAtscriptAnnotatedType;
}FormArrayFieldDef, FormObjectFieldDef, FormUnionFieldDef, FormTupleFieldDef
Extended field defs for structural kinds.
interface FormArrayFieldDef extends FormFieldDef {
itemType: TAtscriptAnnotatedType;
itemField: FormFieldDef;
}
interface FormObjectFieldDef extends FormFieldDef {
objectDef: FormDef;
}
interface FormUnionFieldDef extends FormFieldDef {
unionVariants: FormUnionVariant[];
}
interface FormTupleFieldDef extends FormFieldDef {
itemFields: FormFieldDef[];
}FormUnionVariant
One branch of a union.
interface FormUnionVariant {
label: string;
/** Since 0.1.170: the `@meta.label` text `label` ends with — translate it at render time (`userText`). */
labelText?: string;
/** Since 0.1.165: the UI text code of a generated type name ("1. String" → `UI_FORM_TYPE_STRING`); render it in the UI locale. */
labelCode?: AsUiMessageCode;
type: TAtscriptAnnotatedType;
/** Pre-built FormDef for object variants. */
def?: FormDef;
/** Pre-built field def for primitive variants. */
itemField?: FormFieldDef;
/** "string" | "number" | "boolean" for primitive variants. */
designType?: string;
}TFormAction
interface TFormAction {
id: string;
label: string;
}TFormEntryOptions
A select/radio option — plain string or { key, label } pair.
type TFormEntryOptions = { key: string; label: string } | string;Form factories
createFormDef(type, opts?)
Builds a FormDef from an annotated type. Walks props, pre-resolves structural sub-defs, and caches the flat map.
function createFormDef(type: TAtscriptAnnotatedType, opts?: CreateFormDefOptions): FormDef;
interface CreateFormDefOptions {
versionColumn?: string;
/** `meta.fields` — a field marked `computed` is marked `derived`. Since 0.1.147. */
metaFields?: Record<string, { computed?: boolean }>;
/** `"edit"` — `@db.onUpdate.now` / `.inc` fields are marked `derived`. Default `"create"`. Since 0.1.154. */
mode?: "create" | "edit";
}When opts.versionColumn is supplied, the matching prop is excluded from the returned fields[] (so AsForm's renderer doesn't paint it) but remains in flatMap and in the form's underlying data wrapper. This is the contract OCC needs: hide the version input from users while keeping the value in the wire payload so the server can lift it into $cas. Pass meta.versionColumn directly — it is the logical field name (see MetaResponse). With mode: "edit" it defaults to the top-level @db.column.version field, so an edit form built straight from the type hides it too. Since 0.1.164.
Navigation fields (@db.rel.from / @db.rel.to / @db.rel.via) are left out of the form: they hold related rows, not data the row's own form edits. Annotate one with any @ui.form.* (e.g. @ui.form.order) to include it — an included navigation object renders as a section, and its changes are nested writes to the related table. A skipped navigation field is also skipped by the form validator, and its loaded rows are never sent: not by buildFormDiff (at any depth), not in AsForm's submit data. Since 0.1.164.
omitSkippedNavFields(def, data)
A deep copy of form data (the unwrapped domain value) without the navigation fields def leaves out, at any depth. Returns data itself when there are none. Use it when you send form data yourself instead of through AsForm's submit event or buildFormDiff, which apply it already. Since 0.1.164.
function omitSkippedNavFields<T>(def: FormDef, data: T): T;Recursive types (a tree's children: Node[], mutual references, a union containing the type itself) are supported at any depth: the nested defs repeat instead of expanding forever, and an object reached again inside itself renders as a nested object field rather than inline. Since 0.1.164.
A @db.column.derived field (a top-level column the server computes from a @db.json leaf) needs no option: createFormDef reads the annotation from the type — /meta keeps it in the serialized type since @atscript/db 0.1.142 — and sets FormFieldDef.derived. <AsField> renders the field read-only with no required marker, the validators never fail it (a required derived field left empty on a create form passes), and buildFormDiff never sends it. Since 0.1.144.
A computed view column (@db.compute) carries no annotation on the client — the server keeps it out of the serialized type — so pass opts.metaFields: meta.fields: a field /meta marks computed gets the same derived treatment. Views are read-only, so this matters only for a form you build from a view's type (a read-only detail form, say). Since 0.1.147.
Pass opts.mode: "edit" for a form that edits a stored row. An @db.onUpdate.now field — number.timestamp.updated, which also carries @db.default.now — is set by the server on every update and replace, and a value the client sends is ignored, so an edit form marks it derived too: read-only, never validated, never sent. This applies at any depth (embedded objects, array items, T | null) — but not to a field that references another one (updatedAt: Order.updatedAt), an element of an array of numbers, or a field below a tuple or a union of several types: the server stores those as sent, so they stay editable and validated. In a create form (the default) the field stays editable: with @db.default.now it may be left empty (the server fills it, like number.timestamp.created); a bare @db.onUpdate.now without a default is required on insert. /meta keeps the annotation since @atscript/db 0.1.156. Since 0.1.154.
An @db.onUpdate.inc change counter (@atscript/db 0.1.162+) — a top-level integer the server starts at 0 and increments on every update and replace, ignoring a sent value — gets the same treatment: derived in an edit form; editable in a create form, where it may be left empty (the server starts it at 0). Since @atscript/ui 0.1.159.
// An edit form
formDef.value = createFormDef(deserializeServedType(meta.type), {
mode: "edit",
versionColumn: meta.versionColumn,
metaFields: meta.fields,
});See the Edit forms with optimistic concurrency pattern guide for the end-to-end flow.
buildUnionVariants(type)
Returns the variant list for a union prop — used internally by createFormDef for union fields and union array items.
function buildUnionVariants(type: TAtscriptAnnotatedType): FormUnionVariant[];createFormData(type, resolver?)
Creates the wrapped data container { value: domainData } populated from atscript defaults and @meta.default. The optional resolver (TFormValueResolver) overrides the per-field defaulting strategy.
function createFormData<T extends TAtscriptAnnotatedType>(
type: T,
resolver?: TFormValueResolver,
): { value: TAtscriptDataType<T> };createFormValueResolver(data?, context?)
Returns a value resolver that reads @meta.default or @ui.form.fn.value, given a scope.
type TFormValueResolver = (prop: TAtscriptAnnotatedType, path: string) => unknown;
function createFormValueResolver(
data?: Record<string, unknown>,
context?: Record<string, unknown>,
): TFormValueResolver;Table types
TableDef
Complete table definition built by createTableDef(meta, type).
interface TableDef {
type: TAtscriptAnnotatedType;
columns: ColumnDef[];
flatMap: Map<string, TAtscriptAnnotatedType>;
/** Readable `meta.fields` paths — the gate for `@ui.table.selectWith` / `alwaysSelected`; includes `@ui.table.exclude` fields, excludes `writeOnly` ones (since 0.1.141). */
fetchableFields: Set<string>;
primaryKeys: string[];
/** Preferred row identifier for URL/wire addressing. */
preferredId: string[];
/** `preferredId` + every delegated action's `idMap` path — the fields action identifiers are built from. Equals `preferredId` when no action has an `idMap`. Since 0.1.147. */
identifierFields: string[];
/** Mirrors `MetaResponse.versionColumn` — name of the OCC version column when the table opts into `@db.column.version`. */
versionColumn?: string;
crud: TCrudPermissions;
canRemove: boolean;
actions: TableActionsModel;
searchable: boolean;
vectorSearchable: boolean;
searchIndexes: SearchIndexInfo[];
relations: RelationInfo[];
}createTableDef propagates versionColumn from the meta envelope and skips the matching entry from def.columns, so filter/sort/column-picker dialogs ignore the version column automatically — see Edit forms with optimistic concurrency.
ColumnDef
A single column definition built from field metadata + annotations.
interface ColumnDef {
path: string;
label: string;
type: string;
/**
* Scalar storage kind of the value — what the server's filter guard checks,
* derived from the atscript type by `createTableDef`. Filter UIs and the
* query builder read it to pick the filter kind (a `timestamp` gets a
* date-time filter) and to encode values. `undefined` for arrays, objects,
* JSON and mixed unions: no coercion. Since 0.1.148.
*/
valueKind?: ColumnValueKind;
component?: string;
/** Extra sibling leaf paths to fetch when this column is visible — see [Custom Cells](/tables/custom-cells). */
selectWith?: string[];
sortable: boolean;
/** Value comparisons accepted (the server's `filterable`). */
filterable: boolean;
/** Narrower operators accepted when `filterable` is `false`, e.g. `["$exists"]` on a JSON-stored column. Since 0.1.139. */
filterOps?: string[];
/** `true` for an optional prop, and (since 0.1.165) for a type with a `null` member (`T | null`). */
nullable: boolean;
visible: boolean;
width?: string;
maxLen?: number;
order: number;
/** A literal union's options and (since 0.1.165) a boolean's — `true` / `false`, labelled Yes / No unless `@ui.literalLabel` says otherwise. `value` (since 0.1.148) is the typed literal — `true`, `3` — that a filter sends; `key` is its string form. Always set by `createTableDef`; a hand-built column may omit it. */
options?: { key: string; label: string; value?: string | number | boolean }[];
valueHelpInfo?: ValueHelpInfo;
/** Distinct-values picker (`@ui.valueHelp.distinct`): the table's own controller answers the values of `field`. Since 0.1.148. */
distinct?: { url: string; field: string };
currencyCode?: string;
currencyRefField?: string;
unitCode?: string;
unitRefField?: string;
precisionScale?: number;
/** Synthesised columns (e.g. row-actions) — locked chrome, excluded from `columnNames`. */
fixed?: boolean;
}ColumnValueKind
Since 0.1.148.
type ColumnValueKind =
| "string" // string
| "date" // string.date (stored as `YYYY-MM-DD`)
| "isoDate" // string.isoDate (stored as an ISO date-time string)
| "number" // number, float
| "integer" // number.int (or @expect.int / @db.default.increment / now / agg.count)
| "decimal" // decimal (strings end to end)
| "timestamp" // number.timestamp (epoch milliseconds)
| "boolean";A union whose non-null members agree on one kind takes it (1 | 2 is number, 'a' | 'b' | null is string); anything else has none. See Filterable columns.
MetaResponse
The payload returned by the moost-db /meta endpoint.
interface MetaResponse {
searchable: boolean;
vectorSearchable: boolean;
searchIndexes: SearchIndexInfo[];
primaryKeys: string[];
preferredId: string[];
versionColumn?: string;
crud: TCrudPermissions;
actions: TDbActionInfo[];
relations: RelationInfo[];
fields: Record<string, FieldMeta>;
type: TSerializedAnnotatedType;
/** The controller's declared display-only fields (`@DbDecorations`, `@atscript/moost-db` 0.1.148+) as a serialized plain interface. Absent on older servers. Since 0.1.148. */
decorations?: TSerializedAnnotatedType;
}
interface FieldMeta {
sortable: boolean;
filterable: boolean;
/** Present only when `filterable` is `false` but narrower predicates pass (`@atscript/moost-db` 0.1.132+). Since 0.1.139. */
filterOps?: string[];
/** The caller may write but not read this field (kept in `/meta` for forms). Never a column, never fetchable. Since 0.1.141. */
writeOnly?: boolean;
/** `@db.column.derived` — server-computed; a written value is dropped (`@atscript/db` 0.1.141+). Forms read the annotation from the type instead. Since 0.1.144. */
derived?: boolean;
/** Computed view column (`@db.compute`, `@atscript/db` 0.1.147+). An ordinary column for sorting / filtering; read-only in forms via `CreateFormDefOptions.metaFields`. Since 0.1.147. */
computed?: boolean;
/** Display-only value the controller computes (`@DbDecorations`) — selectable, never filterable / sortable / groupable. `createTableDef` builds its column from `MetaResponse.decorations`. Since 0.1.148. */
decoration?: boolean;
/** `$groupBy` on this field passes the server's gate (`@atscript/moost-db` 0.1.148+). With `filterable` and `@ui.valueHelp.distinct` it enables the distinct-values picker. Since 0.1.148. */
groupable?: boolean;
}
interface SearchIndexInfo {
name: string;
description?: string;
type?: "text" | "vector";
}
interface RelationInfo {
name: string;
direction: "to" | "from" | "via";
isArray: boolean;
/** `@db.rel.filterable` — the server accepts `name: { $some | $none: … }` filters (`@atscript/moost-db` 0.1.147+). Since 0.1.147. */
filterable?: boolean;
}versionColumn?: string — logical field name of the server-managed row version field on OCC-protected tables (declared with @db.column.version in your .as schema). A @db.column 'row_version' rename changes only the storage column; /meta reports the field name you read and write (@atscript/db 0.1.141+ — earlier servers sent the storage name, which broke OCC for renamed fields). Absent on tables that don't opt into OCC. Consumer code should pass this through to createFormDef so the version field doesn't render as an editable input, while still riding in the form data for the server's $cas round-trip. See the Edit forms with optimistic concurrency pattern guide for the full flow.
TableActionsModel
Server-declared actions grouped by level.
interface TableActionsModel {
table: TDbActionInfo[];
row: TDbActionInfo[];
rows: TDbActionInfo[];
default: {
table?: TDbActionInfo;
row?: TDbActionInfo;
rows?: TDbActionInfo;
};
}TableQueryState, SortControl, PaginationControl
interface SortControl {
field: string;
direction: "asc" | "desc";
}
interface PaginationControl {
page: number;
itemsPerPage: number;
}
interface TableQueryState {
sort?: SortControl[];
pagination?: PaginationControl;
search?: string;
filters?: Record<string, unknown>;
}Table factory
createTableDef(meta, type)
Builds a TableDef from a MetaResponse plus the deserialized atscript type.
/** `t` (since 0.1.165) words the default boolean labels; the active UI texts by default. */
function createTableDef(meta: MetaResponse, type: TAtscriptAnnotatedType, t?: UiT): TableDef;See Annotations Reference for how @ui.table.* and @db.* annotations populate ColumnDef.
Since 0.1.148 the server's declared display-only fields become columns too: the top-level props of meta.decorations that meta.fields lists with decoration: true are built by the same code (label, @ui.table.*, display type) as sortable: false, filterable: false, nullable: true columns with no value help, and join flatMap / fetchableFields. A server that sends no decorations is unchanged — see Customization.
Only readable fields become columns: a path must be listed in meta.fields and not be writeOnly. Since 0.1.141 a writeOnly field and a top-level field missing from meta.fields are no longer columns — either would fail the query's $select. See Fields Hidden by Role.
Navigate action hrefs
navigateHrefFor(action, id, preferredId)
Computes, at render time, the href a processor: 'navigate' action would open — interpolating $1 in action.value with the row's URL-encoded preferredId. Lets a custom action-chrome renderer produce the same anchor the built-in <AsRowActions> / <AsTableActions> do. Returns undefined when no link is possible (not a navigate action, or a row-level action with no identifiable pk) → render a <button> and let the client handle the invoke. Since 0.1.147 a delegated action (action.idMap) reads id as this table's row and encodes the owner's identification it maps to, in Object.keys(idMap) order (no link when a mapped column is missing).
function navigateHrefFor(
action: TDbActionInfo,
id: Record<string, unknown> | undefined,
preferredId: readonly string[],
): string | undefined;See Navigate actions for the rendering and click-semantics narrative.
Model nav routes
buildModelRoutes(models, opts?)
Derives a declarative route registry from a list of annotated model types (typically the atscriptModels manifest generated by @atscript/db's dbPlugin({ manifest })). Only DB entities (@db.table / @db.view / @db.view.for) with a derivable path are included; the result is sorted by order ascending (undefined last, stable).
function buildModelRoutes(
models: readonly TAtscriptAnnotatedType[],
opts?: { t?: (text: string) => string | undefined }, // since 0.1.170
): TModelRoute[];opts.t translates the label and the group of a compiled model (the source text is the key; pass useAsLocale().t). A served model is left as it is. See Types compiled into the client.
TModelRoute
One navigable route derived from a DB-backed model's metadata.
interface TModelRoute {
model: TAtscriptAnnotatedType;
/** Route path without leading/trailing slashes — mountable anywhere. */
path: string;
/** Display label — from @meta.label or humanized last path segment. */
label: string;
kind: "table" | "view";
/** Nav section from @ui.nav.group — grouping is the consumer's job. */
group?: string;
/** Position from @ui.nav.order — lower first, undefined last. */
order?: number;
/** From @ui.nav.hidden — hidden routes are still returned; consumers filter. */
hidden?: boolean;
}See Model Routes & Nav for the manifest → routes → router pipeline, the path/label derivation contract, and consumer mapping examples.
Field resolver
The resolver is pluggable so static-only consumers ship with zero new Function overhead and dynamic consumers (@atscript/ui-fns) opt in by replacing the global instance.
FieldResolver
interface FieldResolver {
resolveFieldProp<T>(
prop: TAtscriptAnnotatedType,
fnKey: string,
staticKey: string | undefined,
scope: Record<string, unknown>,
opts?: TResolveOptions<T>,
): T | undefined;
resolveFormProp<T>(
type: TAtscriptAnnotatedType,
fnKey: string,
staticKey: string | undefined,
scope: Record<string, unknown>,
opts?: TResolveOptions<T>,
): T | undefined;
hasComputedAnnotations(prop: TAtscriptAnnotatedType): boolean;
}
interface TResolveOptions<T> {
staticAsBoolean?: boolean;
/** Since 0.1.170: translates a static text of the model before it is returned; a dynamic result is the resolver's own. */
t?: (text: string) => string | undefined;
transform?: (raw: unknown) => T;
}StaticFieldResolver
Class implementing FieldResolver with static-only semantics — fn keys are ignored.
setResolver(resolver) / getResolver() / defaultResolver
function setResolver(resolver: FieldResolver): void;
function getResolver(): FieldResolver;
const defaultResolver: StaticFieldResolver;Standalone helpers
function resolveFieldProp<T>(prop, fnKey, staticKey, scope, opts?): T | undefined;
function resolveFormProp<T>(type, fnKey, staticKey, scope, opts?): T | undefined;
function resolveStatic<T>(metadata, staticKey, opts?): T | undefined;
function hasComputedAnnotations(prop: TAtscriptAnnotatedType): boolean;
function getFieldMeta<K extends keyof AtscriptMetadata>(
prop: TAtscriptAnnotatedType,
key: K,
): AtscriptMetadata[K] | undefined;
/** Whether a metadata key is present on a prop (no resolver needed). */
function hasFieldMeta(prop: TAtscriptAnnotatedType, key: string): boolean;
/**
* SSOT for field hidden resolution — resolves `@ui.form.fn.hidden` (dynamic, via
* the active resolver) with static `@ui.form.hidden` presence as the fallback.
* Absent both → `false` (visible). `scope` is the fn scope for the field
* (`{ v, data, context, entry }`); dynamic resolution needs `@atscript/ui-fns`.
*/
function isFieldHidden(prop: TAtscriptAnnotatedType, scope: Record<string, unknown>): boolean;resolveStatic is exposed so dynamic resolvers (in ui-fns) can fall back to it without duplicating logic. hasFieldMeta and isFieldHidden are shared by AsField and vue-form's useAsVisibleFields; both are re-exported from @atscript/vue-form for container-renderer code.
parseStaticAttrs(value) / resolveAttrs(prop, scope, keys?)
Resolve @ui.form.attr and the dynamic @ui.form.fn.attr counterpart into a single record. keys overrides the static/fn key pair for @ui.table.attr and friends.
function parseStaticAttrs(value: unknown): Record<string, unknown> | undefined;
function resolveAttrs(
prop: TAtscriptAnnotatedType,
scope: Record<string, unknown>,
keys?: { staticKey?: string; fnKey?: string },
): Record<string, unknown> | undefined;Annotation key constants
Every supported annotation has a stringly-typed constant exported from @atscript/ui so consumers can build resolvers, mappers, or codegen against named keys instead of magic strings.
Cross-surface
| Name | Value |
|---|---|
UI_TYPE | "ui.type" |
Form static keys
UI_FORM_PLACEHOLDER, UI_FORM_HINT, UI_FORM_CLASSES, UI_FORM_STYLES, UI_FORM_AUTOCOMPLETE, UI_FORM_DISABLED, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_TYPE, UI_FORM_COMPONENT, UI_FORM_HIDDEN, UI_FORM_ATTR, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_SUBMIT_TEXT, UI_FORM_LABEL_SINGULAR, UI_FORM_ACTION, UI_FORM_PREFIX, UI_FORM_PREFIX_REF, UI_FORM_PREFIX_ICON, UI_FORM_SUFFIX, UI_FORM_SUFFIX_REF, UI_FORM_SUFFIX_ICON, UI_FORM_VALIDATE.
Form dynamic keys
UI_FORM_FN_PREFIX, UI_FORM_FN_LABEL, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_HINT, UI_FORM_FN_HIDDEN, UI_FORM_FN_DISABLED, UI_FORM_FN_READONLY, UI_FORM_FN_OPTIONS, UI_FORM_FN_ATTR, UI_FORM_FN_VALUE, UI_FORM_FN_CLASSES, UI_FORM_FN_STYLES, UI_FORM_FN_TITLE, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_SUBMIT_DISABLED.
Table static keys
UI_TABLE_WIDTH, UI_TABLE_COMPONENT, UI_TABLE_SELECT_WITH, UI_TABLE_EXCLUDE, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_ORDER.
Table dynamic keys
UI_TABLE_FN_PREFIX, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_STYLES.
Dictionary
UI_DICT_LABEL, UI_DICT_DESCR, UI_DICT_ATTR, UI_DICT_FILTERABLE, UI_DICT_SORTABLE, UI_DICT_SEARCHABLE.
Navigation
UI_NAV_GROUP, UI_NAV_ORDER, UI_NAV_HIDDEN — the @ui.nav.* keys read by buildModelRoutes.
DB-aware
DB_REL_FK, DB_HTTP_PATH, DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_UNIT, DB_UNIT_REF, DB_COLUMN_PRECISION.
Workflow
WF_ACTION_WITH_DATA.
Meta / expect
META_LABEL, META_ID, META_DESCRIPTION, META_READONLY, META_REQUIRED, META_DEFAULT, META_SENSITIVE, EXPECT_MAX_LENGTH.
Validators
Both validators let server-managed db fields through, so a create form built from a /meta type isn't blocked on values the server fills in: a @db.column.derived field is never validated, and an absent @db.default*, @db.column.version or @db.onUpdate.inc value passes. A @db.rel.FK field stays required — the form, not the server, supplies it. Since 0.1.144.
getFormValidator also never validates any other field its def marks derived — a computed view column, an edit form's @db.onUpdate.now / .inc field — and neither does <AsField>. createFieldValidator sees only the prop's annotations. Since 0.1.154.
getFormValidator(def, opts?)
Returns a reusable validator bound to a FormDef. Built once, called per submit.
function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): FormValidator;
interface FormValidator {
(callOpts: {
data: Record<string, unknown>;
context?: Record<string, unknown>;
t?: UiT; // since 0.1.165: the app's texts — see below
}): Record<string, string>;
normalize<T>(data: T): T; // since 0.1.165
}Calling it returns an errors record keyed by dot-separated field path (empty when valid). An error on the root type itself (a failing interface-level @ui.form.validate) is keyed __form (since 0.1.158; earlier it was keyed "").
normalize(data) (since 0.1.165) applies the type's @normalize.* annotations (trim, lowercase, uppercase) to the data — copy-on-change, data itself when nothing changes — judged with this validator's options. The validator checks data as given, so validate and submit the normalized value, as the server does:
const validator = getFormValidator(def);
const data = validator.normalize(formData.value);
const errors = validator({ data, t });
if (Object.keys(errors).length === 0) await client.insert(data);createFieldValidator(prop, opts?)
Field-level validator with internal Validator caching. Returns true on success or the first error message string. The value is judged with the prop's @normalize.* applied, as a submit judges it (since 0.1.165); the value itself is not changed.
function createFieldValidator(
prop: TAtscriptAnnotatedType,
opts?: { rootOnly?: boolean; t?: UiT; served?: () => boolean }, // `t` since 0.1.165: words the fallback error; `served` since 0.1.170, see below
): (value: unknown, externalCtx?: { data: unknown; context: unknown; t?: UiT }) => true | string;externalCtx.t / callOpts.t (since 0.1.165) is the app's texts: the t argument of @ui.form.validate rules, and the language every message is reported in (Texts in the user's language, Validation messages in the browser). Without t, the active UI texts are used. <AsForm> passes its app's.
Since 0.1.170. A failing @ui.form.validate rule reports a message already worded with t (error code UI_FORM_VALIDATE_ERROR_CODE), which the validators return as it is. The custom @expect.* / @meta.required messages of a type whose def is served (FormDef.served) are final too: getFormValidator reads it from the def; for createFieldValidator pass served: () => true when the prop's schema was served translated. Validator codes (MIN_LENGTH, …) are always looked up.
UI_FORM_VALIDATE_ERROR_CODE
const UI_FORM_VALIDATE_ERROR_CODE = "UI_FORM_VALIDATE";Since 0.1.170. The code of the error a failing @ui.form.validate rule reports on an atscript Validator (with the ui-fns plugin installed). Its message is final text, already worded with the app's t, so the validators above never look it up again. Not a UI text code (it is not in AS_UI_MESSAGES, your translate never receives it), and not the annotation-key constant UI_FORM_VALIDATE ("ui.form.validate").
isContainerKind(kind)
function isContainerKind(kind: string): boolean;true for the container kinds object, array and tuple (a prop's type.kind). With rootOnly, createFieldValidator validates a container prop at its root only. Union and intersection kinds are not containers. Since 0.1.158.
Default validator plugins
setDefaultValidatorPlugins(plugins) installs validator plugins globally; both getFormValidator and createFieldValidator apply them. getDefaultValidatorPlugins() returns the current list. @atscript/ui-fns uses this to wire its uiFnsValidatorPlugin().
function setDefaultValidatorPlugins(plugins: TValidatorPlugin[]): void;
function getDefaultValidatorPlugins(): TValidatorPlugin[];See the Validation guide for end-to-end usage.
Form diff engine
Framework-agnostic change tracking — diffs a form's current data against a baseline snapshot and produces both a changed-fields list and an @atscript/db patch object, plus a pure 3-way rebase that folds fresh server data back into a form with unsaved local edits. Vue's useAsFormPatch() wraps these. See the Change tracking guide.
buildFormDiff(def, baseline, current, opts?)
Diffs current against baseline (both the WRAPPED { value: domainData } container) and returns the dirty flag, the per-field change list, and a ready-to-ship @atscript/db patch. Revert-aware — a value edited back to its baseline produces no change and no patch entry. Lifts a top-level $cas sibling for optimistic concurrency when the type has a @db.column.version field and opts.cas !== false. The result holds live references into baseline / current — snapshot first if you keep editing (see Change tracking).
function buildFormDiff(
def: FormDef,
baseline: Record<string, unknown>,
current: Record<string, unknown>,
opts?: FormDiffOptions,
): FormDiffResult;FormDiffResult
interface FormDiffResult {
/** True when at least one field changed (revert-aware). */
isDirty: boolean;
/** Per-field changes (revert-aware — reverted fields are absent). */
changes: FormFieldChange[];
/** `@atscript/db` patch — flat, keyed by field; `{}` when nothing changed; carries `$cas` when applicable. */
patch: Record<string, unknown>;
}FormDiffOptions
interface FormDiffOptions {
/**
* Optimistic-concurrency control. `true` (default) auto-includes a top-level
* `$cas: { [versionColumn]: baselineVersion }` whenever the form has a
* `@db.column.version` column, the patch is non-empty, and a baseline integer
* version exists. `false` suppresses it. The version column is never emitted
* as a normal SET regardless. See [Change tracking — `$cas`](/forms/change-tracking#optimistic-concurrency-cas).
*/
cas?: boolean;
}FormFieldChange
One field that differs between baseline and current. kind: 'set' is a scalar / object / union / tuple field whose whole value changed; kind: 'array' is an array whose membership or item content changed. before / after hold live references into the supplied containers.
interface FormFieldChange {
/** Dot-separated path relative to the form root (e.g. `"address.city"`). */
path: string;
kind: "set" | "array";
before: unknown;
after: unknown;
}isPathDirty(changes, path)
Pure predicate over a FormFieldChange[]: true when the field at dot-path path changed. A field is dirty iff some change path equals path OR starts with path + ".", so a leaf matches exactly, an object/section container matches via its leaves, and a whole-array field matches at its root. The trailing dot rules out false positives (item never matches a change at items); the empty root path '' is dirty iff there are any changes. Reuse this to mark changed fields in a non-Vue renderer; Vue's isDirtyPath() / useAsField().isDirty wrap it over the reactive change list. See Change tracking — per-field dirty.
function isPathDirty(changes: FormFieldChange[], path: string): boolean;buildFormRebase(def, baseline, current, upstream, opts?, diffOptions?)
Pure 3-way merge: given the baseline, the live form, and a fresh upstream (all WRAPPED { value: domainData } containers), produces the form rewritten as upstream + the local diff reapplied on top. Untouched fields adopt upstream, local edits survive, both-sides edits are conflicts resolved by opts.conflict. No input is mutated. diffOptions are forwarded to BOTH internal buildFormDiff passes — keep them identical to your own tracking options so the version-column / $cas exclusion matches on both sides. Vue's rebaseOnto() is the thin reactive wrapper over this. See the Change tracking guide.
function buildFormRebase(
def: FormDef,
baseline: Record<string, unknown>,
current: Record<string, unknown>,
upstream: Record<string, unknown>,
opts?: FormRebaseOptions,
diffOptions?: FormDiffOptions,
): FormRebaseResult;FormRebaseOptions
interface FormRebaseOptions {
/**
* How to resolve a field changed on BOTH sides to a different value:
* - `'ours'` (default) — keep the local edit, discard upstream's value.
* - `'theirs'` — take upstream's value, discard the local edit.
* A field changed on both sides to the SAME value is never a conflict.
*/
conflict?: "ours" | "theirs";
}FormRebaseResult
interface FormRebaseResult {
/** The rebased WRAPPED container to install — a fresh clone of `upstream` with the local diff reapplied. */
next: Record<string, unknown>;
/** Paths changed on both sides to different values, plus ancestor-clear paths. De-duplicated. */
conflicts: string[];
/** The surviving diff of `next` against the new baseline (`upstream`); `[]` when fully clean. */
reapplied: FormFieldChange[];
}applyFormChanges(def, data, changes)
Reapplies a FormFieldChange[] onto a WRAPPED container, MUTATING it in place and returning the same reference — the inverse of buildFormDiff. A set change with after === undefined deletes the key; an array change is a whole-array set. Pass a clone, never the live fetched row.
function applyFormChanges(
def: FormDef,
data: Record<string, unknown>,
changes: FormFieldChange[],
): Record<string, unknown>;deepEqual(a, b)
Shared structural comparator behind the diff (order-sensitive arrays, NaN-equal, own-key structural). Use it for the same equality semantics the change tracker applies.
function deepEqual(a: unknown, b: unknown): boolean;deepClone(value, unwrap?)
Structural deep clone of plain JSON-ish data (objects / arrays / primitives / Date), own-enumerable keys only. The optional unwrap hook lets a framework strip a reactive proxy off each visited value first (vue-form passes Vue's toRaw). The single deep-clone primitive for the form engine — used by applyFormChanges, buildFormRebase, and vue-form's baseline snapshot.
type CloneUnwrap = (value: unknown) => unknown;
function deepClone<T>(value: T, unwrap?: CloneUnwrap): T;Path utilities
Form data is wrapped: { value: domainData }. These helpers de-reference the wrapper automatically.
joinPath(prefix, segment)
Joins a dot-separated path prefix with a segment. Empty-safe on both sides: an empty segment returns the prefix as-is, an empty prefix returns the segment as-is (no leading/trailing dots). The single primitive AsField / AsIterator and container renderers use to build absolute child paths. Re-exported from @atscript/vue-form for container-renderer code.
function joinPath(prefix: string, segment: string): string;getByPath(data, path) / setByPath(data, path, value)
function getByPath(obj: Record<string, unknown>, path: string): unknown;
function setByPath(obj: Record<string, unknown>, path: string, value: unknown): void;path === "" returns or replaces the entire obj.value. Intermediate objects are auto-created on set.
detectUnionVariant(value, variants)
Returns the index of the variant matching value. Uses a discriminator when atscript detects one, otherwise probes each variant's validator. Falls back to 0.
function detectUnionVariant(value: unknown, variants: FormUnionVariant[]): number;Value-help
ValueHelpInfo
Sync probe for a dictionary value-help prop (FK or @ui.valueHelp binding).
interface ValueHelpInfo {
/** HTTP path of the value-help target. */
url: string;
/** Field on the target that this FK / binding references — the value a pick commits. */
targetField: string;
/** Static dictionary scope (`@ui.valueHelp`'s filter), AND'd into every picker query. Since 0.1.148. */
filter?: FilterExpr;
/** Target fields the filter pins with `=` — constant in the picker, hidden from its columns. Since 0.1.148. */
pinned?: string[];
}extractValueHelp(prop) / extractLiteralOptions(prop) / isPureLiteralUnion(prop)
function extractValueHelp(prop: TAtscriptAnnotatedType): ValueHelpInfo | undefined;
function extractLiteralOptions(
prop: TAtscriptAnnotatedType,
outer?: TAtscriptAnnotatedType,
t?: UiT, // since 0.1.165 — words the default boolean labels; the active UI texts by default
): { key: string; label: string; value: string | number | boolean }[] | undefined; // `value` since 0.1.148
function isPureLiteralUnion(prop: TAtscriptAnnotatedType): boolean;
/** The labels of an unlabelled boolean's two values. Since 0.1.165. */
const DEFAULT_BOOLEAN_LABELS: Readonly<{ true: string; false: string }>; // { true: "Yes", false: "No" } — English; shown as UI_YES / UI_NO in the UI localeSince 0.1.165 extractLiteralOptions also answers a boolean: the options true / false with DEFAULT_BOOLEAN_LABELS unless @ui.literalLabel names them; null / undefined members of a union (boolean | null, 'a' | 'b' | null) are skipped instead of making the type option-less. isPureLiteralUnion is unchanged, so a form still renders a boolean as a checkbox.
extractValueHelp reads a @ui.valueHelp binding first (since 0.1.148) and returns its filter / pinned; a binding beats @db.rel.FK, and one whose target has no @db.http.path is ignored. It follows reference chains since 0.1.134: when the prop itself has no @db.rel.FK, it hops through ref.type().props[ref.field] (bounded, cycle-safe) until it meets a link that carries @db.rel.FK and whose target has @db.http.path, so a view field projected from an FK column resolves to the dictionary, not the intermediate table. The server does the same in /meta since @atscript/db 0.1.128.
You rarely call it directly: createFormDef() and createTableDef() run it once per field and store the result on the def (FormFieldDef.valueHelpInfo / ColumnDef.valueHelpInfo), which is where renderers read it from.
ValueHelpClient
Thin wrapper over a pre-built Client (from @atscript/db-client) that runs FK-flavoured searches against the value-help target. Most consumers stick to resolveValueHelp() plus their own Client; this class formalises the search semantics (full-text $search when the target is searchable, $or-regex fallback otherwise) so picker UIs don't reimplement them.
class ValueHelpClient {
constructor(client: Client);
search(resolved: ResolvedValueHelp, opts?: ValueHelpSearchOptions): Promise<ValueHelpResult>;
}
interface ValueHelpSearchOptions {
/** Search term. Empty / undefined returns all records. */
text?: string;
/** `"form"` = PK + label + descr; `"filter"` = all dict fields including attrs. Default: `"form"`. */
mode?: "form" | "filter";
/** Max results. Default: 20. */
limit?: number;
/** Override the computed `$select` fields. */
select?: string[];
/** Static scope (`ValueHelpInfo.filter`), AND'd with the search filter and with `$search`. Since 0.1.148. */
filter?: FilterExpr;
/**
* The field the picker commits (`ValueHelpInfo.targetField`). It is always selected and is the
* exact-match key of a non-searchable search. Default: `primaryKeys[0]`. Since 0.1.148.
*/
valueField?: string;
}
interface ValueHelpResult {
items: Record<string, unknown>[];
}setValueHelpCacheTtl(ms) / invalidateValueHelpCache(client?)
Since 0.1.151. In the browser, identical ValueHelpClient.search() calls on the same Client are shared: a call joins a request still in flight, and a settled result is reused for ms milliseconds (default 5000). A form with many pickers on one dictionary sends one request instead of one per picker. Server-side rendering never shares.
function setValueHelpCacheTtl(ms: number): void; // 0 = share in-flight only, < 0 = off
function invalidateValueHelpCache(client?: Client): void; // one client, or all when omittedresetMetaCache() clears every shared search, and so does a backend action or delete run through <AsTable>. Call invalidateValueHelpCache() after writing a dictionary any other way when pickers must refetch immediately.
resolveValueHelp(url, options?) / resetValueHelpCache()
Globally caches resolved value-help endpoints by URL (and UI locale) so multiple fields pointing at the same target share one /meta fetch. options.texts (since 0.1.165) is the app's UI texts, as for getMetaEntry. options.clientFactory (since 0.1.168) is the factory of the host the picker belongs to (a form's or a table's clientFactory): it builds the client when this call creates the entry for the URL and locale — e.g. after a locale switch — instead of the app-wide default.
function resolveValueHelp(
url: string,
options?: { texts?: MetaEntryOptions["texts"]; clientFactory?: ClientFactory },
): Promise<ResolvedValueHelp>;
function resetValueHelpCache(): void;
interface ResolvedValueHelp {
url: string;
primaryKeys: string[];
labelField: string;
descrField: string | undefined;
attrFields: string[];
filterableFields: string[];
sortableFields: string[];
searchable: boolean;
targetType: TAtscriptAnnotatedType;
}valueHelpDictPaths(resolved)
Returns the dict-view path set of a resolved value-help target (PKs + label + descr + attr fields). Filter dialogs use it to clamp visible columns to the dictionary subset.
function valueHelpDictPaths(resolved: ResolvedValueHelp): Set<string>;Option helpers
type TFormEntryOptions =
| { key: string; label: string; value?: string | number | boolean } // `value` since 0.1.165
| string;
function optKey(opt: TFormEntryOptions): string;
function optLabel(opt: TFormEntryOptions): string;
/** What a picker writes into the model: the typed literal (`true`, `3`) when the option has one, else the key (a string option is itself). Since 0.1.148; form options since 0.1.165. */
function optionValue(opt: TFormEntryOptions): string | number | boolean;
/** The `@ui.literalLabel` label of a union column's value (`undefined` when none) — what a custom cell shows. Since 0.1.148. */
function optionLabel(
column: { options?: { key: string; label: string }[] },
value: unknown,
): string | undefined;
function parseStaticOptions(
value: unknown,
t?: (text: string) => string | undefined, // since 0.1.170 — translates labels, never keys
): TFormEntryOptions[] | undefined;
function resolveOptions(
prop: TAtscriptAnnotatedType,
scope: Record<string, unknown>,
labelsFrom?: TAtscriptAnnotatedType, // since 0.1.165
t?: UiT, // since 0.1.165 — words the default boolean labels (pass `useAsLocale().t` from a component)
text?: (text: string) => string | undefined, // since 0.1.170 — translates `@ui.form.options` / `@ui.literalLabel` labels
): TFormEntryOptions[] | undefined;resolveOptions checks @ui.form.fn.options via the active resolver (with @atscript/ui-fns installed), then @ui.form.options, then literal-union (and, since 0.1.165, boolean) extraction. Pass field.labelsFrom as labelsFrom so an array item or a union variant also takes the enclosing prop's @ui.literalLabel labels. The built-in AsSelect, AsRadio and AsMultiSelect bind optionValue(opt), so a select over a boolean or a number union writes true / 3, not "true" / "3" (since 0.1.165); a custom picker should do the same.
Grid layout
Framework-agnostic helpers for @ui.form.grid.colSpan / @ui.form.grid.rowSpan. Each annotation has the shape { desktop, narrow? } — getFieldMeta(prop, UI_FORM_GRID_COL_SPAN) returns a GridSpanArgs.
const DEFAULT_COL_SPAN: number; // 12
const DEFAULT_ROW_SPAN: number; // 1
interface GridSpec {
col: { desktop: number; narrow: number };
row: { desktop: number; narrow: number };
}
interface GridSpanArgs {
desktop: string;
narrow?: string;
}
/** Accepts `"1"`–`"12"` and the aliases `"full"` (12), `"half"` (6), `"third"` (4). */
function parseColSpan(raw: string | undefined): number | undefined;
/** Accepts numeric strings `"1"`+; rejects `"0"`, negatives, decimals, aliases. */
function parseRowSpan(raw: string | undefined): number | undefined;
/** Compose a resolved spec from already-extracted `colSpan` / `rowSpan` annotation values. */
function resolveGridSpec(
colSpan: GridSpanArgs | undefined,
rowSpan: GridSpanArgs | undefined,
): GridSpec;
/** Emit `col-span-X` / `row-span-X` + `as-narrow:` variants for the spec. */
function buildGridClasses(spec: GridSpec): string;See Grid Layout.
Decimal helpers
Framework-agnostic decimal-string formatting and parsing — shared by @atscript/vue-form AsDecimal and @atscript/vue-table cells. Storage is string-only so DB-precision decimals never bounce through floats.
interface CurrencyDisplay {
decimals: number;
symbol: string;
}
interface DecimalParts {
integer: string;
fraction: string;
sign: "+" | "-";
}
interface FormatDecimalOptions {
currency?: string;
locale?: string;
/** Number of fractional digits to display. */
scale?: number;
}
function enforceScale(value: string, scale: number): string;
function formatDecimalForDisplay(value: string, opts?: FormatDecimalOptions): string;
function parseDecimalInput(input: string, opts?: FormatDecimalOptions): string | undefined;
function getCurrencyDecimals(currency: string, locale?: string): number;
function getCurrencyDisplayParts(currency: string, locale?: string): CurrencyDisplay;
function getDecimalSeparator(locale?: string): string;
function getThousandsSeparator(locale?: string): string;
function groupInteger(integer: string, locale?: string): string;
function joinDecimalString(parts: DecimalParts): string;
function splitDecimalString(value: string): DecimalParts;Column helpers
function getSortableColumns(def: TableDef): ColumnDef[];
function getFilterableColumns(def: TableDef): ColumnDef[];
function getColumn(def: TableDef, path: string): ColumnDef | undefined;getFilterableColumns returns the value-filterable columns (filterable: true). To list every column a filter UI can offer — existence-only columns included — filter with isColumnFilterable from @atscript/ui-table.
Error map utilities
/** Error-map key of the form-level error: `"__form"`. */
const FORM_ERROR_KEY: "__form";
/** Turn a validator's error list (`validator.errors`, or a thrown `ValidatorError`'s `errors`) into an error map. A root-level error (empty path) is keyed `__form`; the first error per path wins. */
function validatorErrorsToMap(
errors: ReadonlyArray<{ path: string; message: string }>,
): Record<string, string>;
/** Merge any number of partial error maps; falsy values are dropped, later maps win when both have a string. */
function mergeErrorMaps(
...maps: Array<Record<string, string | undefined> | undefined>
): Record<string, string>;
/** Return `errors` without the entries whose key is in `paths`. Identity-preserving: when no key matches, the ORIGINAL object is returned unchanged — compare `result !== errors` to detect pruning and skip spurious reactive writes. */
function omitPaths(
errors: Record<string, string>,
paths: ReadonlySet<string>,
): Record<string, string>;
/** Yields every ancestor prefix longest-first, including the path itself. `"a.b.c"` → `"a.b.c", "a.b", "a"`. */
function* iteratePathAncestors(path: string): Generator<string>;
/** Build `Map<absolutePath, descendantErrorCount>` so each struct in the tree renders an error-count badge in O(1). */
function buildDescendantErrorCounts(
errors: Record<string, string | undefined>,
): Map<string, number>;buildDescendantErrorCounts powers the count badges on AsObject headers.
validatorErrorsToMap builds the same map getFormValidator returns, so errors from your own Validator (e.g. a server-side check) feed :errors with the keys the form expects. FORM_ERROR_KEY and validatorErrorsToMap are exported since 0.1.158.
Type guards
function isArrayField(field: FormFieldDef): field is FormArrayFieldDef;
function isObjectField(field: FormFieldDef): field is FormObjectFieldDef;
function isUnionField(field: FormFieldDef): field is FormUnionFieldDef;
function isTupleField(field: FormFieldDef): field is FormTupleFieldDef;Misc utilities
function asArray<T>(x: T | T[]): T[];
/** `@ui.form.label.singular` for array fields; falls back to `"item"`. */
/** `@ui.form.label.singular`, else `t("UI_ITEM")` ("item"); `t` defaults to the active UI texts. */
function resolveSingularLabel(prop: TAtscriptAnnotatedType | undefined, t?: UiT): string;
/** Always returns a `MeasurementInfo` — individual fields are `undefined` when their annotation is absent. */
function extractMeasurement(prop: TAtscriptAnnotatedType): MeasurementInfo;
function str(value: unknown): string;extractMeasurement reads @db.amount.currency* / @db.unit* / @db.column.precision and returns a structured info record consumed by AsField for currency/unit adornments.
Client factory
ClientFactory is the contract Vue tables and value-help use to build HTTP clients. Override globally to inject auth headers / retries / interceptors.
type ClientFactory = (url: string, options?: ClientFactoryOptions) => Client; // `Client` from `@atscript/db-client`
type ClientFactoryOptions = Pick<ClientOptions, "metaKey" | "metaStore"> & { locale?: string }; // since 0.1.153; `locale` since 0.1.165
/** What `getDefaultClientFactory()` returns: generic like `Client` (since 0.1.164). */
type TypedClientFactory = <T extends AtscriptClientShape = AtscriptClientShape>(
url: string,
options?: ClientFactoryOptions,
) => Client<T>;
function setDefaultClientFactory(factory: ClientFactory): void;
function getDefaultClientFactory(): TypedClientFactory; // never `undefined` — falls back to `(url, options) => new Client(url, options)`
function resetDefaultClientFactory(): void;The factory you install is any function returning a Client, including one that hands back a cached client. The default factory you read back is generic: pass a model to get a typed client, or nothing for the untyped one. The type argument only types the client; nothing is checked at runtime.
import { Product } from "./models/product.as";
const products = getDefaultClientFactory()<typeof Product>("/api/db/tables/products");
await products.insert({ name: "Lamp", price: 12 }); // typed against ProductSpread the optional second argument into the Client options you build (since 0.1.153): the library passes metaKey for a table given metaKey, metaStore: false during server rendering, and since 0.1.165 the app's UI locale (when it has one), which the client sends as Accept-Language so /meta, action forms and error bodies come back in that language. A factory that ignores it still works, but loses those behaviors.
setDefaultClientFactory((url, options) => new Client(url, { ...options, fetch: appFetch }));A factory that hands back cached clients keeps one per URL and locale — a client answers in the locale it was created with:
const clients = new Map<string, Client>();
setDefaultClientFactory((url, options) => {
const key = `${url}#${options?.locale ?? ""}`;
let client = clients.get(key);
if (!client) clients.set(key, (client = new Client(url, { ...options, fetch: appFetch })));
return client;
});BREAKING
Since 0.1.165 the library asks a factory for a client per URL and locale (options.locale). A factory that caches clients by URL alone hands the first locale's client to every locale: /meta, action forms and errors come back in the wrong language, and that language's texts are merged into the other locale. Key cached clients by URL and options.locale, as above.
Meta cache
A single /meta fetch per URL and UI locale is cached across useTable instances and resolveValueHelp calls. getMetaEntry is synchronous — the promises on the entry resolve once the underlying fetch settles.
function getMetaEntry(
url: string,
factory?: ClientFactory,
options?: MetaEntryOptions,
): MetaCacheEntry;
/** One per UI locale (since 0.1.165): `texts` defaults to the active UI texts; `useTable` passes the app's. */
function getMetaTableDef(
entry: MetaCacheEntry,
texts?: { locale(): string | undefined; t: UiT },
): Promise<TableDef>; // since 0.1.153
function retainMetaEntry(entry: MetaCacheEntry): () => void; // since 0.1.154
function setMetaCacheMaxEntries(max?: number): void; // since 0.1.154 — default 100
function resetMetaCache(): void;
function setMetaCacheIdentity(key: string | null | undefined): void; // since 0.1.151
function getMetaCacheIdentity(): string | null | undefined; // since 0.1.153
function onMetaCacheReset(listener: () => void): () => void; // since 0.1.153
interface MetaEntryOptions {
metaKey?: string; // since 0.1.153 — `/meta` revalidation key, default the URL
/** Since 0.1.165 — the app's UI texts; default: the active ones. Components pass their app's. */
texts?: {
locale(): string | undefined;
merge(locale: string | undefined, served: unknown): void; // receives `/meta` `type.$i18n`
};
}
interface MetaCacheEntry {
client: Client; // from `@atscript/db-client`
meta: Promise<MetaResponse>;
type: Promise<TAtscriptAnnotatedType>; // pre-deserialized
resolved?: Promise<ResolvedValueHelp>; // populated lazily by `resolveValueHelp`
}/meta is projected per user — the server strips the columns, actions and value-help a role may not use — so the cache belongs to one signed-in viewer:
- Bind it to the viewer (since 0.1.151). Call
setMetaCacheIdentity(key)with a key naming the user and role (e.g.`${userId}:${role}`,nullwhen signed out) after login, after logout and whenever you reload the current user. A different key resets the cache; the same key keeps it. Without it, an SPA that logs out and signs in as another user without a page reload keeps rendering the previous user's columns and actions. Binding an identity also turns on the table-presets cache (since 0.1.153). resetMetaCache()drops every entry, the value-help searches shared under them and — since 0.1.151, with@atscript/db-client≥ 0.1.151 — the/metaeach cachedClientmemoizes (Client.invalidateMeta()), so aClientFactorythat reusesClientinstances refetches too. Since 0.1.153 it also clears the@atscript/db-clientmeta stores (the shared default one, and any custommetaStoreyour factory gave a cached client) and runs everyonMetaCacheResetlistener (the presets cache registers one). Components already mounted keep the entry they hold; remount them (e.g. navigate) to pick up the new/meta. Clients you use outside the cache (client.meta(),client.action()on a client you keep yourself) need their owninvalidateMeta()call.- Server rendering never caches (since 0.1.151). Without a browser
window, everygetMetaEntrycall builds a fresh entry, so one viewer's render never sees another's/meta, and since 0.1.153 the factory is asked formetaStore: falseso no/metabody lands in a process-wide store. Your server-sideClientFactorymust not hand oneClientto several requests either — aClientmemoizes its/meta. Never mutate themetaobject an entry resolves to: in-process consumers may share it by reference.
One entry per UI locale
Since 0.1.165. Each entry belongs to the locale of options.texts (in Vue, useTable and the value-help pass the app's texts from provideAsLocale; without texts, the active UI texts, see setUiLocale). Its client is created with that locale, so it asks /meta in it (Accept-Language); the texts /meta serves (type.$i18n: validator templates, built-in UI texts, translated expression texts) are merged into the app's texts for that locale once it arrives. After a locale switch, remounted views get the new locale's entry; switching back finds the previous one still cached. A server render passes the request's texts and gets a fresh, uncached entry as before; nothing is kept per locale in module state. On a server the process-wide texts (setUiLocale, the default without texts) never take served texts — one request's language must not reach the next.
Size limit
Since 0.1.154. The cache keeps the 100 most recently used entries (one per URL and locale); a hit makes an entry the most recent, and older entries beyond the limit are dropped (their type / TableDef, shared per ETag, go with the last entry using them). An app that opens many parametric URLs (/api/db/ticket-issue/${key}) no longer grows the cache for the life of the tab. 100 covers a page's tables plus the dictionaries its filters and forms pick from, and the recent navigation history; revisiting a dropped URL costs one /meta request — a 304 when the db-client meta store still holds its body. Dropping entries never clears the shared default meta store; a custom metaStore your factory supplied is cleared once no cached entry uses it any more, since a reset would no longer reach it.
setMetaCacheMaxEntries(300); // keep more; `Infinity` = no limit, no argument = back to 100Entries in use are never dropped: useTable (so every mounted <AsTableRoot> and its filter pickers) and the form value-help hold their entry until their component unmounts, and may push the cache past the limit while they do. Hold an entry you keep using outside those yourself:
const entry = getMetaEntry(url);
const release = retainMetaEntry(entry);
// … later, when done (idempotent):
release();An entry dropped while you still use it keeps working, but the next getMetaEntry(url) builds a new entry and Client (with the factory passed then), and a dropped entry's Client forgets its memoized /meta. resetMetaCache() and a new setMetaCacheIdentity() key still drop every entry, held or not.
Parametric mounts (metaKey)
Since 0.1.153, with @atscript/db-client ≥ 0.1.153. A controller mounted under a route parameter (/api/db/ticket-issue/:key) serves byte-identical /meta for every key, but each key is its own URL — so each new key used to download the full /meta. Pass the route template as metaKey and every key shares one entry in the db-client meta store: the first visit to a new key sends the stored ETag as If-None-Match and costs a 304.
getMetaEntry(`/api/db/ticket-issue/${key}`, undefined, { metaKey: "/api/db/ticket-issue/:key" });In Vue, pass it on the table: <AsTableRoot :url="/api/db/ticket-issue/${key}" meta-key="/api/db/ticket-issue/:key"> (or useTable(url, { metaKey })).
metaKeyis honoured on the firstgetMetaEntrycall per URL, likefactory. A customClientFactorymust spread its second argument into theClientoptions, or the key never reaches the client.- Entries whose
/metaresolved to the sameETag(Client.metaEtag()) share the deserializedtypeand theTableDef— a new key with an unchanged/metadeserializes nothing. This holds with or withoutmetaKey. - Cross-origin APIs must expose the header (
Access-Control-Expose-Headers: ETag) and allowIf-None-Matchin CORS preflights; otherwise the client falls back to plain downloads. - Use it only when
/metareally does not depend on the route parameter. An app-side meta overlay that reads the parameter makes the bodies (and ETags) differ — still correct, but no304s.
Cross-links
- Forms — Annotations Reference
- Forms — Validation
- Forms — References (FK)
- Tables — Annotations Reference
- @atscript/ui-fns — dynamic resolver
- atscript.dev —
.assyntax andValidator
UI texts
The built-in texts of the components, by code. Narrative: Language & Translations.
AS_UI_MESSAGES — @atscript/ui/messages
import { AS_UI_MESSAGES } from "@atscript/ui/messages";
const AS_UI_MESSAGES: Readonly<Record<AsUiMessageCode, string>>; // { UI_CANCEL: "Cancel", UI_FORM_ADD: "Add {item}", … }
type AsUiMessageCode = keyof typeof AS_UI_MESSAGES;Every code → its English template with {name} placeholders. The subpath imports nothing (no Vue, no DOM): register it on the server with moost's registerMessages(AS_UI_MESSAGES).
userText / fieldText / deserializeServedType / markServedType
Since 0.1.170. The model's own texts of a type compiled into the client, translated at render time with the same keys and rules the server translates a served schema by (Types compiled into the client).
/** Translates one text; `undefined` keeps it. A `UiT` (`useAsLocale().t`) is one. */
type UserTextT = (text: string) => string | undefined;
/** The value of metadata `key` in the app's language: a text key's strings are `t(text)`, any other key stays. Never changes `value`. */
function userText<T>(key: string, value: T, t?: UserTextT): T;
/** `userText` for the static metadata `key` of `prop`. */
function fieldText(prop: TAtscriptAnnotatedType, key: string, t?: UserTextT): unknown;
/** `deserializeAnnotatedType` for a served schema: one carrying `$i18n` (even an empty `{}`) is marked translated, and a form built from it does not translate it again. */
function deserializeServedType(json: TSerializedAnnotatedType): TAtscriptAnnotatedType;
/**
* Marks a root you got from a served, translated schema without `deserializeServedType`:
* `client.getActionForm()` with your own `getActionFormTexts()` handling, or a type carried
* through SSR state. Mark it when the server translated it (it returned `$i18n`).
*/
function markServedType<T extends TAtscriptAnnotatedType>(type: T): T;@atscript/vue-form's built-in components do this for you; use these in a custom component that renders a model text itself.
setUiLocale(locale, translate?)
type UiTextParams = Record<string, unknown>;
type UiTranslate = (
id: string,
params: UiTextParams | undefined,
locale: string | undefined,
) => string | undefined;
type UiT = (id: string, params?: UiTextParams) => string;
function setUiLocale(locale: string | undefined, translate?: UiTranslate): void;Browser-global locale (and optional translator) of the built-in texts, for an app without the Vue provider (provideAsLocale in @atscript/vue-form). Code that produces text outside components — createTableDef boolean labels, @atscript/ui-table chip wording — reads it unless given a t. translate works as in provideAsLocale; its id is a catalog code or, since 0.1.170, the source text of a model text. Never call it on a server rendering for many users.