@microsoft/rayfin-core package

Classes

BaseExpression

Base class for policy expressions, providing the and/or combinators.

ClaimRef

A reference to a claim on the authenticated user's token (for example, claims.sub).

ComparisonExpression

A comparison between two operands (for example, @claims.sub eq @item.user_id).

FieldRef

A reference to a field on the target item (for example, item.user_id).

LogicalExpression

A logical combination of two expressions (for example, (...) and (...)).

User

Built-in User entity representing the system's user table. This is a readonly entity managed by the Rayfin platform backend. Only safe fields are exposed - no passwords or sensitive data.

Interfaces

StandardSchemaV1

The Standard Schema interface.

FailureResult

The result interface if validation fails.

Issue

The issue interface of the failure output.

Options
PathSegment

The path segment interface of the issue.

Props

The Standard Schema properties interface.

SuccessResult

The result interface if validation succeeds.

Types

The Standard types interface.

BaseFieldOptions

Base field options that are common across all field types.

BooleanConstraints

Constraints for a boolean field (@boolean).

BooleanFieldOptions

Boolean field options for true/false values.

ComplexAction

A permission entry that pairs an action with optional field visibility and policy.

DatabasePolicy

A row-level security policy expressed as a database predicate.

DateConstraints

Constraints for a date field (@date).

DateFieldOptions

Date field options for temporal values.

DecimalFieldOptions

Decimal field options for precise numeric values.

EntityClass

Constructor type for a class decorated with @entity(), carrying entity metadata.

EntityInstance

An instance of a decorated entity class.

EntityMetadata

Metadata describing a decorated entity: its name, fields, permissions, and roles.

EnumConstraints

Constraints for an enum field (@set).

FieldMetadata

Metadata describing a single entity field, captured by field decorators.

FieldPermissions

Field-level visibility for a role, restricting which fields the role can access.

IEntity

Structural contract for all entity classes decorated with @entity().

Entities must either omit id entirely (database-generated) or declare id as a string. Non-string IDs are rejected at compile time.

The property name id aligns with the PrimaryKeyField type alias, which is the single source of truth for the PK field name.

IntFieldOptions

Integer field options for whole number fields.

NumberConstraints

Constraints for a numeric-format field (@int, @decimal).

PermissionConfig

A map of role name to the permissions granted to that role.

PolicyExpression

A composable policy expression that serializes to a DAB policy predicate.

PolicyOptions

Options for declaring a typed row-level security policy.

RayfinStandardSchema

A Standard Schema validator with a convenience validate() method.

  • Pass the object to any Standard Schema-compatible library (TanStack Form, Conform, tRPC v11, etc.) — they read ~standard.
  • Call .validate(value) directly from your own form code.
RelationshipConstraints

Constraints for a relationship field (@one, @many).

Relationship fields are not deeply validated by toStandardSchema — they are accepted as-is so that callers can attach related entities to form payloads without re-walking the graph.

RelationshipFieldOptions

Relationship field options for entity relationships.

RoleDeclaration

A fully-resolved role declaration stored in entity metadata.

RoleDeclarationOptions

Options passed to the @role() and @authenticated() decorators.

ScalarMapping

Maps Rayfin scalar keys to their corresponding TypeScript types.

SetFieldOptions

Options for the set field decorator, which constrains a string field to a fixed set of allowed values.

StoragePolicy

A row-level security policy applied to storage (blob) access.

StringConstraints

Constraints for a string-format field (@text, @uuid, @email).

TextFieldOptions

Text field options for string fields.

UUIDFieldOptions

UUID field options for unique identifier fields.

Type Aliases

InferInput

Infers the input type of a Standard.

InferOutput

Infers the output type of a Standard.

Result

The result interface of the validate function.

ActionPolicy

A row-level security policy, either a DatabasePolicy or a StoragePolicy.

ClaimName

The names of claims available on the authenticated user's token.

  • sub — the user's unique identifier.
  • email — the user's email address.
  • role — the user's role.
ClaimsDsl

The DSL for referencing the authenticated user's claims in a policy expression.

ComparisonOperator

Supported comparison operators in policy expressions.

DefaultFieldType

Resolves the type permitted for a field's default value, derived from whether the field is a scalar or an enum.

EntityBase

Base structural type for an entity used as a relationship target.

EnumFieldType

Narrows a FieldType to its enum form (an array of string literals), or never if it is not an enum field.

EnumValueType

Resolves an enum field type to the union of its allowed member values.

FieldConstraints

Discriminated union of all constraint shapes returned by getFieldConstraints.

FieldType

Any value a field's type parameter may take: a scalar, an enum (array of string literals), or a related entity.

FromEntityClass

Extracts the entity instance type from an EntityClass.

ItemProxy

A typed proxy over an entity's fields, exposing each field as a FieldRef for use in policy expressions.

LogicalOperator

Supported logical operators in policy expressions.

Operand

A value that can appear on either side of a comparison: an expression, primitive, Date, or null.

PermissionAction

A permission entry: either a bare SimpleAction or a ComplexAction with field visibility and policy.

PrimaryKeyField

Canonical primary key field name as a string literal type.

All type-level references to the PK field name across rayfin-core and rayfin-data use this alias instead of hardcoded 'id' literals.

RelationFieldType

Narrows a FieldType to the entity class it relates to, or never if it is not a relationship field.

Scalar

Resolves a scalar key (such as 'string') to the canonical scalar type name (such as 'String') used by the generated schema.

ScalarFieldType

Narrows a FieldType to its scalar form, or never if it is not a scalar field.

ScalarTypes

Union of all scalar key identifiers (the keys of ScalarMapping).

ScalarValueType

Resolves a scalar field type to its runtime value type (for example, the 'string' scalar resolves to string).

Scalars

Union of all canonical scalar type names supported by Rayfin fields.

SimpleAction

The set of actions that a role can be granted on an entity.

'*' grants all actions. Used by the @role() and @authenticated() decorators.

Enums

FieldFormat

Field format enum for decorator metadata.

Defines the set of supported field formats that decorators can use to specify the database column type and serialization format.

RelationshipTypes

The set of supported relationship cardinalities.

Functions

authenticated<TEntity>(SimpleAction | SimpleAction[], RoleDeclarationOptions<TEntity>)

Shorthand decorator for authenticated role.

Equivalent to @role('authenticated', actions, options). Authenticated roles require a valid user session.

Example

@entity()
@authenticated('*', {
  check: (claims, item) => claims.sub.eq(item.user_id),
})
export class Todo {
  @uuid()
  id!: string;
  @text()
  user_id!: string;
}
blob(string)

Storage folder decorator for blob storage management.

Marks a class as representing a storage folder configuration. Folder settings inferred from class name and optional parameter:

  • Folder name: parameter value or kebab-case class name
  • Permissions: inferred from @role() decorators
  • Visibility: inferred from permission configuration

Example

@blob('uploads')
@role('authenticated', '*')
export class FileModel {
  @uuid()
  id!: string;

  @text()
  fileName!: string;
}
boolean(BooleanFieldOptions)

Boolean field decorator for true/false values.

Specifies a field as boolean type, mapping to database boolean types (BIT, BOOLEAN, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @boolean()
  isCompleted!: boolean;    // Boolean field (required by default)

  @boolean({ optional: true })
  isArchived?: boolean;     // Optional boolean field
}
createItemProxy<T>()

Creates an ItemProxy that resolves any accessed property to a FieldRef.

date(DateFieldOptions)

Date/datetime field decorator for temporal values.

Specifies a field as date type, mapping to database datetime types (DATETIME2, TIMESTAMP, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @date()
  createdAt!: Date;         // Date field (required by default)

  @date({ optional: true })
  dueDate?: Date;           // Optional date field
}
decimal(DecimalFieldOptions)

Decimal field decorator for precise numeric values.

Specifies a field as decimal/numeric type, mapping to database decimal types (DECIMAL, NUMERIC, etc. depending on dialect). Useful for monetary values and precise numeric calculations.

When no precision or scale is specified, defaults to DECIMAL(18,2) on MSSQL and NUMERIC(18,2) on PostgreSQL. If either precision or scale is provided, both must be specified.

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Product {
  @uuid()
  id!: string;

  @decimal()
  price!: number;           // DECIMAL(18,2) by default

  @decimal({ precision: 10, scale: 4 })
  weight!: number;          // DECIMAL(10,4)

  @decimal({ optional: true })
  discount?: number;        // Optional decimal field
}
email(TextFieldOptions)

Email field decorator for email addresses.

Specifies a field as email type, mapping to database string types with email format validation hints.

The regex pattern is similar to RFC 5322, but has some extra restrictions to catch common mistakes. If you need full UTF-8 support or less strict validation, use a text() field with a custom regex.

The format hint can be used for validation and UI rendering. Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class User {
  @uuid()
  id!: string;

  @email({ unique: true })
  emailAddress!: string;    // Email field with unique constraint (required by default)

  @text()
  name!: string;
}
entity(string)

Marker decorator to indicate this class should be analyzed as a DAB entity.

Entity settings inferred from class name and conventions:

  • Entity name: kebab-case class name (e.g., "Todo" → "todo")
  • Source table: pluralized snake_case name (e.g., "Todo" → "todos")
  • Schema: default schema for the target database dialect

Example

@entity()
export class Todo {
  @uuid()
  id!: string;
}
fieldMetadataToConstraints(FieldMetadata<FieldType, keyof ScalarMapping>)

Translate a raw FieldMetadata entry into a constraint object that is convenient to consume from UI code (form labels, hints, etc.).

getFieldConstraints<T, K>(EntityClass<T>, K & string)

Look up the validation constraints declared by a decorator on a single entity field. Returns undefined when the field does not exist.

Useful for UI code that needs to render constraint hints (e.g., a maxLength indicator on a text input) without taking on the cost of building a full Standard Schema for the entity.

getPrimaryKeyField()

Return the canonical primary key field name at runtime.

All runtime references to the PK field name across rayfin-core and rayfin-data call this function instead of using hardcoded 'id' literals.

int(IntFieldOptions)

Integer field decorator for whole numbers.

Specifies a field as integer type, mapping to database integer types (INT, INTEGER, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @int()
  priority!: number;        // Integer field (required by default)

  @int({ optional: true })
  order?: number;           // Optional integer field
}
many<U>(() => U, RelationshipFieldOptions)

One-to-many relationship decorator.

Marks a field as a relationship to multiple entity instances (collection). Represents the inverse side of a many-to-one relationship. The target entity type should be specified as an array in the TypeScript type annotation.

Example

@entity()
export class Category {
  @uuid()
  id!: string;

  @text()
  name!: string;

  @many(() => Todo)
  todos!: Todo[];          // One-to-many: reverse side of Todo.category
}

@entity()
export class User {
  @uuid()
  id!: string;

  @many(() => Todo)
  assignedTodos!: Todo[];  // One-to-many relationship
}
one<U>(() => U, RelationshipFieldOptions)

One-to-one or many-to-one relationship decorator.

Marks a field as a relationship to a single entity instance. Automatically generates a foreign key column (e.g., category_id for a category field). The target entity type should be specified in the TypeScript type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @one(() => Category)
  category!: Category;     // Many-to-one: generates category_id FK

  @one(() => User)
  assignee?: User;         // Optional many-to-one relationship
}
role<TEntity>("authenticated", SimpleAction | SimpleAction[], RoleDeclarationOptions<TEntity>)

Class-level role decorator.

Declares permissions for the built-in 'authenticated' role with optional typed policy and field visibility.

set<T>(T)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set('low', 'medium', 'high')
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint
}
set<T>(SetFieldOptions<T>)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set({ enum: ['low', 'medium', 'high'] })
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint

  @set({ enum: ['pending', 'completed'], optional: true })
  status?: 'pending' | 'completed';      // Optional enum field
}
set<T>(Omit<SetFieldOptions<T>, "enum">, T)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set({}, 'low', 'medium', 'high')
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint

  @set({ optional: true }, 'pending', 'completed')
  status?: 'pending' | 'completed';      // Optional enum field
}
text(TextFieldOptions)

Text field decorator for long text content.

Specifies a field as text type, mapping to database text types (NVARCHAR(MAX), TEXT, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;           // Required text field (default)

  @text({ optional: true })
  description?: string;     // Optional text field

  @text({ unique: true })
  slug!: string;            // Unique and required text field
}
toStandardSchema<T, K>(EntityClass<T>, { omit?: readonly K[] })

Build a Standard Schema validator for an entity class declared with the Rayfin decorators (@entity, @text, @uuid, @int, @boolean, @set, …).

The returned object implements the ~standard contract and can be passed to any Standard Schema-compatible library. It also exposes a convenience .validate() method so form code doesn't need ['~standard'].validate().

The primary key field (id) is automatically omitted — form schemas never validate server-generated IDs. Pass additional field names via omit for other server-managed fields like timestamps.

Example

import { toStandardSchema } from '@microsoft/rayfin-core';
import { Todo } from '../rayfin/data/Todo.js';

// id is auto-omitted — only list additional fields to exclude
const todoInput = toStandardSchema(Todo, {
  omit: ['createdAt', 'updatedAt'] as const,
});

const result = todoInput.validate(formValues);
if (result.issues) {
  // show errors keyed by issue.path[0]
} else {
  await api.createTodo(result.value);
}
uuid(UUIDFieldOptions)

UUID field decorator for unique identifiers.

Specifies a field as UUID/GUID type, mapping to database UUID types (UNIQUEIDENTIFIER, UUID, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields. Fields named id are automatically inferred as primary keys. Use { unique: true } for unique constraint.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;              // UUID primary key (required by default)

  @uuid()
  userId!: string;          // UUID foreign key (required by default)

  @uuid({ optional: true })
  optionalId?: string;      // Optional UUID field

  @text()
  title!: string;
}

Variables

SystemEntityNames

Set of system entity names that are always valid relationship targets. These entities are managed by the Rayfin platform and do not need to be included in user schema arrays.

claims

The root claims DSL used inside policy callbacks (for example, claims.sub.eq(...)).

item

A generic, untyped item proxy for convenience where a typed entity is not available.

Function Details

authenticated<TEntity>(SimpleAction | SimpleAction[], RoleDeclarationOptions<TEntity>)

Shorthand decorator for authenticated role.

Equivalent to @role('authenticated', actions, options). Authenticated roles require a valid user session.

Example

@entity()
@authenticated('*', {
  check: (claims, item) => claims.sub.eq(item.user_id),
})
export class Todo {
  @uuid()
  id!: string;
  @text()
  user_id!: string;
}
function authenticated<TEntity>(actions?: SimpleAction | SimpleAction[], options?: RoleDeclarationOptions<TEntity>): (target: constructor<TEntity>, context: ClassDecoratorContext<constructor<TEntity>>) => void

Parameters

actions

SimpleAction | SimpleAction[]

The actions this role can perform (default: '*' for all actions)

options

RoleDeclarationOptions<TEntity>

Optional policy and field visibility configuration

Returns

(target: constructor<TEntity>, context: ClassDecoratorContext<constructor<TEntity>>) => void

blob(string)

Storage folder decorator for blob storage management.

Marks a class as representing a storage folder configuration. Folder settings inferred from class name and optional parameter:

  • Folder name: parameter value or kebab-case class name
  • Permissions: inferred from @role() decorators
  • Visibility: inferred from permission configuration

Example

@blob('uploads')
@role('authenticated', '*')
export class FileModel {
  @uuid()
  id!: string;

  @text()
  fileName!: string;
}
function blob(_folderName?: string): (_target: T, context: ClassDecoratorContext<T>) => void

Parameters

_folderName

string

Optional folder name (defaults to kebab-case class name)

Returns

(_target: T, context: ClassDecoratorContext<T>) => void

boolean(BooleanFieldOptions)

Boolean field decorator for true/false values.

Specifies a field as boolean type, mapping to database boolean types (BIT, BOOLEAN, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @boolean()
  isCompleted!: boolean;    // Boolean field (required by default)

  @boolean({ optional: true })
  isArchived?: boolean;     // Optional boolean field
}
function boolean(options?: BooleanFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, boolean | undefined>) => void

Parameters

options
BooleanFieldOptions

Boolean field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, boolean | undefined>) => void

A class field decorator.

createItemProxy<T>()

Creates an ItemProxy that resolves any accessed property to a FieldRef.

function createItemProxy<T>(): ItemProxy<T>

Returns

A proxy where each field access yields a field reference.

date(DateFieldOptions)

Date/datetime field decorator for temporal values.

Specifies a field as date type, mapping to database datetime types (DATETIME2, TIMESTAMP, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @date()
  createdAt!: Date;         // Date field (required by default)

  @date({ optional: true })
  dueDate?: Date;           // Optional date field
}
function date(options?: DateFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, Date | undefined>) => void

Parameters

options
DateFieldOptions

Date field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, Date | undefined>) => void

A class field decorator.

decimal(DecimalFieldOptions)

Decimal field decorator for precise numeric values.

Specifies a field as decimal/numeric type, mapping to database decimal types (DECIMAL, NUMERIC, etc. depending on dialect). Useful for monetary values and precise numeric calculations.

When no precision or scale is specified, defaults to DECIMAL(18,2) on MSSQL and NUMERIC(18,2) on PostgreSQL. If either precision or scale is provided, both must be specified.

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Product {
  @uuid()
  id!: string;

  @decimal()
  price!: number;           // DECIMAL(18,2) by default

  @decimal({ precision: 10, scale: 4 })
  weight!: number;          // DECIMAL(10,4)

  @decimal({ optional: true })
  discount?: number;        // Optional decimal field
}
function decimal(options?: DecimalFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, number | undefined>) => void

Parameters

options
DecimalFieldOptions

Decimal field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, number | undefined>) => void

A class field decorator.

email(TextFieldOptions)

Email field decorator for email addresses.

Specifies a field as email type, mapping to database string types with email format validation hints.

The regex pattern is similar to RFC 5322, but has some extra restrictions to catch common mistakes. If you need full UTF-8 support or less strict validation, use a text() field with a custom regex.

The format hint can be used for validation and UI rendering. Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class User {
  @uuid()
  id!: string;

  @email({ unique: true })
  emailAddress!: string;    // Email field with unique constraint (required by default)

  @text()
  name!: string;
}
function email(options?: TextFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

Parameters

options
TextFieldOptions

Email field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

A class field decorator.

entity(string)

Marker decorator to indicate this class should be analyzed as a DAB entity.

Entity settings inferred from class name and conventions:

  • Entity name: kebab-case class name (e.g., "Todo" → "todo")
  • Source table: pluralized snake_case name (e.g., "Todo" → "todos")
  • Schema: default schema for the target database dialect

Example

@entity()
export class Todo {
  @uuid()
  id!: string;
}
function entity(name?: string): (_target: T, _context: ClassDecoratorContext<T>) => void

Parameters

name

string

Optional explicit entity name; defaults to the class name.

Returns

(_target: T, _context: ClassDecoratorContext<T>) => void

A class decorator that registers the entity.

fieldMetadataToConstraints(FieldMetadata<FieldType, keyof ScalarMapping>)

Translate a raw FieldMetadata entry into a constraint object that is convenient to consume from UI code (form labels, hints, etc.).

function fieldMetadataToConstraints(meta: FieldMetadata<FieldType, keyof ScalarMapping>): FieldConstraints

Parameters

meta

FieldMetadata<FieldType, keyof ScalarMapping>

The field metadata entry to translate.

Returns

The constraint object describing the field.

getFieldConstraints<T, K>(EntityClass<T>, K & string)

Look up the validation constraints declared by a decorator on a single entity field. Returns undefined when the field does not exist.

Useful for UI code that needs to render constraint hints (e.g., a maxLength indicator on a text input) without taking on the cost of building a full Standard Schema for the entity.

function getFieldConstraints<T, K>(entity: EntityClass<T>, field: K & string): FieldConstraints | undefined

Parameters

entity

EntityClass<T>

The entity class to inspect.

field

K & string

The name of the field whose constraints to retrieve.

Returns

FieldConstraints | undefined

The field's constraints, or undefined when the field does not exist.

getPrimaryKeyField()

Return the canonical primary key field name at runtime.

All runtime references to the PK field name across rayfin-core and rayfin-data call this function instead of using hardcoded 'id' literals.

function getPrimaryKeyField(): PrimaryKeyField

Returns

int(IntFieldOptions)

Integer field decorator for whole numbers.

Specifies a field as integer type, mapping to database integer types (INT, INTEGER, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @int()
  priority!: number;        // Integer field (required by default)

  @int({ optional: true })
  order?: number;           // Optional integer field
}
function int(options?: IntFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, number | undefined>) => void

Parameters

options
IntFieldOptions

Integer field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, number | undefined>) => void

A class field decorator.

many<U>(() => U, RelationshipFieldOptions)

One-to-many relationship decorator.

Marks a field as a relationship to multiple entity instances (collection). Represents the inverse side of a many-to-one relationship. The target entity type should be specified as an array in the TypeScript type annotation.

Example

@entity()
export class Category {
  @uuid()
  id!: string;

  @text()
  name!: string;

  @many(() => Todo)
  todos!: Todo[];          // One-to-many: reverse side of Todo.category
}

@entity()
export class User {
  @uuid()
  id!: string;

  @many(() => Todo)
  assignedTodos!: Todo[];  // One-to-many relationship
}
function many<U>(target: () => U, options?: RelationshipFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, InstanceType<U>[] | undefined>) => void

Parameters

target

() => U

A thunk returning the related entity class.

options
RelationshipFieldOptions

Relationship field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, InstanceType<U>[] | undefined>) => void

A class field decorator.

one<U>(() => U, RelationshipFieldOptions)

One-to-one or many-to-one relationship decorator.

Marks a field as a relationship to a single entity instance. Automatically generates a foreign key column (e.g., category_id for a category field). The target entity type should be specified in the TypeScript type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @one(() => Category)
  category!: Category;     // Many-to-one: generates category_id FK

  @one(() => User)
  assignee?: User;         // Optional many-to-one relationship
}
function one<U>(target: () => U, options?: RelationshipFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, InstanceType<U> | undefined>) => void

Parameters

target

() => U

A thunk returning the related entity class.

options
RelationshipFieldOptions

Relationship field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, InstanceType<U> | undefined>) => void

A class field decorator.

role<TEntity>("authenticated", SimpleAction | SimpleAction[], RoleDeclarationOptions<TEntity>)

Class-level role decorator.

Declares permissions for the built-in 'authenticated' role with optional typed policy and field visibility.

function role<TEntity>(roleName: "authenticated", actions: SimpleAction | SimpleAction[], options?: RoleDeclarationOptions<TEntity>): (target: constructor<TEntity>, context: ClassDecoratorContext<constructor<TEntity>>) => void

Parameters

roleName

"authenticated"

The role name (currently only 'authenticated')

actions

SimpleAction | SimpleAction[]

The actions this role can perform

options

RoleDeclarationOptions<TEntity>

Optional policy and field visibility configuration

Returns

(target: constructor<TEntity>, context: ClassDecoratorContext<constructor<TEntity>>) => void

set<T>(T)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set('low', 'medium', 'high')
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint
}
function set<T>(values: T): (target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

Parameters

values

T

Array of allowed string values (must have at least one value)

Returns

(target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

set<T>(SetFieldOptions<T>)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set({ enum: ['low', 'medium', 'high'] })
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint

  @set({ enum: ['pending', 'completed'], optional: true })
  status?: 'pending' | 'completed';      // Optional enum field
}
function set<T>(options: SetFieldOptions<T>): (target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

Parameters

options

SetFieldOptions<T>

Options object including the enum values

Returns

(target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

set<T>(Omit<SetFieldOptions<T>, "enum">, T)

Set field decorator for constrained string values.

Specifies a field as an set (or enum-like) type with a limited set of allowed values. Maps to database string types (NVARCHAR, VARCHAR, etc.) with check constraints. The set values should match the TypeScript union type annotation.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;

  @set({}, 'low', 'medium', 'high')
  priority!: 'low' | 'medium' | 'high';  // Enum field with check constraint

  @set({ optional: true }, 'pending', 'completed')
  status?: 'pending' | 'completed';      // Optional enum field
}
function set<T>(options: Omit<SetFieldOptions<T>, "enum">, values: T): (target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

Parameters

options

Omit<SetFieldOptions<T>, "enum">

Options object including the enum values

values

T

Returns

(target: unknown, context: ClassFieldDecoratorContext<unknown, T[number] | undefined>) => void

text(TextFieldOptions)

Text field decorator for long text content.

Specifies a field as text type, mapping to database text types (NVARCHAR(MAX), TEXT, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;

  @text()
  title!: string;           // Required text field (default)

  @text({ optional: true })
  description?: string;     // Optional text field

  @text({ unique: true })
  slug!: string;            // Unique and required text field
}
function text(options?: TextFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

Parameters

options
TextFieldOptions

Text field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

A class field decorator.

toStandardSchema<T, K>(EntityClass<T>, { omit?: readonly K[] })

Build a Standard Schema validator for an entity class declared with the Rayfin decorators (@entity, @text, @uuid, @int, @boolean, @set, …).

The returned object implements the ~standard contract and can be passed to any Standard Schema-compatible library. It also exposes a convenience .validate() method so form code doesn't need ['~standard'].validate().

The primary key field (id) is automatically omitted — form schemas never validate server-generated IDs. Pass additional field names via omit for other server-managed fields like timestamps.

Example

import { toStandardSchema } from '@microsoft/rayfin-core';
import { Todo } from '../rayfin/data/Todo.js';

// id is auto-omitted — only list additional fields to exclude
const todoInput = toStandardSchema(Todo, {
  omit: ['createdAt', 'updatedAt'] as const,
});

const result = todoInput.validate(formValues);
if (result.issues) {
  // show errors keyed by issue.path[0]
} else {
  await api.createTodo(result.value);
}
function toStandardSchema<T, K>(entity: EntityClass<T>, options?: { omit?: readonly K[] }): RayfinStandardSchema<Omit<T, K | (PrimaryKeyField & (keyof T))>>

Parameters

entity

EntityClass<T>

Entity class decorated with @entity().

options

{ omit?: readonly K[] }

Optional configuration.

  • omit: Field names to exclude from the schema (in addition to id). The validated value type is narrowed to Omit<T, K | 'id'>. Omitted fields are also rejected as unknown if they appear in the input. The K extends keyof T constraint catches typos at compile time.

Returns

RayfinStandardSchema<Omit<T, K | (PrimaryKeyField & (keyof T))>>

uuid(UUIDFieldOptions)

UUID field decorator for unique identifiers.

Specifies a field as UUID/GUID type, mapping to database UUID types (UNIQUEIDENTIFIER, UUID, etc. depending on dialect).

Fields are required by default. Use { optional: true } for nullable fields. Fields named id are automatically inferred as primary keys. Use { unique: true } for unique constraint.

Example

@entity()
export class Todo {
  @uuid()
  id!: string;              // UUID primary key (required by default)

  @uuid()
  userId!: string;          // UUID foreign key (required by default)

  @uuid({ optional: true })
  optionalId?: string;      // Optional UUID field

  @text()
  title!: string;
}
function uuid(options?: UUIDFieldOptions): (_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

Parameters

options
UUIDFieldOptions

UUID field configuration options.

Returns

(_: T, context: ClassFieldDecoratorContext<unknown, string | undefined>) => void

A class field decorator.

Variable Details

SystemEntityNames

Set of system entity names that are always valid relationship targets. These entities are managed by the Rayfin platform and do not need to be included in user schema arrays.

SystemEntityNames: Set<string>

Type

Set<string>

claims

The root claims DSL used inside policy callbacks (for example, claims.sub.eq(...)).

claims: ClaimsDsl

Type

item

A generic, untyped item proxy for convenience where a typed entity is not available.

item: ItemProxy<Record<string, unknown>>

Type

ItemProxy<Record<string, unknown>>