@shivaedev/contract 0.48.0 → 0.50.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 +33 -0
- package/README.md +167 -143
- 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 +12 -5
- package/dist/bind.d.ts.map +1 -1
- package/dist/bind.js +2 -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 -1
- package/dist/clientOperations.d.ts.map +1 -1
- package/dist/clientOperations.js +7 -2
- 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 +6 -8
- package/dist/defineModule.d.ts.map +1 -1
- package/dist/defineModule.js +1 -1
- package/dist/defineModule.js.map +1 -1
- package/dist/failureKind.d.ts +10 -0
- package/dist/failureKind.d.ts.map +1 -0
- package/dist/failureKind.js +20 -0
- package/dist/failureKind.js.map +1 -0
- 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/moduleHandlers.d.ts +3 -3
- package/dist/moduleHandlers.d.ts.map +1 -1
- package/dist/moduleHandlers.js.map +1 -1
- package/dist/moduleProof.d.ts +16 -33
- package/dist/moduleProof.d.ts.map +1 -1
- package/dist/operation.d.ts +4 -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/subject.d.ts +1 -1
- package/dist/subject.d.ts.map +1 -1
- package/dist/subjectLayers.d.ts +1 -1
- package/dist/subjectLayers.d.ts.map +1 -1
- package/dist/subjectLayers.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 +15 -14
- package/src/catchUp.ts +2 -1
- package/src/clientContract.ts +5 -5
- package/src/clientOperations.ts +8 -10
- package/src/contract.ts +2 -0
- package/src/defineModule.ts +17 -14
- package/src/failureKind.ts +33 -0
- package/src/liveSyncRequest.ts +3 -11
- package/src/liveSyncRpc.ts +2 -0
- package/src/moduleHandlers.ts +3 -3
- package/src/moduleProof.ts +29 -46
- package/src/operation.ts +8 -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/subject.ts +1 -1
- package/src/subjectLayers.ts +6 -2
- 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/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], 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,19 @@ 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
|
|
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`.
|
|
130
89
|
|
|
131
|
-
|
|
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).
|
|
132
91
|
|
|
133
|
-
|
|
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`.
|
|
134
93
|
|
|
135
|
-
|
|
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.
|
|
136
95
|
|
|
137
|
-
|
|
96
|
+
`failureKind(error)` from `@shivaedev/contract/failureKind.ts` sorts an operation's failure for its client: `"request"` for a shared request rejection (the `RequestRejection` type in `@shivaedev/errors/taxonomy.ts`), `"framework"` for a `ServerFailure`, an `RpcClientError` or the contract's own `MissingReadPolicy`, `MissingReadPolicies`, `QueryReadDenied` and `WebSocketRequired`, `"framework"` also for a failure without a string `_tag`, and `"app"` for any other tagged failure, which is a rejection the feature declared for itself. `AppRejection<E>` and `FrameworkFailure` are the matching types; `@shivaedev/react` requires a handler only for an `AppRejection`.
|
|
138
97
|
|
|
139
|
-
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 })
|
|
98
|
+
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 })`; `useCreate` and `useEditor` in `@shivaedev/react` place its message on that field, as `@shivaedev/form`'s `rejecting` does for a form used directly.
|
|
140
99
|
|
|
141
|
-
|
|
100
|
+
#### A module defined from its operations
|
|
142
101
|
|
|
143
102
|
A module lists its operations once, with the services they may use, and serves them without hand-written handlers:
|
|
144
103
|
|
|
@@ -150,11 +109,11 @@ import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
|
150
109
|
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
151
110
|
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
152
111
|
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
112
|
+
import { notesWire } from "#generated/modules/notes/notes.ts";
|
|
153
113
|
import { Caller, NotesStore, type StoredNote } from "./services.ts";
|
|
154
114
|
|
|
155
115
|
const notes = collection("notes", Schema.Number);
|
|
156
116
|
export const NoteFields = Schema.Struct({ title: Schema.String });
|
|
157
|
-
export const Note = Schema.Struct({ id: Schema.Number, title: Schema.String });
|
|
158
117
|
export class TitleTaken extends Schema.TaggedError<TitleTaken>()("TitleTaken", fieldRejection(NoteFields)) {}
|
|
159
118
|
|
|
160
119
|
const signedInUser = Effect.flatMap(CurrentViewer, (viewer) =>
|
|
@@ -164,13 +123,12 @@ const signedInUser = Effect.flatMap(CurrentViewer, (viewer) =>
|
|
|
164
123
|
}),
|
|
165
124
|
);
|
|
166
125
|
|
|
167
|
-
function toNotes(stored: readonly StoredNote[]): readonly
|
|
126
|
+
function toNotes(stored: readonly StoredNote[]): readonly { readonly id: number; readonly title: string }[] {
|
|
168
127
|
return stored.map(({ id, title }) => ({ id, title }));
|
|
169
128
|
}
|
|
170
129
|
|
|
171
130
|
export const Create = command("create", {
|
|
172
131
|
payload: NoteFields,
|
|
173
|
-
rejections: { TitleTaken, Unauthorized },
|
|
174
132
|
*run({ title }) {
|
|
175
133
|
const store = yield* NotesStore;
|
|
176
134
|
const owner = yield* signedInUser;
|
|
@@ -181,7 +139,6 @@ export const Create = command("create", {
|
|
|
181
139
|
const { id } = yield* store.insert(title, owner);
|
|
182
140
|
return { id, title };
|
|
183
141
|
},
|
|
184
|
-
success: Note,
|
|
185
142
|
});
|
|
186
143
|
|
|
187
144
|
export const Get = query("get", {
|
|
@@ -195,7 +152,6 @@ export const Get = query("get", {
|
|
|
195
152
|
return Option.exists(note, ({ owner }) => owner === viewer.value.id);
|
|
196
153
|
}),
|
|
197
154
|
reads: ({ id }) => [notes.item(id)],
|
|
198
|
-
rejections: { NotFound },
|
|
199
155
|
*run({ id }) {
|
|
200
156
|
const note = yield* (yield* NotesStore).find(id);
|
|
201
157
|
if (Option.isNone(note)) {
|
|
@@ -203,34 +159,31 @@ export const Get = query("get", {
|
|
|
203
159
|
}
|
|
204
160
|
return { id: note.value.id, title: note.value.title };
|
|
205
161
|
},
|
|
206
|
-
success: Note,
|
|
207
162
|
});
|
|
208
163
|
|
|
209
164
|
export const List = query("list", {
|
|
210
165
|
reads: () => [notes.list],
|
|
211
|
-
rejections: { Unauthorized },
|
|
212
166
|
*run() {
|
|
213
167
|
const store = yield* NotesStore;
|
|
214
168
|
return toNotes(yield* store.owned(yield* signedInUser));
|
|
215
169
|
},
|
|
216
|
-
success: Schema.Array(Note),
|
|
217
170
|
});
|
|
218
171
|
|
|
219
172
|
export const Notes = defineModule({
|
|
220
173
|
middleware: Caller,
|
|
221
174
|
name: "notes",
|
|
222
175
|
operations: [List, Get, Create],
|
|
223
|
-
|
|
176
|
+
wire: notesWire,
|
|
224
177
|
});
|
|
225
178
|
```
|
|
226
179
|
|
|
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,
|
|
180
|
+
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, 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 module lists no services: its type carries, for each operation, the services that operation's `run` and read policy yield, less what its middleware and subject provide per call, and nothing reads them at run time. An operation that starts to yield another service changes only that operation. 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, such as `OperationNameRepeated` when two operations share a name:
|
|
228
181
|
|
|
229
182
|
```
|
|
230
|
-
src/test-support/fixtures/invalid/
|
|
183
|
+
src/test-support/fixtures/invalid/moduleRepeatedName.ts(15,2): error TS2322: Type '"lists"' is not assignable to type '"lists" & NoInfer<OperationNameRepeated<"list">>'.
|
|
231
184
|
```
|
|
232
185
|
|
|
233
|
-
`moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services
|
|
186
|
+
`moduleHandlers(Notes)` builds the module's handler Layer from its operations, and the Layer requires exactly the services the operations yield beyond the middleware and subject, here `NotesStore`, so serving it provides that service on the Layer:
|
|
234
187
|
|
|
235
188
|
```ts
|
|
236
189
|
import { Layer } from "effect";
|
|
@@ -241,23 +194,13 @@ import { NotesStoreLive } from "./store.ts";
|
|
|
241
194
|
export const NotesHandlers = moduleHandlers(Notes).pipe(Layer.provide(NotesStoreLive));
|
|
242
195
|
```
|
|
243
196
|
|
|
244
|
-
|
|
197
|
+
An application registers the module with the server instead, and the [server's `appModules`](https://github.com/ShivaeDev/platform/tree/main/packages/server#host-the-application) refuses a registration list that leaves a service unprovided, naming the module, the operation and the service.
|
|
198
|
+
|
|
199
|
+
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
200
|
|
|
246
201
|
#### The wire and the browser's contract
|
|
247
202
|
|
|
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
|
-
```
|
|
203
|
+
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
204
|
|
|
262
205
|
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
206
|
|
|
@@ -288,18 +231,79 @@ export const Notes = clientContract({
|
|
|
288
231
|
export const notesMatchModule: ClientMatchesModule<typeof Notes, typeof NotesModule> = true;
|
|
289
232
|
```
|
|
290
233
|
|
|
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
|
|
234
|
+
`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.
|
|
235
|
+
|
|
236
|
+
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.
|
|
237
|
+
|
|
238
|
+
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.
|
|
292
239
|
|
|
293
|
-
The
|
|
240
|
+
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
241
|
|
|
295
242
|
```
|
|
296
243
|
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
244
|
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
245
|
```
|
|
299
246
|
|
|
247
|
+
### Operations declared without run
|
|
248
|
+
|
|
249
|
+
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.
|
|
250
|
+
|
|
251
|
+
Keep the shared declaration in a module that both server and client can import:
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
import { Effect, Schema } from "effect";
|
|
255
|
+
import { contract } from "@shivaedev/contract/contract.ts";
|
|
256
|
+
import { collection } from "@shivaedev/changes/keys.ts";
|
|
257
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
258
|
+
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
259
|
+
|
|
260
|
+
export class Note extends Schema.Class<Note>("Note")({
|
|
261
|
+
body: Schema.String,
|
|
262
|
+
id: Schema.Number,
|
|
263
|
+
title: Schema.String,
|
|
264
|
+
}) {}
|
|
265
|
+
export const Draft = Schema.Struct({ body: Schema.String, title: Schema.String });
|
|
266
|
+
export class NoteMissing extends Schema.TaggedError<NoteMissing>()("NoteMissing", { id: Schema.Number }) {}
|
|
267
|
+
export const notes = collection("notes", Note.fields.id);
|
|
268
|
+
|
|
269
|
+
export const Get = query("get", {
|
|
270
|
+
readPolicy: () => Effect.succeed(true),
|
|
271
|
+
payload: { id: Schema.Number },
|
|
272
|
+
success: Note,
|
|
273
|
+
rejections: { NoteMissing },
|
|
274
|
+
reads: ({ id }) => [notes.item(id)],
|
|
275
|
+
});
|
|
276
|
+
export const List = query("list", {
|
|
277
|
+
readPolicy: () => Effect.succeed(true),
|
|
278
|
+
success: Schema.Array(Note),
|
|
279
|
+
reads: () => [notes.list],
|
|
280
|
+
});
|
|
281
|
+
export const Rename = command("rename", {
|
|
282
|
+
payload: { id: Schema.Number, title: Schema.String },
|
|
283
|
+
success: Note,
|
|
284
|
+
rejections: { NoteMissing, Invalid: fieldRejection(Draft, ["title"]) },
|
|
285
|
+
invalidates: ({ id }) => [notes.item(id)],
|
|
286
|
+
});
|
|
287
|
+
export const Create = command("create", {
|
|
288
|
+
payload: Draft,
|
|
289
|
+
success: Note,
|
|
290
|
+
rejections: { Invalid: fieldRejection(Draft) },
|
|
291
|
+
invalidates: (_draft, note) => [notes.item(note.id)],
|
|
292
|
+
});
|
|
293
|
+
export const Notes = contract("notes", { queries: [Get, List], commands: [Rename, Create] });
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
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.
|
|
297
|
+
|
|
298
|
+
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`.
|
|
299
|
+
|
|
300
|
+
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.
|
|
301
|
+
|
|
302
|
+
The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivaedev/contract/operationRpc.ts`.
|
|
303
|
+
|
|
300
304
|
### Whose account a request acts on
|
|
301
305
|
|
|
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.
|
|
306
|
+
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
307
|
|
|
304
308
|
```ts
|
|
305
309
|
import { contract } from "@shivaedev/contract/contract.ts";
|
|
@@ -342,7 +346,7 @@ const refused = Rename.reject.Invalid({ field: "title", message: "Enter a title"
|
|
|
342
346
|
const missing = Get.reject.NoteMissing({ id: 9 });
|
|
343
347
|
```
|
|
344
348
|
|
|
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
|
|
349
|
+
`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
350
|
|
|
347
351
|
### 2. Once per host: native handlers and transport
|
|
348
352
|
|
|
@@ -470,7 +474,7 @@ const readOnce = api.get.run({ id: 1 });
|
|
|
470
474
|
const rename = api.rename.run({ id: 1, title: "Uno" });
|
|
471
475
|
```
|
|
472
476
|
|
|
473
|
-
`one` and `list` are native query atoms. `readOnce` and `rename` are Effects for individual calls. A query's Effect requires `NotesClient`; a command's Effect also requires native `Reactivity`. Commands expose `run`, and have no `query` member.
|
|
477
|
+
`one` and `list` are native query atoms. `readOnce` and `rename` are Effects for individual calls. A query's Effect requires `NotesClient`; a command's Effect also requires native `Reactivity`. Commands expose `run`, the atom `runtime` that provides those services and their declared `payload` schema, and have no `query` member; queries and streams also carry `runtime`. React's action and form hooks take a bound command as it is, as in `useAction(api.rename)`, and a form derives its fields from `payload`.
|
|
474
478
|
|
|
475
479
|
Mount the atoms and run commands through the service's atom runtime in the same registry:
|
|
476
480
|
|
|
@@ -507,7 +511,25 @@ The browser invalidates a command's keys after RPC success, together with a key
|
|
|
507
511
|
|
|
508
512
|
#### Server-only command keys
|
|
509
513
|
|
|
510
|
-
When the affected
|
|
514
|
+
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:
|
|
515
|
+
|
|
516
|
+
```ts
|
|
517
|
+
import { commandResult } from "@shivaedev/contract/commandResult.ts";
|
|
518
|
+
|
|
519
|
+
export const Touch = command("touch", {
|
|
520
|
+
payload: NoteFields,
|
|
521
|
+
*run({ title }) {
|
|
522
|
+
const store = yield* NotesStore;
|
|
523
|
+
const note = (yield* store.owned(yield* signedInUser)).find((owned) => owned.title === title);
|
|
524
|
+
if (note === undefined) {
|
|
525
|
+
return yield* new NotFound({ message: "Note not found" });
|
|
526
|
+
}
|
|
527
|
+
return yield* commandResult({ invalidates: [notes.item(note.id)], result: { id: note.id, title: note.title } });
|
|
528
|
+
},
|
|
529
|
+
});
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
A handler of a declared command does the same around its write:
|
|
511
533
|
|
|
512
534
|
```ts
|
|
513
535
|
import { commandResult } from "@shivaedev/contract/commandResult.ts";
|
|
@@ -894,42 +916,43 @@ Observe raw result streams with `watchHints` from `@shivaedev/test-kits/contract
|
|
|
894
916
|
|
|
895
917
|
Import the module that defines the name; the package has no root entry.
|
|
896
918
|
|
|
897
|
-
| Module | Functions and schemas
|
|
898
|
-
| -------------------------- |
|
|
899
|
-
| `operation.ts` | `query(name, { payload?,
|
|
900
|
-
| `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,
|
|
902
|
-
| `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly its
|
|
903
|
-
| `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build.
|
|
904
|
-
| `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`.
|
|
905
|
-
| `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations.
|
|
906
|
-
| `bind.ts` | `bind(contract, atomRpcService, { registry?, live?, resume?, resumeWindow? }?)`, requiring the registry for session-scoped contracts and exposing `{ query, run }` for queries, `{ run }`
|
|
907
|
-
| `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients.
|
|
908
|
-
| `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs.
|
|
909
|
-
| `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization.
|
|
910
|
-
| `live-server/service.ts` | `LiveServer`, the shared live server service.
|
|
911
|
-
| `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`.
|
|
912
|
-
| `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements.
|
|
913
|
-
| `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams, a `resync` Effect and `synced(token)`.
|
|
914
|
-
| `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware.
|
|
915
|
-
| `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default.
|
|
916
|
-
| `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy.
|
|
917
|
-
| `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`.
|
|
918
|
-
| `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.
|
|
920
|
-
| `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters.
|
|
921
|
-
| `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services.
|
|
922
|
-
| `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type.
|
|
923
|
-
| `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom.
|
|
924
|
-
| `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom.
|
|
925
|
-
| `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`.
|
|
926
|
-
| `clientActivity.ts` | `clientActivity(client)` exposes a native activity Stream with a `current` Effect; `isClientSettled(state)` checks commands, commands not yet reflected and first query results; `isClientIdle(state)` checks all finite work; `activityScreenSignal(activity, settled?)` projects pending work for screen waits.
|
|
927
|
-
| `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`.
|
|
928
|
-
| `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
|
-
| `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag.
|
|
930
|
-
| `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries.
|
|
931
|
-
| `
|
|
932
|
-
| `
|
|
919
|
+
| Module | Functions and schemas |
|
|
920
|
+
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
921
|
+
| `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 })`. |
|
|
922
|
+
| `contract.ts` | `contract(name, { queries?, commands?, streams?, keyScope? })`, returning a native RPC group with `declaration: { name, queries, commands, streams, keyScope }`. |
|
|
923
|
+
| `defineModule.ts` | `defineModule({ name, operations, wire, middleware?, subject?, keyScope? })`, returning the module's contract, whose type carries the services each operation yields. |
|
|
924
|
+
| `moduleHandlers.ts` | `moduleHandlers(module)`, the module's handler Layer, requiring exactly the services its operations yield beyond its middleware and subject. |
|
|
925
|
+
| `clientContract.ts` | `clientContract({ name, wire, payloads?, queries?, commands?, middleware?, subject?, keyScope? })`, the browser's contract of a module that generated files build. |
|
|
926
|
+
| `clientMatchesModule.ts` | `ClientMatchesModule<Client, Module>`, `true` when the browser's contract and the server module have the same RPCs, else `ClientDiffersFromModule`. |
|
|
927
|
+
| `rejection.ts` | `fieldRejection(struct, fields?)`; lower-level `rejectionSet(specs)`, which constructs the rejection classes, union schema and failure helpers used by operations. |
|
|
928
|
+
| `bind.ts` | `bind(contract, atomRpcService, { registry?, live?, resume?, resumeWindow? }?)`, requiring the registry for session-scoped contracts and exposing `{ query, run, runtime }` for queries, `{ run, payload, runtime }` for commands and `{ run, runtime }` with native Streams for streams; `makeClient(contract, { url, protocol?, headers?, webSocketConstructor?, group?, registry?, live?, resume?, resumeWindow? })`, which builds the shared WebSocket client and binds it, with `sync` beside `api`. |
|
|
929
|
+
| `clientKeys.ts` | `KeyContext`, `clientReadKeys`, `clientInvalidationKeys`: registry-local cache keys for custom clients. |
|
|
930
|
+
| `live.ts` | `LiveHint` schema; `live(runtime, { stream, keyContext?, resume?, retryDelay?, retryKeys? })`, exposing `connection`, `paused` and `status`; `isLiveConnection(atom)` tells whether an atom is such a `connection`, which waits for as long as its subscription runs. |
|
|
931
|
+
| `querySubscription.ts` | `querySubscription(rpc, references, viewer)` checks each referenced query, resolves its payload and server-derived keys, and captures its scopes and ongoing authorization. |
|
|
932
|
+
| `live-server/service.ts` | `LiveServer`, the shared live server service. |
|
|
933
|
+
| `live-server/layer.ts` | `liveServerLayer`, providing `LiveServer` and its dispatcher dependency, requiring `Reactivity`. |
|
|
934
|
+
| `live-server/subscribe.ts` | `subscribe(subscription, read?)`, an Effect requiring `LiveServer` that returns an authorized subscription Stream with its policy and query-runner requirements. |
|
|
935
|
+
| `makeLiveServer.ts` | `makeLiveServer`, an Effect requiring `Reactivity` that creates scoped server hint streams, a `resync` Effect and `synced(token)`. |
|
|
936
|
+
| `readPolicy.ts` | `QueryReadPolicy`, `Viewer`, `signedIn`, `CurrentViewer`; `authorizeReads(effect, request, viewer)` for direct handler reruns outside RPC middleware. |
|
|
937
|
+
| `ReadPolicyGuard.ts` | `ReadPolicyGuard`, the defaulted middleware reference attached to contract queries; `readPolicyGuardLayer({ websocket? })`, an optional override that refuses HTTP `$changes` calls by default. |
|
|
938
|
+
| `validateReadPolicies.ts` | `validateReadPolicies(group)`, an Effect that fails with `MissingReadPolicies` when any served or subscribable query omits its policy. |
|
|
939
|
+
| `readPolicyErrors.ts` | `MissingReadPolicies` (boot), `MissingReadPolicy` (native-server request fallback) and `QueryReadDenied`. |
|
|
940
|
+
| `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. |
|
|
941
|
+
| `commandResult.ts` | `commandResult({ result, invalidates })` contributes server-only keys from a guarded command's `run` or handler and returns only its success value. |
|
|
942
|
+
| `serverMetadata.ts` | `QueryDefinition.definition`, `CommandInvalidation.invalidates`, `ChangesQueries.queries`, `ChangesQueries.resolve(references)` and `changesRpc(name, queries)` for server adapters. |
|
|
943
|
+
| `queryKeys.ts` | `queryKeys(queries, references, viewer?)` authorizes references and resolves payload and server-derived keys using the provided services. |
|
|
944
|
+
| `QueryServerReads.ts` | `QueryServerReads<Payload, E, R>`, the server-only resolver type. |
|
|
945
|
+
| `resume.ts` | `resumeSignal({ window?, native? })`, returning a native numeric signal atom. |
|
|
946
|
+
| `querySignals.ts` | `querySignals(query)` exposes completion counts and subscription status as a native atom. |
|
|
947
|
+
| `retainQuery.ts` | `queryRuntime(query)` returns the atom runtime a bound query runs on, so a reader can schedule work on the same Effect `Clock`. |
|
|
948
|
+
| `clientActivity.ts` | `clientActivity(client)` exposes a native activity Stream with a `current` Effect; `isClientSettled(state)` checks commands, commands not yet reflected and first query results; `isClientIdle(state)` checks all finite work; `activityScreenSignal(activity, settled?)` projects pending work for screen waits. |
|
|
949
|
+
| `commandSignal.ts` | `untilReflected(command)` completes a command's Effect when it is reflected; `CommandSignal` receives each `CommandState`. |
|
|
950
|
+
| `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`. |
|
|
951
|
+
| `liveSyncRpc.ts` | `liveSyncRpc`, the RPC group a client declares for that command without importing its operation file, and `LIVE_SYNC`, its tag. |
|
|
952
|
+
| `syncHeader.ts` | `syncClient(headers)` and `syncToken(headers)` read the client name and the sync token a request carries. |
|
|
953
|
+
| `operationKind.ts` | `operationKind(rpc)`: `"read"` for a query, a changes stream or a stream, `"write"` for a command or an RPC no contract marked. |
|
|
954
|
+
| `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. |
|
|
955
|
+
| `screenSync.ts` | `screenSync(client, registry)` runs a client's `sync` through a registry, for a screen driver's `sync` option. |
|
|
933
956
|
|
|
934
957
|
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.
|
|
935
958
|
|
|
@@ -940,6 +963,7 @@ pnpm add @shivaedev/contract effect
|
|
|
940
963
|
```
|
|
941
964
|
|
|
942
965
|
`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.
|
|
966
|
+
|
|
943
967
|
- 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`.
|
|
944
968
|
- Run command Effects with the Reactivity instance that owns the queries to refresh, as in the registry example.
|
|
945
969
|
- Choose a common read key for every query in a full reconciliation scope. A list key does not implicitly cover item queries.
|