@shivaedev/contract 0.47.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +131 -109
- package/dist/adapters/erasedClient.d.ts +18 -0
- package/dist/adapters/erasedClient.d.ts.map +1 -0
- package/dist/adapters/erasedClient.js +10 -0
- package/dist/adapters/erasedClient.js.map +1 -0
- package/dist/automaticLive.d.ts +2 -10
- package/dist/automaticLive.d.ts.map +1 -1
- package/dist/automaticLive.js +3 -1
- package/dist/automaticLive.js.map +1 -1
- package/dist/bind.d.ts +13 -9
- package/dist/bind.d.ts.map +1 -1
- package/dist/bind.js.map +1 -1
- package/dist/catchUp.d.ts +2 -1
- package/dist/catchUp.d.ts.map +1 -1
- package/dist/catchUp.js.map +1 -1
- package/dist/clientContract.d.ts +3 -3
- package/dist/clientContract.d.ts.map +1 -1
- package/dist/clientContract.js +1 -1
- package/dist/clientContract.js.map +1 -1
- package/dist/clientOperations.d.ts +5 -5
- package/dist/clientOperations.d.ts.map +1 -1
- package/dist/clientOperations.js +22 -11
- package/dist/clientOperations.js.map +1 -1
- package/dist/contract.d.ts +1 -0
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js +1 -0
- package/dist/contract.js.map +1 -1
- package/dist/defineModule.d.ts +2 -2
- package/dist/defineModule.d.ts.map +1 -1
- package/dist/defineModule.js +1 -1
- package/dist/defineModule.js.map +1 -1
- package/dist/liveSyncRequest.d.ts +2 -2
- package/dist/liveSyncRequest.d.ts.map +1 -1
- package/dist/liveSyncRequest.js +1 -2
- package/dist/liveSyncRequest.js.map +1 -1
- package/dist/liveSyncRpc.d.ts +1 -0
- package/dist/liveSyncRpc.d.ts.map +1 -1
- package/dist/moduleProof.d.ts +8 -23
- package/dist/moduleProof.d.ts.map +1 -1
- package/dist/operation.d.ts +5 -5
- package/dist/operation.d.ts.map +1 -1
- package/dist/operation.js +2 -2
- package/dist/operation.js.map +1 -1
- package/dist/operationKind.d.ts +3 -0
- package/dist/operationKind.d.ts.map +1 -0
- package/dist/operationKind.js +14 -0
- package/dist/operationKind.js.map +1 -0
- package/dist/rpcClient.d.ts +2 -1
- package/dist/rpcClient.d.ts.map +1 -1
- package/dist/rpcClient.js.map +1 -1
- package/dist/runProof.d.ts +3 -41
- package/dist/runProof.d.ts.map +1 -1
- package/dist/servedOperation.d.ts +28 -25
- package/dist/servedOperation.d.ts.map +1 -1
- package/dist/servedOperation.js +9 -3
- package/dist/servedOperation.js.map +1 -1
- package/dist/serverMetadata.d.ts.map +1 -1
- package/dist/serverMetadata.js +6 -1
- package/dist/serverMetadata.js.map +1 -1
- package/dist/subject.d.ts +1 -1
- package/dist/subject.d.ts.map +1 -1
- package/dist/subjectHeader.d.ts +5 -0
- package/dist/subjectHeader.d.ts.map +1 -0
- package/dist/subjectHeader.js +14 -0
- package/dist/subjectHeader.js.map +1 -0
- package/dist/subjectLayers.d.ts +1 -1
- package/dist/subjectLayers.d.ts.map +1 -1
- package/dist/subjectLayers.js.map +1 -1
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +2 -1
- package/dist/wire.js.map +1 -1
- package/dist/wireProof.d.ts +48 -0
- package/dist/wireProof.d.ts.map +1 -0
- package/dist/wireProof.js +2 -0
- package/dist/wireProof.js.map +1 -0
- package/package.json +15 -15
- package/src/adapters/erasedClient.ts +43 -0
- package/src/automaticLive.ts +5 -15
- package/src/bind.ts +17 -9
- package/src/catchUp.ts +2 -1
- package/src/clientContract.ts +5 -5
- package/src/clientOperations.ts +30 -19
- package/src/contract.ts +2 -0
- package/src/defineModule.ts +4 -4
- package/src/liveSyncRequest.ts +3 -11
- package/src/liveSyncRpc.ts +2 -0
- package/src/moduleProof.ts +18 -27
- package/src/operation.ts +9 -16
- package/src/operationKind.ts +15 -0
- package/src/rpcClient.ts +3 -3
- package/src/runProof.ts +3 -61
- package/src/servedOperation.ts +47 -47
- package/src/serverMetadata.ts +6 -1
- package/src/subject.ts +1 -1
- package/src/subjectHeader.ts +17 -0
- package/src/subjectLayers.ts +6 -2
- package/src/wire.ts +2 -1
- package/src/wireProof.ts +104 -0
- package/dist/successProof.d.ts +0 -51
- package/dist/successProof.d.ts.map +0 -1
- package/dist/successProof.js +0 -2
- package/dist/successProof.js.map +0 -1
- package/src/successProof.ts +0 -120
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.49.0 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `operationKind(rpc)` from `@shivaedev/contract/operationKind.ts` tells whether an RPC reads or writes.
|
|
8
|
+
- a contract's `declaration.subject` records the subject declaration it names.
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- Require Effect 4.1.4 and its matching platform packages.
|
|
13
|
+
- a handler may also fail with an error that one of its contract's RPC middleware declares, as native Effect 4.1.4 `Rpc` handlers do. Any other undeclared error still fails compilation.
|
|
14
|
+
|
|
15
|
+
### Breaking
|
|
16
|
+
|
|
17
|
+
- `ChangesClient` moves from `automaticLive.ts` to `adapters/erasedClient.ts`, and `automaticLive` takes the contract's `AtomRpcClient<unknown, string, Rpc.Any>`. `liveSyncRequest` takes a flat client of `Rpc.Any | LiveSyncRpc` (`LiveSyncRpc` from `liveSyncRpc.ts`) and returns the sync command's typed Effect. Import `ChangesClient` from its new module; a client made by `makeClient` or `RpcClient.make` over a group that includes `liveSyncRpc` already has the new type.
|
|
18
|
+
- `SubjectDeclaration["middleware"]` may now fail, and `subjectLayers(group)` carries that failure in its error channel. A custom native RPC host that builds `subjectLayers(group)` handles or propagates the declarations' start-time failures, such as `DelegationRuleMissing`; hosts built with `appHost` need no change.
|
|
19
|
+
- An operation written with `run` no longer accepts `success` or `rejections`; its module's wire supplies both. Delete the two fields from every `query(name, { ..., *run })` and `command(name, { ..., *run })`. An operation declared without `run` keeps them, as before.
|
|
20
|
+
- A run-form command's `invalidates` no longer receives the result: it is `invalidates(payload, viewer?)`. Move keys computed from the result into `run` and return through `commandResult` from `@shivaedev/contract/commandResult.ts`: change `invalidates: (_draft, note) => [notes.item(note.id)]` to `return yield* commandResult({ invalidates: [notes.item(note.id)], result: note })` at the end of `run`. Those keys are published on the server after success and reach live subscriptions; they do not enter the browser's `invalidates`. A command whose `invalidates` read the viewer from its third argument reads it from the second. `clientContract`'s `commands` take the same `invalidates(payload, viewer?)`; files written by `@shivaedev/build` copy the operation's `invalidates` and need only `pnpm generate`.
|
|
21
|
+
- `defineModule` requires `wire`. A module without one passes its generated wire, as in `defineModule({ ..., wire: notesWire })` with `notesWire` from `#generated/modules/<module>/<Module>.ts`, or writes `wire: { <operation>: { rejections: { ... }, success: <schema> } }` by hand for each operation that returns a value or raises a rejection. An operation missing from the wire is `OperationMissingFromWire` when its `run` returns a value or raises a rejection; `OperationFailsOutsideItsRejections` no longer exists.
|
|
22
|
+
- `ResultNeedsDeclaredSuccess`, `RunDeclaration`'s success and rejection parameters, `SuccessSchema`, `Pending`, `RejectionProblem` and the problems `SuccessDiffersFromRun`, `SuccessClassNotReturned`, `ArrayMutabilityDiffers`, `RunFailsOutsideRejections`, `RejectionsRunNeverRaises`, `RejectionClassDiffers` and `RejectionAutomatic` are removed; a stale wire still reports `WireSuccessStale` or `WireRejectionsStale`. `successProof.ts` is now `wireProof.ts`, exporting `SuccessDiffers` and `RejectionsDiffer`.
|
|
23
|
+
|
|
24
|
+
## 0.48.0 - 2026-11-19
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- a bound query's options take `subject`, and a query's, command's or stream's `run` takes `{ subject }` as its second argument, so one client and its one socket, including a browser's or Capacitor app's first-frame bearer socket, act for the actor and any number of delegated subjects at once. `subjectHeader.ts` exports `subjectHeader`, `withSubject` and `subjectSerializationKey`.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- a defined module's operations carry `GeneratedSuccess` for every success their wire supplies, so a payload or rejection that marks a name sensitive no longer fails host start or `layerMemoryProtocol` with `SensitiveFieldConflict` when the generated success names it too. Hand-written contracts keep their check.
|
|
33
|
+
- two bound queries with different subjects and the same `serializationKey` now serialize under separate keys, so SSR hydration no longer gives one subject's result to the other.
|
|
34
|
+
|
|
3
35
|
## 0.47.0 - 2026-11-18
|
|
4
36
|
|
|
5
37
|
### Added
|
package/README.md
CHANGED
|
@@ -1,98 +1,57 @@
|
|
|
1
1
|
# @shivaedev/contract
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Write a feature's queries and commands once, as their payload and their `run`, and get the RPC boundary, its expected failures and its refresh keys from them. The operations become native Effect RPC definitions, and a client binding connects their dependency keys to native AtomRpc queries.
|
|
4
4
|
|
|
5
5
|
## Why you want this
|
|
6
6
|
|
|
7
|
-
A feature often repeats its inputs, results and errors on both sides of an RPC boundary, then separately wires which views a write should refresh. Those copies are easy to make disagree.
|
|
7
|
+
A feature often repeats its inputs, results and errors on both sides of an RPC boundary, then separately wires which views a write should refresh. Those copies are easy to make disagree. Write each operation as the logic it runs and list it in a module; the result type, the failures and the services come from that logic:
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
|
-
import {
|
|
11
|
-
import { contract } from "@shivaedev/contract/contract.ts";
|
|
10
|
+
import { Schema } from "effect";
|
|
12
11
|
import { collection } from "@shivaedev/changes/keys.ts";
|
|
12
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
13
13
|
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
14
|
+
import { notesWire } from "#generated/modules/notes/Notes.ts";
|
|
15
|
+
import { NotesStore } from "./store.ts";
|
|
14
16
|
|
|
15
17
|
const notes = collection("notes", Schema.Number);
|
|
16
|
-
|
|
18
|
+
|
|
19
|
+
const List = query("list", {
|
|
20
|
+
reads: () => [notes.list],
|
|
21
|
+
*run() {
|
|
22
|
+
return yield* (yield* NotesStore).titles();
|
|
23
|
+
},
|
|
24
|
+
});
|
|
17
25
|
const Rename = command("rename", {
|
|
18
|
-
payload: { id: Schema.Number, title: Schema.String },
|
|
19
26
|
invalidates: ({ id }) => [notes.item(id)],
|
|
27
|
+
payload: { id: Schema.Number, title: Schema.String },
|
|
28
|
+
*run({ id, title }) {
|
|
29
|
+
yield* (yield* NotesStore).rename(id, title);
|
|
30
|
+
},
|
|
20
31
|
});
|
|
21
|
-
|
|
32
|
+
|
|
33
|
+
export const Notes = defineModule({ name: "notes", operations: [List, Rename], requires: [NotesStore], wire: notesWire });
|
|
22
34
|
```
|
|
23
35
|
|
|
24
|
-
`Notes` is a native RPC group with `notes.list` and `notes.rename`
|
|
36
|
+
`Notes` is a native RPC group with `notes.list` and `notes.rename`, served by the operations themselves. Nothing restates what `list` returns or how `rename` fails: [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build) writes those schemas from `run`'s types into `notesWire`, and the compiler checks them against `run` on every type check. When a bound rename succeeds, the note's key refreshes its readers and the list; an item query for another note keeps its result. Handlers, middleware and transport use Effect's own APIs.
|
|
25
37
|
|
|
26
38
|
## Using it
|
|
27
39
|
|
|
28
40
|
### How to think about it
|
|
29
41
|
|
|
30
|
-
An **operation**
|
|
42
|
+
An **operation** is a query or a command written as its `payload` schema and a generator `*run`. Everything else about its boundary is derived from `run`: what it returns, the tagged failures it raises, and the services it needs. A **query** listens on the keys its repository reads name, or on the keys it declares in `reads`; a **command** announces the keys its repository writes name, plus any it declares in `invalidates`. A **rejection** is an expected typed failure that `run` raises, such as a missing note or an invalid title. Middleware failures and RPC client failures remain separate parts of the native client's error type.
|
|
31
43
|
|
|
32
|
-
A **
|
|
44
|
+
A **module** lists its operations with the services they may use and serves them without hand-written handlers. Types are erased, so the schemas the server encodes with and the browser decodes with must exist as values: the module's **wire** holds them, generated from `run`'s types, and the browser imports a **browser contract** generated beside it, which carries no `run`. A module is a native `RpcGroup`. Its RPC tags are the module name and operation name joined by a dot. A **binding** connects a module or contract to an existing `AtomRpc.Service`: queries get native query atoms and call Effects, while commands get call Effects that invalidate after success.
|
|
33
45
|
|
|
34
|
-
A **collection key** names a dependency. Its item key identifies one item; its list key identifies a list in that collection. Keys do not hold data. Native query atoms hold results, and native Reactivity asks matching queries to run again.
|
|
46
|
+
A **collection key** names a dependency. Its item key identifies one item; its list key identifies a list in that collection. Keys do not hold data. Native query atoms hold results, and native Reactivity asks matching queries to run again. Live subscriptions use those same keys to rerun each subscriber’s authorized query on the server and push its changed result.
|
|
35
47
|
|
|
36
|
-
|
|
48
|
+
An operation can also be declared without `run`, stating its `success` schema, its `rejections` and a command's `invalidates` by hand, and grouped with `contract`. That form is for a boundary served by hand-written handlers, as [operations declared without run](#operations-declared-without-run) describes; a feature of an application is written as a module.
|
|
37
49
|
|
|
38
|
-
### 1. Once per feature:
|
|
50
|
+
### 1. Once per feature: operations and their module
|
|
39
51
|
|
|
40
|
-
|
|
52
|
+
#### An operation written as its payload and run
|
|
41
53
|
|
|
42
|
-
|
|
43
|
-
import { Effect, Schema } from "effect";
|
|
44
|
-
import { contract } from "@shivaedev/contract/contract.ts";
|
|
45
|
-
import { collection } from "@shivaedev/changes/keys.ts";
|
|
46
|
-
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
47
|
-
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
48
|
-
|
|
49
|
-
export class Note extends Schema.Class<Note>("Note")({
|
|
50
|
-
body: Schema.String,
|
|
51
|
-
id: Schema.Number,
|
|
52
|
-
title: Schema.String,
|
|
53
|
-
}) {}
|
|
54
|
-
export const Draft = Schema.Struct({ body: Schema.String, title: Schema.String });
|
|
55
|
-
export class NoteMissing extends Schema.TaggedError<NoteMissing>()("NoteMissing", { id: Schema.Number }) {}
|
|
56
|
-
export const notes = collection("notes", Note.fields.id);
|
|
57
|
-
|
|
58
|
-
export const Get = query("get", {
|
|
59
|
-
readPolicy: () => Effect.succeed(true),
|
|
60
|
-
payload: { id: Schema.Number },
|
|
61
|
-
success: Note,
|
|
62
|
-
rejections: { NoteMissing },
|
|
63
|
-
reads: ({ id }) => [notes.item(id)],
|
|
64
|
-
});
|
|
65
|
-
export const List = query("list", {
|
|
66
|
-
readPolicy: () => Effect.succeed(true),
|
|
67
|
-
success: Schema.Array(Note),
|
|
68
|
-
reads: () => [notes.list],
|
|
69
|
-
});
|
|
70
|
-
export const Rename = command("rename", {
|
|
71
|
-
payload: { id: Schema.Number, title: Schema.String },
|
|
72
|
-
success: Note,
|
|
73
|
-
rejections: { NoteMissing, Invalid: fieldRejection(Draft, ["title"]) },
|
|
74
|
-
invalidates: ({ id }) => [notes.item(id)],
|
|
75
|
-
});
|
|
76
|
-
export const Create = command("create", {
|
|
77
|
-
payload: Draft,
|
|
78
|
-
success: Note,
|
|
79
|
-
rejections: { Invalid: fieldRejection(Draft) },
|
|
80
|
-
invalidates: (_draft, note) => [notes.item(note.id)],
|
|
81
|
-
});
|
|
82
|
-
export const Notes = contract("notes", { queries: [Get, List], commands: [Rename, Create] });
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
Save this module as `notes.ts`. The payload can be struct fields, as in `Get`, or a schema, as in `Create`. An omitted payload or success is `Schema.Void`; no declared rejections gives `Schema.Never`. The server resolves `reads` with the decoded payload and session viewer. For local command dependencies, the browser also evaluates it with `Option.none()`; return no viewer keys for that case. Authorized subscription scopes always come from the server. `invalidates` receives the decoded payload, successful result and optional session viewer, so a create call can invalidate the ID the server assigned.
|
|
86
|
-
|
|
87
|
-
The collection's ID schema gives `item` its ID type. Here, `notes.item` takes a number. Query and command callbacks retain their payload and result types, including when the operations are declared inline inside `contract`.
|
|
88
|
-
|
|
89
|
-
Operation names must differ within a contract, including across queries, commands and streams. Literal duplicate declarations fail compilation. If the compiler cannot see the names in an array, the server reports duplicate names as an Effect defect while validating the contract during host startup.
|
|
90
|
-
|
|
91
|
-
The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivaedev/contract/operationRpc.ts`.
|
|
92
|
-
|
|
93
|
-
### An operation written as its payload and run
|
|
94
|
-
|
|
95
|
-
An operation can also be written as its business logic: a `payload` schema and a generator `*run`, with no `Effect.gen` wrapper. Its success, rejections, services and the read policy's failures are inferred from `run`:
|
|
54
|
+
An operation is its business logic: a `payload` schema and a generator `*run`, with no `Effect.gen` wrapper. Its success, rejections, services and the read policy's failures are inferred from `run`:
|
|
96
55
|
|
|
97
56
|
```ts
|
|
98
57
|
import { Effect, Schema } from "effect";
|
|
@@ -126,19 +85,17 @@ export const List = query("list", {
|
|
|
126
85
|
|
|
127
86
|
Here `NotesRepository` is a `@shivaedev/sql` repository whose model marks `userId` as a bucket. Its insert announces the new row and its owner's bucket, so `Create` declares no `invalidates`, and `List` declares no `reads`: its `findMany` pins the owner's bucket, so the live list listens on it.
|
|
128
87
|
|
|
129
|
-
`Create.run` is an Effect-returning function, so another operation composes it with `yield* Create.run({ title })`, and `Create`'s services and failures join that operation's types. A query without `readPolicy` gets `signedIn`, at run time and in its type. It may declare `reads`, `serverReads` and `readsCollections` (which need a `permissionReadPolicy`); one that declares none listens on what its repository reads filter by, as [query policies, record keys and buckets](#query-policies-record-keys-and-buckets) explains. A
|
|
130
|
-
|
|
131
|
-
`success` and `rejections` are optional. A declared one must equal what `run` infers, checked on the declaration object, and each mismatch is a compile error that names the operation and the problem: `RunReturnsAny` when `run` returns `any`, such as the result of `JSON.parse`, which would otherwise pass every check (decode the value with a schema, or type it); `SuccessDiffersFromRun` when the declared success's type and `run`'s return type are not mutually assignable, or when an object that `run` returns and a `Schema.Struct` that the success holds in the same position, at the top or in an array, struct field, tuple, record, union or `Option`, have different keys, such as an optional property only one of them has, which the `Struct` would drop or never send; `SuccessClassNotReturned` when the success is a `Schema.Class`, or holds one in an array, struct field, tuple, record, union or `Option`, and `run` returns something other than that class in that position, such as an object literal of its fields, which fails to encode; `ArrayMutabilityDiffers` when they differ only in array mutability, because `Schema.Array` decodes a readonly array (return one, or declare `Schema.mutable`); `RunFailsOutsideRejections` when `run` or the read policy can fail with a tag that `rejections` misses; `RejectionsRunNeverRaises` for a listed tag nothing raises; `RejectionClassDiffers` when a listed class and the class `run` raises under the same tag differ in shape, such as a local `NotFound` with other fields than the shared one; `RejectionAutomatic` for a listed `InternalServerError` or `ServiceUnavailable`. Rejections are exported classes keyed by their `_tag`. A failure that states `isRetryable` (such as `SqlError`), `SchemaError` and `QueryReadDenied` are never rejections. While the declaration forms above are still accepted, such an error starts with "No overload matches this call" and its last line names the problem.
|
|
88
|
+
`Create.run` is an Effect-returning function, so another operation composes it with `yield* Create.run({ title })`, and `Create`'s services and failures join that operation's types. A query without `readPolicy` gets `signedIn`, at run time and in its type. It may declare `reads`, `serverReads` and `readsCollections` (which need a `permissionReadPolicy`); one that declares none listens on what its repository reads filter by, as [query policies, record keys and buckets](#query-policies-record-keys-and-buckets) explains. A payload-free operation omits `payload` and gets `Schema.Void`.
|
|
132
89
|
|
|
133
|
-
|
|
90
|
+
A command without `invalidates` announces no keys of its own. Its `invalidates` takes the decoded payload and returns keys; object keys are sorted, so `invalidates` is checked before `run` and cannot see `run`'s result. A command that must announce keys computed from what it did, such as the note it found by title or the people a move affected, contributes them from inside `run` with [`commandResult`](#server-only-command-keys).
|
|
134
91
|
|
|
135
|
-
|
|
92
|
+
An operation written this way states no `success` or `rejections`: its module's wire supplies both. On its own, outside a module, it is served with `Schema.Void` and only `InternalServerError` and `ServiceUnavailable`. Every operation written this way carries those two in its type and its rejection set. Nothing adds `Conflict`: an operation that answers a constraint violation as a domain failure maps it by constraint name in `run`, and inference carries the result. A failure that states `isRetryable` (such as `SqlError`), `SchemaError` and `QueryReadDenied` are never rejections. Rejections are exported classes keyed by their `_tag`.
|
|
136
93
|
|
|
137
|
-
|
|
94
|
+
`run` must not return `any`, such as the result of `JSON.parse`, which would otherwise pass every check: such an operation is a compile error that names it and `RunReturnsAny` (decode the value with a schema, or type it). While the declaration form is still accepted, that error starts with "No overload matches this call" and its last line names the problem. Biome's `useYield` refuses a `*run` that yields nothing, so a `run` that needs no service still yields an Effect.
|
|
138
95
|
|
|
139
96
|
A field failure is an exported tagged class built from the payload's fields with `fieldRejection`, as `TitleTaken` above. `run` raises it with `yield* new TitleTaken({ field, message })`, and `@shivaedev/form`'s `rejecting` places its message on that field.
|
|
140
97
|
|
|
141
|
-
|
|
98
|
+
#### A module defined from its operations
|
|
142
99
|
|
|
143
100
|
A module lists its operations once, with the services they may use, and serves them without hand-written handlers:
|
|
144
101
|
|
|
@@ -150,11 +107,11 @@ import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
|
150
107
|
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
151
108
|
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
152
109
|
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
110
|
+
import { notesWire } from "#generated/modules/notes/notes.ts";
|
|
153
111
|
import { Caller, NotesStore, type StoredNote } from "./services.ts";
|
|
154
112
|
|
|
155
113
|
const notes = collection("notes", Schema.Number);
|
|
156
114
|
export const NoteFields = Schema.Struct({ title: Schema.String });
|
|
157
|
-
export const Note = Schema.Struct({ id: Schema.Number, title: Schema.String });
|
|
158
115
|
export class TitleTaken extends Schema.TaggedError<TitleTaken>()("TitleTaken", fieldRejection(NoteFields)) {}
|
|
159
116
|
|
|
160
117
|
const signedInUser = Effect.flatMap(CurrentViewer, (viewer) =>
|
|
@@ -164,13 +121,12 @@ const signedInUser = Effect.flatMap(CurrentViewer, (viewer) =>
|
|
|
164
121
|
}),
|
|
165
122
|
);
|
|
166
123
|
|
|
167
|
-
function toNotes(stored: readonly StoredNote[]): readonly
|
|
124
|
+
function toNotes(stored: readonly StoredNote[]): readonly { readonly id: number; readonly title: string }[] {
|
|
168
125
|
return stored.map(({ id, title }) => ({ id, title }));
|
|
169
126
|
}
|
|
170
127
|
|
|
171
128
|
export const Create = command("create", {
|
|
172
129
|
payload: NoteFields,
|
|
173
|
-
rejections: { TitleTaken, Unauthorized },
|
|
174
130
|
*run({ title }) {
|
|
175
131
|
const store = yield* NotesStore;
|
|
176
132
|
const owner = yield* signedInUser;
|
|
@@ -181,7 +137,6 @@ export const Create = command("create", {
|
|
|
181
137
|
const { id } = yield* store.insert(title, owner);
|
|
182
138
|
return { id, title };
|
|
183
139
|
},
|
|
184
|
-
success: Note,
|
|
185
140
|
});
|
|
186
141
|
|
|
187
142
|
export const Get = query("get", {
|
|
@@ -195,7 +150,6 @@ export const Get = query("get", {
|
|
|
195
150
|
return Option.exists(note, ({ owner }) => owner === viewer.value.id);
|
|
196
151
|
}),
|
|
197
152
|
reads: ({ id }) => [notes.item(id)],
|
|
198
|
-
rejections: { NotFound },
|
|
199
153
|
*run({ id }) {
|
|
200
154
|
const note = yield* (yield* NotesStore).find(id);
|
|
201
155
|
if (Option.isNone(note)) {
|
|
@@ -203,17 +157,14 @@ export const Get = query("get", {
|
|
|
203
157
|
}
|
|
204
158
|
return { id: note.value.id, title: note.value.title };
|
|
205
159
|
},
|
|
206
|
-
success: Note,
|
|
207
160
|
});
|
|
208
161
|
|
|
209
162
|
export const List = query("list", {
|
|
210
163
|
reads: () => [notes.list],
|
|
211
|
-
rejections: { Unauthorized },
|
|
212
164
|
*run() {
|
|
213
165
|
const store = yield* NotesStore;
|
|
214
166
|
return toNotes(yield* store.owned(yield* signedInUser));
|
|
215
167
|
},
|
|
216
|
-
success: Schema.Array(Note),
|
|
217
168
|
});
|
|
218
169
|
|
|
219
170
|
export const Notes = defineModule({
|
|
@@ -221,13 +172,14 @@ export const Notes = defineModule({
|
|
|
221
172
|
name: "notes",
|
|
222
173
|
operations: [List, Get, Create],
|
|
223
174
|
requires: [NotesStore],
|
|
175
|
+
wire: notesWire,
|
|
224
176
|
});
|
|
225
177
|
```
|
|
226
178
|
|
|
227
|
-
Here `NotesStore` is an ordinary service, `StoredNote` the row it returns, and `Caller` an RPC middleware that sets the viewer. `defineModule` takes the operations written as payload and run, the services they may use in `requires`, optionally `middleware`, `subject` and `keyScope` as `contract` does
|
|
179
|
+
Here `NotesStore` is an ordinary service, `StoredNote` the row it returns, and `Caller` an RPC middleware that sets the viewer. `defineModule` takes the operations written as payload and run, the services they may use in `requires`, its `wire` (below), and optionally `middleware`, `subject` and `keyScope` as `contract` does. It returns the module's contract, so `bind`, `makeClient` and a host accept it as they accept any contract. Each of its RPCs carries the `DefinedModule` annotation from the same file with the module's name, so a host can tell a module's queries from a contract's. The compiler checks `requires`, and the module does not keep the list at run time. A definition without `wire` is a compile error that says the property is missing. Its generics check the definition on the `name` line, so the first line of the compiler's message names the operation and its problem: `OperationNeedsUndeclaredServices` when an operation's `run` or read policy uses a service that neither `requires` nor the middleware or subject provides, and `OperationNameRepeated` when two operations share a name:
|
|
228
180
|
|
|
229
181
|
```
|
|
230
|
-
src/test-support/fixtures/invalid/moduleUndeclaredService.ts(
|
|
182
|
+
src/test-support/fixtures/invalid/moduleUndeclaredService.ts(22,2): error TS2322: Type '"imports"' is not assignable to type '"imports" & NoInfer<OperationNeedsUndeclaredServices<"importTitle", NoteSource>>'.
|
|
231
183
|
```
|
|
232
184
|
|
|
233
185
|
`moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services in `requires`:
|
|
@@ -241,23 +193,11 @@ import { NotesStoreLive } from "./store.ts";
|
|
|
241
193
|
export const NotesHandlers = moduleHandlers(Notes).pipe(Layer.provide(NotesStoreLive));
|
|
242
194
|
```
|
|
243
195
|
|
|
244
|
-
Each operation runs in a span named after the module and the operation, such as `Notes.create`. A query's read policy is checked inside its handler before `run`, with the module's services, so a policy reads a repository directly, as `Get` does above; a live subscription to the query checks the same policy. Failures pass the RPC boundary from `@shivaedev/errors`: a
|
|
196
|
+
Each operation runs in a span named after the module and the operation, such as `Notes.create`. A query's read policy is checked inside its handler before `run`, with the module's services, so a policy reads a repository directly, as `Get` does above; a live subscription to the query checks the same policy. Failures pass the RPC boundary from `@shivaedev/errors`: a rejection the wire lists reaches the client as itself, an unlisted failure that states `isRetryable` answers `ServiceUnavailable`, and anything else answers `InternalServerError`, for the policy of a live subscription too. A command without `invalidates` publishes only the keys its writes announce.
|
|
245
197
|
|
|
246
198
|
#### The wire and the browser's contract
|
|
247
199
|
|
|
248
|
-
Types are erased, so the success schema and rejection classes the server encodes with and the browser decodes with must exist as values. [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build) writes them from each module's `run` types into one file per module under `src/generated/`, which stays out of Git
|
|
249
|
-
|
|
250
|
-
```ts
|
|
251
|
-
import { notesWire } from "#generated/modules/notes/notes.ts";
|
|
252
|
-
|
|
253
|
-
export const Notes = defineModule({
|
|
254
|
-
middleware: Caller,
|
|
255
|
-
name: "notes",
|
|
256
|
-
operations: [List, Get, Create],
|
|
257
|
-
requires: [NotesStore],
|
|
258
|
-
wire: notesWire,
|
|
259
|
-
});
|
|
260
|
-
```
|
|
200
|
+
Types are erased, so the success schema and rejection classes the server encodes with and the browser decodes with must exist as values. [`@shivaedev/build`](https://github.com/ShivaeDev/platform/tree/main/packages/build) writes them from each module's `run` types into one file per module under `src/generated/`, which stays out of Git; an application runs it as `pnpm generate`. The module file passes its wire, as `Notes` does above, and every operation is served with its wire entry's success and rejections, plus `InternalServerError` and `ServiceUnavailable`. A wire entry's success describes only the shape: its RPC carries `GeneratedSuccess` from `@shivaedev/errors/GeneratedSuccess.ts`, so the host neither collects sensitive names from it nor treats its fields as public. Mark a sensitive field on the server's model instead, as the [errors README](https://github.com/ShivaeDev/platform/tree/main/packages/errors#masking-secrets-in-failures) describes.
|
|
261
201
|
|
|
262
202
|
The file the generator writes exports the wire, the browser's contract built by `clientContract` from the wire, the copied payloads, `reads` and `invalidates`, and the module's name, middleware, subject and key scope, and it ends with a type-level assertion that the browser's contract and the server module have the same RPCs:
|
|
263
203
|
|
|
@@ -288,18 +228,79 @@ export const Notes = clientContract({
|
|
|
288
228
|
export const notesMatchModule: ClientMatchesModule<typeof Notes, typeof NotesModule> = true;
|
|
289
229
|
```
|
|
290
230
|
|
|
291
|
-
`clientContract` requires a wire entry for every query and command it declares. The browser imports `Notes` from that file and binds it like any contract; it carries no `run`, read policy or service, and its import graph reaches no server code. A command's `invalidates` and a query's `reads` work in the browser exactly as on
|
|
231
|
+
`clientContract` requires a wire entry for every query and command it declares. The browser imports `Notes` from that file and binds it like any contract; it carries no `run`, read policy or service, and its import graph reaches no server code. A command's `invalidates` and a query's `reads` work in the browser exactly as on the server. Over RPC's JSON serialization, a `Schema.Date` field arrives as a `Date` equal to the one `run` returned, and a rejection the wire lists arrives as its class. Neither the browser's contract nor an operation without a read policy can be served: `contract()` requires one on every query, and a host refuses a query without one at start-up.
|
|
232
|
+
|
|
233
|
+
The compiler compares the wire with `run` on every type check, and a stale file is an error on the module's `name` line that names the operation, one problem per operation: `WireSuccessStale` when the entry's success differs from what `run` returns, `WireRejectionsStale` when its rejection tags or classes differ from what `run` and a query's read policy raise, other than infrastructure failures, and `OperationMissingFromWire` when an operation has no entry and its `run` returns a value or raises a rejection. A success differs when its type and `run`'s return type are not mutually assignable; when they differ only in array mutability, because `Schema.Array` decodes a readonly array; when an object that `run` returns and a `Schema.Struct` that the success holds in the same position, at the top or in an array, struct field, tuple, record, union or `Option`, have different keys, such as an optional property only one of them has, which the `Struct` would drop or never send; and when the success holds a `Schema.Class` in such a position and `run` returns something other than that class there, such as an object literal of its fields, which fails to encode. Rejections differ when `run` raises a tag the entry does not list, the entry lists a tag nothing raises or one of the automatic two, or a listed class and the class `run` raises under the same tag differ in shape, such as a local `NotFound` with other fields than the shared one.
|
|
292
234
|
|
|
293
|
-
|
|
235
|
+
TypeScript compares classes by shape, so two cases still compile: a rejection class whose twin of the same shape is what `run` raises, and a helper typed to return a readonly interface of the same shape where the success is a `Schema.Class`. Neither is silent at run time: the twin is not the listed class, so the boundary answers `InternalServerError` and reports it, and the plain object fails to encode. The generator resolves both by declaration. A `Schema.Struct` behind another schema, such as a transformation, a brand or `Schema.suspend`, is compared with `run` only by mutual assignability, so an optional property that only one side has still compiles there and is dropped or never sent.
|
|
236
|
+
|
|
237
|
+
The browser's assertion fails with `ClientDiffersFromModule`, naming the operations whose RPCs differ. `ClientMatchesModule` compares the operations' payloads, successes and rejections; a stale copy of a query's `reads`, a command's `invalidates` or the key scope in the generated file still compiles; the generator keeps those current, because a change to them makes `shivaedev-build generate --check` report the file stale. A stale wire and a stale browser contract read:
|
|
294
238
|
|
|
295
239
|
```
|
|
296
240
|
src/test-support/fixtures/invalid/moduleStaleRejection.ts(9,2): error TS2322: Type '"staleRejection"' is not assignable to type '"staleRejection" & NoInfer<WireRejectionsStale<"create", "the generated file is stale; run pnpm generate", "TitleTaken" | "Unauthorized", "Unauthorized">>'.
|
|
297
241
|
src/test-support/fixtures/invalid/staleNotes.ts(17,14): error TS2322: Type 'boolean' is not assignable to type 'ClientDiffersFromModule<"create", "the generated file is stale; run pnpm generate">'.
|
|
298
242
|
```
|
|
299
243
|
|
|
244
|
+
### Operations declared without run
|
|
245
|
+
|
|
246
|
+
A boundary served by hand-written handlers, such as a contract a native `RpcServer` hosts with `toLayer`, declares each operation without `run`: its `success` schema, its `rejections` and, for a command, the keys it `invalidates`. `contract` groups such operations into a native `RpcGroup`. A **stream** is always declared this way: it declares an element schema in `success`, typed rejections and the keys it reads, and its handler returns a native `Stream`. The sections that follow host and bind this declaration; a module serves itself with `moduleHandlers` and binds the same way.
|
|
247
|
+
|
|
248
|
+
Keep the shared declaration in a module that both server and client can import:
|
|
249
|
+
|
|
250
|
+
```ts
|
|
251
|
+
import { Effect, Schema } from "effect";
|
|
252
|
+
import { contract } from "@shivaedev/contract/contract.ts";
|
|
253
|
+
import { collection } from "@shivaedev/changes/keys.ts";
|
|
254
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
255
|
+
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
256
|
+
|
|
257
|
+
export class Note extends Schema.Class<Note>("Note")({
|
|
258
|
+
body: Schema.String,
|
|
259
|
+
id: Schema.Number,
|
|
260
|
+
title: Schema.String,
|
|
261
|
+
}) {}
|
|
262
|
+
export const Draft = Schema.Struct({ body: Schema.String, title: Schema.String });
|
|
263
|
+
export class NoteMissing extends Schema.TaggedError<NoteMissing>()("NoteMissing", { id: Schema.Number }) {}
|
|
264
|
+
export const notes = collection("notes", Note.fields.id);
|
|
265
|
+
|
|
266
|
+
export const Get = query("get", {
|
|
267
|
+
readPolicy: () => Effect.succeed(true),
|
|
268
|
+
payload: { id: Schema.Number },
|
|
269
|
+
success: Note,
|
|
270
|
+
rejections: { NoteMissing },
|
|
271
|
+
reads: ({ id }) => [notes.item(id)],
|
|
272
|
+
});
|
|
273
|
+
export const List = query("list", {
|
|
274
|
+
readPolicy: () => Effect.succeed(true),
|
|
275
|
+
success: Schema.Array(Note),
|
|
276
|
+
reads: () => [notes.list],
|
|
277
|
+
});
|
|
278
|
+
export const Rename = command("rename", {
|
|
279
|
+
payload: { id: Schema.Number, title: Schema.String },
|
|
280
|
+
success: Note,
|
|
281
|
+
rejections: { NoteMissing, Invalid: fieldRejection(Draft, ["title"]) },
|
|
282
|
+
invalidates: ({ id }) => [notes.item(id)],
|
|
283
|
+
});
|
|
284
|
+
export const Create = command("create", {
|
|
285
|
+
payload: Draft,
|
|
286
|
+
success: Note,
|
|
287
|
+
rejections: { Invalid: fieldRejection(Draft) },
|
|
288
|
+
invalidates: (_draft, note) => [notes.item(note.id)],
|
|
289
|
+
});
|
|
290
|
+
export const Notes = contract("notes", { queries: [Get, List], commands: [Rename, Create] });
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Save this module as `notes.ts`. The payload can be struct fields, as in `Get`, or a schema, as in `Create`. An omitted payload or success is `Schema.Void`; no declared rejections gives `Schema.Never`. A declared query requires `readPolicy`, and a declared command requires `invalidates`. The server resolves `reads` with the decoded payload and session viewer. For local command dependencies, the browser also evaluates it with `Option.none()`; return no viewer keys for that case. Authorized subscription scopes always come from the server. A declared command's `invalidates` receives the decoded payload, successful result and optional session viewer, so a create call can invalidate the ID the server assigned.
|
|
294
|
+
|
|
295
|
+
The collection's ID schema gives `item` its ID type. Here, `notes.item` takes a number. Query and command callbacks retain their payload and result types, including when the operations are declared inline inside `contract`.
|
|
296
|
+
|
|
297
|
+
Operation names must differ within a contract, including across queries, commands and streams. Literal duplicate declarations fail compilation. If the compiler cannot see the names in an array, the server reports duplicate names as an Effect defect while validating the contract during host startup.
|
|
298
|
+
|
|
299
|
+
The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivaedev/contract/operationRpc.ts`.
|
|
300
|
+
|
|
300
301
|
### Whose account a request acts on
|
|
301
302
|
|
|
302
|
-
Set `subject` on a contract to a browser-safe declaration from `@shivaedev/identity/subject.ts`: `selfSubject` selects the session account; `accountSubject({ permission, refusal, deny })` permits another account only with the permission's `any` grant. The declaration applies to the application RPCs and their changes stream. Native middleware carries its typed failures and supplies the branded `Subject` service to handlers and the application services they call. Business payloads need no owner id.
|
|
303
|
+
Set `subject` on a contract to a browser-safe declaration from `@shivaedev/identity/subject.ts`: `selfSubject` selects the session account; `accountSubject({ permission, refusal, deny })` permits another account only with the permission's `any` grant. `delegatedSubject({ service, refusal, deny })` asks the application's rule per call, with a `kind` of `read` for queries and streams or `write` for commands. A contract's `declaration.subject` records the declaration it names. The declaration applies to the application RPCs and their changes stream. Native middleware carries its typed failures and supplies the branded `Subject` service to handlers and the application services they call. Business payloads need no owner id.
|
|
303
304
|
|
|
304
305
|
```ts
|
|
305
306
|
import { contract } from "@shivaedev/contract/contract.ts";
|
|
@@ -310,7 +311,7 @@ const Save = command("save", { invalidates: () => [] });
|
|
|
310
311
|
export const Account = contract("account", { commands: [Save], subject: selfSubject });
|
|
311
312
|
```
|
|
312
313
|
|
|
313
|
-
Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save` without an account id. The session host installs the resolver; handlers read `Subject` from the request environment. See [identity's subject guide](https://github.com/ShivaeDev/platform/tree/main/packages/identity#declared-request-subjects) for delegated selection and refusal declarations.
|
|
314
|
+
Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save` without an account id. For a delegated subject, the client names the account per call: a bound query takes `subject` in its options and a query's, command's or stream's `run` takes `{ subject }` as its second argument, as in `api.title.query(undefined, { subject: "bob" })` and `api.rename.run({ title }, { subject: "bob" })`. The option sets the call's `x-platform-subject` message header, so one client and its one socket serve the actor's own data and any number of subjects, each live query keeping its own subject on its changes stream. Queries with different subjects are different atoms, keep separate retained results, and serialize under separate keys when they share a `serializationKey`. The session host installs the resolver; handlers read `Subject` from the request environment. See [identity's subject guide](https://github.com/ShivaeDev/platform/tree/main/packages/identity#declared-request-subjects) for delegated selection and refusal declarations.
|
|
314
315
|
|
|
315
316
|
### Expected failures
|
|
316
317
|
|
|
@@ -342,7 +343,7 @@ const refused = Rename.reject.Invalid({ field: "title", message: "Enter a title"
|
|
|
342
343
|
const missing = Get.reject.NoteMissing({ id: 9 });
|
|
343
344
|
```
|
|
344
345
|
|
|
345
|
-
`invalid` is the generated class instance. `refused` and `missing` are failed Effects, with the corresponding rejection in their error channel. Each operation also exposes `payload`, `success` and `error`, so another boundary can use its schemas directly. A handler
|
|
346
|
+
`invalid` is the generated class instance. `refused` and `missing` are failed Effects, with the corresponding rejection in their error channel. Each operation also exposes `payload`, `success` and `error`, so another boundary can use its schemas directly. A handler may fail with its declared rejections or with an error that one of the contract's RPC middleware declares, as native `Rpc` handlers do; failing with any other error fails compilation.
|
|
346
347
|
|
|
347
348
|
### 2. Once per host: native handlers and transport
|
|
348
349
|
|
|
@@ -507,7 +508,25 @@ The browser invalidates a command's keys after RPC success, together with a key
|
|
|
507
508
|
|
|
508
509
|
#### Server-only command keys
|
|
509
510
|
|
|
510
|
-
When the affected
|
|
511
|
+
When the affected keys depend on what the command did, such as the note it found or the people a move affected, return the success through `commandResult`: from inside a command's `run`, or from a declared command's server handler. Its `invalidates` keys join the command's declared keys at the command guard. Only `result` becomes the RPC success; the extra keys and the audience used to find them stay on the server. In a module, the note a command found by its title announces itself this way:
|
|
512
|
+
|
|
513
|
+
```ts
|
|
514
|
+
import { commandResult } from "@shivaedev/contract/commandResult.ts";
|
|
515
|
+
|
|
516
|
+
export const Touch = command("touch", {
|
|
517
|
+
payload: NoteFields,
|
|
518
|
+
*run({ title }) {
|
|
519
|
+
const store = yield* NotesStore;
|
|
520
|
+
const note = (yield* store.owned(yield* signedInUser)).find((owned) => owned.title === title);
|
|
521
|
+
if (note === undefined) {
|
|
522
|
+
return yield* new NotFound({ message: "Note not found" });
|
|
523
|
+
}
|
|
524
|
+
return yield* commandResult({ invalidates: [notes.item(note.id)], result: { id: note.id, title: note.title } });
|
|
525
|
+
},
|
|
526
|
+
});
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
A handler of a declared command does the same around its write:
|
|
511
530
|
|
|
512
531
|
```ts
|
|
513
532
|
import { commandResult } from "@shivaedev/contract/commandResult.ts";
|
|
@@ -896,9 +915,9 @@ Import the module that defines the name; the package has no root entry.
|
|
|
896
915
|
|
|
897
916
|
| Module | Functions and schemas |
|
|
898
917
|
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
899
|
-
| `operation.ts` | `query(name, { payload?,
|
|
918
|
+
| `operation.ts` | `query(name, { payload?, *run, readPolicy?, reads?, serverReads?, readsCollections? })` and `command(name, { payload?, *run, invalidates?(payload, viewer?) })` with an Effect-returning `run`; declared without run: `query(name, { payload?, success?, rejections?, readPolicy, reads?, serverReads? })`, `command(name, { payload?, success?, rejections?, invalidates(payload, result, viewer?) })` and `stream(name, { payload?, success, rejections?, reads })`. |
|
|
900
919
|
| `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
|
|
901
|
-
| `defineModule.ts` | `defineModule({ name, operations, requires, middleware?, subject?, keyScope
|
|
920
|
+
| `defineModule.ts` | `defineModule({ name, operations, requires, wire, middleware?, subject?, keyScope? })`, returning the module's contract. |
|
|
902
921
|
| `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly its `requires`. |
|
|
903
922
|
| `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build. |
|
|
904
923
|
| `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`. |
|
|
@@ -916,7 +935,7 @@ Import the module that defines the name; the package has no root entry.
|
|
|
916
935
|
| `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
|
|
917
936
|
| `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
|
|
918
937
|
| `CommandGuard.ts` | `guardCommands(group)` places command publication inside viewer-providing middleware; `commandGuardLayer(boundary)` evaluates declared invalidations for that viewer and delegates publication to the host boundary. |
|
|
919
|
-
| `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command handler and returns only its success value.
|
|
938
|
+
| `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command's `run` or handler and returns only its success value. |
|
|
920
939
|
| `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
|
|
921
940
|
| `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
|
|
922
941
|
| `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
|
|
@@ -928,9 +947,11 @@ Import the module that defines the name; the package has no root entry.
|
|
|
928
947
|
| `LiveSync.ts` | `LiveSync`, the host's contract of the `platform.liveSync.request` command that carries a sync token and writes nothing. Browser code takes the same command from `liveSyncRpc.ts`. |
|
|
929
948
|
| `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag. |
|
|
930
949
|
| `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries. |
|
|
950
|
+
| `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked. |
|
|
951
|
+
| `subjectHeader.ts` | `subjectHeader(headers)` reads the account a call names; `withSubject(headers, subject)` and `subjectSerializationKey(key, headers)` are what bound operations use to send it and to keep serialized results apart. |
|
|
931
952
|
| `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option. |
|
|
932
953
|
|
|
933
|
-
A bound query’s optional second argument accepts `headers` and `serializationKey`. Successful results remain in their owning registry for five minutes after the last reader leaves, up to 100 idle queries, evicting the least recently left first. Reopening a query immediately returns the retained success with native `waiting: true` while a new subscription or read supplies fresh data. Execution stops between readers. Configure the registry’s `queryRetention` atom from `@shivaedev/contract/queryRetention.ts` with `{ timeToLive: "1 minute", capacity: 50 }`, or set React’s `SessionBoundary` prop of the same name. Zero for either disables idle retention. Expiry runs on the query runtime’s Effect Clock. Registry disposal clears all retained results; applications outside `SessionBoundary` own that disposal when their session changes. A native resume source receives a callback and returns a cleanup function.
|
|
954
|
+
A bound query’s optional second argument accepts `headers`, `subject` and `serializationKey`. Successful results remain in their owning registry for five minutes after the last reader leaves, up to 100 idle queries, evicting the least recently left first. Reopening a query immediately returns the retained success with native `waiting: true` while a new subscription or read supplies fresh data. Execution stops between readers. Configure the registry’s `queryRetention` atom from `@shivaedev/contract/queryRetention.ts` with `{ timeToLive: "1 minute", capacity: 50 }`, or set React’s `SessionBoundary` prop of the same name. Zero for either disables idle retention. Expiry runs on the query runtime’s Effect Clock. Registry disposal clears all retained results; applications outside `SessionBoundary` own that disposal when their session changes. A native resume source receives a callback and returns a cleanup function.
|
|
934
955
|
|
|
935
956
|
### Install, setup and limits
|
|
936
957
|
|
|
@@ -939,6 +960,7 @@ pnpm add @shivaedev/contract effect
|
|
|
939
960
|
```
|
|
940
961
|
|
|
941
962
|
`effect` is a peer, and the package needs Node.js 24 or newer. Choose the native server host separately; this package supplies no server process or HTTP transport implementation.
|
|
963
|
+
|
|
942
964
|
- Put schema declarations where server and browser can share them. Put service, authorization and transaction implementations on the server. React rendering and editable forms belong to `react` and `form`.
|
|
943
965
|
- Run command Effects with the Reactivity instance that owns the queries to refresh, as in the registry example.
|
|
944
966
|
- Choose a common read key for every query in a full reconciliation scope. A list key does not implicitly cover item queries.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Schema } from "effect";
|
|
2
|
+
import type * as AtomRpc from "effect/reactivity/AtomRpc";
|
|
3
|
+
import type { Rpc, RpcSchema } from "effect/rpc";
|
|
4
|
+
import type { QueryUpdate } from "#queryUpdate.ts";
|
|
5
|
+
type OperationsClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>;
|
|
6
|
+
export type UnaryClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>>;
|
|
7
|
+
export type StreamingClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, RpcSchema.Stream<Schema.Top, Schema.Top>, Schema.Never>>;
|
|
8
|
+
export type ChangesClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<`${string}.$changes`, Schema.Struct<{
|
|
9
|
+
queries: Schema.$Array<Schema.Struct<{
|
|
10
|
+
query: Schema.String;
|
|
11
|
+
payload: Schema.Unknown;
|
|
12
|
+
}>>;
|
|
13
|
+
}>, RpcSchema.Stream<Schema.Schema<QueryUpdate>, Schema.Unknown>, Schema.Never>>;
|
|
14
|
+
export declare function unaryClient(client: OperationsClient): UnaryClient;
|
|
15
|
+
export declare function streamingClient(client: OperationsClient): StreamingClient;
|
|
16
|
+
export declare function changesClient(client: OperationsClient): ChangesClient;
|
|
17
|
+
export {};
|
|
18
|
+
//# sourceMappingURL=erasedClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"erasedClient.d.ts","sourceRoot":"","sources":["../../src/adapters/erasedClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,KAAK,OAAO,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAKnD,KAAK,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AAExE,MAAM,MAAM,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtH,MAAM,MAAM,eAAe,GAAG,OAAO,CAAC,aAAa,CAClD,OAAO,EACP,MAAM,EACN,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CACnF,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,CAChD,OAAO,EACP,MAAM,EACN,GAAG,CAAC,GAAG,CACN,GAAG,MAAM,WAAW,EACpB,MAAM,CAAC,MAAM,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAA;KAAE,CAAC,CAAC,CAAA;CAAE,CAAC,EAC3G,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,EAC5D,MAAM,CAAC,KAAK,CACZ,CACD,CAAC;AAEF,wBAAgB,WAAW,CAAC,MAAM,EAAE,gBAAgB,GAAG,WAAW,CAAC;AAKnE,wBAAgB,eAAe,CAAC,MAAM,EAAE,gBAAgB,GAAG,eAAe,CAAC;AAK3E,wBAAgB,aAAa,CAAC,MAAM,EAAE,gBAAgB,GAAG,aAAa,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"erasedClient.js","sourceRoot":"","sources":["../../src/adapters/erasedClient.ts"],"names":[],"mappings":"AA8BA,MAAM,UAAU,WAAW,CAAC,MAAe;IAC1C,OAAO,MAAM,CAAC;AACf,CAAC;AAGD,MAAM,UAAU,eAAe,CAAC,MAAe;IAC9C,OAAO,MAAM,CAAC;AACf,CAAC;AAGD,MAAM,UAAU,aAAa,CAAC,MAAe;IAC5C,OAAO,MAAM,CAAC;AACf,CAAC"}
|
package/dist/automaticLive.d.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import { type Schema } from "effect";
|
|
2
1
|
import type { Headers } from "effect/http";
|
|
3
2
|
import type * as AsyncResult from "effect/reactivity/AsyncResult";
|
|
4
3
|
import * as Atom from "effect/reactivity/Atom";
|
|
5
4
|
import type * as AtomRpc from "effect/reactivity/AtomRpc";
|
|
6
|
-
import type { Rpc
|
|
5
|
+
import type { Rpc } from "effect/rpc";
|
|
7
6
|
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
8
7
|
import type { BindingOwner } from "#adapters/bindingOwner.ts";
|
|
9
8
|
import { type LiveStatus } from "#live.ts";
|
|
10
|
-
import type { QueryUpdate } from "#queryUpdate.ts";
|
|
11
9
|
import { type ResumeSource, type ResumeWindow } from "#resume.ts";
|
|
12
10
|
import type { QueryReference } from "#serverMetadata.ts";
|
|
13
11
|
export declare const LiveConnection: unique symbol;
|
|
@@ -19,13 +17,7 @@ export interface LiveBound {
|
|
|
19
17
|
readonly status: Atom.Atom<LiveStatus<unknown>>;
|
|
20
18
|
};
|
|
21
19
|
}
|
|
22
|
-
export
|
|
23
|
-
queries: Schema.$Array<Schema.Struct<{
|
|
24
|
-
query: Schema.String;
|
|
25
|
-
payload: Schema.Unknown;
|
|
26
|
-
}>>;
|
|
27
|
-
}>, RpcSchema.Stream<Schema.Schema<QueryUpdate>, Schema.Unknown>, Schema.Never>>;
|
|
28
|
-
export declare function automaticLive(service: ChangesClient, name: string, owner?: BindingOwner, resume?: ResumeSource, enabled?: boolean, resumeWindow?: ResumeWindow): {
|
|
20
|
+
export declare function automaticLive(operations: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>, name: string, owner?: BindingOwner, resume?: ResumeSource, enabled?: boolean, resumeWindow?: ResumeWindow): {
|
|
29
21
|
query: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>, reference: QueryReference, keys: readonly Key[], equivalent: (left: A, right: A) => boolean, decode: (value: unknown) => A, reactive: (source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) => Atom.Atom<AsyncResult.AsyncResult<A, E>>, headers?: Headers.Input) => any;
|
|
30
22
|
subscription: {
|
|
31
23
|
connection: Atom.Atom<LiveStatus<unknown>>;
|