@shivaedev/contract 0.50.0 → 0.52.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 +16 -0
- package/README.md +114 -80
- package/dist/adapters/activityState.d.ts +1 -0
- package/dist/adapters/activityState.d.ts.map +1 -1
- package/dist/adapters/activityState.js +7 -1
- package/dist/adapters/activityState.js.map +1 -1
- package/dist/clientActivities.d.ts +2 -2
- package/dist/clientActivities.d.ts.map +1 -1
- package/dist/clientActivities.js +9 -6
- package/dist/clientActivities.js.map +1 -1
- package/dist/clientOperations.d.ts.map +1 -1
- package/dist/clientOperations.js +5 -1
- package/dist/clientOperations.js.map +1 -1
- package/dist/commandSignal.d.ts.map +1 -1
- package/dist/commandSignal.js +17 -13
- package/dist/commandSignal.js.map +1 -1
- package/dist/connectionReadiness.js +1 -1
- package/dist/connectionReadiness.js.map +1 -1
- package/dist/live.d.ts.map +1 -1
- package/dist/live.js +16 -6
- package/dist/live.js.map +1 -1
- package/dist/liveHintQueue.d.ts.map +1 -1
- package/dist/liveHintQueue.js +19 -14
- package/dist/liveHintQueue.js.map +1 -1
- package/dist/querySubscription.js +5 -1
- package/dist/querySubscription.js.map +1 -1
- package/dist/reflection.d.ts.map +1 -1
- package/dist/reflection.js +3 -3
- package/dist/reflection.js.map +1 -1
- package/dist/runProof.d.ts +2 -1
- package/dist/runProof.d.ts.map +1 -1
- package/dist/servedOperation.d.ts.map +1 -1
- package/dist/servedOperation.js +2 -1
- package/dist/servedOperation.js.map +1 -1
- package/dist/socketProtocol.js +1 -1
- package/dist/socketProtocol.js.map +1 -1
- package/dist/staleWrite.d.ts +10 -0
- package/dist/staleWrite.d.ts.map +1 -0
- package/dist/staleWrite.js +14 -0
- package/dist/staleWrite.js.map +1 -0
- package/dist/warmQueries.d.ts +3 -0
- package/dist/warmQueries.d.ts.map +1 -0
- package/dist/warmQueries.js +4 -0
- package/dist/warmQueries.js.map +1 -0
- package/package.json +6 -6
- package/src/adapters/activityState.ts +7 -1
- package/src/clientActivities.ts +9 -6
- package/src/clientOperations.ts +5 -1
- package/src/commandSignal.ts +16 -12
- package/src/connectionReadiness.ts +1 -1
- package/src/live.ts +19 -6
- package/src/liveHintQueue.ts +20 -14
- package/src/querySubscription.ts +7 -1
- package/src/reflection.ts +88 -86
- package/src/runProof.ts +3 -1
- package/src/servedOperation.ts +2 -1
- package/src/socketProtocol.ts +1 -1
- package/src/staleWrite.ts +23 -0
- package/src/warmQueries.ts +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.52.0 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `warmQueries` in `warmQueries.ts`, a registry atom naming the queries a session keeps mounted. A query listed there when it mounts does not hold back the client activity's `firstSettled` flag while it awaits its first result; it still counts in `initialQueries`.
|
|
8
|
+
|
|
9
|
+
## 0.51.0 - 2026-11-20
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- a stale versioned write that reaches the end of an operation's `run` answers the caller with the shared `Conflict` from `@shivaedev/errors/taxonomy.ts`, whose message tells the person to refresh and try again. The generated wire lists `Conflict` for that operation, so its client sees a typed rejection and the default notice shows the message.
|
|
14
|
+
|
|
15
|
+
### Breaking
|
|
16
|
+
|
|
17
|
+
- an operation's `run` now fails with `Conflict` where its body lets an `OptimisticConcurrencyError` from an `@shivaedev/sql` repository through, so code that calls `Operation.run` and catches `OptimisticConcurrencyError` after it catches `Conflict` instead. Delete each `Effect.catchTag("OptimisticConcurrencyError", …)` in `run` that only returned a `Conflict`; keep one that answers something else.
|
|
18
|
+
|
|
3
19
|
## 0.50.0 - 2026-11-20
|
|
4
20
|
|
|
5
21
|
### Added
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ export const Notes = defineModule({ name: "notes", operations: [List, Rename], w
|
|
|
41
41
|
|
|
42
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.
|
|
43
43
|
|
|
44
|
-
A **module** lists its operations
|
|
44
|
+
A **module** lists its operations and serves them without hand-written handlers; its type carries the services they yield. 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.
|
|
45
45
|
|
|
46
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.
|
|
47
47
|
|
|
@@ -89,7 +89,7 @@ Here `NotesRepository` is a `@shivaedev/sql` repository whose model marks `userI
|
|
|
89
89
|
|
|
90
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).
|
|
91
91
|
|
|
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`.
|
|
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. A stale versioned write is the one failure `run` answers for the operation: an `OptimisticConcurrencyError` from an `@shivaedev/sql` repository that reaches the end of `run` becomes the shared `Conflict`, with a message telling the person to refresh, so the operation's type, its generated wire and its client list `Conflict`. An operation that wants another answer catches `OptimisticConcurrencyError` itself, and inference carries what it raises instead. Nothing else 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`.
|
|
93
93
|
|
|
94
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.
|
|
95
95
|
|
|
@@ -99,7 +99,7 @@ A field failure is an exported tagged class built from the payload's fields with
|
|
|
99
99
|
|
|
100
100
|
#### A module defined from its operations
|
|
101
101
|
|
|
102
|
-
A module lists its operations once
|
|
102
|
+
A module lists its operations once and serves them without hand-written handlers:
|
|
103
103
|
|
|
104
104
|
```ts
|
|
105
105
|
import { Effect, Option, Schema } from "effect";
|
|
@@ -109,7 +109,7 @@ import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
|
109
109
|
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
110
110
|
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
111
111
|
import { fieldRejection } from "@shivaedev/contract/rejection.ts";
|
|
112
|
-
import { notesWire } from "#generated/modules/notes/
|
|
112
|
+
import { notesWire } from "#generated/modules/notes/Notes.ts";
|
|
113
113
|
import { Caller, NotesStore, type StoredNote } from "./services.ts";
|
|
114
114
|
|
|
115
115
|
const notes = collection("notes", Schema.Number);
|
|
@@ -188,7 +188,7 @@ src/test-support/fixtures/invalid/moduleRepeatedName.ts(15,2): error TS2322: Typ
|
|
|
188
188
|
```ts
|
|
189
189
|
import { Layer } from "effect";
|
|
190
190
|
import { moduleHandlers } from "@shivaedev/contract/moduleHandlers.ts";
|
|
191
|
-
import { Notes } from "./
|
|
191
|
+
import { Notes } from "./Notes.ts";
|
|
192
192
|
import { NotesStoreLive } from "./store.ts";
|
|
193
193
|
|
|
194
194
|
export const NotesHandlers = moduleHandlers(Notes).pipe(Layer.provide(NotesStoreLive));
|
|
@@ -209,7 +209,7 @@ import { Schema } from "effect";
|
|
|
209
209
|
import { Unauthorized } from "@shivaedev/errors/taxonomy.ts";
|
|
210
210
|
import { clientContract } from "@shivaedev/contract/clientContract.ts";
|
|
211
211
|
import type { ClientMatchesModule } from "@shivaedev/contract/clientMatchesModule.ts";
|
|
212
|
-
import type { Notes as NotesModule } from "#modules/notes/
|
|
212
|
+
import type { Notes as NotesModule } from "#modules/notes/Notes.ts";
|
|
213
213
|
import { Caller, NoteFields, notes, TitleTaken } from "#modules/notes/model.ts";
|
|
214
214
|
|
|
215
215
|
const Note = Schema.Struct({ createdAt: Schema.Date, id: Schema.Number, title: Schema.String });
|
|
@@ -303,22 +303,31 @@ The native RPC mapping types `OperationRpc` and `Tag` are exported from `@shivae
|
|
|
303
303
|
|
|
304
304
|
### Whose account a request acts on
|
|
305
305
|
|
|
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
|
|
306
|
+
Set `subject` on a module or 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 each operation's `run` and the application services it calls. Business payloads need no owner id.
|
|
307
307
|
|
|
308
308
|
```ts
|
|
309
|
-
import {
|
|
309
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
310
310
|
import { command } from "@shivaedev/contract/operation.ts";
|
|
311
|
-
import { selfSubject } from "@shivaedev/identity/subject.ts";
|
|
311
|
+
import { selfSubject, Subject } from "@shivaedev/identity/subject.ts";
|
|
312
|
+
import { accountWire } from "#generated/modules/account/Account.ts";
|
|
313
|
+
import { PreferenceFields } from "#modules/account/model.ts";
|
|
314
|
+
import { Profiles } from "./services.ts";
|
|
312
315
|
|
|
313
|
-
const Save = command("save", {
|
|
314
|
-
|
|
316
|
+
const Save = command("save", {
|
|
317
|
+
payload: PreferenceFields,
|
|
318
|
+
*run({ title }) {
|
|
319
|
+
const { id } = yield* Subject;
|
|
320
|
+
yield* (yield* Profiles).rename(id, title);
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
export const Account = defineModule({ name: "account", operations: [Save], subject: selfSubject, wire: accountWire });
|
|
315
324
|
```
|
|
316
325
|
|
|
317
|
-
Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save`
|
|
326
|
+
`PreferenceFields` is `Schema.Struct({ title: Schema.String })` and `Profiles` an application service whose `rename` takes the account's `SubjectId`. Contracts with declared subjects can be exported from published packages with TypeScript declaration output. The client calls `account.save` with only its title. 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; operations 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.
|
|
318
327
|
|
|
319
328
|
### Expected failures
|
|
320
329
|
|
|
321
|
-
Import the shared expected failures from `@shivaedev/errors/taxonomy.ts`: `NotFound`, `Unauthorized`, `Forbidden`, `BadRequest`, `Conflict`, `PreconditionFailed`, `TooManyRequests`, `AuthUnavailable`, `InternalServerError` and `ServiceUnavailable`. Each class is a tagged error schema with a string `message`; `BadRequest` and `Conflict` also accept an optional string `field`. Declare only the failures an operation can return:
|
|
330
|
+
Import the shared expected failures from `@shivaedev/errors/taxonomy.ts`: `NotFound`, `Unauthorized`, `Forbidden`, `BadRequest`, `Conflict`, `PreconditionFailed`, `TooManyRequests`, `AuthUnavailable`, `InternalServerError` and `ServiceUnavailable`. Each class is a tagged error schema with a string `message`; `BadRequest` and `Conflict` also accept an optional string `field`. An operation written with `run` raises them and its wire lists them; the rest of this section is about RPCs that state their failures by hand, as native `Rpc` definitions and operations declared without run do. Declare only the failures an operation can return:
|
|
322
331
|
|
|
323
332
|
```ts
|
|
324
333
|
import { Effect, Schema } from "effect";
|
|
@@ -350,7 +359,7 @@ const missing = Get.reject.NoteMissing({ id: 9 });
|
|
|
350
359
|
|
|
351
360
|
### 2. Once per host: native handlers and transport
|
|
352
361
|
|
|
353
|
-
|
|
362
|
+
An application registers its defined modules with the [server's host](https://github.com/ShivaeDev/platform/tree/main/packages/server#host-the-application), which builds their handlers with `moduleHandlers`, and writes no handlers. A boundary of operations declared without run is implemented with native `of` and `toLayer`:
|
|
354
363
|
|
|
355
364
|
```ts
|
|
356
365
|
import { Effect, Ref, Stream } from "effect";
|
|
@@ -438,7 +447,7 @@ export class NotesClient extends AtomRpc.Service<NotesClient>()("app/NotesClient
|
|
|
438
447
|
export const api = bind(Notes, NotesClient, { live: false });
|
|
439
448
|
```
|
|
440
449
|
|
|
441
|
-
Save the client module as `client.ts`. The [native RPC guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/native-rpc.md) covers hosting; the [
|
|
450
|
+
Save the client module as `client.ts`. The [native RPC guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/native-rpc.md) covers hosting; the [feature guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/add-a-feature.md) composes a defined module, request identity, SQL and a rendered client in the starter.
|
|
442
451
|
|
|
443
452
|
### Build a shared WebSocket client
|
|
444
453
|
|
|
@@ -543,7 +552,7 @@ const move = ({ id, household }) =>
|
|
|
543
552
|
result: pot,
|
|
544
553
|
invalidates: [...before, ...after].map((viewerId) => pots.bucket.viewerId(viewerId)),
|
|
545
554
|
});
|
|
546
|
-
}).pipe(transact(
|
|
555
|
+
}).pipe(transact());
|
|
547
556
|
```
|
|
548
557
|
|
|
549
558
|
Here `audienceFor` reads household members and people who ate from the pot from the application's database, `movePot` performs the write, and `pots` declares a `viewerId` bucket. Read the audience after the write to include new readers, and retain the old audience when the write removes access. Each viewer's list reads its own bucket. Keep these reads and the write in the same transaction when they must describe one change.
|
|
@@ -590,7 +599,7 @@ The wait rests on a sync token. The client names itself on each live stream and
|
|
|
590
599
|
|
|
591
600
|
`clientActivity(client)` from `@shivaedev/contract/clientActivity.ts` returns a native Effect `Stream` with a `current` Effect for a client made by `makeClient`. Its state includes `connectionStatus`, a `"live" | "reconnecting" | "waiting-for-connection"` value aggregated across mounted queries from all bindings of the same client service, with live subscription changes debounced for 300 ms on the client runtime’s Clock and held commands reported immediately. Refused subscriptions do not count as reconnecting. The stream also exposes its native `connectionStatus` atom for React readers.
|
|
592
601
|
|
|
593
|
-
The state's `firstSettled` flag is `false` until a mounted query has delivered its first success or failure and, with that, no mounted query awaits a first result and no command is in flight. It then stays `true` for that client: a later command or a newly mounted query does not turn it back, and a client that mounts no query never turns it on. The stream exposes it as its native `firstSettled` atom, which React reads through `useFirstSettled`.
|
|
602
|
+
The state's `firstSettled` flag is `false` until a mounted query has delivered its first success or failure and, with that, no mounted query awaits a first result and no command is in flight. It then stays `true` for that client: a later command or a newly mounted query does not turn it back, and a client that mounts no query never turns it on. A query listed in the registry's `warmQueries` atom from `@shivaedev/contract/warmQueries.ts` when it is mounted, which React's `SessionBoundary` sets from its `warm` prop, does not hold the flag back while it awaits its first result; it still counts in `initialQueries`, so screen stories wait for it. The stream exposes it as its native `firstSettled` atom, which React reads through `useFirstSettled`.
|
|
594
603
|
|
|
595
604
|
For screen stories, pass `activityScreenSignal(clientActivity(client))` to a test-story screen driver's `activity` option. By default, `settle()` waits for commands until they are reflected and for the first result of each mounted query, then flushes the renderer. Contract identifies commands from its own RPC annotations; kits need no query-name exceptions. The activity state's `commands` count includes commands held for a connection, `unreflectedCommands` counts commands from the moment they are sent until they are reflected or fail, and `initialQueries` counts mounted queries until their first success or failure. Unmounting releases that query's pending activity. `isClientSettled(state)` checks these three counts. An open live query that has delivered its first result, including one awaiting a later refresh, does not keep a screen story pending.
|
|
596
605
|
|
|
@@ -612,45 +621,57 @@ Mount the query to start it. Wait on `completions` for `completed > before` afte
|
|
|
612
621
|
|
|
613
622
|
### Session-owned keys
|
|
614
623
|
|
|
615
|
-
A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records.
|
|
624
|
+
A self-only feature, such as a user's preferences, reads and changes only the signed-in account's records. Define its module with `keyScope: "session"` and let its operations read the account from request-local `Identity`, so payloads carry no owner field, and reads and invalidations name a logical item key for the record:
|
|
616
625
|
|
|
617
626
|
```ts
|
|
618
|
-
|
|
619
|
-
|
|
627
|
+
import { collection } from "@shivaedev/changes/keys.ts";
|
|
628
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
629
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
630
|
+
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
631
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
632
|
+
import { preferencesWire } from "#generated/modules/preferences/Preferences.ts";
|
|
633
|
+
import { PreferenceFields, preferences } from "#modules/preferences/model.ts";
|
|
634
|
+
import { PreferencesStore } from "./services.ts";
|
|
635
|
+
|
|
636
|
+
const Self = query("self", {
|
|
637
|
+
reads: () => [preferences.item("self")],
|
|
638
|
+
*run() {
|
|
639
|
+
const { id } = yield* Identity;
|
|
640
|
+
return yield* (yield* PreferencesStore).read(id);
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
const Save = command("save", {
|
|
644
|
+
invalidates: () => [preferences.item("self")],
|
|
645
|
+
payload: PreferenceFields,
|
|
646
|
+
*run({ title }) {
|
|
647
|
+
const { id } = yield* Identity;
|
|
648
|
+
return yield* (yield* PreferencesStore).save(id, title);
|
|
649
|
+
},
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
export const Preferences = defineModule({
|
|
620
653
|
keyScope: "session",
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
}),
|
|
634
|
-
],
|
|
635
|
-
}).middleware(Authenticated);
|
|
654
|
+
middleware: Authenticated,
|
|
655
|
+
name: "preferences",
|
|
656
|
+
operations: [Self, Save],
|
|
657
|
+
wire: preferencesWire,
|
|
658
|
+
});
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
`model.ts` declares `preferences` as `collection("preferences", Schema.String)` and `PreferenceFields` as `Schema.Struct({ title: Schema.String })`, and `PreferencesStore` is the application's persistence service. The browser binds the generated contract with the session's registry:
|
|
662
|
+
|
|
663
|
+
```ts
|
|
664
|
+
import { bind } from "@shivaedev/contract/bind.ts";
|
|
665
|
+
import { Preferences } from "#generated/modules/preferences/Preferences.ts";
|
|
636
666
|
|
|
637
667
|
const api = bind(Preferences, Client, { registry });
|
|
638
668
|
const self = api.self.query(undefined);
|
|
639
669
|
const save = api.save.run({ title: "My preferences" });
|
|
640
670
|
```
|
|
641
671
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
Handlers read the account from request-local `Identity`, imported from `@shivaedev/identity/identity.ts`:
|
|
672
|
+
`Client` is the application's native AtomRpc service, and `registry` is the atom registry that owns the session's queries. In React, `SessionBoundary` supplies that registry to `connect`, as [react's session-scoped bindings](https://github.com/ShivaeDev/platform/blob/main/packages/react/README.md#session-scoped-bindings) show.
|
|
645
673
|
|
|
646
|
-
|
|
647
|
-
Preferences.application.toLayer({
|
|
648
|
-
"preferences.self": () => Effect.flatMap(Identity, ({ id }) => store.read(id)),
|
|
649
|
-
"preferences.save": ({ title }) => Effect.flatMap(Identity, ({ id }) => store.save(id, title)),
|
|
650
|
-
});
|
|
651
|
-
```
|
|
652
|
-
|
|
653
|
-
`store` is the application's persistence service. No owner or client key scope is accepted from a request. The database app host uses plain repository keys for every subscriber and rechecks each subscriber’s read policy before delivery.
|
|
674
|
+
No owner or client key scope is accepted from a request. The database app host uses plain repository keys for every subscriber and rechecks each subscriber’s read policy before delivery.
|
|
654
675
|
|
|
655
676
|
The registry is required for session-scoped bindings. Query atoms and live connections belong in it; command and one-off query Effects execute through it. Explicit streams also run through its client, preserving the session transport and headers; disposing the registry ends those streams. Streams on ordinary contracts use the caller's client. A successful command invalidates its registry's prefixed keys, while a rejected command declares no invalidation. Ordinary contracts keep unscoped keys and the two-argument `bind` call.
|
|
656
677
|
|
|
@@ -708,21 +729,22 @@ Server adapters import `LiveServer` from `@shivaedev/contract/live-server/servic
|
|
|
708
729
|
|
|
709
730
|
Contract groups carry their read-policy guard into native `RpcServer` hosts and Platform’s application host. An ordinary query evaluates its policy once per request, after identity middleware supplies `CurrentViewer` from its validated session. A false policy returns `QueryReadDenied` without running the handler. Native hosts need no policy middleware or guard Layer. Real HTTP stories exercise both hosts with allowed and denied counted policies; they prove this RPC boundary, not an application’s session or deployment policy. Platform’s application host refuses HTTP `$changes` calls with `WebSocketRequired`; subscriptions use its WebSocket protocol. Subscription delivery and pushed reruns continue to check current access.
|
|
710
731
|
|
|
711
|
-
A query
|
|
732
|
+
A query's `readPolicy(payload, viewer)` returns an Effect boolean, and a query declares `reads` only when its reads do not name its keys, as described below. `viewer` is the session's `Option<{ id: string }>`; the browser does not send the identity. `signedIn` from `readPolicy.ts` allows any signed-in viewer and refuses a signed-out viewer, and a query written with `run` that states no policy gets it. `QueryReadPolicy<Payload, E, R>` preserves typed failures and required services. A policy's typed failures join the query's rejections, so a failing access check reaches the client as that failure, including during live reads. Only a successful `false` denies access. [Policy services](#policy-services) explains richer session requirements and where to provide implementations.
|
|
712
733
|
|
|
713
734
|
```ts
|
|
714
|
-
import { Schema } from "effect";
|
|
715
735
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
716
|
-
import {
|
|
736
|
+
import { NotesRepository, SessionUser } from "./services.ts";
|
|
717
737
|
|
|
718
738
|
const Mine = query("mine", {
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
739
|
+
*run() {
|
|
740
|
+
const repository = yield* NotesRepository;
|
|
741
|
+
const { id: userId } = yield* SessionUser;
|
|
742
|
+
return yield* repository.findMany({ select: ["title"], where: { userId } });
|
|
743
|
+
},
|
|
722
744
|
});
|
|
723
745
|
```
|
|
724
746
|
|
|
725
|
-
`Mine` declares no `reads`. Its
|
|
747
|
+
`Mine` declares no policy and no `reads`. Its `run` reads `findMany({ where: { userId } })` through a `@shivaedev/sql` repository, which names the viewer's `userId` bucket, so the live query listens on that bucket. On a repository model, annotate tenant fields with `bucket()` from `@shivaedev/changes/buckets.ts` so writes announce the affected buckets. For an admin page spanning every tenant, declare `readsCollections` beside a permission read policy:
|
|
726
748
|
|
|
727
749
|
```ts
|
|
728
750
|
import { Effect, Schema } from "effect";
|
|
@@ -732,14 +754,16 @@ import { query } from "@shivaedev/contract/operation.ts";
|
|
|
732
754
|
import { permissionReadPolicy } from "@shivaedev/contract/permissionReadPolicy.ts";
|
|
733
755
|
import { SessionUser } from "@shivaedev/identity/identity.ts";
|
|
734
756
|
import { hasPermission } from "@shivaedev/identity/permission.ts";
|
|
757
|
+
import { NotesRepository } from "./services.ts";
|
|
735
758
|
|
|
736
759
|
const notes = collection("notes", Schema.Number);
|
|
737
760
|
const ManageNotes = permission("notes.manage").any;
|
|
738
761
|
const AllNotes = query("allNotes", {
|
|
739
|
-
success: Schema.Array(Schema.String),
|
|
740
762
|
readPolicy: permissionReadPolicy(ManageNotes, (required) => Effect.map(SessionUser, (user) => hasPermission(user, required))),
|
|
741
|
-
reads: () => [],
|
|
742
763
|
readsCollections: [notes],
|
|
764
|
+
*run() {
|
|
765
|
+
return yield* (yield* NotesRepository).findMany({ select: ["title"] });
|
|
766
|
+
},
|
|
743
767
|
});
|
|
744
768
|
```
|
|
745
769
|
|
|
@@ -753,25 +777,26 @@ For dependencies that need server data, add `serverReads(payload, viewer)`, an E
|
|
|
753
777
|
import { Context, Effect, Schema } from "effect";
|
|
754
778
|
import type { Key } from "@shivaedev/changes/keys.ts";
|
|
755
779
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
756
|
-
import { signedIn } from "@shivaedev/contract/readPolicy.ts";
|
|
757
780
|
|
|
758
781
|
class TimelineData extends Context.Service<
|
|
759
782
|
TimelineData,
|
|
760
783
|
{
|
|
784
|
+
readonly entries: (workspaceId: string) => Effect.Effect<readonly string[]>;
|
|
761
785
|
readonly readKeys: (workspaceId: string) => Effect.Effect<readonly Key[]>;
|
|
762
786
|
}
|
|
763
787
|
>()("app/TimelineData") {}
|
|
764
788
|
|
|
765
789
|
const Timeline = query("timeline", {
|
|
766
790
|
payload: { workspaceId: Schema.String },
|
|
767
|
-
success: Schema.Array(Schema.String),
|
|
768
|
-
readPolicy: signedIn,
|
|
769
791
|
reads: () => [],
|
|
770
792
|
serverReads: ({ workspaceId }) => Effect.flatMap(TimelineData, (data) => data.readKeys(workspaceId)),
|
|
793
|
+
*run({ workspaceId }) {
|
|
794
|
+
return yield* (yield* TimelineData).entries(workspaceId);
|
|
795
|
+
},
|
|
771
796
|
});
|
|
772
797
|
```
|
|
773
798
|
|
|
774
|
-
Provide `TimelineData` on the server to
|
|
799
|
+
Provide `TimelineData` on the server to read the workspace's entries, and to load its lists and return their keys. Use an application policy that checks workspace access; derived keys are refresh dependencies and grant no read access. Each write must publish the same keys. After every rerun the server evaluates `reads` and `serverReads` again and replaces the subscription's registrations, so the keys follow the workspace while the subscription stays open. A list that joins is watched once a rerun has seen it, so the write that adds a list must publish a key the query already reads, such as a workspace bucket that `serverReads` also returns. Once a rerun has seen a list leave, that list's writes no longer rerun the query. The browser never runs `serverReads`; matching changes rerun the affected query on the server.
|
|
775
800
|
|
|
776
801
|
A handler can also name keys while it runs, with `recordRead(keys)` from `@shivaedev/changes/readRecorder.ts`, before the statement that reads by them. The live subscription registers each recorded key with the host the moment it is recorded, before that statement is sent, and matches it alongside the keys from `reads`, `serverReads` and `readsCollections`. A key recorded on a rerun is therefore watched before its read, where a `serverReads` key is watched only once the rerun has finished. A key that is already registered is not registered again, so a handler that reads the same row many times registers its key once. Nothing the query's read policy records counts, whether through repository reads or its own `recordRead` calls: permission changes refresh nothing live, so a write to a row only the policy reads does not rerun the query.
|
|
777
802
|
|
|
@@ -786,7 +811,13 @@ import { Context, Effect, Option, Schema } from "effect";
|
|
|
786
811
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
787
812
|
import { NotFound } from "@shivaedev/errors/taxonomy.ts";
|
|
788
813
|
|
|
789
|
-
class
|
|
814
|
+
class PrivateNotes extends Context.Service<
|
|
815
|
+
PrivateNotes,
|
|
816
|
+
{
|
|
817
|
+
readonly owner: (id: number) => Effect.Effect<Option.Option<string>>;
|
|
818
|
+
readonly title: (id: number) => Effect.Effect<string>;
|
|
819
|
+
}
|
|
820
|
+
>()("app/PrivateNotes") {}
|
|
790
821
|
const PrivateNote = query("privateNote", {
|
|
791
822
|
payload: { id: Schema.Number },
|
|
792
823
|
readPolicy: ({ id }, viewer) =>
|
|
@@ -794,40 +825,41 @@ const PrivateNote = query("privateNote", {
|
|
|
794
825
|
if (Option.isNone(viewer)) {
|
|
795
826
|
return false;
|
|
796
827
|
}
|
|
797
|
-
const owner = yield* (yield*
|
|
828
|
+
const owner = yield* (yield* PrivateNotes).owner(id);
|
|
798
829
|
if (Option.isNone(owner) || owner.value !== viewer.value.id) {
|
|
799
830
|
return yield* new NotFound({ message: "Note not found" });
|
|
800
831
|
}
|
|
801
832
|
return true;
|
|
802
833
|
}),
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
834
|
+
*run({ id }) {
|
|
835
|
+
return yield* (yield* PrivateNotes).title(id);
|
|
836
|
+
},
|
|
806
837
|
});
|
|
807
838
|
```
|
|
808
839
|
|
|
809
|
-
The
|
|
840
|
+
The module's registration provides `PrivateNotes`; the browser's generated contract carries no read policy. The generator lists the policy's `NotFound` among the query's rejections, and the same typed rejection reaches ordinary reads and live subscriptions.
|
|
810
841
|
|
|
811
842
|
A record key, `notes.item(id)`, names one record. A bucket, `notes.bucket.userId(id)`, names every row with that field value. Declare bucket fields on the collection model with their schemas. A list may add title, state or other filters to its input and handler, but those filters never narrow its bucket. It reruns whenever any row in that bucket changes, including a row excluded by the filter. Writers explicitly announce the record and affected buckets with the same constructors from `@shivaedev/changes/keys.ts`.
|
|
812
843
|
|
|
813
|
-
The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial results. Every query
|
|
844
|
+
The same query policy guards running the query and subscribing to it. A subscription is meant to carry one query. It names query references, never arbitrary record or bucket keys. If a subscription mixes queries the viewer may and may not read, the entire subscription is refused with `QueryReadDenied`; it delivers no partial results. Every query has a policy: one written with `run` gets `signedIn` when it states none, and one declared without run requires `readPolicy`, including queries used only through one-off `run` calls, so TypeScript rejects a policy-less declaration before handlers or a live server can be built. Platform’s application host validates the complete RPC group while building its Layer, before listening; untyped declarations missing policies fail with `MissingReadPolicies`, whose `queries` and `message` name every affected RPC. Native hosts enforce read policies automatically at request time. `MissingReadPolicy` remains a request-time refusal for untyped declarations served through native servers that bypass that boot check, on plain calls and subscriptions alike. Reads outside a declared query acquire no automatic subscription.
|
|
814
845
|
|
|
815
846
|
Session middleware supplies `CurrentViewer` after validating the session. Each rerun uses a freshly loaded session and the same authorized handler as an ordinary read. A removed session ends the subscription with `Unauthorized`; a current session denied by the read policy receives `QueryReadDenied`, with no query SQL and its stored hash cleared. The established subscription stays open for later authorized changes. Raw consumers handle `Result`, `Unchanged` and `QueryReadDenied`.
|
|
816
847
|
|
|
817
848
|
### Policy services
|
|
818
849
|
|
|
819
|
-
Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the
|
|
850
|
+
Use the policy's `viewer` argument for the viewer ID. Read richer session context from Effect requirements. For example, a policy service can require `SessionUserWithProviderAccounts` from `@shivaedev/identity/identity.ts` and yield its `providerAccounts` Effect. Apply `AuthenticatedUserWithProviderAccounts` middleware to the module and merge `authenticatedUserWithProviderAccountsLayer()` from `@shivaedev/identity/server/session.ts` into the handlers the host serves, with the shared `SessionPolicy` Layer provided once by the application host. The middleware provides this request-local context for both RPC calls and live reruns, including each policy recheck before a result is delivered. Session-backed hosts reload that context before each rerun, and use the same snapshot for its policy and query rerun.
|
|
820
851
|
|
|
821
|
-
Keep the policy service tag
|
|
852
|
+
Keep the policy service's tag beside the query and its implementation in server code. Its method retains the session service in its requirements so the session is read when the policy runs:
|
|
822
853
|
|
|
823
854
|
```ts
|
|
824
855
|
import { Context, Effect, Option, Schema } from "effect";
|
|
825
|
-
import {
|
|
856
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
826
857
|
import { query } from "@shivaedev/contract/operation.ts";
|
|
827
858
|
import type { Viewer } from "@shivaedev/contract/readPolicy.ts";
|
|
828
859
|
import { AuthUnavailable, Unauthorized } from "@shivaedev/errors/taxonomy.ts";
|
|
829
860
|
import { SessionUserWithProviderAccounts } from "@shivaedev/identity/identity.ts";
|
|
830
861
|
import { AuthenticatedUserWithProviderAccounts } from "@shivaedev/identity/middleware.ts";
|
|
862
|
+
import { documentsWire } from "#generated/modules/documents/Documents.ts";
|
|
831
863
|
|
|
832
864
|
class ReadAccess extends Context.Service<
|
|
833
865
|
ReadAccess,
|
|
@@ -842,17 +874,23 @@ class ReadAccess extends Context.Service<
|
|
|
842
874
|
const Get = query("get", {
|
|
843
875
|
payload: { accountId: Schema.String },
|
|
844
876
|
readPolicy: ({ accountId }, viewer) => Effect.flatMap(ReadAccess, (access) => access.allows(accountId, viewer)),
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
877
|
+
*run({ accountId }) {
|
|
878
|
+
return yield* Effect.succeed(`Document for ${accountId}`);
|
|
879
|
+
},
|
|
880
|
+
});
|
|
881
|
+
export const Documents = defineModule({
|
|
882
|
+
middleware: AuthenticatedUserWithProviderAccounts,
|
|
883
|
+
name: "documents",
|
|
884
|
+
operations: [Get],
|
|
885
|
+
wire: documentsWire,
|
|
848
886
|
});
|
|
849
|
-
const Documents = contract("documents", { queries: [Get] }).middleware(AuthenticatedUserWithProviderAccounts);
|
|
850
887
|
```
|
|
851
888
|
|
|
852
|
-
|
|
889
|
+
The generator lists the policy's `AuthUnavailable` and `Unauthorized` among the query's rejections. Provide the implementation from the module's registration:
|
|
853
890
|
|
|
854
891
|
```ts
|
|
855
892
|
import { Effect, Layer, Option } from "effect";
|
|
893
|
+
import type { AppModule } from "@shivaedev/server/AppModule.ts";
|
|
856
894
|
|
|
857
895
|
const ReadAccessLive = Layer.succeed(ReadAccess, {
|
|
858
896
|
allows: (accountId, viewer) =>
|
|
@@ -866,14 +904,10 @@ const ReadAccessLive = Layer.succeed(ReadAccess, {
|
|
|
866
904
|
);
|
|
867
905
|
}),
|
|
868
906
|
});
|
|
869
|
-
const
|
|
870
|
-
.toLayer({
|
|
871
|
-
"documents.get": ({ accountId }) => Effect.succeed(`Document for ${accountId}`),
|
|
872
|
-
})
|
|
873
|
-
.pipe(Layer.provide(ReadAccessLive));
|
|
907
|
+
export const documents = { module: Documents, services: ReadAccessLive } satisfies AppModule;
|
|
874
908
|
```
|
|
875
909
|
|
|
876
|
-
The
|
|
910
|
+
The module's handlers check the policy with the services the registration provides, for RPC calls and subscriptions alike. Request-local services take precedence over those services; a session value installed while building the handlers cannot replace the current viewer's session. The policy runs again for live reruns; its allow or deny result is not cached.
|
|
877
911
|
|
|
878
912
|
### In-memory clients in story kits
|
|
879
913
|
|
|
@@ -8,5 +8,6 @@ export declare function activityState(): {
|
|
|
8
8
|
change: (key: Exclude<keyof ClientActivityState, "connectionStatus" | "firstSettled">, delta: number) => void;
|
|
9
9
|
hold: () => () => void;
|
|
10
10
|
setConnection: (connectionStatus: ConnectionStatus) => void;
|
|
11
|
+
warming: (delta: number) => void;
|
|
11
12
|
};
|
|
12
13
|
//# sourceMappingURL=activityState.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activityState.d.ts","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,QAAQ,CAAC;AACjD,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,gBAAgB,EAAmB,MAAM,oBAAoB,CAAC;AAEtG,wBAAgB,aAAa;
|
|
1
|
+
{"version":3,"file":"activityState.d.ts","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,QAAQ,CAAC;AACjD,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,gBAAgB,EAAmB,MAAM,oBAAoB,CAAC;AAEtG,wBAAgB,aAAa;IA4B3B,QAAQ;;;IACR,QAAQ;IAIR,MAAM,QAAQ,OAAO,CAAC,MAAM,mBAAmB,EAAE,kBAAkB,GAAG,cAAc,CAAC,SAAS,MAAM;IAGpG,IAAI;IAQJ,aAAa,qBAAqB,gBAAgB;IAIlD,OAAO,UAAU,MAAM;EAKxB"}
|
|
@@ -2,6 +2,7 @@ import { Effect, SubscriptionRef } from "effect";
|
|
|
2
2
|
import { isClientSettled } from "#clientActivity.ts";
|
|
3
3
|
export function activityState() {
|
|
4
4
|
let held = 0;
|
|
5
|
+
let warmWaiting = 0;
|
|
5
6
|
let answered = false;
|
|
6
7
|
let connection = "live";
|
|
7
8
|
const state = Effect.runSync(SubscriptionRef.make({
|
|
@@ -19,7 +20,8 @@ export function activityState() {
|
|
|
19
20
|
Effect.runSync(SubscriptionRef.update(state, (current) => (current.connectionStatus === connectionStatus ? current : { ...current, connectionStatus })));
|
|
20
21
|
}
|
|
21
22
|
function latched(current) {
|
|
22
|
-
|
|
23
|
+
const settled = isClientSettled({ ...current, initialQueries: current.initialQueries - warmWaiting });
|
|
24
|
+
return answered && !current.firstSettled && settled ? { ...current, firstSettled: true } : current;
|
|
23
25
|
}
|
|
24
26
|
return {
|
|
25
27
|
activity: Object.assign(SubscriptionRef.changes(state), { current: SubscriptionRef.get(state) }),
|
|
@@ -42,6 +44,10 @@ export function activityState() {
|
|
|
42
44
|
connection = connectionStatus;
|
|
43
45
|
publish();
|
|
44
46
|
},
|
|
47
|
+
warming: (delta) => {
|
|
48
|
+
warmWaiting += delta;
|
|
49
|
+
Effect.runSync(SubscriptionRef.update(state, latched));
|
|
50
|
+
},
|
|
45
51
|
};
|
|
46
52
|
}
|
|
47
53
|
//# sourceMappingURL=activityState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activityState.js","sourceRoot":"","sources":["../../src/adapters/activityState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACjD,OAAO,EAAmD,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAEtG,M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,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;QACxD,CAAC;QACD,MAAM,EAAE,CAAC,GAA4E,EAAE,KAAa,EAAE,EAAE;YACvG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QAClH,CAAC;QACD,IAAI,EAAE,GAAG,EAAE;YACV,IAAI,IAAI,CAAC,CAAC;YACV,OAAO,EAAE,CAAC;YACV,OAAO,GAAG,EAAE;gBACX,IAAI,IAAI,CAAC,CAAC;gBACV,OAAO,EAAE,CAAC;YACX,CAAC,CAAC;QACH,CAAC;QACD,aAAa,EAAE,CAAC,gBAAkC,EAAE,EAAE;YACrD,UAAU,GAAG,gBAAgB,CAAC;YAC9B,OAAO,EAAE,CAAC;QACX,CAAC;QACD,OAAO,EAAE,CAAC,KAAa,EAAE,EAAE;YAC1B,WAAW,IAAI,KAAK,CAAC;YACrB,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;QACxD,CAAC;KACD,CAAC;AACH,CAAC"}
|
|
@@ -13,7 +13,7 @@ export declare const clientActivities: WeakMap<object, {
|
|
|
13
13
|
reflecting: () => () => void;
|
|
14
14
|
statuses: Atom.Writable<ReadonlyMap<object, import("./live.ts").LiveStatus<unknown>>, ReadonlyMap<object, import("./live.ts").LiveStatus<unknown>>>;
|
|
15
15
|
track: <A, E, R>(effect: Effect.Effect<A, E, R>, command?: boolean) => Effect.Effect<A, E, R>;
|
|
16
|
-
watch: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E
|
|
16
|
+
watch: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>, warm: (get: Atom.AtomContext) => boolean) => Atom.Atom<AsyncResult.AsyncResult<A, E>>;
|
|
17
17
|
}>;
|
|
18
18
|
export declare function makeActivity(factory: Atom.RuntimeFactory): {
|
|
19
19
|
activity: import("effect/Stream").Stream<import("./clientActivity.ts").ClientActivityState, never, never> & {
|
|
@@ -27,6 +27,6 @@ export declare function makeActivity(factory: Atom.RuntimeFactory): {
|
|
|
27
27
|
reflecting: () => () => void;
|
|
28
28
|
statuses: Atom.Writable<ReadonlyMap<object, import("./live.ts").LiveStatus<unknown>>, ReadonlyMap<object, import("./live.ts").LiveStatus<unknown>>>;
|
|
29
29
|
track: <A, E, R>(effect: Effect.Effect<A, E, R>, command?: boolean) => Effect.Effect<A, E, R>;
|
|
30
|
-
watch: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E
|
|
30
|
+
watch: <A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>, warm: (get: Atom.AtomContext) => boolean) => Atom.Atom<AsyncResult.AsyncResult<A, E>>;
|
|
31
31
|
};
|
|
32
32
|
//# sourceMappingURL=clientActivities.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clientActivities.d.ts","sourceRoot":"","sources":["../src/clientActivities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,WAAW,MAAM,+BAA+B,CAAC;AAC7D,OAAO,KAAK,KAAK,IAAI,MAAM,wBAAwB,CAAC;AAMpD,eAAO,MAAM,gBAAgB;;;;;;;;
|
|
1
|
+
{"version":3,"file":"clientActivities.d.ts","sourceRoot":"","sources":["../src/clientActivities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,WAAW,MAAM,+BAA+B,CAAC;AAC7D,OAAO,KAAK,KAAK,IAAI,MAAM,wBAAwB,CAAC;AAMpD,eAAO,MAAM,gBAAgB;;;;;;;;WA+EpB,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;YAtEhC,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;YAwBvC,CAAC,EAAE,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,WAAW,KAAK,OAAO;EAjCxC,CAAC;AAEvE,wBAAgB,YAAY,CAAC,OAAO,EAAE,IAAI,CAAC,cAAc;;;;;;;;WA6EhD,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;;YAtEhC,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;YAwBvC,CAAC,EAAE,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,WAAW,KAAK,OAAO;EA4D7G"}
|
package/dist/clientActivities.js
CHANGED
|
@@ -5,7 +5,7 @@ import { clientConnection } from "#adapters/clientConnection.ts";
|
|
|
5
5
|
import { wrapAtom } from "#wrapAtom.ts";
|
|
6
6
|
export const clientActivities = new WeakMap();
|
|
7
7
|
export function makeActivity(factory) {
|
|
8
|
-
const { activity, answered, change, hold, setConnection } = activityState();
|
|
8
|
+
const { activity, answered, change, hold, setConnection, warming } = activityState();
|
|
9
9
|
const connection = clientConnection(factory, setConnection, activity);
|
|
10
10
|
function begin(key) {
|
|
11
11
|
change(key, 1);
|
|
@@ -21,21 +21,22 @@ export function makeActivity(factory) {
|
|
|
21
21
|
};
|
|
22
22
|
}), () => effect, (end) => Effect.sync(end));
|
|
23
23
|
}
|
|
24
|
-
function counter(
|
|
24
|
+
function counter(apply) {
|
|
25
25
|
let pending = false;
|
|
26
26
|
function set(next) {
|
|
27
27
|
if (pending !== next) {
|
|
28
28
|
pending = next;
|
|
29
|
-
|
|
29
|
+
apply(next ? 1 : -1);
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
return { release: () => set(false), set };
|
|
33
33
|
}
|
|
34
|
-
function watch(atom) {
|
|
34
|
+
function watch(atom, warm) {
|
|
35
35
|
const watched = wrapAtom(atom, (get) => {
|
|
36
36
|
get.mount(connection.status);
|
|
37
|
-
const refreshing = counter("refreshingAtoms");
|
|
38
|
-
const initial = counter("initialQueries");
|
|
37
|
+
const refreshing = counter((delta) => change("refreshingAtoms", delta));
|
|
38
|
+
const initial = counter((delta) => change("initialQueries", delta));
|
|
39
|
+
const warmInitial = counter(warming);
|
|
39
40
|
let received = false;
|
|
40
41
|
let active = true;
|
|
41
42
|
let published = false;
|
|
@@ -46,6 +47,7 @@ export function makeActivity(factory) {
|
|
|
46
47
|
const first = !(received || AsyncResult.isInitial(result));
|
|
47
48
|
received ||= first;
|
|
48
49
|
initial.set(!received);
|
|
50
|
+
warmInitial.set(!received && warm(get));
|
|
49
51
|
refreshing.set(result.waiting || AsyncResult.isInitial(result));
|
|
50
52
|
if (first) {
|
|
51
53
|
answered();
|
|
@@ -54,6 +56,7 @@ export function makeActivity(factory) {
|
|
|
54
56
|
get.addFinalizer(() => {
|
|
55
57
|
active = false;
|
|
56
58
|
refreshing.release();
|
|
59
|
+
warmInitial.release();
|
|
57
60
|
initial.release();
|
|
58
61
|
});
|
|
59
62
|
function publish(result) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clientActivities.js","sourceRoot":"","sources":["../src/clientActivities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,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