# TypeScript author

Describe your software once, in TypeScript: schemas, operations, events, policies. The `dryv` CLI compiles it and generates code from it with reusable packs.

## Install

```bash
npm install -D @dryvcode/author @dryvcode/compiler
curl -fsSL https://dryvcode.com/install.sh | sh
dryv init --author typescript --author-path dryv/contracts/index.ts --yes
```

Create `dryv/contracts/index.ts` with the example below, then run `dryv validate` and `dryv plan`. Run `dryv docs authoring` for tips. This package only describes meaning; it does not generate code or write files.

## Quick start

## Model

```text
full definitions -> Group registration -> lightweight typed refs
                                      \
                                       -> App composition
```

Groups own full declarations. Registration names supply local identity and return lightweight typed refs. Relationships use those refs rather than raw builders.

```ts
import { dryv, field, property, schema } from "@dryvcode/author";

const shared = dryv.group({ name: "shared" });
const values = shared.properties({
  UserId: property.string.uuid(),
  Email: property.string.email(),
  CreatedAt: property.temporal.instant().precision("millisecond"),
});

const users = dryv.group({ name: "users" });
const schemas = users.schemas({
  User: schema({
    id: field(values.UserId).system(),
    email: field(values.Email),
    createdAt: field(values.CreatedAt).system(),
  }),
});

schemas.User.field("email");

export default dryv.app({ name: "example" }).groups(shared, users);
```

The compiler qualifies local identities at the Author/Runtime boundary:

```text
users + User -> users.User -> #/schemas/users.User
```

Runtime registries remain flat by semantic kind. Group ancestry affects semantic scope, never canonical declaration identity. `.` is reserved for compiler qualification and cannot appear in authored Group names, App names, or registration keys.

## Registered refs

Reusable declarations must be registered before another declaration can reference them.

```ts
const Id = property.string.uuid();

// invalid: raw definition
// field(Id)

const shared = dryv.group({ name: "shared" });
const values = shared.properties({ Id });

field(values.Id); // valid
```

This rule applies across Schemas, Properties, Policies, Operations, Events, Failures, Workflows, Views, Presentations, Features, and Applications. `unknown()` and `dynamic()` are intrinsic targets and remain inline.

## Properties

`group.properties({...})` classifies reusable value meaning into the canonical registries:

```text
primitives
enums
composites
literals
unions
records
tuples
generics
temporal
```

There are no reusable `unknown` or `dynamic` registries.

Examples:

```ts
const base = shared.properties({
  Id: property.string.uuid(),
  Name: property.string(),
  Count: property.number.nonNegativeInteger(),
  Active: property.literal("active"),
  CreatedAt: property.temporal.instant().precision("millisecond"),
});

const advanced = shared.properties({
  Coordinates: property.composite({
    x: field(base.Count),
    y: field(base.Count),
  }),
  Identifier: property.union({
    discriminant: "kind",
    members: { id: base.Id, active: base.Active },
  }),
  Pair: property.tuple(base.Id, base.Active),
  Labels: property.record(base.Id, base.Name),
  Box: property.generic.define((T) => property.composite({ value: field(T) })),
});
```

Generic applications consume a registered generic definition and registered arguments:

```ts
shared.properties({
  UserBox: property.generic.apply(advanced.Box, [schemas.User]),
});
```

Properties may carry their property-specific description/examples/lifecycle semantics. Universal `tags` and structured `explanations` are only exposed where the Runtime contract supports them; they are not silently accepted on Properties or Expressions.

## Expressions

Expressions are named reusable declarations with a closed Dryv vocabulary.

```ts
import { context, expression, value } from "@dryvcode/author";

const expressions = users.expressions({
  IsOwner: expression.equal(
    context("actor", "id"),
    context("resource", "ownerId"),
  ),
  CurrentDate: expression.date(
    expression.inTimeZone(expression.now(), "Africa/Nairobi"),
  ),
  DefaultName: value("unknown"),
});
```

Registered Expression refs are consumed by Policy rules, temporal dynamic bounds, Schema defaults, and composite invariants. There is no arbitrary custom-AST escape hatch.

## Policies

Policies are reusable semantic requirements, not framework guards or middleware definitions.

```ts
const policies = users.policies({
  CanRead: policy()
    .requires({ actor: schemas.User, resource: schemas.User })
    .provides({ id: values.UserId })
    .rule(expressions.IsOwner),
});
```

A Policy may intentionally have no rule. Context values are registered Property/Schema refs and rules are registered boolean Expression refs.

Groups and Applications may also declare scope policies:

```ts
users.policies(policies.CanRead);

dryv.app({ name: "example" }).groups(users).policies(policies.CanRead);
```

Effective inherited scope is Runtime/inspection responsibility; Authoring records only the declared scope.

## Schemas

Schema field meaning is flat in Author state and canonical Runtime IR. There is no field `usage` wrapper.

```ts
const users = dryv.group({ name: "users" });
const schemas = users.schemas({
  User: schema({
    id: field(values.UserId).system(),
    email: field(values.Email)
      .optional()
      .nullable()
      .query({ filter: ["equal", "contains"], sort: true, search: true }),
    names: field(values.Name).array({ min: 1 }),
  }),
});
```

Field helpers include:

- `.required()` / `.optional()`;
- `.nullable()`;
- `.array(...)`;
- `.default(...)`;
- `.system()` / `.createOnly()`;
- `.query(...)`;
- `.sensitive()`;
- `.policy(...)`;
- `.relation(...)` / `.related(...)`;
- `.sources(...)`;
- `.tags(...)` / `.explain(...)` where Runtime field metadata is supported.

The retired `.mutation(...)` shortcut is intentionally not supported.

### Effective field references and relations

`SchemaRef.field(...)` represents semantic effective-field identity. The compiler emits `{ $ref: <schema>, field: <name> }`, not a physical `/fields/...` pointer.

```ts
const entities = users.schemas({
  Entity: schema({ id: field(values.UserId) }).abstract(),
});

users.schemas({
  Membership: schema({
    ownerId: field(values.UserId).relation({
      target: () => entities.Entity.field("id"),
      cardinality: relation.manyToOne(),
      onDelete: relation.restrict(),
    }),
  }),
});
```

### Operations: one input, one output

An operation takes one input, like a component's props, and returns one output:

```ts
const UpdateUser = operation()
  .input({ userId: sharedProperties.Id, body: userSchemas.UpdateUserBody }) // named fields
  .output(userSchemas.User);
const FindUsers = operation()
  .input(userSchemas.UserListQuery)
  .output(userSchemas.UserList); // one schema

UpdateUser.facets({
  http: http("PATCH", "/users/{userId}")
    .input(UpdateUser.in.userId, path()) // the path name defaults to the field name
    .input(UpdateUser.in.body, body())
    .output(UpdateUser.out, respond(200)),
});
FindUsers.facets({
  http: http("GET", "/users")
    .input(FindUsers.in, queryObject())
    .output(FindUsers.out),
});
```

### Trusted record scope

Bind a persisted Schema field to a named value from a Policy that the Operation requires:

```ts
const currentTenant = policies.CurrentTenant;
const ListOrders = operation()
  .role("list")
  .input(schemas.OrderQuery)
  .output(schemas.OrderRead)
  .requires(currentTenant)
  .scope({
    target: schemas.Order.field("tenantId"),
    source: { policy: currentTenant, name: "tenantId" },
  });
```

Use multiple binding objects for multiple persisted fields. The compiler preserves the explicit schema-field and Policy references, sorts canonical bindings deterministically, and omits `scope` when none is declared. Runtime validates role, persistence, references and types. Authoring does not evaluate Policies or execute queries; the generated application must obtain trusted values from its Policy evaluation context and apply the constraints.

`Op.in.<field>` refers to one field, `Op.in` to a whole schema input, and `Op.out` to the output. `idempotentBy("userId")`, `source.resolve(op).output().input("userId", source.value())` and `part.invoke(op, { userId: "contextName" })` also use field names.

### Field-local sources

There is no root Source declaration or `group.sources(...)` registry. Source meaning belongs to the Schema field that consumes it.

```ts
const operations = users.operations({
  ListStatuses: operation().output(statusSchemas.StatusList),
});

users.schemas({
  Filter: schema({
    status: field(values.Name).sources({
      choices: source.options(operations.ListStatuses).output(),
    }),
  }),
});
```

Input bindings use `source.value()` for the consuming field value or `source.field(() => schemaRef.field(...))` for another effective Schema field. If a source operation has exactly one output, the compiler may infer it; otherwise `.output(...)` is required.

### Storage facets

There is no root Storage declaration or storage registry. Portable storage semantics belong to `schema.facets.storage`.

```ts
const stored = users.schemas({
  User: schema({
    id: field(values.UserId),
    email: field(values.Email),
  }).facets({
    storage: storage("users")
      .primaryKey("id")
      .indexes({ fields: ["email"], unique: true }),
  }),
});
```

Concrete stored Schemas require a storage name. Abstract Schemas may contribute inherited storage rules without a concrete name.

### Projection selectors

Projection selection is Author-only convenience. The compiler resolves selectors against effective source fields and emits explicit canonical `projection.fields`.

```ts
users.schemas({
  UserRead: schema({}).projection(
    projection(stored.User)
      .purpose("read")
      .pick("id", "email")
      .rename({ email: "contactEmail" })
      .usage({ email: { optional: true } }),
  ),
});
```

Supported helpers are `.pick(...)`, `.omit(...)`, `.rename(...)`, `.usage(...)`, `.purpose(...)`, and `.policies(...)`. Projection-from-projection, projection inheritance, abstract projections, projection storage facets, unknown selections, and output collisions are rejected.

## Universal semantic metadata

The hardened Runtime contracts currently expose universal metadata on:

- Application;
- Group;
- Policy;
- Schema;
- Schema/composite fields.

Authoring uses:

```ts
const users = dryv
  .group({ name: "users" })
  .tags("domain")
  .explain("info", "User capabilities");
```

Tags are normalized deterministically. Explanations compile as `{ kind, text }`. Empty/default metadata is omitted.

## App composition

The root App is the canonical root Application composition.

```ts
export default dryv
  .app({ name: "example", description: "Example" })
  .groups(shared, users)
  .policies(policies.CanRead)
  .facets({ http: { root: "/api" } });
```

The App may compose Groups, policies, HTTP scope, features, surfaces, and presentations. It is not a separate semantic model.

## Next

Docs: https://docs.dryvcode.com/docs · Compiler: [`@dryvcode/compiler`](https://www.npmjs.com/package/@dryvcode/compiler) · Python version: [`dryv-author`](https://pypi.org/project/dryv-author/)
